1/* Build expressions with type checking for C++ compiler.
2   Copyright (C) 1987-2022 Free Software Foundation, Inc.
3   Hacked by Michael Tiemann (tiemann@cygnus.com)
4
5This file is part of GCC.
6
7GCC is free software; you can redistribute it and/or modify
8it under the terms of the GNU General Public License as published by
9the Free Software Foundation; either version 3, or (at your option)
10any later version.
11
12GCC is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
18along with GCC; see the file COPYING3.  If not see
19<http://www.gnu.org/licenses/>.  */
20
21
22/* This file is part of the C++ front end.
23   It contains routines to build C++ expressions given their operands,
24   including computing the types of the result, C and C++ specific error
25   checks, and some optimization.  */
26
27#include "config.h"
28#include "system.h"
29#include "coretypes.h"
30#include "target.h"
31#include "cp-tree.h"
32#include "stor-layout.h"
33#include "varasm.h"
34#include "intl.h"
35#include "convert.h"
36#include "c-family/c-objc.h"
37#include "c-family/c-ubsan.h"
38#include "gcc-rich-location.h"
39#include "stringpool.h"
40#include "attribs.h"
41#include "asan.h"
42#include "gimplify.h"
43
44static tree cp_build_addr_expr_strict (tree, tsubst_flags_t);
45static tree cp_build_function_call (tree, tree, tsubst_flags_t);
46static tree pfn_from_ptrmemfunc (tree);
47static tree delta_from_ptrmemfunc (tree);
48static tree convert_for_assignment (tree, tree, impl_conv_rhs, tree, int,
49				    tsubst_flags_t, int);
50static tree cp_pointer_int_sum (location_t, enum tree_code, tree, tree,
51				tsubst_flags_t);
52static tree rationalize_conditional_expr (enum tree_code, tree,
53					  tsubst_flags_t);
54static bool comp_ptr_ttypes_real (tree, tree, int);
55static bool comp_except_types (tree, tree, bool);
56static bool comp_array_types (const_tree, const_tree, compare_bounds_t, bool);
57static tree pointer_diff (location_t, tree, tree, tree, tsubst_flags_t, tree *);
58static tree get_delta_difference (tree, tree, bool, bool, tsubst_flags_t);
59static void casts_away_constness_r (tree *, tree *, tsubst_flags_t);
60static bool casts_away_constness (tree, tree, tsubst_flags_t);
61static bool maybe_warn_about_returning_address_of_local (tree, location_t = UNKNOWN_LOCATION);
62static void error_args_num (location_t, tree, bool);
63static int convert_arguments (tree, vec<tree, va_gc> **, tree, int,
64                              tsubst_flags_t);
65static bool is_std_move_p (tree);
66static bool is_std_forward_p (tree);
67
68/* Do `exp = require_complete_type (exp);' to make sure exp
69   does not have an incomplete type.  (That includes void types.)
70   Returns error_mark_node if the VALUE does not have
71   complete type when this function returns.  */
72
73tree
74require_complete_type_sfinae (tree value, tsubst_flags_t complain)
75{
76  tree type;
77
78  if (processing_template_decl || value == error_mark_node)
79    return value;
80
81  if (TREE_CODE (value) == OVERLOAD)
82    type = unknown_type_node;
83  else
84    type = TREE_TYPE (value);
85
86  if (type == error_mark_node)
87    return error_mark_node;
88
89  /* First, detect a valid value with a complete type.  */
90  if (COMPLETE_TYPE_P (type))
91    return value;
92
93  if (complete_type_or_maybe_complain (type, value, complain))
94    return value;
95  else
96    return error_mark_node;
97}
98
99tree
100require_complete_type (tree value)
101{
102  return require_complete_type_sfinae (value, tf_warning_or_error);
103}
104
105/* Try to complete TYPE, if it is incomplete.  For example, if TYPE is
106   a template instantiation, do the instantiation.  Returns TYPE,
107   whether or not it could be completed, unless something goes
108   horribly wrong, in which case the error_mark_node is returned.  */
109
110tree
111complete_type (tree type)
112{
113  if (type == NULL_TREE)
114    /* Rather than crash, we return something sure to cause an error
115       at some point.  */
116    return error_mark_node;
117
118  if (type == error_mark_node || COMPLETE_TYPE_P (type))
119    ;
120  else if (TREE_CODE (type) == ARRAY_TYPE)
121    {
122      tree t = complete_type (TREE_TYPE (type));
123      unsigned int needs_constructing, has_nontrivial_dtor;
124      if (COMPLETE_TYPE_P (t) && !dependent_type_p (type))
125	layout_type (type);
126      needs_constructing
127	= TYPE_NEEDS_CONSTRUCTING (TYPE_MAIN_VARIANT (t));
128      has_nontrivial_dtor
129	= TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TYPE_MAIN_VARIANT (t));
130      for (t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
131	{
132	  TYPE_NEEDS_CONSTRUCTING (t) = needs_constructing;
133	  TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t) = has_nontrivial_dtor;
134	}
135    }
136  else if (CLASS_TYPE_P (type))
137    {
138      if (modules_p ())
139	/* TYPE could be a class member we've not loaded the definition of.  */
140	lazy_load_pendings (TYPE_NAME (TYPE_MAIN_VARIANT (type)));
141
142      if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
143	instantiate_class_template (TYPE_MAIN_VARIANT (type));
144    }
145
146  return type;
147}
148
149/* Like complete_type, but issue an error if the TYPE cannot be completed.
150   VALUE is used for informative diagnostics.
151   Returns NULL_TREE if the type cannot be made complete.  */
152
153tree
154complete_type_or_maybe_complain (tree type, tree value, tsubst_flags_t complain)
155{
156  type = complete_type (type);
157  if (type == error_mark_node)
158    /* We already issued an error.  */
159    return NULL_TREE;
160  else if (!COMPLETE_TYPE_P (type))
161    {
162      if (complain & tf_error)
163	cxx_incomplete_type_diagnostic (value, type, DK_ERROR);
164      note_failed_type_completion_for_satisfaction (type);
165      return NULL_TREE;
166    }
167  else
168    return type;
169}
170
171tree
172complete_type_or_else (tree type, tree value)
173{
174  return complete_type_or_maybe_complain (type, value, tf_warning_or_error);
175}
176
177
178/* Return the common type of two parameter lists.
179   We assume that comptypes has already been done and returned 1;
180   if that isn't so, this may crash.
181
182   As an optimization, free the space we allocate if the parameter
183   lists are already common.  */
184
185static tree
186commonparms (tree p1, tree p2)
187{
188  tree oldargs = p1, newargs, n;
189  int i, len;
190  int any_change = 0;
191
192  len = list_length (p1);
193  newargs = tree_last (p1);
194
195  if (newargs == void_list_node)
196    i = 1;
197  else
198    {
199      i = 0;
200      newargs = 0;
201    }
202
203  for (; i < len; i++)
204    newargs = tree_cons (NULL_TREE, NULL_TREE, newargs);
205
206  n = newargs;
207
208  for (i = 0; p1;
209       p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2), n = TREE_CHAIN (n), i++)
210    {
211      if (TREE_PURPOSE (p1) && !TREE_PURPOSE (p2))
212	{
213	  TREE_PURPOSE (n) = TREE_PURPOSE (p1);
214	  any_change = 1;
215	}
216      else if (! TREE_PURPOSE (p1))
217	{
218	  if (TREE_PURPOSE (p2))
219	    {
220	      TREE_PURPOSE (n) = TREE_PURPOSE (p2);
221	      any_change = 1;
222	    }
223	}
224      else
225	{
226	  if (simple_cst_equal (TREE_PURPOSE (p1), TREE_PURPOSE (p2)) != 1)
227	    any_change = 1;
228	  TREE_PURPOSE (n) = TREE_PURPOSE (p2);
229	}
230      if (TREE_VALUE (p1) != TREE_VALUE (p2))
231	{
232	  any_change = 1;
233	  TREE_VALUE (n) = merge_types (TREE_VALUE (p1), TREE_VALUE (p2));
234	}
235      else
236	TREE_VALUE (n) = TREE_VALUE (p1);
237    }
238  if (! any_change)
239    return oldargs;
240
241  return newargs;
242}
243
244/* Given a type, perhaps copied for a typedef,
245   find the "original" version of it.  */
246static tree
247original_type (tree t)
248{
249  int quals = cp_type_quals (t);
250  while (t != error_mark_node
251	 && TYPE_NAME (t) != NULL_TREE)
252    {
253      tree x = TYPE_NAME (t);
254      if (TREE_CODE (x) != TYPE_DECL)
255	break;
256      x = DECL_ORIGINAL_TYPE (x);
257      if (x == NULL_TREE)
258	break;
259      t = x;
260    }
261  return cp_build_qualified_type (t, quals);
262}
263
264/* Merge the attributes of type OTHER_TYPE into the attributes of type TYPE
265   and return a variant of TYPE with the merged attributes.  */
266
267static tree
268merge_type_attributes_from (tree type, tree other_type)
269{
270  tree attrs = targetm.merge_type_attributes (type, other_type);
271  attrs = restrict_type_identity_attributes_to (attrs, TYPE_ATTRIBUTES (type));
272  return cp_build_type_attribute_variant (type, attrs);
273}
274
275/* Return the common type for two arithmetic types T1 and T2 under the
276   usual arithmetic conversions.  The default conversions have already
277   been applied, and enumerated types converted to their compatible
278   integer types.  */
279
280static tree
281cp_common_type (tree t1, tree t2)
282{
283  enum tree_code code1 = TREE_CODE (t1);
284  enum tree_code code2 = TREE_CODE (t2);
285  tree attributes;
286  int i;
287
288
289  /* In what follows, we slightly generalize the rules given in [expr] so
290     as to deal with `long long' and `complex'.  First, merge the
291     attributes.  */
292  attributes = (*targetm.merge_type_attributes) (t1, t2);
293
294  if (SCOPED_ENUM_P (t1) || SCOPED_ENUM_P (t2))
295    {
296      if (TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
297	return build_type_attribute_variant (t1, attributes);
298      else
299	return NULL_TREE;
300    }
301
302  /* FIXME: Attributes.  */
303  gcc_assert (ARITHMETIC_TYPE_P (t1)
304	      || VECTOR_TYPE_P (t1)
305	      || UNSCOPED_ENUM_P (t1));
306  gcc_assert (ARITHMETIC_TYPE_P (t2)
307	      || VECTOR_TYPE_P (t2)
308	      || UNSCOPED_ENUM_P (t2));
309
310  /* If one type is complex, form the common type of the non-complex
311     components, then make that complex.  Use T1 or T2 if it is the
312     required type.  */
313  if (code1 == COMPLEX_TYPE || code2 == COMPLEX_TYPE)
314    {
315      tree subtype1 = code1 == COMPLEX_TYPE ? TREE_TYPE (t1) : t1;
316      tree subtype2 = code2 == COMPLEX_TYPE ? TREE_TYPE (t2) : t2;
317      tree subtype
318	= type_after_usual_arithmetic_conversions (subtype1, subtype2);
319
320      if (code1 == COMPLEX_TYPE && TREE_TYPE (t1) == subtype)
321	return build_type_attribute_variant (t1, attributes);
322      else if (code2 == COMPLEX_TYPE && TREE_TYPE (t2) == subtype)
323	return build_type_attribute_variant (t2, attributes);
324      else
325	return build_type_attribute_variant (build_complex_type (subtype),
326					     attributes);
327    }
328
329  if (code1 == VECTOR_TYPE)
330    {
331      /* When we get here we should have two vectors of the same size.
332	 Just prefer the unsigned one if present.  */
333      if (TYPE_UNSIGNED (t1))
334	return merge_type_attributes_from (t1, t2);
335      else
336	return merge_type_attributes_from (t2, t1);
337    }
338
339  /* If only one is real, use it as the result.  */
340  if (code1 == REAL_TYPE && code2 != REAL_TYPE)
341    return build_type_attribute_variant (t1, attributes);
342  if (code2 == REAL_TYPE && code1 != REAL_TYPE)
343    return build_type_attribute_variant (t2, attributes);
344
345  /* Both real or both integers; use the one with greater precision.  */
346  if (TYPE_PRECISION (t1) > TYPE_PRECISION (t2))
347    return build_type_attribute_variant (t1, attributes);
348  else if (TYPE_PRECISION (t2) > TYPE_PRECISION (t1))
349    return build_type_attribute_variant (t2, attributes);
350
351  /* The types are the same; no need to do anything fancy.  */
352  if (TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
353    return build_type_attribute_variant (t1, attributes);
354
355  if (code1 != REAL_TYPE)
356    {
357      /* If one is unsigned long long, then convert the other to unsigned
358	 long long.  */
359      if (same_type_p (TYPE_MAIN_VARIANT (t1), long_long_unsigned_type_node)
360	  || same_type_p (TYPE_MAIN_VARIANT (t2), long_long_unsigned_type_node))
361	return build_type_attribute_variant (long_long_unsigned_type_node,
362					     attributes);
363      /* If one is a long long, and the other is an unsigned long, and
364	 long long can represent all the values of an unsigned long, then
365	 convert to a long long.  Otherwise, convert to an unsigned long
366	 long.  Otherwise, if either operand is long long, convert the
367	 other to long long.
368
369	 Since we're here, we know the TYPE_PRECISION is the same;
370	 therefore converting to long long cannot represent all the values
371	 of an unsigned long, so we choose unsigned long long in that
372	 case.  */
373      if (same_type_p (TYPE_MAIN_VARIANT (t1), long_long_integer_type_node)
374	  || same_type_p (TYPE_MAIN_VARIANT (t2), long_long_integer_type_node))
375	{
376	  tree t = ((TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2))
377		    ? long_long_unsigned_type_node
378		    : long_long_integer_type_node);
379	  return build_type_attribute_variant (t, attributes);
380	}
381
382      /* Go through the same procedure, but for longs.  */
383      if (same_type_p (TYPE_MAIN_VARIANT (t1), long_unsigned_type_node)
384	  || same_type_p (TYPE_MAIN_VARIANT (t2), long_unsigned_type_node))
385	return build_type_attribute_variant (long_unsigned_type_node,
386					     attributes);
387      if (same_type_p (TYPE_MAIN_VARIANT (t1), long_integer_type_node)
388	  || same_type_p (TYPE_MAIN_VARIANT (t2), long_integer_type_node))
389	{
390	  tree t = ((TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2))
391		    ? long_unsigned_type_node : long_integer_type_node);
392	  return build_type_attribute_variant (t, attributes);
393	}
394
395      /* For __intN types, either the type is __int128 (and is lower
396	 priority than the types checked above, but higher than other
397	 128-bit types) or it's known to not be the same size as other
398	 types (enforced in toplev.cc).  Prefer the unsigned type. */
399      for (i = 0; i < NUM_INT_N_ENTS; i ++)
400	{
401	  if (int_n_enabled_p [i]
402	      && (same_type_p (TYPE_MAIN_VARIANT (t1), int_n_trees[i].signed_type)
403		  || same_type_p (TYPE_MAIN_VARIANT (t2), int_n_trees[i].signed_type)
404		  || same_type_p (TYPE_MAIN_VARIANT (t1), int_n_trees[i].unsigned_type)
405		  || same_type_p (TYPE_MAIN_VARIANT (t2), int_n_trees[i].unsigned_type)))
406	    {
407	      tree t = ((TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2))
408			? int_n_trees[i].unsigned_type
409			: int_n_trees[i].signed_type);
410	      return build_type_attribute_variant (t, attributes);
411	    }
412	}
413
414      /* Otherwise prefer the unsigned one.  */
415      if (TYPE_UNSIGNED (t1))
416	return build_type_attribute_variant (t1, attributes);
417      else
418	return build_type_attribute_variant (t2, attributes);
419    }
420  else
421    {
422      if (same_type_p (TYPE_MAIN_VARIANT (t1), long_double_type_node)
423	  || same_type_p (TYPE_MAIN_VARIANT (t2), long_double_type_node))
424	return build_type_attribute_variant (long_double_type_node,
425					     attributes);
426      if (same_type_p (TYPE_MAIN_VARIANT (t1), double_type_node)
427	  || same_type_p (TYPE_MAIN_VARIANT (t2), double_type_node))
428	return build_type_attribute_variant (double_type_node,
429					     attributes);
430      if (same_type_p (TYPE_MAIN_VARIANT (t1), float_type_node)
431	  || same_type_p (TYPE_MAIN_VARIANT (t2), float_type_node))
432	return build_type_attribute_variant (float_type_node,
433					     attributes);
434
435      /* Two floating-point types whose TYPE_MAIN_VARIANTs are none of
436	 the standard C++ floating-point types.  Logic earlier in this
437	 function has already eliminated the possibility that
438	 TYPE_PRECISION (t2) != TYPE_PRECISION (t1), so there's no
439	 compelling reason to choose one or the other.  */
440      return build_type_attribute_variant (t1, attributes);
441    }
442}
443
444/* T1 and T2 are arithmetic or enumeration types.  Return the type
445   that will result from the "usual arithmetic conversions" on T1 and
446   T2 as described in [expr].  */
447
448tree
449type_after_usual_arithmetic_conversions (tree t1, tree t2)
450{
451  gcc_assert (ARITHMETIC_TYPE_P (t1)
452	      || VECTOR_TYPE_P (t1)
453	      || UNSCOPED_ENUM_P (t1));
454  gcc_assert (ARITHMETIC_TYPE_P (t2)
455	      || VECTOR_TYPE_P (t2)
456	      || UNSCOPED_ENUM_P (t2));
457
458  /* Perform the integral promotions.  We do not promote real types here.  */
459  if (INTEGRAL_OR_ENUMERATION_TYPE_P (t1)
460      && INTEGRAL_OR_ENUMERATION_TYPE_P (t2))
461    {
462      t1 = type_promotes_to (t1);
463      t2 = type_promotes_to (t2);
464    }
465
466  return cp_common_type (t1, t2);
467}
468
469static void
470composite_pointer_error (const op_location_t &location,
471			 diagnostic_t kind, tree t1, tree t2,
472			 composite_pointer_operation operation)
473{
474  switch (operation)
475    {
476    case CPO_COMPARISON:
477      emit_diagnostic (kind, location, 0,
478		       "comparison between "
479		       "distinct pointer types %qT and %qT lacks a cast",
480		       t1, t2);
481      break;
482    case CPO_CONVERSION:
483      emit_diagnostic (kind, location, 0,
484		       "conversion between "
485		       "distinct pointer types %qT and %qT lacks a cast",
486		       t1, t2);
487      break;
488    case CPO_CONDITIONAL_EXPR:
489      emit_diagnostic (kind, location, 0,
490		       "conditional expression between "
491		       "distinct pointer types %qT and %qT lacks a cast",
492		       t1, t2);
493      break;
494    default:
495      gcc_unreachable ();
496    }
497}
498
499/* Subroutine of composite_pointer_type to implement the recursive
500   case.  See that function for documentation of the parameters.  And ADD_CONST
501   is used to track adding "const" where needed.  */
502
503static tree
504composite_pointer_type_r (const op_location_t &location,
505			  tree t1, tree t2, bool *add_const,
506			  composite_pointer_operation operation,
507			  tsubst_flags_t complain)
508{
509  tree pointee1;
510  tree pointee2;
511  tree result_type;
512  tree attributes;
513
514  /* Determine the types pointed to by T1 and T2.  */
515  if (TYPE_PTR_P (t1))
516    {
517      pointee1 = TREE_TYPE (t1);
518      pointee2 = TREE_TYPE (t2);
519    }
520  else
521    {
522      pointee1 = TYPE_PTRMEM_POINTED_TO_TYPE (t1);
523      pointee2 = TYPE_PTRMEM_POINTED_TO_TYPE (t2);
524    }
525
526  /* [expr.type]
527
528     If T1 and T2 are similar types, the result is the cv-combined type of
529     T1 and T2.  */
530  if (same_type_ignoring_top_level_qualifiers_p (pointee1, pointee2))
531    result_type = pointee1;
532  else if ((TYPE_PTR_P (pointee1) && TYPE_PTR_P (pointee2))
533	   || (TYPE_PTRMEM_P (pointee1) && TYPE_PTRMEM_P (pointee2)))
534    {
535      result_type = composite_pointer_type_r (location, pointee1, pointee2,
536					      add_const, operation, complain);
537      if (result_type == error_mark_node)
538	return error_mark_node;
539    }
540  else
541    {
542      if (complain & tf_error)
543	composite_pointer_error (location, DK_PERMERROR,
544				 t1, t2, operation);
545      else
546	return error_mark_node;
547      result_type = void_type_node;
548    }
549  const int q1 = cp_type_quals (pointee1);
550  const int q2 = cp_type_quals (pointee2);
551  const int quals = q1 | q2;
552  result_type = cp_build_qualified_type (result_type,
553					 (quals | (*add_const
554						   ? TYPE_QUAL_CONST
555						   : TYPE_UNQUALIFIED)));
556  /* The cv-combined type can add "const" as per [conv.qual]/3.3 (except for
557     the TLQ).  The reason is that both T1 and T2 can then be converted to the
558     cv-combined type of T1 and T2.  */
559  if (quals != q1 || quals != q2)
560    *add_const = true;
561  /* If the original types were pointers to members, so is the
562     result.  */
563  if (TYPE_PTRMEM_P (t1))
564    {
565      if (!same_type_p (TYPE_PTRMEM_CLASS_TYPE (t1),
566			TYPE_PTRMEM_CLASS_TYPE (t2)))
567	{
568	  if (complain & tf_error)
569	    composite_pointer_error (location, DK_PERMERROR,
570				     t1, t2, operation);
571	  else
572	    return error_mark_node;
573	}
574      result_type = build_ptrmem_type (TYPE_PTRMEM_CLASS_TYPE (t1),
575				       result_type);
576    }
577  else
578    result_type = build_pointer_type (result_type);
579
580  /* Merge the attributes.  */
581  attributes = (*targetm.merge_type_attributes) (t1, t2);
582  return build_type_attribute_variant (result_type, attributes);
583}
584
585/* Return the composite pointer type (see [expr.type]) for T1 and T2.
586   ARG1 and ARG2 are the values with those types.  The OPERATION is to
587   describe the operation between the pointer types,
588   in case an error occurs.
589
590   This routine also implements the computation of a common type for
591   pointers-to-members as per [expr.eq].  */
592
593tree
594composite_pointer_type (const op_location_t &location,
595			tree t1, tree t2, tree arg1, tree arg2,
596			composite_pointer_operation operation,
597			tsubst_flags_t complain)
598{
599  tree class1;
600  tree class2;
601
602  /* [expr.type]
603
604     If one operand is a null pointer constant, the composite pointer
605     type is the type of the other operand.  */
606  if (null_ptr_cst_p (arg1))
607    return t2;
608  if (null_ptr_cst_p (arg2))
609    return t1;
610
611  /* We have:
612
613       [expr.type]
614
615       If one of the operands has type "pointer to cv1 void", then
616       the other has type "pointer to cv2 T", and the composite pointer
617       type is "pointer to cv12 void", where cv12 is the union of cv1
618       and cv2.
619
620    If either type is a pointer to void, make sure it is T1.  */
621  if (TYPE_PTR_P (t2) && VOID_TYPE_P (TREE_TYPE (t2)))
622    std::swap (t1, t2);
623
624  /* Now, if T1 is a pointer to void, merge the qualifiers.  */
625  if (TYPE_PTR_P (t1) && VOID_TYPE_P (TREE_TYPE (t1)))
626    {
627      tree attributes;
628      tree result_type;
629
630      if (TYPE_PTRFN_P (t2))
631	{
632	  if (complain & tf_error)
633	    {
634	      switch (operation)
635		{
636		case CPO_COMPARISON:
637		  pedwarn (location, OPT_Wpedantic,
638			   "ISO C++ forbids comparison between pointer "
639			   "of type %<void *%> and pointer-to-function");
640		  break;
641		case CPO_CONVERSION:
642		  pedwarn (location, OPT_Wpedantic,
643			   "ISO C++ forbids conversion between pointer "
644			   "of type %<void *%> and pointer-to-function");
645		  break;
646		case CPO_CONDITIONAL_EXPR:
647		  pedwarn (location, OPT_Wpedantic,
648			   "ISO C++ forbids conditional expression between "
649			   "pointer of type %<void *%> and "
650			   "pointer-to-function");
651		  break;
652		default:
653		  gcc_unreachable ();
654		}
655	    }
656	  else
657	    return error_mark_node;
658        }
659      result_type
660	= cp_build_qualified_type (void_type_node,
661				   (cp_type_quals (TREE_TYPE (t1))
662				    | cp_type_quals (TREE_TYPE (t2))));
663      result_type = build_pointer_type (result_type);
664      /* Merge the attributes.  */
665      attributes = (*targetm.merge_type_attributes) (t1, t2);
666      return build_type_attribute_variant (result_type, attributes);
667    }
668
669  if (c_dialect_objc () && TYPE_PTR_P (t1)
670      && TYPE_PTR_P (t2))
671    {
672      if (objc_have_common_type (t1, t2, -3, NULL_TREE))
673	return objc_common_type (t1, t2);
674    }
675
676  /* if T1 or T2 is "pointer to noexcept function" and the other type is
677     "pointer to function", where the function types are otherwise the same,
678     "pointer to function" */
679  if (fnptr_conv_p (t1, t2))
680    return t1;
681  if (fnptr_conv_p (t2, t1))
682    return t2;
683
684  /* [expr.eq] permits the application of a pointer conversion to
685     bring the pointers to a common type.  */
686  if (TYPE_PTR_P (t1) && TYPE_PTR_P (t2)
687      && CLASS_TYPE_P (TREE_TYPE (t1))
688      && CLASS_TYPE_P (TREE_TYPE (t2))
689      && !same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (t1),
690						     TREE_TYPE (t2)))
691    {
692      class1 = TREE_TYPE (t1);
693      class2 = TREE_TYPE (t2);
694
695      if (DERIVED_FROM_P (class1, class2))
696	t2 = (build_pointer_type
697	      (cp_build_qualified_type (class1, cp_type_quals (class2))));
698      else if (DERIVED_FROM_P (class2, class1))
699	t1 = (build_pointer_type
700	      (cp_build_qualified_type (class2, cp_type_quals (class1))));
701      else
702        {
703          if (complain & tf_error)
704	    composite_pointer_error (location, DK_ERROR, t1, t2, operation);
705          return error_mark_node;
706        }
707    }
708  /* [expr.eq] permits the application of a pointer-to-member
709     conversion to change the class type of one of the types.  */
710  else if (TYPE_PTRMEM_P (t1)
711           && !same_type_p (TYPE_PTRMEM_CLASS_TYPE (t1),
712			    TYPE_PTRMEM_CLASS_TYPE (t2)))
713    {
714      class1 = TYPE_PTRMEM_CLASS_TYPE (t1);
715      class2 = TYPE_PTRMEM_CLASS_TYPE (t2);
716
717      if (DERIVED_FROM_P (class1, class2))
718	t1 = build_ptrmem_type (class2, TYPE_PTRMEM_POINTED_TO_TYPE (t1));
719      else if (DERIVED_FROM_P (class2, class1))
720	t2 = build_ptrmem_type (class1, TYPE_PTRMEM_POINTED_TO_TYPE (t2));
721      else
722        {
723          if (complain & tf_error)
724            switch (operation)
725              {
726              case CPO_COMPARISON:
727                error_at (location, "comparison between distinct "
728			  "pointer-to-member types %qT and %qT lacks a cast",
729			  t1, t2);
730                break;
731              case CPO_CONVERSION:
732                error_at (location, "conversion between distinct "
733			  "pointer-to-member types %qT and %qT lacks a cast",
734			  t1, t2);
735                break;
736              case CPO_CONDITIONAL_EXPR:
737                error_at (location, "conditional expression between distinct "
738			  "pointer-to-member types %qT and %qT lacks a cast",
739			  t1, t2);
740                break;
741              default:
742                gcc_unreachable ();
743              }
744          return error_mark_node;
745        }
746    }
747
748  bool add_const = false;
749  return composite_pointer_type_r (location, t1, t2, &add_const, operation,
750				   complain);
751}
752
753/* Return the merged type of two types.
754   We assume that comptypes has already been done and returned 1;
755   if that isn't so, this may crash.
756
757   This just combines attributes and default arguments; any other
758   differences would cause the two types to compare unalike.  */
759
760tree
761merge_types (tree t1, tree t2)
762{
763  enum tree_code code1;
764  enum tree_code code2;
765  tree attributes;
766
767  /* Save time if the two types are the same.  */
768  if (t1 == t2)
769    return t1;
770  if (original_type (t1) == original_type (t2))
771    return t1;
772
773  /* If one type is nonsense, use the other.  */
774  if (t1 == error_mark_node)
775    return t2;
776  if (t2 == error_mark_node)
777    return t1;
778
779  /* Handle merging an auto redeclaration with a previous deduced
780     return type.  */
781  if (is_auto (t1))
782    return t2;
783
784  /* Merge the attributes.  */
785  attributes = (*targetm.merge_type_attributes) (t1, t2);
786
787  if (TYPE_PTRMEMFUNC_P (t1))
788    t1 = TYPE_PTRMEMFUNC_FN_TYPE (t1);
789  if (TYPE_PTRMEMFUNC_P (t2))
790    t2 = TYPE_PTRMEMFUNC_FN_TYPE (t2);
791
792  code1 = TREE_CODE (t1);
793  code2 = TREE_CODE (t2);
794  if (code1 != code2)
795    {
796      gcc_assert (code1 == TYPENAME_TYPE || code2 == TYPENAME_TYPE);
797      if (code1 == TYPENAME_TYPE)
798	{
799          t1 = resolve_typename_type (t1, /*only_current_p=*/true);
800	  code1 = TREE_CODE (t1);
801	}
802      else
803	{
804          t2 = resolve_typename_type (t2, /*only_current_p=*/true);
805	  code2 = TREE_CODE (t2);
806	}
807    }
808
809  switch (code1)
810    {
811    case POINTER_TYPE:
812    case REFERENCE_TYPE:
813      /* For two pointers, do this recursively on the target type.  */
814      {
815	tree target = merge_types (TREE_TYPE (t1), TREE_TYPE (t2));
816	int quals = cp_type_quals (t1);
817
818	if (code1 == POINTER_TYPE)
819	  {
820	    t1 = build_pointer_type (target);
821	    if (TREE_CODE (target) == METHOD_TYPE)
822	      t1 = build_ptrmemfunc_type (t1);
823	  }
824	else
825	  t1 = cp_build_reference_type (target, TYPE_REF_IS_RVALUE (t1));
826	t1 = build_type_attribute_variant (t1, attributes);
827	t1 = cp_build_qualified_type (t1, quals);
828
829	return t1;
830      }
831
832    case OFFSET_TYPE:
833      {
834	int quals;
835	tree pointee;
836	quals = cp_type_quals (t1);
837	pointee = merge_types (TYPE_PTRMEM_POINTED_TO_TYPE (t1),
838			       TYPE_PTRMEM_POINTED_TO_TYPE (t2));
839	t1 = build_ptrmem_type (TYPE_PTRMEM_CLASS_TYPE (t1),
840				pointee);
841	t1 = cp_build_qualified_type (t1, quals);
842	break;
843      }
844
845    case ARRAY_TYPE:
846      {
847	tree elt = merge_types (TREE_TYPE (t1), TREE_TYPE (t2));
848	/* Save space: see if the result is identical to one of the args.  */
849	if (elt == TREE_TYPE (t1) && TYPE_DOMAIN (t1))
850	  return build_type_attribute_variant (t1, attributes);
851	if (elt == TREE_TYPE (t2) && TYPE_DOMAIN (t2))
852	  return build_type_attribute_variant (t2, attributes);
853	/* Merge the element types, and have a size if either arg has one.  */
854	t1 = build_cplus_array_type
855	  (elt, TYPE_DOMAIN (TYPE_DOMAIN (t1) ? t1 : t2));
856	break;
857      }
858
859    case FUNCTION_TYPE:
860      /* Function types: prefer the one that specified arg types.
861	 If both do, merge the arg types.  Also merge the return types.  */
862      {
863	tree valtype = merge_types (TREE_TYPE (t1), TREE_TYPE (t2));
864	tree p1 = TYPE_ARG_TYPES (t1);
865	tree p2 = TYPE_ARG_TYPES (t2);
866	tree parms;
867
868	/* Save space: see if the result is identical to one of the args.  */
869	if (valtype == TREE_TYPE (t1) && ! p2)
870	  return cp_build_type_attribute_variant (t1, attributes);
871	if (valtype == TREE_TYPE (t2) && ! p1)
872	  return cp_build_type_attribute_variant (t2, attributes);
873
874	/* Simple way if one arg fails to specify argument types.  */
875	if (p1 == NULL_TREE || TREE_VALUE (p1) == void_type_node)
876	  parms = p2;
877	else if (p2 == NULL_TREE || TREE_VALUE (p2) == void_type_node)
878	  parms = p1;
879	else
880	  parms = commonparms (p1, p2);
881
882	cp_cv_quals quals = type_memfn_quals (t1);
883	cp_ref_qualifier rqual = type_memfn_rqual (t1);
884	gcc_assert (quals == type_memfn_quals (t2));
885	gcc_assert (rqual == type_memfn_rqual (t2));
886
887	tree rval = build_function_type (valtype, parms);
888	rval = apply_memfn_quals (rval, quals);
889	tree raises = merge_exception_specifiers (TYPE_RAISES_EXCEPTIONS (t1),
890						  TYPE_RAISES_EXCEPTIONS (t2));
891	bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t1);
892	t1 = build_cp_fntype_variant (rval, rqual, raises, late_return_type_p);
893	break;
894      }
895
896    case METHOD_TYPE:
897      {
898	/* Get this value the long way, since TYPE_METHOD_BASETYPE
899	   is just the main variant of this.  */
900	tree basetype = class_of_this_parm (t2);
901	tree raises = merge_exception_specifiers (TYPE_RAISES_EXCEPTIONS (t1),
902						  TYPE_RAISES_EXCEPTIONS (t2));
903	cp_ref_qualifier rqual = type_memfn_rqual (t1);
904	tree t3;
905	bool late_return_type_1_p = TYPE_HAS_LATE_RETURN_TYPE (t1);
906
907	/* If this was a member function type, get back to the
908	   original type of type member function (i.e., without
909	   the class instance variable up front.  */
910	t1 = build_function_type (TREE_TYPE (t1),
911				  TREE_CHAIN (TYPE_ARG_TYPES (t1)));
912	t2 = build_function_type (TREE_TYPE (t2),
913				  TREE_CHAIN (TYPE_ARG_TYPES (t2)));
914	t3 = merge_types (t1, t2);
915	t3 = build_method_type_directly (basetype, TREE_TYPE (t3),
916					 TYPE_ARG_TYPES (t3));
917	t1 = build_cp_fntype_variant (t3, rqual, raises, late_return_type_1_p);
918	break;
919      }
920
921    case TYPENAME_TYPE:
922      /* There is no need to merge attributes into a TYPENAME_TYPE.
923	 When the type is instantiated it will have whatever
924	 attributes result from the instantiation.  */
925      return t1;
926
927    default:;
928      if (attribute_list_equal (TYPE_ATTRIBUTES (t1), attributes))
929	return t1;
930      else if (attribute_list_equal (TYPE_ATTRIBUTES (t2), attributes))
931	return t2;
932      break;
933    }
934
935  return cp_build_type_attribute_variant (t1, attributes);
936}
937
938/* Return the ARRAY_TYPE type without its domain.  */
939
940tree
941strip_array_domain (tree type)
942{
943  tree t2;
944  gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
945  if (TYPE_DOMAIN (type) == NULL_TREE)
946    return type;
947  t2 = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
948  return cp_build_type_attribute_variant (t2, TYPE_ATTRIBUTES (type));
949}
950
951/* Wrapper around cp_common_type that is used by c-common.cc and other
952   front end optimizations that remove promotions.
953
954   Return the common type for two arithmetic types T1 and T2 under the
955   usual arithmetic conversions.  The default conversions have already
956   been applied, and enumerated types converted to their compatible
957   integer types.  */
958
959tree
960common_type (tree t1, tree t2)
961{
962  /* If one type is nonsense, use the other  */
963  if (t1 == error_mark_node)
964    return t2;
965  if (t2 == error_mark_node)
966    return t1;
967
968  return cp_common_type (t1, t2);
969}
970
971/* Return the common type of two pointer types T1 and T2.  This is the
972   type for the result of most arithmetic operations if the operands
973   have the given two types.
974
975   We assume that comp_target_types has already been done and returned
976   nonzero; if that isn't so, this may crash.  */
977
978tree
979common_pointer_type (tree t1, tree t2)
980{
981  gcc_assert ((TYPE_PTR_P (t1) && TYPE_PTR_P (t2))
982              || (TYPE_PTRDATAMEM_P (t1) && TYPE_PTRDATAMEM_P (t2))
983              || (TYPE_PTRMEMFUNC_P (t1) && TYPE_PTRMEMFUNC_P (t2)));
984
985  return composite_pointer_type (input_location, t1, t2,
986				 error_mark_node, error_mark_node,
987                                 CPO_CONVERSION, tf_warning_or_error);
988}
989
990/* Compare two exception specifier types for exactness or subsetness, if
991   allowed. Returns false for mismatch, true for match (same, or
992   derived and !exact).
993
994   [except.spec] "If a class X ... objects of class X or any class publicly
995   and unambiguously derived from X. Similarly, if a pointer type Y * ...
996   exceptions of type Y * or that are pointers to any type publicly and
997   unambiguously derived from Y. Otherwise a function only allows exceptions
998   that have the same type ..."
999   This does not mention cv qualifiers and is different to what throw
1000   [except.throw] and catch [except.catch] will do. They will ignore the
1001   top level cv qualifiers, and allow qualifiers in the pointer to class
1002   example.
1003
1004   We implement the letter of the standard.  */
1005
1006static bool
1007comp_except_types (tree a, tree b, bool exact)
1008{
1009  if (same_type_p (a, b))
1010    return true;
1011  else if (!exact)
1012    {
1013      if (cp_type_quals (a) || cp_type_quals (b))
1014	return false;
1015
1016      if (TYPE_PTR_P (a) && TYPE_PTR_P (b))
1017	{
1018	  a = TREE_TYPE (a);
1019	  b = TREE_TYPE (b);
1020	  if (cp_type_quals (a) || cp_type_quals (b))
1021	    return false;
1022	}
1023
1024      if (TREE_CODE (a) != RECORD_TYPE
1025	  || TREE_CODE (b) != RECORD_TYPE)
1026	return false;
1027
1028      if (publicly_uniquely_derived_p (a, b))
1029	return true;
1030    }
1031  return false;
1032}
1033
1034/* Return true if TYPE1 and TYPE2 are equivalent exception specifiers.
1035   If EXACT is ce_derived, T2 can be stricter than T1 (according to 15.4/5).
1036   If EXACT is ce_type, the C++17 type compatibility rules apply.
1037   If EXACT is ce_normal, the compatibility rules in 15.4/3 apply.
1038   If EXACT is ce_exact, the specs must be exactly the same. Exception lists
1039   are unordered, but we've already filtered out duplicates. Most lists will
1040   be in order, we should try to make use of that.  */
1041
1042bool
1043comp_except_specs (const_tree t1, const_tree t2, int exact)
1044{
1045  const_tree probe;
1046  const_tree base;
1047  int  length = 0;
1048
1049  if (t1 == t2)
1050    return true;
1051
1052  /* First handle noexcept.  */
1053  if (exact < ce_exact)
1054    {
1055      if (exact == ce_type
1056	  && (canonical_eh_spec (CONST_CAST_TREE (t1))
1057	      == canonical_eh_spec (CONST_CAST_TREE (t2))))
1058	return true;
1059
1060      /* noexcept(false) is compatible with no exception-specification,
1061	 and less strict than any spec.  */
1062      if (t1 == noexcept_false_spec)
1063	return t2 == NULL_TREE || exact == ce_derived;
1064      /* Even a derived noexcept(false) is compatible with no
1065	 exception-specification.  */
1066      if (t2 == noexcept_false_spec)
1067	return t1 == NULL_TREE;
1068
1069      /* Otherwise, if we aren't looking for an exact match, noexcept is
1070	 equivalent to throw().  */
1071      if (t1 == noexcept_true_spec)
1072	t1 = empty_except_spec;
1073      if (t2 == noexcept_true_spec)
1074	t2 = empty_except_spec;
1075    }
1076
1077  /* If any noexcept is left, it is only comparable to itself;
1078     either we're looking for an exact match or we're redeclaring a
1079     template with dependent noexcept.  */
1080  if ((t1 && TREE_PURPOSE (t1))
1081      || (t2 && TREE_PURPOSE (t2)))
1082    return (t1 && t2
1083	    && cp_tree_equal (TREE_PURPOSE (t1), TREE_PURPOSE (t2)));
1084
1085  if (t1 == NULL_TREE)			   /* T1 is ...  */
1086    return t2 == NULL_TREE || exact == ce_derived;
1087  if (!TREE_VALUE (t1))			   /* t1 is EMPTY */
1088    return t2 != NULL_TREE && !TREE_VALUE (t2);
1089  if (t2 == NULL_TREE)			   /* T2 is ...  */
1090    return false;
1091  if (TREE_VALUE (t1) && !TREE_VALUE (t2)) /* T2 is EMPTY, T1 is not */
1092    return exact == ce_derived;
1093
1094  /* Neither set is ... or EMPTY, make sure each part of T2 is in T1.
1095     Count how many we find, to determine exactness. For exact matching and
1096     ordered T1, T2, this is an O(n) operation, otherwise its worst case is
1097     O(nm).  */
1098  for (base = t1; t2 != NULL_TREE; t2 = TREE_CHAIN (t2))
1099    {
1100      for (probe = base; probe != NULL_TREE; probe = TREE_CHAIN (probe))
1101	{
1102	  tree a = TREE_VALUE (probe);
1103	  tree b = TREE_VALUE (t2);
1104
1105	  if (comp_except_types (a, b, exact))
1106	    {
1107	      if (probe == base && exact > ce_derived)
1108		base = TREE_CHAIN (probe);
1109	      length++;
1110	      break;
1111	    }
1112	}
1113      if (probe == NULL_TREE)
1114	return false;
1115    }
1116  return exact == ce_derived || base == NULL_TREE || length == list_length (t1);
1117}
1118
1119/* Compare the array types T1 and T2.  CB says how we should behave when
1120   comparing array bounds: bounds_none doesn't allow dimensionless arrays,
1121   bounds_either says than any array can be [], bounds_first means that
1122   onlt T1 can be an array with unknown bounds.  STRICT is true if
1123   qualifiers must match when comparing the types of the array elements.  */
1124
1125static bool
1126comp_array_types (const_tree t1, const_tree t2, compare_bounds_t cb,
1127		  bool strict)
1128{
1129  tree d1;
1130  tree d2;
1131  tree max1, max2;
1132
1133  if (t1 == t2)
1134    return true;
1135
1136  /* The type of the array elements must be the same.  */
1137  if (strict
1138      ? !same_type_p (TREE_TYPE (t1), TREE_TYPE (t2))
1139      : !similar_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1140    return false;
1141
1142  d1 = TYPE_DOMAIN (t1);
1143  d2 = TYPE_DOMAIN (t2);
1144
1145  if (d1 == d2)
1146    return true;
1147
1148  /* If one of the arrays is dimensionless, and the other has a
1149     dimension, they are of different types.  However, it is valid to
1150     write:
1151
1152       extern int a[];
1153       int a[3];
1154
1155     by [basic.link]:
1156
1157       declarations for an array object can specify
1158       array types that differ by the presence or absence of a major
1159       array bound (_dcl.array_).  */
1160  if (!d1 && d2)
1161    return cb >= bounds_either;
1162  else if (d1 && !d2)
1163    return cb == bounds_either;
1164
1165  /* Check that the dimensions are the same.  */
1166
1167  if (!cp_tree_equal (TYPE_MIN_VALUE (d1), TYPE_MIN_VALUE (d2)))
1168    return false;
1169  max1 = TYPE_MAX_VALUE (d1);
1170  max2 = TYPE_MAX_VALUE (d2);
1171
1172  if (!cp_tree_equal (max1, max2))
1173    return false;
1174
1175  return true;
1176}
1177
1178/* Compare the relative position of T1 and T2 into their respective
1179   template parameter list.
1180   T1 and T2 must be template parameter types.
1181   Return TRUE if T1 and T2 have the same position, FALSE otherwise.  */
1182
1183static bool
1184comp_template_parms_position (tree t1, tree t2)
1185{
1186  tree index1, index2;
1187  gcc_assert (t1 && t2
1188	      && TREE_CODE (t1) == TREE_CODE (t2)
1189	      && (TREE_CODE (t1) == BOUND_TEMPLATE_TEMPLATE_PARM
1190		  || TREE_CODE (t1) == TEMPLATE_TEMPLATE_PARM
1191		  || TREE_CODE (t1) == TEMPLATE_TYPE_PARM));
1192
1193  index1 = TEMPLATE_TYPE_PARM_INDEX (TYPE_MAIN_VARIANT (t1));
1194  index2 = TEMPLATE_TYPE_PARM_INDEX (TYPE_MAIN_VARIANT (t2));
1195
1196  /* Then compare their relative position.  */
1197  if (TEMPLATE_PARM_IDX (index1) != TEMPLATE_PARM_IDX (index2)
1198      || TEMPLATE_PARM_LEVEL (index1) != TEMPLATE_PARM_LEVEL (index2)
1199      || (TEMPLATE_PARM_PARAMETER_PACK (index1)
1200	  != TEMPLATE_PARM_PARAMETER_PACK (index2)))
1201    return false;
1202
1203  /* In C++14 we can end up comparing 'auto' to a normal template
1204     parameter.  Don't confuse them.  */
1205  if (cxx_dialect >= cxx14 && (is_auto (t1) || is_auto (t2)))
1206    return TYPE_IDENTIFIER (t1) == TYPE_IDENTIFIER (t2);
1207
1208  return true;
1209}
1210
1211/* Heuristic check if two parameter types can be considered ABI-equivalent.  */
1212
1213static bool
1214cxx_safe_arg_type_equiv_p (tree t1, tree t2)
1215{
1216  t1 = TYPE_MAIN_VARIANT (t1);
1217  t2 = TYPE_MAIN_VARIANT (t2);
1218
1219  if (TYPE_PTR_P (t1)
1220      && TYPE_PTR_P (t2))
1221    return true;
1222
1223  /* The signedness of the parameter matters only when an integral
1224     type smaller than int is promoted to int, otherwise only the
1225     precision of the parameter matters.
1226     This check should make sure that the callee does not see
1227     undefined values in argument registers.  */
1228  if (INTEGRAL_TYPE_P (t1)
1229      && INTEGRAL_TYPE_P (t2)
1230      && TYPE_PRECISION (t1) == TYPE_PRECISION (t2)
1231      && (TYPE_UNSIGNED (t1) == TYPE_UNSIGNED (t2)
1232	  || !targetm.calls.promote_prototypes (NULL_TREE)
1233	  || TYPE_PRECISION (t1) >= TYPE_PRECISION (integer_type_node)))
1234    return true;
1235
1236  return same_type_p (t1, t2);
1237}
1238
1239/* Check if a type cast between two function types can be considered safe.  */
1240
1241static bool
1242cxx_safe_function_type_cast_p (tree t1, tree t2)
1243{
1244  if (TREE_TYPE (t1) == void_type_node &&
1245      TYPE_ARG_TYPES (t1) == void_list_node)
1246    return true;
1247
1248  if (TREE_TYPE (t2) == void_type_node &&
1249      TYPE_ARG_TYPES (t2) == void_list_node)
1250    return true;
1251
1252  if (!cxx_safe_arg_type_equiv_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1253    return false;
1254
1255  for (t1 = TYPE_ARG_TYPES (t1), t2 = TYPE_ARG_TYPES (t2);
1256       t1 && t2;
1257       t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1258    if (!cxx_safe_arg_type_equiv_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1259      return false;
1260
1261  return true;
1262}
1263
1264/* Subroutine in comptypes.  */
1265
1266static bool
1267structural_comptypes (tree t1, tree t2, int strict)
1268{
1269  /* Both should be types that are not obviously the same.  */
1270  gcc_checking_assert (t1 != t2 && TYPE_P (t1) && TYPE_P (t2));
1271
1272  /* Suppress typename resolution under spec_hasher::equal in place of calling
1273     push_to_top_level there.  */
1274  if (!comparing_specializations)
1275    {
1276      /* TYPENAME_TYPEs should be resolved if the qualifying scope is the
1277	 current instantiation.  */
1278      if (TREE_CODE (t1) == TYPENAME_TYPE)
1279	t1 = resolve_typename_type (t1, /*only_current_p=*/true);
1280
1281      if (TREE_CODE (t2) == TYPENAME_TYPE)
1282	t2 = resolve_typename_type (t2, /*only_current_p=*/true);
1283    }
1284
1285  if (TYPE_PTRMEMFUNC_P (t1))
1286    t1 = TYPE_PTRMEMFUNC_FN_TYPE (t1);
1287  if (TYPE_PTRMEMFUNC_P (t2))
1288    t2 = TYPE_PTRMEMFUNC_FN_TYPE (t2);
1289
1290  /* Different classes of types can't be compatible.  */
1291  if (TREE_CODE (t1) != TREE_CODE (t2))
1292    return false;
1293
1294  /* Qualifiers must match.  For array types, we will check when we
1295     recur on the array element types.  */
1296  if (TREE_CODE (t1) != ARRAY_TYPE
1297      && cp_type_quals (t1) != cp_type_quals (t2))
1298    return false;
1299  if (TREE_CODE (t1) == FUNCTION_TYPE
1300      && type_memfn_quals (t1) != type_memfn_quals (t2))
1301    return false;
1302  /* Need to check this before TYPE_MAIN_VARIANT.
1303     FIXME function qualifiers should really change the main variant.  */
1304  if (FUNC_OR_METHOD_TYPE_P (t1))
1305    {
1306      if (type_memfn_rqual (t1) != type_memfn_rqual (t2))
1307	return false;
1308      if (flag_noexcept_type
1309	  && !comp_except_specs (TYPE_RAISES_EXCEPTIONS (t1),
1310				 TYPE_RAISES_EXCEPTIONS (t2),
1311				 ce_type))
1312	return false;
1313    }
1314
1315  /* Allow for two different type nodes which have essentially the same
1316     definition.  Note that we already checked for equality of the type
1317     qualifiers (just above).  */
1318  if (TREE_CODE (t1) != ARRAY_TYPE
1319      && TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
1320    goto check_alias;
1321
1322  /* Compare the types.  Return false on known not-same. Break on not
1323     known.   Never return true from this switch -- you'll break
1324     specialization comparison.    */
1325  switch (TREE_CODE (t1))
1326    {
1327    case VOID_TYPE:
1328    case BOOLEAN_TYPE:
1329      /* All void and bool types are the same.  */
1330      break;
1331
1332    case OPAQUE_TYPE:
1333    case INTEGER_TYPE:
1334    case FIXED_POINT_TYPE:
1335    case REAL_TYPE:
1336      /* With these nodes, we can't determine type equivalence by
1337	 looking at what is stored in the nodes themselves, because
1338	 two nodes might have different TYPE_MAIN_VARIANTs but still
1339	 represent the same type.  For example, wchar_t and int could
1340	 have the same properties (TYPE_PRECISION, TYPE_MIN_VALUE,
1341	 TYPE_MAX_VALUE, etc.), but have different TYPE_MAIN_VARIANTs
1342	 and are distinct types. On the other hand, int and the
1343	 following typedef
1344
1345           typedef int INT __attribute((may_alias));
1346
1347	 have identical properties, different TYPE_MAIN_VARIANTs, but
1348	 represent the same type.  The canonical type system keeps
1349	 track of equivalence in this case, so we fall back on it.  */
1350      if (TYPE_CANONICAL (t1) != TYPE_CANONICAL (t2))
1351	return false;
1352
1353      /* We don't need or want the attribute comparison.  */
1354      goto check_alias;
1355
1356    case TEMPLATE_TEMPLATE_PARM:
1357    case BOUND_TEMPLATE_TEMPLATE_PARM:
1358      if (!comp_template_parms_position (t1, t2))
1359	return false;
1360      if (!comp_template_parms
1361	  (DECL_TEMPLATE_PARMS (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t1)),
1362	   DECL_TEMPLATE_PARMS (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t2))))
1363	return false;
1364      if (TREE_CODE (t1) == TEMPLATE_TEMPLATE_PARM)
1365	break;
1366      /* Don't check inheritance.  */
1367      strict = COMPARE_STRICT;
1368      /* Fall through.  */
1369
1370    case RECORD_TYPE:
1371    case UNION_TYPE:
1372      if (TYPE_TEMPLATE_INFO (t1) && TYPE_TEMPLATE_INFO (t2)
1373	  && (TYPE_TI_TEMPLATE (t1) == TYPE_TI_TEMPLATE (t2)
1374	      || TREE_CODE (t1) == BOUND_TEMPLATE_TEMPLATE_PARM)
1375	  && comp_template_args (TYPE_TI_ARGS (t1), TYPE_TI_ARGS (t2)))
1376	break;
1377
1378      if ((strict & COMPARE_BASE) && DERIVED_FROM_P (t1, t2))
1379	break;
1380      else if ((strict & COMPARE_DERIVED) && DERIVED_FROM_P (t2, t1))
1381	break;
1382
1383      return false;
1384
1385    case OFFSET_TYPE:
1386      if (!comptypes (TYPE_OFFSET_BASETYPE (t1), TYPE_OFFSET_BASETYPE (t2),
1387		      strict & ~COMPARE_REDECLARATION))
1388	return false;
1389      if (!same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1390	return false;
1391      break;
1392
1393    case REFERENCE_TYPE:
1394      if (TYPE_REF_IS_RVALUE (t1) != TYPE_REF_IS_RVALUE (t2))
1395	return false;
1396      /* fall through to checks for pointer types */
1397      gcc_fallthrough ();
1398
1399    case POINTER_TYPE:
1400      if (TYPE_MODE (t1) != TYPE_MODE (t2)
1401	  || !same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1402	return false;
1403      break;
1404
1405    case METHOD_TYPE:
1406    case FUNCTION_TYPE:
1407      /* Exception specs and memfn_rquals were checked above.  */
1408      if (!same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1409	return false;
1410      if (!compparms (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2)))
1411	return false;
1412      break;
1413
1414    case ARRAY_TYPE:
1415      /* Target types must match incl. qualifiers.  */
1416      if (!comp_array_types (t1, t2, ((strict & COMPARE_REDECLARATION)
1417				      ? bounds_either : bounds_none),
1418			     /*strict=*/true))
1419	return false;
1420      break;
1421
1422    case TEMPLATE_TYPE_PARM:
1423      /* If T1 and T2 don't have the same relative position in their
1424	 template parameters set, they can't be equal.  */
1425      if (!comp_template_parms_position (t1, t2))
1426	return false;
1427      /* If T1 and T2 don't represent the same class template deduction,
1428         they aren't equal.  */
1429      if (CLASS_PLACEHOLDER_TEMPLATE (t1)
1430	  != CLASS_PLACEHOLDER_TEMPLATE (t2))
1431	return false;
1432      /* Constrained 'auto's are distinct from parms that don't have the same
1433	 constraints.  */
1434      if (!equivalent_placeholder_constraints (t1, t2))
1435	return false;
1436      break;
1437
1438    case TYPENAME_TYPE:
1439      if (!cp_tree_equal (TYPENAME_TYPE_FULLNAME (t1),
1440			  TYPENAME_TYPE_FULLNAME (t2)))
1441	return false;
1442      /* Qualifiers don't matter on scopes.  */
1443      if (!same_type_ignoring_top_level_qualifiers_p (TYPE_CONTEXT (t1),
1444						      TYPE_CONTEXT (t2)))
1445	return false;
1446      break;
1447
1448    case UNBOUND_CLASS_TEMPLATE:
1449      if (!cp_tree_equal (TYPE_IDENTIFIER (t1), TYPE_IDENTIFIER (t2)))
1450	return false;
1451      if (!same_type_p (TYPE_CONTEXT (t1), TYPE_CONTEXT (t2)))
1452	return false;
1453      break;
1454
1455    case COMPLEX_TYPE:
1456      if (!same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1457	return false;
1458      break;
1459
1460    case VECTOR_TYPE:
1461      if (gnu_vector_type_p (t1) != gnu_vector_type_p (t2)
1462	  || maybe_ne (TYPE_VECTOR_SUBPARTS (t1), TYPE_VECTOR_SUBPARTS (t2))
1463	  || !same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1464	return false;
1465      break;
1466
1467    case TYPE_PACK_EXPANSION:
1468      return (same_type_p (PACK_EXPANSION_PATTERN (t1),
1469			   PACK_EXPANSION_PATTERN (t2))
1470	      && comp_template_args (PACK_EXPANSION_EXTRA_ARGS (t1),
1471				     PACK_EXPANSION_EXTRA_ARGS (t2)));
1472
1473    case DECLTYPE_TYPE:
1474      if (DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t1)
1475          != DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t2))
1476	return false;
1477      if (DECLTYPE_FOR_LAMBDA_CAPTURE (t1) != DECLTYPE_FOR_LAMBDA_CAPTURE (t2))
1478	return false;
1479      if (DECLTYPE_FOR_LAMBDA_PROXY (t1) != DECLTYPE_FOR_LAMBDA_PROXY (t2))
1480	return false;
1481      if (!cp_tree_equal (DECLTYPE_TYPE_EXPR (t1), DECLTYPE_TYPE_EXPR (t2)))
1482        return false;
1483      break;
1484
1485    case UNDERLYING_TYPE:
1486      if (!same_type_p (UNDERLYING_TYPE_TYPE (t1), UNDERLYING_TYPE_TYPE (t2)))
1487	return false;
1488      break;
1489
1490    case TYPEOF_TYPE:
1491      if (!cp_tree_equal (TYPEOF_TYPE_EXPR (t1), TYPEOF_TYPE_EXPR (t2)))
1492	return false;
1493      break;
1494
1495    default:
1496      return false;
1497    }
1498
1499  /* If we get here, we know that from a target independent POV the
1500     types are the same.  Make sure the target attributes are also
1501     the same.  */
1502  if (!comp_type_attributes (t1, t2))
1503    return false;
1504
1505 check_alias:
1506  if (comparing_dependent_aliases)
1507    {
1508      /* Don't treat an alias template specialization with dependent
1509	 arguments as equivalent to its underlying type when used as a
1510	 template argument; we need them to be distinct so that we
1511	 substitute into the specialization arguments at instantiation
1512	 time.  And aliases can't be equivalent without being ==, so
1513	 we don't need to look any deeper.  */
1514      tree dep1 = dependent_alias_template_spec_p (t1, nt_transparent);
1515      tree dep2 = dependent_alias_template_spec_p (t2, nt_transparent);
1516      if ((dep1 || dep2) && dep1 != dep2)
1517	return false;
1518    }
1519
1520  return true;
1521}
1522
1523/* Return true if T1 and T2 are related as allowed by STRICT.  STRICT
1524   is a bitwise-or of the COMPARE_* flags.  */
1525
1526bool
1527comptypes (tree t1, tree t2, int strict)
1528{
1529  gcc_checking_assert (t1 && t2);
1530
1531  /* TYPE_ARGUMENT_PACKS are not really types.  */
1532  gcc_checking_assert (TREE_CODE (t1) != TYPE_ARGUMENT_PACK
1533		       && TREE_CODE (t2) != TYPE_ARGUMENT_PACK);
1534
1535  if (t1 == t2)
1536    return true;
1537
1538  /* Suppress errors caused by previously reported errors.  */
1539  if (t1 == error_mark_node || t2 == error_mark_node)
1540    return false;
1541
1542  if (strict == COMPARE_STRICT)
1543    {
1544      if (TYPE_STRUCTURAL_EQUALITY_P (t1) || TYPE_STRUCTURAL_EQUALITY_P (t2))
1545	/* At least one of the types requires structural equality, so
1546	   perform a deep check. */
1547	return structural_comptypes (t1, t2, strict);
1548
1549      if (flag_checking && param_use_canonical_types)
1550	{
1551	  bool result = structural_comptypes (t1, t2, strict);
1552
1553	  if (result && TYPE_CANONICAL (t1) != TYPE_CANONICAL (t2))
1554	    /* The two types are structurally equivalent, but their
1555	       canonical types were different. This is a failure of the
1556	       canonical type propagation code.*/
1557	    internal_error
1558	      ("canonical types differ for identical types %qT and %qT",
1559	       t1, t2);
1560	  else if (!result && TYPE_CANONICAL (t1) == TYPE_CANONICAL (t2))
1561	    /* Two types are structurally different, but the canonical
1562	       types are the same. This means we were over-eager in
1563	       assigning canonical types. */
1564	    internal_error
1565	      ("same canonical type node for different types %qT and %qT",
1566	       t1, t2);
1567
1568	  return result;
1569	}
1570      if (!flag_checking && param_use_canonical_types)
1571	return TYPE_CANONICAL (t1) == TYPE_CANONICAL (t2);
1572      else
1573	return structural_comptypes (t1, t2, strict);
1574    }
1575  else if (strict == COMPARE_STRUCTURAL)
1576    return structural_comptypes (t1, t2, COMPARE_STRICT);
1577  else
1578    return structural_comptypes (t1, t2, strict);
1579}
1580
1581/* Returns nonzero iff TYPE1 and TYPE2 are the same type, ignoring
1582   top-level qualifiers.  */
1583
1584bool
1585same_type_ignoring_top_level_qualifiers_p (tree type1, tree type2)
1586{
1587  if (type1 == error_mark_node || type2 == error_mark_node)
1588    return false;
1589  if (type1 == type2)
1590    return true;
1591
1592  type1 = cp_build_qualified_type (type1, TYPE_UNQUALIFIED);
1593  type2 = cp_build_qualified_type (type2, TYPE_UNQUALIFIED);
1594  return same_type_p (type1, type2);
1595}
1596
1597/* Returns nonzero iff TYPE1 and TYPE2 are similar, as per [conv.qual].  */
1598
1599bool
1600similar_type_p (tree type1, tree type2)
1601{
1602  if (type1 == error_mark_node || type2 == error_mark_node)
1603    return false;
1604
1605  /* Informally, two types are similar if, ignoring top-level cv-qualification:
1606     * they are the same type; or
1607     * they are both pointers, and the pointed-to types are similar; or
1608     * they are both pointers to member of the same class, and the types of
1609       the pointed-to members are similar; or
1610     * they are both arrays of the same size or both arrays of unknown bound,
1611       and the array element types are similar.  */
1612
1613  if (same_type_ignoring_top_level_qualifiers_p (type1, type2))
1614    return true;
1615
1616  if ((TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
1617      || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
1618      || (TREE_CODE (type1) == ARRAY_TYPE && TREE_CODE (type2) == ARRAY_TYPE))
1619    return comp_ptr_ttypes_const (type1, type2, bounds_either);
1620
1621  return false;
1622}
1623
1624/* Helper function for layout_compatible_type_p and
1625   is_corresponding_member_aggr.  Advance to next members (NULL if
1626   no further ones) and return true if those members are still part of
1627   the common initial sequence.  */
1628
1629bool
1630next_common_initial_sequence (tree &memb1, tree &memb2)
1631{
1632  while (memb1)
1633    {
1634      if (TREE_CODE (memb1) != FIELD_DECL
1635	  || (DECL_FIELD_IS_BASE (memb1) && is_empty_field (memb1)))
1636	{
1637	  memb1 = DECL_CHAIN (memb1);
1638	  continue;
1639	}
1640      if (DECL_FIELD_IS_BASE (memb1))
1641	{
1642	  memb1 = TYPE_FIELDS (TREE_TYPE (memb1));
1643	  continue;
1644	}
1645      break;
1646    }
1647  while (memb2)
1648    {
1649      if (TREE_CODE (memb2) != FIELD_DECL
1650	  || (DECL_FIELD_IS_BASE (memb2) && is_empty_field (memb2)))
1651	{
1652	  memb2 = DECL_CHAIN (memb2);
1653	  continue;
1654	}
1655      if (DECL_FIELD_IS_BASE (memb2))
1656	{
1657	  memb2 = TYPE_FIELDS (TREE_TYPE (memb2));
1658	  continue;
1659	}
1660      break;
1661    }
1662  if (memb1 == NULL_TREE && memb2 == NULL_TREE)
1663    return true;
1664  if (memb1 == NULL_TREE || memb2 == NULL_TREE)
1665    return false;
1666  if (DECL_BIT_FIELD_TYPE (memb1))
1667    {
1668      if (!DECL_BIT_FIELD_TYPE (memb2))
1669	return false;
1670      if (!layout_compatible_type_p (DECL_BIT_FIELD_TYPE (memb1),
1671				     DECL_BIT_FIELD_TYPE (memb2)))
1672	return false;
1673      if (TYPE_PRECISION (TREE_TYPE (memb1))
1674	  != TYPE_PRECISION (TREE_TYPE (memb2)))
1675	return false;
1676    }
1677  else if (DECL_BIT_FIELD_TYPE (memb2))
1678    return false;
1679  else if (!layout_compatible_type_p (TREE_TYPE (memb1), TREE_TYPE (memb2)))
1680    return false;
1681  if ((!lookup_attribute ("no_unique_address", DECL_ATTRIBUTES (memb1)))
1682      != !lookup_attribute ("no_unique_address", DECL_ATTRIBUTES (memb2)))
1683    return false;
1684  if (!tree_int_cst_equal (bit_position (memb1), bit_position (memb2)))
1685    return false;
1686  return true;
1687}
1688
1689/* Return true if TYPE1 and TYPE2 are layout-compatible types.  */
1690
1691bool
1692layout_compatible_type_p (tree type1, tree type2)
1693{
1694  if (type1 == error_mark_node || type2 == error_mark_node)
1695    return false;
1696  if (type1 == type2)
1697    return true;
1698  if (TREE_CODE (type1) != TREE_CODE (type2))
1699    return false;
1700
1701  type1 = cp_build_qualified_type (type1, TYPE_UNQUALIFIED);
1702  type2 = cp_build_qualified_type (type2, TYPE_UNQUALIFIED);
1703
1704  if (TREE_CODE (type1) == ENUMERAL_TYPE)
1705    return (TYPE_ALIGN (type1) == TYPE_ALIGN (type2)
1706	    && tree_int_cst_equal (TYPE_SIZE (type1), TYPE_SIZE (type2))
1707	    && same_type_p (finish_underlying_type (type1),
1708			    finish_underlying_type (type2)));
1709
1710  if (CLASS_TYPE_P (type1)
1711      && std_layout_type_p (type1)
1712      && std_layout_type_p (type2)
1713      && TYPE_ALIGN (type1) == TYPE_ALIGN (type2)
1714      && tree_int_cst_equal (TYPE_SIZE (type1), TYPE_SIZE (type2)))
1715    {
1716      tree field1 = TYPE_FIELDS (type1);
1717      tree field2 = TYPE_FIELDS (type2);
1718      if (TREE_CODE (type1) == RECORD_TYPE)
1719	{
1720	  while (1)
1721	    {
1722	      if (!next_common_initial_sequence (field1, field2))
1723		return false;
1724	      if (field1 == NULL_TREE)
1725		return true;
1726	      field1 = DECL_CHAIN (field1);
1727	      field2 = DECL_CHAIN (field2);
1728	    }
1729	}
1730      /* Otherwise both types must be union types.
1731	 The standard says:
1732	 "Two standard-layout unions are layout-compatible if they have
1733	 the same number of non-static data members and corresponding
1734	 non-static data members (in any order) have layout-compatible
1735	 types."
1736	 but the code anticipates that bitfield vs. non-bitfield,
1737	 different bitfield widths or presence/absence of
1738	 [[no_unique_address]] should be checked as well.  */
1739      auto_vec<tree, 16> vec;
1740      unsigned int count = 0;
1741      for (; field1; field1 = DECL_CHAIN (field1))
1742	if (TREE_CODE (field1) == FIELD_DECL)
1743	  count++;
1744      for (; field2; field2 = DECL_CHAIN (field2))
1745	if (TREE_CODE (field2) == FIELD_DECL)
1746	  vec.safe_push (field2);
1747      /* Discussions on core lean towards treating multiple union fields
1748	 of the same type as the same field, so this might need changing
1749	 in the future.  */
1750      if (count != vec.length ())
1751	return false;
1752      for (field1 = TYPE_FIELDS (type1); field1; field1 = DECL_CHAIN (field1))
1753	{
1754	  if (TREE_CODE (field1) != FIELD_DECL)
1755	    continue;
1756	  unsigned int j;
1757	  tree t1 = DECL_BIT_FIELD_TYPE (field1);
1758	  if (t1 == NULL_TREE)
1759	    t1 = TREE_TYPE (field1);
1760	  FOR_EACH_VEC_ELT (vec, j, field2)
1761	    {
1762	      tree t2 = DECL_BIT_FIELD_TYPE (field2);
1763	      if (t2 == NULL_TREE)
1764		t2 = TREE_TYPE (field2);
1765	      if (DECL_BIT_FIELD_TYPE (field1))
1766		{
1767		  if (!DECL_BIT_FIELD_TYPE (field2))
1768		    continue;
1769		  if (TYPE_PRECISION (TREE_TYPE (field1))
1770		      != TYPE_PRECISION (TREE_TYPE (field2)))
1771		    continue;
1772		}
1773	      else if (DECL_BIT_FIELD_TYPE (field2))
1774		continue;
1775	      if (!layout_compatible_type_p (t1, t2))
1776		continue;
1777	      if ((!lookup_attribute ("no_unique_address",
1778				      DECL_ATTRIBUTES (field1)))
1779		  != !lookup_attribute ("no_unique_address",
1780					DECL_ATTRIBUTES (field2)))
1781		continue;
1782	      break;
1783	    }
1784	  if (j == vec.length ())
1785	    return false;
1786	  vec.unordered_remove (j);
1787	}
1788      return true;
1789    }
1790
1791  return same_type_p (type1, type2);
1792}
1793
1794/* Returns 1 if TYPE1 is at least as qualified as TYPE2.  */
1795
1796bool
1797at_least_as_qualified_p (const_tree type1, const_tree type2)
1798{
1799  int q1 = cp_type_quals (type1);
1800  int q2 = cp_type_quals (type2);
1801
1802  /* All qualifiers for TYPE2 must also appear in TYPE1.  */
1803  return (q1 & q2) == q2;
1804}
1805
1806/* Returns 1 if TYPE1 is more cv-qualified than TYPE2, -1 if TYPE2 is
1807   more cv-qualified that TYPE1, and 0 otherwise.  */
1808
1809int
1810comp_cv_qualification (int q1, int q2)
1811{
1812  if (q1 == q2)
1813    return 0;
1814
1815  if ((q1 & q2) == q2)
1816    return 1;
1817  else if ((q1 & q2) == q1)
1818    return -1;
1819
1820  return 0;
1821}
1822
1823int
1824comp_cv_qualification (const_tree type1, const_tree type2)
1825{
1826  int q1 = cp_type_quals (type1);
1827  int q2 = cp_type_quals (type2);
1828  return comp_cv_qualification (q1, q2);
1829}
1830
1831/* Returns 1 if the cv-qualification signature of TYPE1 is a proper
1832   subset of the cv-qualification signature of TYPE2, and the types
1833   are similar.  Returns -1 if the other way 'round, and 0 otherwise.  */
1834
1835int
1836comp_cv_qual_signature (tree type1, tree type2)
1837{
1838  if (comp_ptr_ttypes_real (type2, type1, -1))
1839    return 1;
1840  else if (comp_ptr_ttypes_real (type1, type2, -1))
1841    return -1;
1842  else
1843    return 0;
1844}
1845
1846/* Subroutines of `comptypes'.  */
1847
1848/* Return true if two parameter type lists PARMS1 and PARMS2 are
1849   equivalent in the sense that functions with those parameter types
1850   can have equivalent types.  The two lists must be equivalent,
1851   element by element.  */
1852
1853bool
1854compparms (const_tree parms1, const_tree parms2)
1855{
1856  const_tree t1, t2;
1857
1858  /* An unspecified parmlist matches any specified parmlist
1859     whose argument types don't need default promotions.  */
1860
1861  for (t1 = parms1, t2 = parms2;
1862       t1 || t2;
1863       t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1864    {
1865      /* If one parmlist is shorter than the other,
1866	 they fail to match.  */
1867      if (!t1 || !t2)
1868	return false;
1869      if (!same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1870	return false;
1871    }
1872  return true;
1873}
1874
1875
1876/* Process a sizeof or alignof expression where the operand is a type.
1877   STD_ALIGNOF indicates whether an alignof has C++11 (minimum alignment)
1878   or GNU (preferred alignment) semantics; it is ignored if OP is
1879   SIZEOF_EXPR.  */
1880
1881tree
1882cxx_sizeof_or_alignof_type (location_t loc, tree type, enum tree_code op,
1883			    bool std_alignof, bool complain)
1884{
1885  gcc_assert (op == SIZEOF_EXPR || op == ALIGNOF_EXPR);
1886  if (type == error_mark_node)
1887    return error_mark_node;
1888
1889  type = non_reference (type);
1890  if (TREE_CODE (type) == METHOD_TYPE)
1891    {
1892      if (complain)
1893	{
1894	  pedwarn (loc, OPT_Wpointer_arith,
1895		   "invalid application of %qs to a member function",
1896		   OVL_OP_INFO (false, op)->name);
1897	  return size_one_node;
1898	}
1899      else
1900	return error_mark_node;
1901    }
1902  else if (VOID_TYPE_P (type) && std_alignof)
1903    {
1904      if (complain)
1905	error_at (loc, "invalid application of %qs to a void type",
1906		  OVL_OP_INFO (false, op)->name);
1907      return error_mark_node;
1908    }
1909
1910  bool dependent_p = dependent_type_p (type);
1911  if (!dependent_p)
1912    complete_type (type);
1913  if (dependent_p
1914      /* VLA types will have a non-constant size.  In the body of an
1915	 uninstantiated template, we don't need to try to compute the
1916	 value, because the sizeof expression is not an integral
1917	 constant expression in that case.  And, if we do try to
1918	 compute the value, we'll likely end up with SAVE_EXPRs, which
1919	 the template substitution machinery does not expect to see.  */
1920      || (processing_template_decl
1921	  && COMPLETE_TYPE_P (type)
1922	  && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST))
1923    {
1924      tree value = build_min (op, size_type_node, type);
1925      TREE_READONLY (value) = 1;
1926      if (op == ALIGNOF_EXPR && std_alignof)
1927	ALIGNOF_EXPR_STD_P (value) = true;
1928      SET_EXPR_LOCATION (value, loc);
1929      return value;
1930    }
1931
1932  return c_sizeof_or_alignof_type (loc, complete_type (type),
1933				   op == SIZEOF_EXPR, std_alignof,
1934				   complain);
1935}
1936
1937/* Return the size of the type, without producing any warnings for
1938   types whose size cannot be taken.  This routine should be used only
1939   in some other routine that has already produced a diagnostic about
1940   using the size of such a type.  */
1941tree
1942cxx_sizeof_nowarn (tree type)
1943{
1944  if (TREE_CODE (type) == FUNCTION_TYPE
1945      || VOID_TYPE_P (type)
1946      || TREE_CODE (type) == ERROR_MARK)
1947    return size_one_node;
1948  else if (!COMPLETE_TYPE_P (type))
1949    return size_zero_node;
1950  else
1951    return cxx_sizeof_or_alignof_type (input_location, type,
1952				       SIZEOF_EXPR, false, false);
1953}
1954
1955/* Process a sizeof expression where the operand is an expression.  */
1956
1957static tree
1958cxx_sizeof_expr (location_t loc, tree e, tsubst_flags_t complain)
1959{
1960  if (e == error_mark_node)
1961    return error_mark_node;
1962
1963  if (instantiation_dependent_uneval_expression_p (e))
1964    {
1965      e = build_min (SIZEOF_EXPR, size_type_node, e);
1966      TREE_SIDE_EFFECTS (e) = 0;
1967      TREE_READONLY (e) = 1;
1968      SET_EXPR_LOCATION (e, loc);
1969
1970      return e;
1971    }
1972
1973  location_t e_loc = cp_expr_loc_or_loc (e, loc);
1974  STRIP_ANY_LOCATION_WRAPPER (e);
1975
1976  /* To get the size of a static data member declared as an array of
1977     unknown bound, we need to instantiate it.  */
1978  if (VAR_P (e)
1979      && VAR_HAD_UNKNOWN_BOUND (e)
1980      && DECL_TEMPLATE_INSTANTIATION (e))
1981    instantiate_decl (e, /*defer_ok*/true, /*expl_inst_mem*/false);
1982
1983  if (TREE_CODE (e) == PARM_DECL
1984      && DECL_ARRAY_PARAMETER_P (e)
1985      && (complain & tf_warning))
1986    {
1987      auto_diagnostic_group d;
1988      if (warning_at (e_loc, OPT_Wsizeof_array_argument,
1989		      "%<sizeof%> on array function parameter %qE "
1990		      "will return size of %qT", e, TREE_TYPE (e)))
1991	inform (DECL_SOURCE_LOCATION (e), "declared here");
1992    }
1993
1994  e = mark_type_use (e);
1995
1996  if (bitfield_p (e))
1997    {
1998      if (complain & tf_error)
1999	error_at (e_loc,
2000		  "invalid application of %<sizeof%> to a bit-field");
2001      else
2002        return error_mark_node;
2003      e = char_type_node;
2004    }
2005  else if (is_overloaded_fn (e))
2006    {
2007      if (complain & tf_error)
2008	permerror (e_loc, "ISO C++ forbids applying %<sizeof%> to "
2009		   "an expression of function type");
2010      else
2011        return error_mark_node;
2012      e = char_type_node;
2013    }
2014  else if (type_unknown_p (e))
2015    {
2016      if (complain & tf_error)
2017        cxx_incomplete_type_error (e_loc, e, TREE_TYPE (e));
2018      else
2019        return error_mark_node;
2020      e = char_type_node;
2021    }
2022  else
2023    e = TREE_TYPE (e);
2024
2025  return cxx_sizeof_or_alignof_type (loc, e, SIZEOF_EXPR, false,
2026				     complain & tf_error);
2027}
2028
2029/* Implement the __alignof keyword: Return the minimum required
2030   alignment of E, measured in bytes.  For VAR_DECL's and
2031   FIELD_DECL's return DECL_ALIGN (which can be set from an
2032   "aligned" __attribute__ specification).  STD_ALIGNOF acts
2033   like in cxx_sizeof_or_alignof_type.  */
2034
2035static tree
2036cxx_alignof_expr (location_t loc, tree e, bool std_alignof,
2037		  tsubst_flags_t complain)
2038{
2039  tree t;
2040
2041  if (e == error_mark_node)
2042    return error_mark_node;
2043
2044  if (processing_template_decl)
2045    {
2046      e = build_min (ALIGNOF_EXPR, size_type_node, e);
2047      TREE_SIDE_EFFECTS (e) = 0;
2048      TREE_READONLY (e) = 1;
2049      SET_EXPR_LOCATION (e, loc);
2050      ALIGNOF_EXPR_STD_P (e) = std_alignof;
2051
2052      return e;
2053    }
2054
2055  location_t e_loc = cp_expr_loc_or_loc (e, loc);
2056  STRIP_ANY_LOCATION_WRAPPER (e);
2057
2058  e = mark_type_use (e);
2059
2060  if (!verify_type_context (loc, TCTX_ALIGNOF, TREE_TYPE (e),
2061			    !(complain & tf_error)))
2062    {
2063      if (!(complain & tf_error))
2064	return error_mark_node;
2065      t = size_one_node;
2066    }
2067  else if (VAR_P (e))
2068    t = size_int (DECL_ALIGN_UNIT (e));
2069  else if (bitfield_p (e))
2070    {
2071      if (complain & tf_error)
2072	error_at (e_loc,
2073		  "invalid application of %<__alignof%> to a bit-field");
2074      else
2075        return error_mark_node;
2076      t = size_one_node;
2077    }
2078  else if (TREE_CODE (e) == COMPONENT_REF
2079	   && TREE_CODE (TREE_OPERAND (e, 1)) == FIELD_DECL)
2080    t = size_int (DECL_ALIGN_UNIT (TREE_OPERAND (e, 1)));
2081  else if (is_overloaded_fn (e))
2082    {
2083      if (complain & tf_error)
2084	permerror (e_loc, "ISO C++ forbids applying %<__alignof%> to "
2085		   "an expression of function type");
2086      else
2087        return error_mark_node;
2088      if (TREE_CODE (e) == FUNCTION_DECL)
2089	t = size_int (DECL_ALIGN_UNIT (e));
2090      else
2091	t = size_one_node;
2092    }
2093  else if (type_unknown_p (e))
2094    {
2095      if (complain & tf_error)
2096        cxx_incomplete_type_error (e_loc, e, TREE_TYPE (e));
2097      else
2098        return error_mark_node;
2099      t = size_one_node;
2100    }
2101  else
2102    return cxx_sizeof_or_alignof_type (loc, TREE_TYPE (e),
2103				       ALIGNOF_EXPR, std_alignof,
2104                                       complain & tf_error);
2105
2106  return fold_convert_loc (loc, size_type_node, t);
2107}
2108
2109/* Process a sizeof or alignof expression E with code OP where the operand
2110   is an expression. STD_ALIGNOF acts like in cxx_sizeof_or_alignof_type.  */
2111
2112tree
2113cxx_sizeof_or_alignof_expr (location_t loc, tree e, enum tree_code op,
2114			    bool std_alignof, bool complain)
2115{
2116  gcc_assert (op == SIZEOF_EXPR || op == ALIGNOF_EXPR);
2117  if (op == SIZEOF_EXPR)
2118    return cxx_sizeof_expr (loc, e, complain? tf_warning_or_error : tf_none);
2119  else
2120    return cxx_alignof_expr (loc, e, std_alignof,
2121			     complain? tf_warning_or_error : tf_none);
2122}
2123
2124/*  Build a representation of an expression 'alignas(E).'  Return the
2125    folded integer value of E if it is an integral constant expression
2126    that resolves to a valid alignment.  If E depends on a template
2127    parameter, return a syntactic representation tree of kind
2128    ALIGNOF_EXPR.  Otherwise, return an error_mark_node if the
2129    expression is ill formed, or NULL_TREE if E is NULL_TREE.  */
2130
2131tree
2132cxx_alignas_expr (tree e)
2133{
2134  if (e == NULL_TREE || e == error_mark_node
2135      || (!TYPE_P (e) && !require_potential_rvalue_constant_expression (e)))
2136    return e;
2137
2138  if (TYPE_P (e))
2139    /* [dcl.align]/3:
2140
2141	   When the alignment-specifier is of the form
2142	   alignas(type-id), it shall have the same effect as
2143	   alignas(alignof(type-id)).  */
2144
2145    return cxx_sizeof_or_alignof_type (input_location,
2146				       e, ALIGNOF_EXPR,
2147				       /*std_alignof=*/true,
2148				       /*complain=*/true);
2149
2150  /* If we reach this point, it means the alignas expression if of
2151     the form "alignas(assignment-expression)", so we should follow
2152     what is stated by [dcl.align]/2.  */
2153
2154  if (value_dependent_expression_p (e))
2155    /* Leave value-dependent expression alone for now. */
2156    return e;
2157
2158  e = instantiate_non_dependent_expr (e);
2159  e = mark_rvalue_use (e);
2160
2161  /* [dcl.align]/2 says:
2162
2163         the assignment-expression shall be an integral constant
2164	 expression.  */
2165
2166  if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (e)))
2167    {
2168      error ("%<alignas%> argument has non-integral type %qT", TREE_TYPE (e));
2169      return error_mark_node;
2170    }
2171
2172  return cxx_constant_value (e);
2173}
2174
2175
2176/* EXPR is being used in a context that is not a function call.
2177   Enforce:
2178
2179     [expr.ref]
2180
2181     The expression can be used only as the left-hand operand of a
2182     member function call.
2183
2184     [expr.mptr.operator]
2185
2186     If the result of .* or ->* is a function, then that result can be
2187     used only as the operand for the function call operator ().
2188
2189   by issuing an error message if appropriate.  Returns true iff EXPR
2190   violates these rules.  */
2191
2192bool
2193invalid_nonstatic_memfn_p (location_t loc, tree expr, tsubst_flags_t complain)
2194{
2195  if (expr == NULL_TREE)
2196    return false;
2197  /* Don't enforce this in MS mode.  */
2198  if (flag_ms_extensions)
2199    return false;
2200  if (is_overloaded_fn (expr) && !really_overloaded_fn (expr))
2201    expr = get_first_fn (expr);
2202  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (expr))
2203    {
2204      if (complain & tf_error)
2205	{
2206	  if (DECL_P (expr))
2207	    {
2208	      error_at (loc, "invalid use of non-static member function %qD",
2209			expr);
2210	      inform (DECL_SOURCE_LOCATION (expr), "declared here");
2211	    }
2212	  else
2213	    error_at (loc, "invalid use of non-static member function of "
2214		      "type %qT", TREE_TYPE (expr));
2215	}
2216      return true;
2217    }
2218  return false;
2219}
2220
2221/* If EXP is a reference to a bit-field, and the type of EXP does not
2222   match the declared type of the bit-field, return the declared type
2223   of the bit-field.  Otherwise, return NULL_TREE.  */
2224
2225tree
2226is_bitfield_expr_with_lowered_type (const_tree exp)
2227{
2228  switch (TREE_CODE (exp))
2229    {
2230    case COND_EXPR:
2231      if (!is_bitfield_expr_with_lowered_type (TREE_OPERAND (exp, 1)
2232					       ? TREE_OPERAND (exp, 1)
2233					       : TREE_OPERAND (exp, 0)))
2234	return NULL_TREE;
2235      return is_bitfield_expr_with_lowered_type (TREE_OPERAND (exp, 2));
2236
2237    case COMPOUND_EXPR:
2238      return is_bitfield_expr_with_lowered_type (TREE_OPERAND (exp, 1));
2239
2240    case MODIFY_EXPR:
2241    case SAVE_EXPR:
2242    case UNARY_PLUS_EXPR:
2243    case PREDECREMENT_EXPR:
2244    case PREINCREMENT_EXPR:
2245    case POSTDECREMENT_EXPR:
2246    case POSTINCREMENT_EXPR:
2247    case NEGATE_EXPR:
2248    case NON_LVALUE_EXPR:
2249    case BIT_NOT_EXPR:
2250      return is_bitfield_expr_with_lowered_type (TREE_OPERAND (exp, 0));
2251
2252    case COMPONENT_REF:
2253      {
2254	tree field;
2255
2256	field = TREE_OPERAND (exp, 1);
2257	if (TREE_CODE (field) != FIELD_DECL || !DECL_BIT_FIELD_TYPE (field))
2258	  return NULL_TREE;
2259	if (same_type_ignoring_top_level_qualifiers_p
2260	    (TREE_TYPE (exp), DECL_BIT_FIELD_TYPE (field)))
2261	  return NULL_TREE;
2262	return DECL_BIT_FIELD_TYPE (field);
2263      }
2264
2265    case VAR_DECL:
2266      if (DECL_HAS_VALUE_EXPR_P (exp))
2267	return is_bitfield_expr_with_lowered_type (DECL_VALUE_EXPR
2268						   (CONST_CAST_TREE (exp)));
2269      return NULL_TREE;
2270
2271    case VIEW_CONVERT_EXPR:
2272      if (location_wrapper_p (exp))
2273	return is_bitfield_expr_with_lowered_type (TREE_OPERAND (exp, 0));
2274      else
2275	return NULL_TREE;
2276
2277    default:
2278      return NULL_TREE;
2279    }
2280}
2281
2282/* Like is_bitfield_with_lowered_type, except that if EXP is not a
2283   bitfield with a lowered type, the type of EXP is returned, rather
2284   than NULL_TREE.  */
2285
2286tree
2287unlowered_expr_type (const_tree exp)
2288{
2289  tree type;
2290  tree etype = TREE_TYPE (exp);
2291
2292  type = is_bitfield_expr_with_lowered_type (exp);
2293  if (type)
2294    type = cp_build_qualified_type (type, cp_type_quals (etype));
2295  else
2296    type = etype;
2297
2298  return type;
2299}
2300
2301/* Perform the conversions in [expr] that apply when an lvalue appears
2302   in an rvalue context: the lvalue-to-rvalue, array-to-pointer, and
2303   function-to-pointer conversions.  In addition, bitfield references are
2304   converted to their declared types. Note that this function does not perform
2305   the lvalue-to-rvalue conversion for class types. If you need that conversion
2306   for class types, then you probably need to use force_rvalue.
2307
2308   Although the returned value is being used as an rvalue, this
2309   function does not wrap the returned expression in a
2310   NON_LVALUE_EXPR; the caller is expected to be mindful of the fact
2311   that the return value is no longer an lvalue.  */
2312
2313tree
2314decay_conversion (tree exp,
2315		  tsubst_flags_t complain,
2316		  bool reject_builtin /* = true */)
2317{
2318  tree type;
2319  enum tree_code code;
2320  location_t loc = cp_expr_loc_or_input_loc (exp);
2321
2322  type = TREE_TYPE (exp);
2323  if (type == error_mark_node)
2324    return error_mark_node;
2325
2326  exp = resolve_nondeduced_context_or_error (exp, complain);
2327
2328  code = TREE_CODE (type);
2329
2330  if (error_operand_p (exp))
2331    return error_mark_node;
2332
2333  if (NULLPTR_TYPE_P (type) && !TREE_SIDE_EFFECTS (exp))
2334    {
2335      mark_rvalue_use (exp, loc, reject_builtin);
2336      return nullptr_node;
2337    }
2338
2339  /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
2340     Leave such NOP_EXPRs, since RHS is being used in non-lvalue context.  */
2341  if (code == VOID_TYPE)
2342    {
2343      if (complain & tf_error)
2344	error_at (loc, "void value not ignored as it ought to be");
2345      return error_mark_node;
2346    }
2347  if (invalid_nonstatic_memfn_p (loc, exp, complain))
2348    return error_mark_node;
2349  if (code == FUNCTION_TYPE || is_overloaded_fn (exp))
2350    {
2351      exp = mark_lvalue_use (exp);
2352      if (reject_builtin && reject_gcc_builtin (exp, loc))
2353	return error_mark_node;
2354      return cp_build_addr_expr (exp, complain);
2355    }
2356  if (code == ARRAY_TYPE)
2357    {
2358      tree adr;
2359      tree ptrtype;
2360
2361      exp = mark_lvalue_use (exp);
2362
2363      if (INDIRECT_REF_P (exp))
2364	return build_nop (build_pointer_type (TREE_TYPE (type)),
2365			  TREE_OPERAND (exp, 0));
2366
2367      if (TREE_CODE (exp) == COMPOUND_EXPR)
2368	{
2369	  tree op1 = decay_conversion (TREE_OPERAND (exp, 1), complain);
2370	  if (op1 == error_mark_node)
2371            return error_mark_node;
2372	  return build2 (COMPOUND_EXPR, TREE_TYPE (op1),
2373			 TREE_OPERAND (exp, 0), op1);
2374	}
2375
2376      if (!obvalue_p (exp)
2377	  && ! (TREE_CODE (exp) == CONSTRUCTOR && TREE_STATIC (exp)))
2378	{
2379	  if (complain & tf_error)
2380	    error_at (loc, "invalid use of non-lvalue array");
2381	  return error_mark_node;
2382	}
2383
2384      /* Don't let an array compound literal decay to a pointer.  It can
2385	 still be used to initialize an array or bind to a reference.  */
2386      if (TREE_CODE (exp) == TARGET_EXPR)
2387	{
2388	  if (complain & tf_error)
2389	    error_at (loc, "taking address of temporary array");
2390	  return error_mark_node;
2391	}
2392
2393      ptrtype = build_pointer_type (TREE_TYPE (type));
2394
2395      if (VAR_P (exp))
2396	{
2397	  if (!cxx_mark_addressable (exp))
2398	    return error_mark_node;
2399	  adr = build_nop (ptrtype, build_address (exp));
2400	  return adr;
2401	}
2402      /* This way is better for a COMPONENT_REF since it can
2403	 simplify the offset for a component.  */
2404      adr = cp_build_addr_expr (exp, complain);
2405      return cp_convert (ptrtype, adr, complain);
2406    }
2407
2408  /* Otherwise, it's the lvalue-to-rvalue conversion.  */
2409  exp = mark_rvalue_use (exp, loc, reject_builtin);
2410
2411  /* If a bitfield is used in a context where integral promotion
2412     applies, then the caller is expected to have used
2413     default_conversion.  That function promotes bitfields correctly
2414     before calling this function.  At this point, if we have a
2415     bitfield referenced, we may assume that is not subject to
2416     promotion, and that, therefore, the type of the resulting rvalue
2417     is the declared type of the bitfield.  */
2418  exp = convert_bitfield_to_declared_type (exp);
2419
2420  /* We do not call rvalue() here because we do not want to wrap EXP
2421     in a NON_LVALUE_EXPR.  */
2422
2423  /* [basic.lval]
2424
2425     Non-class rvalues always have cv-unqualified types.  */
2426  type = TREE_TYPE (exp);
2427  if (!CLASS_TYPE_P (type) && cv_qualified_p (type))
2428    exp = build_nop (cv_unqualified (type), exp);
2429
2430  if (!complete_type_or_maybe_complain (type, exp, complain))
2431    return error_mark_node;
2432
2433  return exp;
2434}
2435
2436/* Perform preparatory conversions, as part of the "usual arithmetic
2437   conversions".  In particular, as per [expr]:
2438
2439     Whenever an lvalue expression appears as an operand of an
2440     operator that expects the rvalue for that operand, the
2441     lvalue-to-rvalue, array-to-pointer, or function-to-pointer
2442     standard conversions are applied to convert the expression to an
2443     rvalue.
2444
2445   In addition, we perform integral promotions here, as those are
2446   applied to both operands to a binary operator before determining
2447   what additional conversions should apply.  */
2448
2449static tree
2450cp_default_conversion (tree exp, tsubst_flags_t complain)
2451{
2452  /* Check for target-specific promotions.  */
2453  tree promoted_type = targetm.promoted_type (TREE_TYPE (exp));
2454  if (promoted_type)
2455    exp = cp_convert (promoted_type, exp, complain);
2456  /* Perform the integral promotions first so that bitfield
2457     expressions (which may promote to "int", even if the bitfield is
2458     declared "unsigned") are promoted correctly.  */
2459  else if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (exp)))
2460    exp = cp_perform_integral_promotions (exp, complain);
2461  /* Perform the other conversions.  */
2462  exp = decay_conversion (exp, complain);
2463
2464  return exp;
2465}
2466
2467/* C version.  */
2468
2469tree
2470default_conversion (tree exp)
2471{
2472  return cp_default_conversion (exp, tf_warning_or_error);
2473}
2474
2475/* EXPR is an expression with an integral or enumeration type.
2476   Perform the integral promotions in [conv.prom], and return the
2477   converted value.  */
2478
2479tree
2480cp_perform_integral_promotions (tree expr, tsubst_flags_t complain)
2481{
2482  tree type;
2483  tree promoted_type;
2484
2485  expr = mark_rvalue_use (expr);
2486  if (error_operand_p (expr))
2487    return error_mark_node;
2488
2489  type = TREE_TYPE (expr);
2490
2491  /* [conv.prom]
2492
2493     A prvalue for an integral bit-field (11.3.9) can be converted to a prvalue
2494     of type int if int can represent all the values of the bit-field;
2495     otherwise, it can be converted to unsigned int if unsigned int can
2496     represent all the values of the bit-field. If the bit-field is larger yet,
2497     no integral promotion applies to it. If the bit-field has an enumerated
2498     type, it is treated as any other value of that type for promotion
2499     purposes.  */
2500  tree bitfield_type = is_bitfield_expr_with_lowered_type (expr);
2501  if (bitfield_type
2502      && (TREE_CODE (bitfield_type) == ENUMERAL_TYPE
2503	  || TYPE_PRECISION (type) > TYPE_PRECISION (integer_type_node)))
2504    type = bitfield_type;
2505
2506  gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
2507  /* Scoped enums don't promote.  */
2508  if (SCOPED_ENUM_P (type))
2509    return expr;
2510  promoted_type = type_promotes_to (type);
2511  if (type != promoted_type)
2512    expr = cp_convert (promoted_type, expr, complain);
2513  else if (bitfield_type && bitfield_type != type)
2514    /* Prevent decay_conversion from converting to bitfield_type.  */
2515    expr = build_nop (type, expr);
2516  return expr;
2517}
2518
2519/* C version.  */
2520
2521tree
2522perform_integral_promotions (tree expr)
2523{
2524  return cp_perform_integral_promotions (expr, tf_warning_or_error);
2525}
2526
2527/* Returns nonzero iff exp is a STRING_CST or the result of applying
2528   decay_conversion to one.  */
2529
2530int
2531string_conv_p (const_tree totype, const_tree exp, int warn)
2532{
2533  tree t;
2534
2535  if (!TYPE_PTR_P (totype))
2536    return 0;
2537
2538  t = TREE_TYPE (totype);
2539  if (!same_type_p (t, char_type_node)
2540      && !same_type_p (t, char8_type_node)
2541      && !same_type_p (t, char16_type_node)
2542      && !same_type_p (t, char32_type_node)
2543      && !same_type_p (t, wchar_type_node))
2544    return 0;
2545
2546  location_t loc = EXPR_LOC_OR_LOC (exp, input_location);
2547
2548  STRIP_ANY_LOCATION_WRAPPER (exp);
2549
2550  if (TREE_CODE (exp) == STRING_CST)
2551    {
2552      /* Make sure that we don't try to convert between char and wide chars.  */
2553      if (!same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (exp))), t))
2554	return 0;
2555    }
2556  else
2557    {
2558      /* Is this a string constant which has decayed to 'const char *'?  */
2559      t = build_pointer_type (cp_build_qualified_type (t, TYPE_QUAL_CONST));
2560      if (!same_type_p (TREE_TYPE (exp), t))
2561	return 0;
2562      STRIP_NOPS (exp);
2563      if (TREE_CODE (exp) != ADDR_EXPR
2564	  || TREE_CODE (TREE_OPERAND (exp, 0)) != STRING_CST)
2565	return 0;
2566    }
2567  if (warn)
2568    {
2569      if (cxx_dialect >= cxx11)
2570	pedwarn (loc, OPT_Wwrite_strings,
2571		 "ISO C++ forbids converting a string constant to %qT",
2572		 totype);
2573      else
2574	warning_at (loc, OPT_Wwrite_strings,
2575		    "deprecated conversion from string constant to %qT",
2576		    totype);
2577    }
2578
2579  return 1;
2580}
2581
2582/* Given a COND_EXPR, MIN_EXPR, or MAX_EXPR in T, return it in a form that we
2583   can, for example, use as an lvalue.  This code used to be in
2584   unary_complex_lvalue, but we needed it to deal with `a = (d == c) ? b : c'
2585   expressions, where we're dealing with aggregates.  But now it's again only
2586   called from unary_complex_lvalue.  The case (in particular) that led to
2587   this was with CODE == ADDR_EXPR, since it's not an lvalue when we'd
2588   get it there.  */
2589
2590static tree
2591rationalize_conditional_expr (enum tree_code code, tree t,
2592                              tsubst_flags_t complain)
2593{
2594  location_t loc = cp_expr_loc_or_input_loc (t);
2595
2596  /* For MIN_EXPR or MAX_EXPR, fold-const.cc has arranged things so that
2597     the first operand is always the one to be used if both operands
2598     are equal, so we know what conditional expression this used to be.  */
2599  if (TREE_CODE (t) == MIN_EXPR || TREE_CODE (t) == MAX_EXPR)
2600    {
2601      tree op0 = TREE_OPERAND (t, 0);
2602      tree op1 = TREE_OPERAND (t, 1);
2603
2604      /* The following code is incorrect if either operand side-effects.  */
2605      gcc_assert (!TREE_SIDE_EFFECTS (op0)
2606		  && !TREE_SIDE_EFFECTS (op1));
2607      return
2608	build_conditional_expr (loc,
2609				build_x_binary_op (loc,
2610						   (TREE_CODE (t) == MIN_EXPR
2611						    ? LE_EXPR : GE_EXPR),
2612						   op0, TREE_CODE (op0),
2613						   op1, TREE_CODE (op1),
2614						   NULL_TREE,
2615						   /*overload=*/NULL,
2616						   complain),
2617                                cp_build_unary_op (code, op0, false, complain),
2618                                cp_build_unary_op (code, op1, false, complain),
2619                                complain);
2620    }
2621
2622  tree op1 = TREE_OPERAND (t, 1);
2623  if (TREE_CODE (op1) != THROW_EXPR)
2624    op1 = cp_build_unary_op (code, op1, false, complain);
2625  tree op2 = TREE_OPERAND (t, 2);
2626  if (TREE_CODE (op2) != THROW_EXPR)
2627    op2 = cp_build_unary_op (code, op2, false, complain);
2628
2629  return
2630    build_conditional_expr (loc, TREE_OPERAND (t, 0), op1, op2, complain);
2631}
2632
2633/* Given the TYPE of an anonymous union field inside T, return the
2634   FIELD_DECL for the field.  If not found return NULL_TREE.  Because
2635   anonymous unions can nest, we must also search all anonymous unions
2636   that are directly reachable.  */
2637
2638tree
2639lookup_anon_field (tree, tree type)
2640{
2641  tree field;
2642
2643  type = TYPE_MAIN_VARIANT (type);
2644  field = ANON_AGGR_TYPE_FIELD (type);
2645  gcc_assert (field);
2646  return field;
2647}
2648
2649/* Build an expression representing OBJECT.MEMBER.  OBJECT is an
2650   expression; MEMBER is a DECL or baselink.  If ACCESS_PATH is
2651   non-NULL, it indicates the path to the base used to name MEMBER.
2652   If PRESERVE_REFERENCE is true, the expression returned will have
2653   REFERENCE_TYPE if the MEMBER does.  Otherwise, the expression
2654   returned will have the type referred to by the reference.
2655
2656   This function does not perform access control; that is either done
2657   earlier by the parser when the name of MEMBER is resolved to MEMBER
2658   itself, or later when overload resolution selects one of the
2659   functions indicated by MEMBER.  */
2660
2661tree
2662build_class_member_access_expr (cp_expr object, tree member,
2663				tree access_path, bool preserve_reference,
2664				tsubst_flags_t complain)
2665{
2666  tree object_type;
2667  tree member_scope;
2668  tree result = NULL_TREE;
2669  tree using_decl = NULL_TREE;
2670
2671  if (error_operand_p (object) || error_operand_p (member))
2672    return error_mark_node;
2673
2674  gcc_assert (DECL_P (member) || BASELINK_P (member));
2675
2676  /* [expr.ref]
2677
2678     The type of the first expression shall be "class object" (of a
2679     complete type).  */
2680  object_type = TREE_TYPE (object);
2681  if (!currently_open_class (object_type)
2682      && !complete_type_or_maybe_complain (object_type, object, complain))
2683    return error_mark_node;
2684  if (!CLASS_TYPE_P (object_type))
2685    {
2686      if (complain & tf_error)
2687	{
2688	  if (INDIRECT_TYPE_P (object_type)
2689	      && CLASS_TYPE_P (TREE_TYPE (object_type)))
2690	    error ("request for member %qD in %qE, which is of pointer "
2691		   "type %qT (maybe you meant to use %<->%> ?)",
2692		   member, object.get_value (), object_type);
2693	  else
2694	    error ("request for member %qD in %qE, which is of non-class "
2695		   "type %qT", member, object.get_value (), object_type);
2696	}
2697      return error_mark_node;
2698    }
2699
2700  /* The standard does not seem to actually say that MEMBER must be a
2701     member of OBJECT_TYPE.  However, that is clearly what is
2702     intended.  */
2703  if (DECL_P (member))
2704    {
2705      member_scope = DECL_CLASS_CONTEXT (member);
2706      if (!mark_used (member, complain) && !(complain & tf_error))
2707	return error_mark_node;
2708
2709      if (TREE_UNAVAILABLE (member))
2710	error_unavailable_use (member, NULL_TREE);
2711      else if (TREE_DEPRECATED (member))
2712	warn_deprecated_use (member, NULL_TREE);
2713    }
2714  else
2715    member_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (member));
2716  /* If MEMBER is from an anonymous aggregate, MEMBER_SCOPE will
2717     presently be the anonymous union.  Go outwards until we find a
2718     type related to OBJECT_TYPE.  */
2719  while ((ANON_AGGR_TYPE_P (member_scope) || UNSCOPED_ENUM_P (member_scope))
2720	 && !same_type_ignoring_top_level_qualifiers_p (member_scope,
2721							object_type))
2722    member_scope = TYPE_CONTEXT (member_scope);
2723  if (!member_scope || !DERIVED_FROM_P (member_scope, object_type))
2724    {
2725      if (complain & tf_error)
2726	{
2727	  if (TREE_CODE (member) == FIELD_DECL)
2728	    error ("invalid use of non-static data member %qE", member);
2729	  else
2730	    error ("%qD is not a member of %qT", member, object_type);
2731	}
2732      return error_mark_node;
2733    }
2734
2735  /* Transform `(a, b).x' into `(*(a, &b)).x', `(a ? b : c).x' into
2736     `(*(a ?  &b : &c)).x', and so on.  A COND_EXPR is only an lvalue
2737     in the front end; only _DECLs and _REFs are lvalues in the back end.  */
2738  if (tree temp = unary_complex_lvalue (ADDR_EXPR, object))
2739    {
2740      temp = cp_build_fold_indirect_ref (temp);
2741      if (!lvalue_p (object) && lvalue_p (temp))
2742	/* Preserve rvalueness.  */
2743	temp = move (temp);
2744      object = temp;
2745    }
2746
2747  /* In [expr.ref], there is an explicit list of the valid choices for
2748     MEMBER.  We check for each of those cases here.  */
2749  if (VAR_P (member))
2750    {
2751      /* A static data member.  */
2752      result = member;
2753      mark_exp_read (object);
2754
2755      if (tree wrap = maybe_get_tls_wrapper_call (result))
2756	/* Replace an evaluated use of the thread_local variable with
2757	   a call to its wrapper.  */
2758	result = wrap;
2759
2760      /* If OBJECT has side-effects, they are supposed to occur.  */
2761      if (TREE_SIDE_EFFECTS (object))
2762	result = build2 (COMPOUND_EXPR, TREE_TYPE (result), object, result);
2763    }
2764  else if (TREE_CODE (member) == FIELD_DECL)
2765    {
2766      /* A non-static data member.  */
2767      bool null_object_p;
2768      int type_quals;
2769      tree member_type;
2770
2771      if (INDIRECT_REF_P (object))
2772	null_object_p =
2773	  integer_zerop (tree_strip_nop_conversions (TREE_OPERAND (object, 0)));
2774      else
2775	null_object_p = false;
2776
2777      /* Convert OBJECT to the type of MEMBER.  */
2778      if (!same_type_p (TYPE_MAIN_VARIANT (object_type),
2779			TYPE_MAIN_VARIANT (member_scope)))
2780	{
2781	  tree binfo;
2782	  base_kind kind;
2783
2784	  /* We didn't complain above about a currently open class, but now we
2785	     must: we don't know how to refer to a base member before layout is
2786	     complete.  But still don't complain in a template.  */
2787	  if (!cp_unevaluated_operand
2788	      && !dependent_type_p (object_type)
2789	      && !complete_type_or_maybe_complain (object_type, object,
2790						   complain))
2791	    return error_mark_node;
2792
2793	  binfo = lookup_base (access_path ? access_path : object_type,
2794			       member_scope, ba_unique, &kind, complain);
2795	  if (binfo == error_mark_node)
2796	    return error_mark_node;
2797
2798	  /* It is invalid to try to get to a virtual base of a
2799	     NULL object.  The most common cause is invalid use of
2800	     offsetof macro.  */
2801	  if (null_object_p && kind == bk_via_virtual)
2802	    {
2803	      if (complain & tf_error)
2804		{
2805		  error ("invalid access to non-static data member %qD in "
2806			 "virtual base of NULL object", member);
2807		}
2808	      return error_mark_node;
2809	    }
2810
2811	  /* Convert to the base.  */
2812	  object = build_base_path (PLUS_EXPR, object, binfo,
2813				    /*nonnull=*/1, complain);
2814	  /* If we found the base successfully then we should be able
2815	     to convert to it successfully.  */
2816	  gcc_assert (object != error_mark_node);
2817	}
2818
2819      /* If MEMBER is from an anonymous aggregate, we have converted
2820	 OBJECT so that it refers to the class containing the
2821	 anonymous union.  Generate a reference to the anonymous union
2822	 itself, and recur to find MEMBER.  */
2823      if (ANON_AGGR_TYPE_P (DECL_CONTEXT (member))
2824	  /* When this code is called from build_field_call, the
2825	     object already has the type of the anonymous union.
2826	     That is because the COMPONENT_REF was already
2827	     constructed, and was then disassembled before calling
2828	     build_field_call.  After the function-call code is
2829	     cleaned up, this waste can be eliminated.  */
2830	  && (!same_type_ignoring_top_level_qualifiers_p
2831	      (TREE_TYPE (object), DECL_CONTEXT (member))))
2832	{
2833	  tree anonymous_union;
2834
2835	  anonymous_union = lookup_anon_field (TREE_TYPE (object),
2836					       DECL_CONTEXT (member));
2837	  object = build_class_member_access_expr (object,
2838						   anonymous_union,
2839						   /*access_path=*/NULL_TREE,
2840						   preserve_reference,
2841						   complain);
2842	}
2843
2844      /* Compute the type of the field, as described in [expr.ref].  */
2845      type_quals = TYPE_UNQUALIFIED;
2846      member_type = TREE_TYPE (member);
2847      if (!TYPE_REF_P (member_type))
2848	{
2849	  type_quals = (cp_type_quals (member_type)
2850			| cp_type_quals (object_type));
2851
2852	  /* A field is const (volatile) if the enclosing object, or the
2853	     field itself, is const (volatile).  But, a mutable field is
2854	     not const, even within a const object.  */
2855	  if (DECL_MUTABLE_P (member))
2856	    type_quals &= ~TYPE_QUAL_CONST;
2857	  member_type = cp_build_qualified_type (member_type, type_quals);
2858	}
2859
2860      result = build3_loc (input_location, COMPONENT_REF, member_type,
2861			   object, member, NULL_TREE);
2862
2863      /* Mark the expression const or volatile, as appropriate.  Even
2864	 though we've dealt with the type above, we still have to mark the
2865	 expression itself.  */
2866      if (type_quals & TYPE_QUAL_CONST)
2867	TREE_READONLY (result) = 1;
2868      if (type_quals & TYPE_QUAL_VOLATILE)
2869	TREE_THIS_VOLATILE (result) = 1;
2870    }
2871  else if (BASELINK_P (member))
2872    {
2873      /* The member is a (possibly overloaded) member function.  */
2874      tree functions;
2875      tree type;
2876
2877      /* If the MEMBER is exactly one static member function, then we
2878	 know the type of the expression.  Otherwise, we must wait
2879	 until overload resolution has been performed.  */
2880      functions = BASELINK_FUNCTIONS (member);
2881      if (TREE_CODE (functions) == FUNCTION_DECL
2882	  && DECL_STATIC_FUNCTION_P (functions))
2883	type = TREE_TYPE (functions);
2884      else
2885	type = unknown_type_node;
2886      /* Note that we do not convert OBJECT to the BASELINK_BINFO
2887	 base.  That will happen when the function is called.  */
2888      result = build3_loc (input_location, COMPONENT_REF, type, object, member,
2889			   NULL_TREE);
2890    }
2891  else if (TREE_CODE (member) == CONST_DECL)
2892    {
2893      /* The member is an enumerator.  */
2894      result = member;
2895      /* If OBJECT has side-effects, they are supposed to occur.  */
2896      if (TREE_SIDE_EFFECTS (object))
2897	result = build2 (COMPOUND_EXPR, TREE_TYPE (result),
2898			 object, result);
2899    }
2900  else if ((using_decl = strip_using_decl (member)) != member)
2901    result = build_class_member_access_expr (object,
2902					     using_decl,
2903					     access_path, preserve_reference,
2904					     complain);
2905  else
2906    {
2907      if (complain & tf_error)
2908	error ("invalid use of %qD", member);
2909      return error_mark_node;
2910    }
2911
2912  if (!preserve_reference)
2913    /* [expr.ref]
2914
2915       If E2 is declared to have type "reference to T", then ... the
2916       type of E1.E2 is T.  */
2917    result = convert_from_reference (result);
2918
2919  return result;
2920}
2921
2922/* Return the destructor denoted by OBJECT.SCOPE::DTOR_NAME, or, if
2923   SCOPE is NULL, by OBJECT.DTOR_NAME, where DTOR_NAME is ~type.  */
2924
2925tree
2926lookup_destructor (tree object, tree scope, tree dtor_name,
2927		   tsubst_flags_t complain)
2928{
2929  tree object_type = TREE_TYPE (object);
2930  tree dtor_type = TREE_OPERAND (dtor_name, 0);
2931  tree expr;
2932
2933  /* We've already complained about this destructor.  */
2934  if (dtor_type == error_mark_node)
2935    return error_mark_node;
2936
2937  if (scope && !check_dtor_name (scope, dtor_type))
2938    {
2939      if (complain & tf_error)
2940	error ("qualified type %qT does not match destructor name ~%qT",
2941	       scope, dtor_type);
2942      return error_mark_node;
2943    }
2944  if (is_auto (dtor_type))
2945    dtor_type = object_type;
2946  else if (identifier_p (dtor_type))
2947    {
2948      /* In a template, names we can't find a match for are still accepted
2949	 destructor names, and we check them here.  */
2950      if (check_dtor_name (object_type, dtor_type))
2951	dtor_type = object_type;
2952      else
2953	{
2954	  if (complain & tf_error)
2955	    error ("object type %qT does not match destructor name ~%qT",
2956		   object_type, dtor_type);
2957	  return error_mark_node;
2958	}
2959
2960    }
2961  else if (!DERIVED_FROM_P (dtor_type, TYPE_MAIN_VARIANT (object_type)))
2962    {
2963      if (complain & tf_error)
2964	error ("the type being destroyed is %qT, but the destructor "
2965	       "refers to %qT", TYPE_MAIN_VARIANT (object_type), dtor_type);
2966      return error_mark_node;
2967    }
2968  expr = lookup_member (dtor_type, complete_dtor_identifier,
2969			/*protect=*/1, /*want_type=*/false,
2970			tf_warning_or_error);
2971  if (!expr)
2972    {
2973      if (complain & tf_error)
2974	cxx_incomplete_type_error (dtor_name, dtor_type);
2975      return error_mark_node;
2976    }
2977  expr = (adjust_result_of_qualified_name_lookup
2978	  (expr, dtor_type, object_type));
2979  if (scope == NULL_TREE)
2980    /* We need to call adjust_result_of_qualified_name_lookup in case the
2981       destructor names a base class, but we unset BASELINK_QUALIFIED_P so
2982       that we still get virtual function binding.  */
2983    BASELINK_QUALIFIED_P (expr) = false;
2984  return expr;
2985}
2986
2987/* An expression of the form "A::template B" has been resolved to
2988   DECL.  Issue a diagnostic if B is not a template or template
2989   specialization.  */
2990
2991void
2992check_template_keyword (tree decl)
2993{
2994  /* The standard says:
2995
2996      [temp.names]
2997
2998      If a name prefixed by the keyword template is not a member
2999      template, the program is ill-formed.
3000
3001     DR 228 removed the restriction that the template be a member
3002     template.
3003
3004     DR 96, if accepted would add the further restriction that explicit
3005     template arguments must be provided if the template keyword is
3006     used, but, as of 2005-10-16, that DR is still in "drafting".  If
3007     this DR is accepted, then the semantic checks here can be
3008     simplified, as the entity named must in fact be a template
3009     specialization, rather than, as at present, a set of overloaded
3010     functions containing at least one template function.  */
3011  if (TREE_CODE (decl) != TEMPLATE_DECL
3012      && TREE_CODE (decl) != TEMPLATE_ID_EXPR)
3013    {
3014      if (VAR_P (decl))
3015	{
3016	  if (DECL_USE_TEMPLATE (decl)
3017	      && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
3018	    ;
3019	  else
3020	    permerror (input_location, "%qD is not a template", decl);
3021	}
3022      else if (!is_overloaded_fn (decl))
3023	permerror (input_location, "%qD is not a template", decl);
3024      else
3025	{
3026	  bool found = false;
3027
3028	  for (lkp_iterator iter (MAYBE_BASELINK_FUNCTIONS (decl));
3029	       !found && iter; ++iter)
3030	    {
3031	      tree fn = *iter;
3032	      if (TREE_CODE (fn) == TEMPLATE_DECL
3033		  || TREE_CODE (fn) == TEMPLATE_ID_EXPR
3034		  || (TREE_CODE (fn) == FUNCTION_DECL
3035		      && DECL_USE_TEMPLATE (fn)
3036		      && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (fn))))
3037		found = true;
3038	    }
3039	  if (!found)
3040	    permerror (input_location, "%qD is not a template", decl);
3041	}
3042    }
3043}
3044
3045/* Record that an access failure occurred on BASETYPE_PATH attempting
3046   to access DECL, where DIAG_DECL should be used for diagnostics.  */
3047
3048void
3049access_failure_info::record_access_failure (tree basetype_path,
3050					    tree decl, tree diag_decl)
3051{
3052  m_was_inaccessible = true;
3053  m_basetype_path = basetype_path;
3054  m_decl = decl;
3055  m_diag_decl = diag_decl;
3056}
3057
3058/* If an access failure was recorded, then attempt to locate an
3059   accessor function for the pertinent field.
3060   Otherwise, return NULL_TREE.  */
3061
3062tree
3063access_failure_info::get_any_accessor (bool const_p) const
3064{
3065  if (!was_inaccessible_p ())
3066    return NULL_TREE;
3067
3068  tree accessor
3069    = locate_field_accessor (m_basetype_path, m_diag_decl, const_p);
3070  if (!accessor)
3071    return NULL_TREE;
3072
3073  /* The accessor must itself be accessible for it to be a reasonable
3074     suggestion.  */
3075  if (!accessible_p (m_basetype_path, accessor, true))
3076    return NULL_TREE;
3077
3078  return accessor;
3079}
3080
3081/* Add a fix-it hint to RICHLOC suggesting the use of ACCESSOR_DECL, by
3082   replacing the primary location in RICHLOC with "accessor()".  */
3083
3084void
3085access_failure_info::add_fixit_hint (rich_location *richloc,
3086				     tree accessor_decl)
3087{
3088  pretty_printer pp;
3089  pp_string (&pp, IDENTIFIER_POINTER (DECL_NAME (accessor_decl)));
3090  pp_string (&pp, "()");
3091  richloc->add_fixit_replace (pp_formatted_text (&pp));
3092}
3093
3094/* If an access failure was recorded, then attempt to locate an
3095   accessor function for the pertinent field, and if one is
3096   available, add a note and fix-it hint suggesting using it.  */
3097
3098void
3099access_failure_info::maybe_suggest_accessor (bool const_p) const
3100{
3101  tree accessor = get_any_accessor (const_p);
3102  if (accessor == NULL_TREE)
3103    return;
3104  rich_location richloc (line_table, input_location);
3105  add_fixit_hint (&richloc, accessor);
3106  inform (&richloc, "field %q#D can be accessed via %q#D",
3107	  m_diag_decl, accessor);
3108}
3109
3110/* Subroutine of finish_class_member_access_expr.
3111   Issue an error about NAME not being a member of ACCESS_PATH (or
3112   OBJECT_TYPE), potentially providing a fix-it hint for misspelled
3113   names.  */
3114
3115static void
3116complain_about_unrecognized_member (tree access_path, tree name,
3117				    tree object_type)
3118{
3119  /* Attempt to provide a hint about misspelled names.  */
3120  tree guessed_id = lookup_member_fuzzy (access_path, name,
3121					 /*want_type=*/false);
3122  if (guessed_id == NULL_TREE)
3123    {
3124      /* No hint.  */
3125      error ("%q#T has no member named %qE",
3126	     TREE_CODE (access_path) == TREE_BINFO
3127	     ? TREE_TYPE (access_path) : object_type, name);
3128      return;
3129    }
3130
3131  location_t bogus_component_loc = input_location;
3132  gcc_rich_location rich_loc (bogus_component_loc);
3133
3134  /* Check that the guessed name is accessible along access_path.  */
3135  access_failure_info afi;
3136  lookup_member (access_path, guessed_id, /*protect=*/1,
3137		 /*want_type=*/false, /*complain=*/false,
3138		 &afi);
3139  if (afi.was_inaccessible_p ())
3140    {
3141      tree accessor = afi.get_any_accessor (TYPE_READONLY (object_type));
3142      if (accessor)
3143	{
3144	  /* The guessed name isn't directly accessible, but can be accessed
3145	     via an accessor member function.  */
3146	  afi.add_fixit_hint (&rich_loc, accessor);
3147	  error_at (&rich_loc,
3148		    "%q#T has no member named %qE;"
3149		    " did you mean %q#D? (accessible via %q#D)",
3150		    TREE_CODE (access_path) == TREE_BINFO
3151		    ? TREE_TYPE (access_path) : object_type,
3152		    name, afi.get_diag_decl (), accessor);
3153	}
3154      else
3155	{
3156	  /* The guessed name isn't directly accessible, and no accessor
3157	     member function could be found.  */
3158	  error_at (&rich_loc,
3159		    "%q#T has no member named %qE;"
3160		    " did you mean %q#D? (not accessible from this context)",
3161		    TREE_CODE (access_path) == TREE_BINFO
3162		    ? TREE_TYPE (access_path) : object_type,
3163		    name, afi.get_diag_decl ());
3164	  complain_about_access (afi.get_decl (), afi.get_diag_decl (),
3165				 afi.get_diag_decl (), false, ak_none);
3166	}
3167    }
3168  else
3169    {
3170      /* The guessed name is directly accessible; suggest it.  */
3171      rich_loc.add_fixit_misspelled_id (bogus_component_loc,
3172					guessed_id);
3173      error_at (&rich_loc,
3174		"%q#T has no member named %qE;"
3175		" did you mean %qE?",
3176		TREE_CODE (access_path) == TREE_BINFO
3177		? TREE_TYPE (access_path) : object_type,
3178		name, guessed_id);
3179    }
3180}
3181
3182/* This function is called by the parser to process a class member
3183   access expression of the form OBJECT.NAME.  NAME is a node used by
3184   the parser to represent a name; it is not yet a DECL.  It may,
3185   however, be a BASELINK where the BASELINK_FUNCTIONS is a
3186   TEMPLATE_ID_EXPR.  Templates must be looked up by the parser, and
3187   there is no reason to do the lookup twice, so the parser keeps the
3188   BASELINK.  TEMPLATE_P is true iff NAME was explicitly declared to
3189   be a template via the use of the "A::template B" syntax.  */
3190
3191tree
3192finish_class_member_access_expr (cp_expr object, tree name, bool template_p,
3193				 tsubst_flags_t complain)
3194{
3195  tree expr;
3196  tree object_type;
3197  tree member;
3198  tree access_path = NULL_TREE;
3199  tree orig_object = object;
3200  tree orig_name = name;
3201
3202  if (object == error_mark_node || name == error_mark_node)
3203    return error_mark_node;
3204
3205  /* If OBJECT is an ObjC class instance, we must obey ObjC access rules.  */
3206  if (!objc_is_public (object, name))
3207    return error_mark_node;
3208
3209  object_type = TREE_TYPE (object);
3210
3211  if (processing_template_decl)
3212    {
3213      if (/* If OBJECT is dependent, so is OBJECT.NAME.  */
3214	  type_dependent_object_expression_p (object)
3215	  /* If NAME is "f<args>", where either 'f' or 'args' is
3216	     dependent, then the expression is dependent.  */
3217	  || (TREE_CODE (name) == TEMPLATE_ID_EXPR
3218	      && dependent_template_id_p (TREE_OPERAND (name, 0),
3219					  TREE_OPERAND (name, 1)))
3220	  /* If NAME is "T::X" where "T" is dependent, then the
3221	     expression is dependent.  */
3222	  || (TREE_CODE (name) == SCOPE_REF
3223	      && TYPE_P (TREE_OPERAND (name, 0))
3224	      && dependent_scope_p (TREE_OPERAND (name, 0)))
3225	  /* If NAME is operator T where "T" is dependent, we can't
3226	     lookup until we instantiate the T.  */
3227	  || (TREE_CODE (name) == IDENTIFIER_NODE
3228	      && IDENTIFIER_CONV_OP_P (name)
3229	      && dependent_type_p (TREE_TYPE (name))))
3230	{
3231	dependent:
3232	  return build_min_nt_loc (UNKNOWN_LOCATION, COMPONENT_REF,
3233				   orig_object, orig_name, NULL_TREE);
3234	}
3235      object = build_non_dependent_expr (object);
3236    }
3237  else if (c_dialect_objc ()
3238	   && identifier_p (name)
3239	   && (expr = objc_maybe_build_component_ref (object, name)))
3240    return expr;
3241
3242  /* [expr.ref]
3243
3244     The type of the first expression shall be "class object" (of a
3245     complete type).  */
3246  if (!currently_open_class (object_type)
3247      && !complete_type_or_maybe_complain (object_type, object, complain))
3248    return error_mark_node;
3249  if (!CLASS_TYPE_P (object_type))
3250    {
3251      if (complain & tf_error)
3252	{
3253	  if (INDIRECT_TYPE_P (object_type)
3254	      && CLASS_TYPE_P (TREE_TYPE (object_type)))
3255	    error ("request for member %qD in %qE, which is of pointer "
3256		   "type %qT (maybe you meant to use %<->%> ?)",
3257		   name, object.get_value (), object_type);
3258	  else
3259	    error ("request for member %qD in %qE, which is of non-class "
3260		   "type %qT", name, object.get_value (), object_type);
3261	}
3262      return error_mark_node;
3263    }
3264
3265  if (BASELINK_P (name))
3266    /* A member function that has already been looked up.  */
3267    member = name;
3268  else
3269    {
3270      bool is_template_id = false;
3271      tree template_args = NULL_TREE;
3272      tree scope = NULL_TREE;
3273
3274      access_path = object_type;
3275
3276      if (TREE_CODE (name) == SCOPE_REF)
3277	{
3278	  /* A qualified name.  The qualifying class or namespace `S'
3279	     has already been looked up; it is either a TYPE or a
3280	     NAMESPACE_DECL.  */
3281	  scope = TREE_OPERAND (name, 0);
3282	  name = TREE_OPERAND (name, 1);
3283
3284	  /* If SCOPE is a namespace, then the qualified name does not
3285	     name a member of OBJECT_TYPE.  */
3286	  if (TREE_CODE (scope) == NAMESPACE_DECL)
3287	    {
3288	      if (complain & tf_error)
3289		error ("%<%D::%D%> is not a member of %qT",
3290		       scope, name, object_type);
3291	      return error_mark_node;
3292	    }
3293	}
3294
3295      if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
3296	{
3297	  is_template_id = true;
3298	  template_args = TREE_OPERAND (name, 1);
3299	  name = TREE_OPERAND (name, 0);
3300
3301	  if (!identifier_p (name))
3302	    name = OVL_NAME (name);
3303	}
3304
3305      if (scope)
3306	{
3307	  if (TREE_CODE (scope) == ENUMERAL_TYPE)
3308	    {
3309	      gcc_assert (!is_template_id);
3310	      /* Looking up a member enumerator (c++/56793).  */
3311	      if (!TYPE_CLASS_SCOPE_P (scope)
3312		  || !DERIVED_FROM_P (TYPE_CONTEXT (scope), object_type))
3313		{
3314		  if (complain & tf_error)
3315		    error ("%<%D::%D%> is not a member of %qT",
3316			   scope, name, object_type);
3317		  return error_mark_node;
3318		}
3319	      tree val = lookup_enumerator (scope, name);
3320	      if (!val)
3321		{
3322		  if (complain & tf_error)
3323		    error ("%qD is not a member of %qD",
3324			   name, scope);
3325		  return error_mark_node;
3326		}
3327
3328	      if (TREE_SIDE_EFFECTS (object))
3329		val = build2 (COMPOUND_EXPR, TREE_TYPE (val), object, val);
3330	      return val;
3331	    }
3332
3333	  gcc_assert (CLASS_TYPE_P (scope));
3334	  gcc_assert (identifier_p (name) || TREE_CODE (name) == BIT_NOT_EXPR);
3335
3336	  if (constructor_name_p (name, scope))
3337	    {
3338	      if (complain & tf_error)
3339		error ("cannot call constructor %<%T::%D%> directly",
3340		       scope, name);
3341	      return error_mark_node;
3342	    }
3343
3344	  /* Find the base of OBJECT_TYPE corresponding to SCOPE.  */
3345	  access_path = lookup_base (object_type, scope, ba_check,
3346				     NULL, complain);
3347	  if (access_path == error_mark_node)
3348	    return error_mark_node;
3349	  if (!access_path)
3350	    {
3351	      if (any_dependent_bases_p (object_type))
3352		goto dependent;
3353	      if (complain & tf_error)
3354		error ("%qT is not a base of %qT", scope, object_type);
3355	      return error_mark_node;
3356	    }
3357	}
3358
3359      if (TREE_CODE (name) == BIT_NOT_EXPR)
3360	{
3361	  if (dependent_type_p (object_type))
3362	    /* The destructor isn't declared yet.  */
3363	    goto dependent;
3364	  member = lookup_destructor (object, scope, name, complain);
3365	}
3366      else
3367	{
3368	  /* Look up the member.  */
3369	  access_failure_info afi;
3370	  if (processing_template_decl)
3371	    /* Even though this class member access expression is at this
3372	       point not dependent, the member itself may be dependent, and
3373	       we must not potentially push a access check for a dependent
3374	       member onto TI_DEFERRED_ACCESS_CHECKS.  So don't check access
3375	       ahead of time here; we're going to redo this member lookup at
3376	       instantiation time anyway.  */
3377	    push_deferring_access_checks (dk_no_check);
3378	  member = lookup_member (access_path, name, /*protect=*/1,
3379				  /*want_type=*/false, complain,
3380				  &afi);
3381	  if (processing_template_decl)
3382	    pop_deferring_access_checks ();
3383	  afi.maybe_suggest_accessor (TYPE_READONLY (object_type));
3384	  if (member == NULL_TREE)
3385	    {
3386	      if (dependent_type_p (object_type))
3387		/* Try again at instantiation time.  */
3388		goto dependent;
3389	      if (complain & tf_error)
3390		complain_about_unrecognized_member (access_path, name,
3391						    object_type);
3392	      return error_mark_node;
3393	    }
3394	  if (member == error_mark_node)
3395	    return error_mark_node;
3396	  if (DECL_P (member)
3397	      && any_dependent_type_attributes_p (DECL_ATTRIBUTES (member)))
3398	    /* Dependent type attributes on the decl mean that the TREE_TYPE is
3399	       wrong, so don't use it.  */
3400	    goto dependent;
3401	  if (TREE_CODE (member) == USING_DECL && DECL_DEPENDENT_P (member))
3402	    goto dependent;
3403	}
3404
3405      if (is_template_id)
3406	{
3407	  tree templ = member;
3408
3409	  if (BASELINK_P (templ))
3410	    member = lookup_template_function (templ, template_args);
3411	  else if (variable_template_p (templ))
3412	    member = (lookup_and_finish_template_variable
3413		      (templ, template_args, complain));
3414	  else
3415	    {
3416	      if (complain & tf_error)
3417		error ("%qD is not a member template function", name);
3418	      return error_mark_node;
3419	    }
3420	}
3421    }
3422
3423  if (TREE_UNAVAILABLE (member))
3424    error_unavailable_use (member, NULL_TREE);
3425  else if (TREE_DEPRECATED (member))
3426    warn_deprecated_use (member, NULL_TREE);
3427
3428  if (template_p)
3429    check_template_keyword (member);
3430
3431  expr = build_class_member_access_expr (object, member, access_path,
3432					 /*preserve_reference=*/false,
3433					 complain);
3434  if (processing_template_decl && expr != error_mark_node)
3435    {
3436      if (BASELINK_P (member))
3437	{
3438	  if (TREE_CODE (orig_name) == SCOPE_REF)
3439	    BASELINK_QUALIFIED_P (member) = 1;
3440	  orig_name = member;
3441	}
3442      return build_min_non_dep (COMPONENT_REF, expr,
3443				orig_object, orig_name,
3444				NULL_TREE);
3445    }
3446
3447  return expr;
3448}
3449
3450/* Build a COMPONENT_REF of OBJECT and MEMBER with the appropriate
3451   type.  */
3452
3453tree
3454build_simple_component_ref (tree object, tree member)
3455{
3456  tree type = cp_build_qualified_type (TREE_TYPE (member),
3457				       cp_type_quals (TREE_TYPE (object)));
3458  return build3_loc (input_location,
3459		     COMPONENT_REF, type,
3460		     object, member, NULL_TREE);
3461}
3462
3463/* Return an expression for the MEMBER_NAME field in the internal
3464   representation of PTRMEM, a pointer-to-member function.  (Each
3465   pointer-to-member function type gets its own RECORD_TYPE so it is
3466   more convenient to access the fields by name than by FIELD_DECL.)
3467   This routine converts the NAME to a FIELD_DECL and then creates the
3468   node for the complete expression.  */
3469
3470tree
3471build_ptrmemfunc_access_expr (tree ptrmem, tree member_name)
3472{
3473  tree ptrmem_type;
3474  tree member;
3475
3476  if (TREE_CODE (ptrmem) == CONSTRUCTOR)
3477    {
3478      for (auto &e: CONSTRUCTOR_ELTS (ptrmem))
3479	if (e.index && DECL_P (e.index) && DECL_NAME (e.index) == member_name)
3480	  return e.value;
3481      gcc_unreachable ();
3482    }
3483
3484  /* This code is a stripped down version of
3485     build_class_member_access_expr.  It does not work to use that
3486     routine directly because it expects the object to be of class
3487     type.  */
3488  ptrmem_type = TREE_TYPE (ptrmem);
3489  gcc_assert (TYPE_PTRMEMFUNC_P (ptrmem_type));
3490  for (member = TYPE_FIELDS (ptrmem_type); member;
3491       member = DECL_CHAIN (member))
3492    if (DECL_NAME (member) == member_name)
3493      break;
3494  return build_simple_component_ref (ptrmem, member);
3495}
3496
3497/* Return a TREE_LIST of namespace-scope overloads for the given operator,
3498   and for any other relevant operator.  */
3499
3500static tree
3501op_unqualified_lookup (tree_code code, bool is_assign)
3502{
3503  tree lookups = NULL_TREE;
3504
3505  if (cxx_dialect >= cxx20 && !is_assign)
3506    {
3507      if (code == NE_EXPR)
3508	{
3509	  /* != can get rewritten in terms of ==.  */
3510	  tree fnname = ovl_op_identifier (false, EQ_EXPR);
3511	  if (tree fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE))
3512	    lookups = tree_cons (fnname, fns, lookups);
3513	}
3514      else if (code == GT_EXPR || code == LE_EXPR
3515	       || code == LT_EXPR || code == GE_EXPR)
3516	{
3517	  /* These can get rewritten in terms of <=>.  */
3518	  tree fnname = ovl_op_identifier (false, SPACESHIP_EXPR);
3519	  if (tree fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE))
3520	    lookups = tree_cons (fnname, fns, lookups);
3521	}
3522    }
3523
3524  tree fnname = ovl_op_identifier (is_assign, code);
3525  if (tree fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE))
3526    lookups = tree_cons (fnname, fns, lookups);
3527
3528  if (lookups)
3529    return lookups;
3530  else
3531    return build_tree_list (NULL_TREE, NULL_TREE);
3532}
3533
3534/* Create a DEPENDENT_OPERATOR_TYPE for a dependent operator expression of
3535   the given operator.  LOOKUPS, if non-NULL, is the result of phase 1
3536   name lookup for the given operator.  */
3537
3538tree
3539build_dependent_operator_type (tree lookups, tree_code code, bool is_assign)
3540{
3541  if (lookups)
3542    /* We're partially instantiating a dependent operator expression, and
3543       LOOKUPS is the result of phase 1 name lookup that we performed
3544       earlier at template definition time, so just reuse the corresponding
3545       DEPENDENT_OPERATOR_TYPE.  */
3546    return TREE_TYPE (lookups);
3547
3548  /* Otherwise we're processing a dependent operator expression at template
3549     definition time, so perform phase 1 name lookup now.  */
3550  lookups = op_unqualified_lookup (code, is_assign);
3551
3552  tree type = cxx_make_type (DEPENDENT_OPERATOR_TYPE);
3553  DEPENDENT_OPERATOR_TYPE_SAVED_LOOKUPS (type) = lookups;
3554  TREE_TYPE (lookups) = type;
3555  return type;
3556}
3557
3558/* Given an expression PTR for a pointer, return an expression
3559   for the value pointed to.
3560   ERRORSTRING is the name of the operator to appear in error messages.
3561
3562   This function may need to overload OPERATOR_FNNAME.
3563   Must also handle REFERENCE_TYPEs for C++.  */
3564
3565tree
3566build_x_indirect_ref (location_t loc, tree expr, ref_operator errorstring,
3567		      tree lookups, tsubst_flags_t complain)
3568{
3569  tree orig_expr = expr;
3570  tree rval;
3571  tree overload = NULL_TREE;
3572
3573  if (processing_template_decl)
3574    {
3575      /* Retain the type if we know the operand is a pointer.  */
3576      if (TREE_TYPE (expr) && INDIRECT_TYPE_P (TREE_TYPE (expr)))
3577	{
3578	  if (expr == current_class_ptr
3579	      || (TREE_CODE (expr) == NOP_EXPR
3580		  && TREE_OPERAND (expr, 0) == current_class_ptr
3581		  && (same_type_ignoring_top_level_qualifiers_p
3582			(TREE_TYPE (expr), TREE_TYPE (current_class_ptr)))))
3583	    return current_class_ref;
3584	  return build_min (INDIRECT_REF, TREE_TYPE (TREE_TYPE (expr)), expr);
3585	}
3586      if (type_dependent_expression_p (expr))
3587	{
3588	  expr = build_min_nt_loc (loc, INDIRECT_REF, expr);
3589	  TREE_TYPE (expr)
3590	    = build_dependent_operator_type (lookups, INDIRECT_REF, false);
3591	  return expr;
3592	}
3593      expr = build_non_dependent_expr (expr);
3594    }
3595
3596  rval = build_new_op (loc, INDIRECT_REF, LOOKUP_NORMAL, expr,
3597		       NULL_TREE, NULL_TREE, lookups,
3598		       &overload, complain);
3599  if (!rval)
3600    rval = cp_build_indirect_ref (loc, expr, errorstring, complain);
3601
3602  if (processing_template_decl && rval != error_mark_node)
3603    {
3604      if (overload != NULL_TREE)
3605	return (build_min_non_dep_op_overload
3606		(INDIRECT_REF, rval, overload, orig_expr));
3607
3608      return build_min_non_dep (INDIRECT_REF, rval, orig_expr);
3609    }
3610  else
3611    return rval;
3612}
3613
3614/* Like c-family strict_aliasing_warning, but don't warn for dependent
3615   types or expressions.  */
3616
3617static bool
3618cp_strict_aliasing_warning (location_t loc, tree type, tree expr)
3619{
3620  if (processing_template_decl)
3621    {
3622      tree e = expr;
3623      STRIP_NOPS (e);
3624      if (dependent_type_p (type) || type_dependent_expression_p (e))
3625	return false;
3626    }
3627  return strict_aliasing_warning (loc, type, expr);
3628}
3629
3630/* The implementation of the above, and of indirection implied by other
3631   constructs.  If DO_FOLD is true, fold away INDIRECT_REF of ADDR_EXPR.  */
3632
3633static tree
3634cp_build_indirect_ref_1 (location_t loc, tree ptr, ref_operator errorstring,
3635			 tsubst_flags_t complain, bool do_fold)
3636{
3637  tree pointer, type;
3638
3639  /* RO_NULL should only be used with the folding entry points below, not
3640     cp_build_indirect_ref.  */
3641  gcc_checking_assert (errorstring != RO_NULL || do_fold);
3642
3643  if (ptr == current_class_ptr
3644      || (TREE_CODE (ptr) == NOP_EXPR
3645	  && TREE_OPERAND (ptr, 0) == current_class_ptr
3646	  && (same_type_ignoring_top_level_qualifiers_p
3647	      (TREE_TYPE (ptr), TREE_TYPE (current_class_ptr)))))
3648    return current_class_ref;
3649
3650  pointer = (TYPE_REF_P (TREE_TYPE (ptr))
3651	     ? ptr : decay_conversion (ptr, complain));
3652  if (pointer == error_mark_node)
3653    return error_mark_node;
3654
3655  type = TREE_TYPE (pointer);
3656
3657  if (INDIRECT_TYPE_P (type))
3658    {
3659      /* [expr.unary.op]
3660
3661	 If the type of the expression is "pointer to T," the type
3662	 of  the  result  is  "T."  */
3663      tree t = TREE_TYPE (type);
3664
3665      if ((CONVERT_EXPR_P (ptr)
3666	   || TREE_CODE (ptr) == VIEW_CONVERT_EXPR)
3667	  && (!CLASS_TYPE_P (t) || !CLASSTYPE_EMPTY_P (t)))
3668	{
3669	  /* If a warning is issued, mark it to avoid duplicates from
3670	     the backend.  This only needs to be done at
3671	     warn_strict_aliasing > 2.  */
3672	  if (warn_strict_aliasing > 2
3673	      && cp_strict_aliasing_warning (EXPR_LOCATION (ptr),
3674					     type, TREE_OPERAND (ptr, 0)))
3675	    suppress_warning (ptr, OPT_Wstrict_aliasing);
3676	}
3677
3678      if (VOID_TYPE_P (t))
3679	{
3680	  /* A pointer to incomplete type (other than cv void) can be
3681	     dereferenced [expr.unary.op]/1  */
3682          if (complain & tf_error)
3683            error_at (loc, "%qT is not a pointer-to-object type", type);
3684	  return error_mark_node;
3685	}
3686      else if (do_fold && TREE_CODE (pointer) == ADDR_EXPR
3687	       && same_type_p (t, TREE_TYPE (TREE_OPERAND (pointer, 0))))
3688	/* The POINTER was something like `&x'.  We simplify `*&x' to
3689	   `x'.  */
3690	return TREE_OPERAND (pointer, 0);
3691      else
3692	{
3693	  tree ref = build1 (INDIRECT_REF, t, pointer);
3694
3695	  /* We *must* set TREE_READONLY when dereferencing a pointer to const,
3696	     so that we get the proper error message if the result is used
3697	     to assign to.  Also, &* is supposed to be a no-op.  */
3698	  TREE_READONLY (ref) = CP_TYPE_CONST_P (t);
3699	  TREE_THIS_VOLATILE (ref) = CP_TYPE_VOLATILE_P (t);
3700	  TREE_SIDE_EFFECTS (ref)
3701	    = (TREE_THIS_VOLATILE (ref) || TREE_SIDE_EFFECTS (pointer));
3702	  return ref;
3703	}
3704    }
3705  else if (!(complain & tf_error))
3706    /* Don't emit any errors; we'll just return ERROR_MARK_NODE later.  */
3707    ;
3708  /* `pointer' won't be an error_mark_node if we were given a
3709     pointer to member, so it's cool to check for this here.  */
3710  else if (TYPE_PTRMEM_P (type))
3711    switch (errorstring)
3712      {
3713         case RO_ARRAY_INDEXING:
3714           error_at (loc,
3715		     "invalid use of array indexing on pointer to member");
3716           break;
3717         case RO_UNARY_STAR:
3718           error_at (loc, "invalid use of unary %<*%> on pointer to member");
3719           break;
3720         case RO_IMPLICIT_CONVERSION:
3721           error_at (loc, "invalid use of implicit conversion on pointer "
3722		     "to member");
3723           break;
3724         case RO_ARROW_STAR:
3725           error_at (loc, "left hand operand of %<->*%> must be a pointer to "
3726		     "class, but is a pointer to member of type %qT", type);
3727           break;
3728         default:
3729           gcc_unreachable ();
3730      }
3731  else if (pointer != error_mark_node)
3732    invalid_indirection_error (loc, type, errorstring);
3733
3734  return error_mark_node;
3735}
3736
3737/* Entry point used by c-common, which expects folding.  */
3738
3739tree
3740build_indirect_ref (location_t loc, tree ptr, ref_operator errorstring)
3741{
3742  return cp_build_indirect_ref_1 (loc, ptr, errorstring,
3743				  tf_warning_or_error, true);
3744}
3745
3746/* Entry point used by internal indirection needs that don't correspond to any
3747   syntactic construct.  */
3748
3749tree
3750cp_build_fold_indirect_ref (tree pointer)
3751{
3752  return cp_build_indirect_ref_1 (input_location, pointer, RO_NULL,
3753				  tf_warning_or_error, true);
3754}
3755
3756/* Entry point used by indirection needs that correspond to some syntactic
3757   construct.  */
3758
3759tree
3760cp_build_indirect_ref (location_t loc, tree ptr, ref_operator errorstring,
3761		       tsubst_flags_t complain)
3762{
3763  return cp_build_indirect_ref_1 (loc, ptr, errorstring, complain, false);
3764}
3765
3766/* This handles expressions of the form "a[i]", which denotes
3767   an array reference.
3768
3769   This is logically equivalent in C to *(a+i), but we may do it differently.
3770   If A is a variable or a member, we generate a primitive ARRAY_REF.
3771   This avoids forcing the array out of registers, and can work on
3772   arrays that are not lvalues (for example, members of structures returned
3773   by functions).
3774
3775   If INDEX is of some user-defined type, it must be converted to
3776   integer type.  Otherwise, to make a compatible PLUS_EXPR, it
3777   will inherit the type of the array, which will be some pointer type.
3778
3779   LOC is the location to use in building the array reference.  */
3780
3781tree
3782cp_build_array_ref (location_t loc, tree array, tree idx,
3783		    tsubst_flags_t complain)
3784{
3785  tree ret;
3786
3787  if (idx == 0)
3788    {
3789      if (complain & tf_error)
3790	error_at (loc, "subscript missing in array reference");
3791      return error_mark_node;
3792    }
3793
3794  if (TREE_TYPE (array) == error_mark_node
3795      || TREE_TYPE (idx) == error_mark_node)
3796    return error_mark_node;
3797
3798  /* If ARRAY is a COMPOUND_EXPR or COND_EXPR, move our reference
3799     inside it.  */
3800  switch (TREE_CODE (array))
3801    {
3802    case COMPOUND_EXPR:
3803      {
3804	tree value = cp_build_array_ref (loc, TREE_OPERAND (array, 1), idx,
3805					 complain);
3806	ret = build2 (COMPOUND_EXPR, TREE_TYPE (value),
3807		      TREE_OPERAND (array, 0), value);
3808	SET_EXPR_LOCATION (ret, loc);
3809	return ret;
3810      }
3811
3812    case COND_EXPR:
3813      ret = build_conditional_expr
3814	       (loc, TREE_OPERAND (array, 0),
3815	       cp_build_array_ref (loc, TREE_OPERAND (array, 1), idx,
3816				   complain),
3817	       cp_build_array_ref (loc, TREE_OPERAND (array, 2), idx,
3818				   complain),
3819	       complain);
3820      protected_set_expr_location (ret, loc);
3821      return ret;
3822
3823    default:
3824      break;
3825    }
3826
3827  bool non_lvalue = convert_vector_to_array_for_subscript (loc, &array, idx);
3828
3829  if (TREE_CODE (TREE_TYPE (array)) == ARRAY_TYPE)
3830    {
3831      tree rval, type;
3832
3833      warn_array_subscript_with_type_char (loc, idx);
3834
3835      if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (idx)))
3836	{
3837	  if (complain & tf_error)
3838	    error_at (loc, "array subscript is not an integer");
3839	  return error_mark_node;
3840	}
3841
3842      /* Apply integral promotions *after* noticing character types.
3843	 (It is unclear why we do these promotions -- the standard
3844	 does not say that we should.  In fact, the natural thing would
3845	 seem to be to convert IDX to ptrdiff_t; we're performing
3846	 pointer arithmetic.)  */
3847      idx = cp_perform_integral_promotions (idx, complain);
3848
3849      idx = maybe_fold_non_dependent_expr (idx, complain);
3850
3851      /* An array that is indexed by a non-constant
3852	 cannot be stored in a register; we must be able to do
3853	 address arithmetic on its address.
3854	 Likewise an array of elements of variable size.  */
3855      if (TREE_CODE (idx) != INTEGER_CST
3856	  || (COMPLETE_TYPE_P (TREE_TYPE (TREE_TYPE (array)))
3857	      && (TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (array))))
3858		  != INTEGER_CST)))
3859	{
3860	  if (!cxx_mark_addressable (array, true))
3861	    return error_mark_node;
3862	}
3863
3864      /* An array that is indexed by a constant value which is not within
3865	 the array bounds cannot be stored in a register either; because we
3866	 would get a crash in store_bit_field/extract_bit_field when trying
3867	 to access a non-existent part of the register.  */
3868      if (TREE_CODE (idx) == INTEGER_CST
3869	  && TYPE_DOMAIN (TREE_TYPE (array))
3870	  && ! int_fits_type_p (idx, TYPE_DOMAIN (TREE_TYPE (array))))
3871	{
3872	  if (!cxx_mark_addressable (array))
3873	    return error_mark_node;
3874	}
3875
3876      /* Note in C++ it is valid to subscript a `register' array, since
3877	 it is valid to take the address of something with that
3878	 storage specification.  */
3879      if (extra_warnings)
3880	{
3881	  tree foo = array;
3882	  while (TREE_CODE (foo) == COMPONENT_REF)
3883	    foo = TREE_OPERAND (foo, 0);
3884	  if (VAR_P (foo) && DECL_REGISTER (foo)
3885	      && (complain & tf_warning))
3886	    warning_at (loc, OPT_Wextra,
3887			"subscripting array declared %<register%>");
3888	}
3889
3890      type = TREE_TYPE (TREE_TYPE (array));
3891      rval = build4 (ARRAY_REF, type, array, idx, NULL_TREE, NULL_TREE);
3892      /* Array ref is const/volatile if the array elements are
3893	 or if the array is..  */
3894      TREE_READONLY (rval)
3895	|= (CP_TYPE_CONST_P (type) | TREE_READONLY (array));
3896      TREE_SIDE_EFFECTS (rval)
3897	|= (CP_TYPE_VOLATILE_P (type) | TREE_SIDE_EFFECTS (array));
3898      TREE_THIS_VOLATILE (rval)
3899	|= (CP_TYPE_VOLATILE_P (type) | TREE_THIS_VOLATILE (array));
3900      ret = require_complete_type_sfinae (rval, complain);
3901      protected_set_expr_location (ret, loc);
3902      if (non_lvalue)
3903	ret = non_lvalue_loc (loc, ret);
3904      return ret;
3905    }
3906
3907  {
3908    tree ar = cp_default_conversion (array, complain);
3909    tree ind = cp_default_conversion (idx, complain);
3910    tree first = NULL_TREE;
3911
3912    if (flag_strong_eval_order == 2 && TREE_SIDE_EFFECTS (ind))
3913      ar = first = save_expr (ar);
3914
3915    /* Put the integer in IND to simplify error checking.  */
3916    if (TREE_CODE (TREE_TYPE (ar)) == INTEGER_TYPE)
3917      std::swap (ar, ind);
3918
3919    if (ar == error_mark_node || ind == error_mark_node)
3920      return error_mark_node;
3921
3922    if (!TYPE_PTR_P (TREE_TYPE (ar)))
3923      {
3924	if (complain & tf_error)
3925	  error_at (loc, "subscripted value is neither array nor pointer");
3926	return error_mark_node;
3927      }
3928    if (TREE_CODE (TREE_TYPE (ind)) != INTEGER_TYPE)
3929      {
3930	if (complain & tf_error)
3931	  error_at (loc, "array subscript is not an integer");
3932	return error_mark_node;
3933      }
3934
3935    warn_array_subscript_with_type_char (loc, idx);
3936
3937    ret = cp_build_binary_op (input_location, PLUS_EXPR, ar, ind, complain);
3938    if (first)
3939      ret = build2_loc (loc, COMPOUND_EXPR, TREE_TYPE (ret), first, ret);
3940    ret = cp_build_indirect_ref (loc, ret, RO_ARRAY_INDEXING, complain);
3941    protected_set_expr_location (ret, loc);
3942    if (non_lvalue)
3943      ret = non_lvalue_loc (loc, ret);
3944    return ret;
3945  }
3946}
3947
3948/* Entry point for Obj-C++.  */
3949
3950tree
3951build_array_ref (location_t loc, tree array, tree idx)
3952{
3953  return cp_build_array_ref (loc, array, idx, tf_warning_or_error);
3954}
3955
3956/* Resolve a pointer to member function.  INSTANCE is the object
3957   instance to use, if the member points to a virtual member.
3958
3959   This used to avoid checking for virtual functions if basetype
3960   has no virtual functions, according to an earlier ANSI draft.
3961   With the final ISO C++ rules, such an optimization is
3962   incorrect: A pointer to a derived member can be static_cast
3963   to pointer-to-base-member, as long as the dynamic object
3964   later has the right member.  So now we only do this optimization
3965   when we know the dynamic type of the object.  */
3966
3967tree
3968get_member_function_from_ptrfunc (tree *instance_ptrptr, tree function,
3969				  tsubst_flags_t complain)
3970{
3971  if (TREE_CODE (function) == OFFSET_REF)
3972    function = TREE_OPERAND (function, 1);
3973
3974  if (TYPE_PTRMEMFUNC_P (TREE_TYPE (function)))
3975    {
3976      tree idx, delta, e1, e2, e3, vtbl;
3977      bool nonvirtual;
3978      tree fntype = TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (function));
3979      tree basetype = TYPE_METHOD_BASETYPE (TREE_TYPE (fntype));
3980
3981      tree instance_ptr = *instance_ptrptr;
3982      tree instance_save_expr = 0;
3983      if (instance_ptr == error_mark_node)
3984	{
3985	  if (TREE_CODE (function) == PTRMEM_CST)
3986	    {
3987	      /* Extracting the function address from a pmf is only
3988		 allowed with -Wno-pmf-conversions. It only works for
3989		 pmf constants.  */
3990	      e1 = build_addr_func (PTRMEM_CST_MEMBER (function), complain);
3991	      e1 = convert (fntype, e1);
3992	      return e1;
3993	    }
3994	  else
3995	    {
3996	      if (complain & tf_error)
3997		error ("object missing in use of %qE", function);
3998	      return error_mark_node;
3999	    }
4000	}
4001
4002      /* True if we know that the dynamic type of the object doesn't have
4003	 virtual functions, so we can assume the PFN field is a pointer.  */
4004      nonvirtual = (COMPLETE_TYPE_P (basetype)
4005		    && !TYPE_POLYMORPHIC_P (basetype)
4006		    && resolves_to_fixed_type_p (instance_ptr, 0));
4007
4008      /* If we don't really have an object (i.e. in an ill-formed
4009	 conversion from PMF to pointer), we can't resolve virtual
4010	 functions anyway.  */
4011      if (!nonvirtual && is_dummy_object (instance_ptr))
4012	nonvirtual = true;
4013
4014      if (TREE_SIDE_EFFECTS (instance_ptr))
4015	instance_ptr = instance_save_expr = save_expr (instance_ptr);
4016
4017      if (TREE_SIDE_EFFECTS (function))
4018	function = save_expr (function);
4019
4020      /* Start by extracting all the information from the PMF itself.  */
4021      e3 = pfn_from_ptrmemfunc (function);
4022      delta = delta_from_ptrmemfunc (function);
4023      idx = build1 (NOP_EXPR, vtable_index_type, e3);
4024      switch (TARGET_PTRMEMFUNC_VBIT_LOCATION)
4025	{
4026	  int flag_sanitize_save;
4027	case ptrmemfunc_vbit_in_pfn:
4028	  e1 = cp_build_binary_op (input_location,
4029				   BIT_AND_EXPR, idx, integer_one_node,
4030				   complain);
4031	  idx = cp_build_binary_op (input_location,
4032				    MINUS_EXPR, idx, integer_one_node,
4033				    complain);
4034	  if (idx == error_mark_node)
4035	    return error_mark_node;
4036	  break;
4037
4038	case ptrmemfunc_vbit_in_delta:
4039	  e1 = cp_build_binary_op (input_location,
4040				   BIT_AND_EXPR, delta, integer_one_node,
4041				   complain);
4042	  /* Don't instrument the RSHIFT_EXPR we're about to create because
4043	     we're going to use DELTA number of times, and that wouldn't play
4044	     well with SAVE_EXPRs therein.  */
4045	  flag_sanitize_save = flag_sanitize;
4046	  flag_sanitize = 0;
4047	  delta = cp_build_binary_op (input_location,
4048				      RSHIFT_EXPR, delta, integer_one_node,
4049				      complain);
4050	  flag_sanitize = flag_sanitize_save;
4051	  if (delta == error_mark_node)
4052	    return error_mark_node;
4053	  break;
4054
4055	default:
4056	  gcc_unreachable ();
4057	}
4058
4059      if (e1 == error_mark_node)
4060	return error_mark_node;
4061
4062      /* Convert down to the right base before using the instance.  A
4063	 special case is that in a pointer to member of class C, C may
4064	 be incomplete.  In that case, the function will of course be
4065	 a member of C, and no conversion is required.  In fact,
4066	 lookup_base will fail in that case, because incomplete
4067	 classes do not have BINFOs.  */
4068      if (!same_type_ignoring_top_level_qualifiers_p
4069	  (basetype, TREE_TYPE (TREE_TYPE (instance_ptr))))
4070	{
4071	  basetype = lookup_base (TREE_TYPE (TREE_TYPE (instance_ptr)),
4072				  basetype, ba_check, NULL, complain);
4073	  instance_ptr = build_base_path (PLUS_EXPR, instance_ptr, basetype,
4074					  1, complain);
4075	  if (instance_ptr == error_mark_node)
4076	    return error_mark_node;
4077	}
4078      /* ...and then the delta in the PMF.  */
4079      instance_ptr = fold_build_pointer_plus (instance_ptr, delta);
4080
4081      /* Hand back the adjusted 'this' argument to our caller.  */
4082      *instance_ptrptr = instance_ptr;
4083
4084      if (nonvirtual)
4085	/* Now just return the pointer.  */
4086	return e3;
4087
4088      /* Next extract the vtable pointer from the object.  */
4089      vtbl = build1 (NOP_EXPR, build_pointer_type (vtbl_ptr_type_node),
4090		     instance_ptr);
4091      vtbl = cp_build_fold_indirect_ref (vtbl);
4092      if (vtbl == error_mark_node)
4093	return error_mark_node;
4094
4095      /* Finally, extract the function pointer from the vtable.  */
4096      e2 = fold_build_pointer_plus_loc (input_location, vtbl, idx);
4097      e2 = cp_build_fold_indirect_ref (e2);
4098      if (e2 == error_mark_node)
4099	return error_mark_node;
4100      TREE_CONSTANT (e2) = 1;
4101
4102      /* When using function descriptors, the address of the
4103	 vtable entry is treated as a function pointer.  */
4104      if (TARGET_VTABLE_USES_DESCRIPTORS)
4105	e2 = build1 (NOP_EXPR, TREE_TYPE (e2),
4106		     cp_build_addr_expr (e2, complain));
4107
4108      e2 = fold_convert (TREE_TYPE (e3), e2);
4109      e1 = build_conditional_expr (input_location, e1, e2, e3, complain);
4110      if (e1 == error_mark_node)
4111	return error_mark_node;
4112
4113      /* Make sure this doesn't get evaluated first inside one of the
4114	 branches of the COND_EXPR.  */
4115      if (instance_save_expr)
4116	e1 = build2 (COMPOUND_EXPR, TREE_TYPE (e1),
4117		     instance_save_expr, e1);
4118
4119      function = e1;
4120    }
4121  return function;
4122}
4123
4124/* Used by the C-common bits.  */
4125tree
4126build_function_call (location_t /*loc*/,
4127		     tree function, tree params)
4128{
4129  return cp_build_function_call (function, params, tf_warning_or_error);
4130}
4131
4132/* Used by the C-common bits.  */
4133tree
4134build_function_call_vec (location_t /*loc*/, vec<location_t> /*arg_loc*/,
4135			 tree function, vec<tree, va_gc> *params,
4136			 vec<tree, va_gc> * /*origtypes*/, tree orig_function)
4137{
4138  vec<tree, va_gc> *orig_params = params;
4139  tree ret = cp_build_function_call_vec (function, &params,
4140					 tf_warning_or_error, orig_function);
4141
4142  /* cp_build_function_call_vec can reallocate PARAMS by adding
4143     default arguments.  That should never happen here.  Verify
4144     that.  */
4145  gcc_assert (params == orig_params);
4146
4147  return ret;
4148}
4149
4150/* Build a function call using a tree list of arguments.  */
4151
4152static tree
4153cp_build_function_call (tree function, tree params, tsubst_flags_t complain)
4154{
4155  tree ret;
4156
4157  releasing_vec vec;
4158  for (; params != NULL_TREE; params = TREE_CHAIN (params))
4159    vec_safe_push (vec, TREE_VALUE (params));
4160  ret = cp_build_function_call_vec (function, &vec, complain);
4161  return ret;
4162}
4163
4164/* Build a function call using varargs.  */
4165
4166tree
4167cp_build_function_call_nary (tree function, tsubst_flags_t complain, ...)
4168{
4169  va_list args;
4170  tree ret, t;
4171
4172  releasing_vec vec;
4173  va_start (args, complain);
4174  for (t = va_arg (args, tree); t != NULL_TREE; t = va_arg (args, tree))
4175    vec_safe_push (vec, t);
4176  va_end (args);
4177  ret = cp_build_function_call_vec (function, &vec, complain);
4178  return ret;
4179}
4180
4181/* Build a function call using a vector of arguments.
4182   If FUNCTION is the result of resolving an overloaded target built-in,
4183   ORIG_FNDECL is the original function decl, otherwise it is null.
4184   PARAMS may be NULL if there are no parameters.  This changes the
4185   contents of PARAMS.  */
4186
4187tree
4188cp_build_function_call_vec (tree function, vec<tree, va_gc> **params,
4189			    tsubst_flags_t complain, tree orig_fndecl)
4190{
4191  tree fntype, fndecl;
4192  int is_method;
4193  tree original = function;
4194  int nargs;
4195  tree *argarray;
4196  tree parm_types;
4197  vec<tree, va_gc> *allocated = NULL;
4198  tree ret;
4199
4200  /* For Objective-C, convert any calls via a cast to OBJC_TYPE_REF
4201     expressions, like those used for ObjC messenger dispatches.  */
4202  if (params != NULL && !vec_safe_is_empty (*params))
4203    function = objc_rewrite_function_call (function, (**params)[0]);
4204
4205  /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
4206     Strip such NOP_EXPRs, since FUNCTION is used in non-lvalue context.  */
4207  if (TREE_CODE (function) == NOP_EXPR
4208      && TREE_TYPE (function) == TREE_TYPE (TREE_OPERAND (function, 0)))
4209    function = TREE_OPERAND (function, 0);
4210
4211  if (TREE_CODE (function) == FUNCTION_DECL)
4212    {
4213      if (!mark_used (function, complain))
4214	return error_mark_node;
4215      fndecl = function;
4216
4217      /* Convert anything with function type to a pointer-to-function.  */
4218      if (DECL_MAIN_P (function))
4219	{
4220	  if (complain & tf_error)
4221	    pedwarn (input_location, OPT_Wpedantic,
4222		     "ISO C++ forbids calling %<::main%> from within program");
4223	  else
4224	    return error_mark_node;
4225	}
4226      function = build_addr_func (function, complain);
4227    }
4228  else
4229    {
4230      fndecl = NULL_TREE;
4231
4232      function = build_addr_func (function, complain);
4233    }
4234
4235  if (function == error_mark_node)
4236    return error_mark_node;
4237
4238  fntype = TREE_TYPE (function);
4239
4240  if (TYPE_PTRMEMFUNC_P (fntype))
4241    {
4242      if (complain & tf_error)
4243	error ("must use %<.*%> or %<->*%> to call pointer-to-member "
4244	       "function in %<%E (...)%>, e.g. %<(... ->* %E) (...)%>",
4245	       original, original);
4246      return error_mark_node;
4247    }
4248
4249  is_method = (TYPE_PTR_P (fntype)
4250	       && TREE_CODE (TREE_TYPE (fntype)) == METHOD_TYPE);
4251
4252  if (!(TYPE_PTRFN_P (fntype)
4253	|| is_method
4254	|| TREE_CODE (function) == TEMPLATE_ID_EXPR))
4255    {
4256      if (complain & tf_error)
4257	{
4258	  if (!flag_diagnostics_show_caret)
4259	    error_at (input_location,
4260		      "%qE cannot be used as a function", original);
4261	  else if (DECL_P (original))
4262	    error_at (input_location,
4263		      "%qD cannot be used as a function", original);
4264	  else
4265	    error_at (input_location,
4266		      "expression cannot be used as a function");
4267	}
4268
4269      return error_mark_node;
4270    }
4271
4272  /* fntype now gets the type of function pointed to.  */
4273  fntype = TREE_TYPE (fntype);
4274  parm_types = TYPE_ARG_TYPES (fntype);
4275
4276  if (params == NULL)
4277    {
4278      allocated = make_tree_vector ();
4279      params = &allocated;
4280    }
4281
4282    nargs = convert_arguments (parm_types, params, fndecl, LOOKUP_NORMAL,
4283			       complain);
4284  if (nargs < 0)
4285    return error_mark_node;
4286
4287  argarray = (*params)->address ();
4288
4289  /* Check for errors in format strings and inappropriately
4290     null parameters.  */
4291  bool warned_p = check_function_arguments (input_location, fndecl, fntype,
4292					    nargs, argarray, NULL);
4293
4294  ret = build_cxx_call (function, nargs, argarray, complain, orig_fndecl);
4295
4296  if (warned_p)
4297    {
4298      tree c = extract_call_expr (ret);
4299      if (TREE_CODE (c) == CALL_EXPR)
4300	suppress_warning (c, OPT_Wnonnull);
4301    }
4302
4303  if (allocated != NULL)
4304    release_tree_vector (allocated);
4305
4306  return ret;
4307}
4308
4309/* Subroutine of convert_arguments.
4310   Print an error message about a wrong number of arguments.  */
4311
4312static void
4313error_args_num (location_t loc, tree fndecl, bool too_many_p)
4314{
4315  if (fndecl)
4316    {
4317      if (TREE_CODE (TREE_TYPE (fndecl)) == METHOD_TYPE)
4318	{
4319	  if (DECL_NAME (fndecl) == NULL_TREE
4320	      || (DECL_NAME (fndecl)
4321		  == DECL_NAME (TYPE_NAME (DECL_CONTEXT (fndecl)))))
4322	    error_at (loc,
4323		      too_many_p
4324		      ? G_("too many arguments to constructor %q#D")
4325		      : G_("too few arguments to constructor %q#D"),
4326		      fndecl);
4327	  else
4328	    error_at (loc,
4329		      too_many_p
4330		      ? G_("too many arguments to member function %q#D")
4331		      : G_("too few arguments to member function %q#D"),
4332		      fndecl);
4333	}
4334      else
4335	error_at (loc,
4336		  too_many_p
4337		  ? G_("too many arguments to function %q#D")
4338		  : G_("too few arguments to function %q#D"),
4339		  fndecl);
4340      if (!DECL_IS_UNDECLARED_BUILTIN (fndecl))
4341	inform (DECL_SOURCE_LOCATION (fndecl), "declared here");
4342    }
4343  else
4344    {
4345      if (c_dialect_objc ()  &&  objc_message_selector ())
4346	error_at (loc,
4347		  too_many_p
4348		  ? G_("too many arguments to method %q#D")
4349		  : G_("too few arguments to method %q#D"),
4350		  objc_message_selector ());
4351      else
4352	error_at (loc, too_many_p ? G_("too many arguments to function")
4353		                  : G_("too few arguments to function"));
4354    }
4355}
4356
4357/* Convert the actual parameter expressions in the list VALUES to the
4358   types in the list TYPELIST.  The converted expressions are stored
4359   back in the VALUES vector.
4360   If parmdecls is exhausted, or when an element has NULL as its type,
4361   perform the default conversions.
4362
4363   NAME is an IDENTIFIER_NODE or 0.  It is used only for error messages.
4364
4365   This is also where warnings about wrong number of args are generated.
4366
4367   Returns the actual number of arguments processed (which might be less
4368   than the length of the vector), or -1 on error.
4369
4370   In C++, unspecified trailing parameters can be filled in with their
4371   default arguments, if such were specified.  Do so here.  */
4372
4373static int
4374convert_arguments (tree typelist, vec<tree, va_gc> **values, tree fndecl,
4375		   int flags, tsubst_flags_t complain)
4376{
4377  tree typetail;
4378  unsigned int i;
4379
4380  /* Argument passing is always copy-initialization.  */
4381  flags |= LOOKUP_ONLYCONVERTING;
4382
4383  for (i = 0, typetail = typelist;
4384       i < vec_safe_length (*values);
4385       i++)
4386    {
4387      tree type = typetail ? TREE_VALUE (typetail) : 0;
4388      tree val = (**values)[i];
4389
4390      if (val == error_mark_node || type == error_mark_node)
4391	return -1;
4392
4393      if (type == void_type_node)
4394	{
4395          if (complain & tf_error)
4396            {
4397	      error_args_num (input_location, fndecl, /*too_many_p=*/true);
4398              return i;
4399            }
4400          else
4401            return -1;
4402	}
4403
4404      /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
4405	 Strip such NOP_EXPRs, since VAL is used in non-lvalue context.  */
4406      if (TREE_CODE (val) == NOP_EXPR
4407	  && TREE_TYPE (val) == TREE_TYPE (TREE_OPERAND (val, 0))
4408	  && (type == 0 || !TYPE_REF_P (type)))
4409	val = TREE_OPERAND (val, 0);
4410
4411      if (type == 0 || !TYPE_REF_P (type))
4412	{
4413	  if (TREE_CODE (TREE_TYPE (val)) == ARRAY_TYPE
4414	      || FUNC_OR_METHOD_TYPE_P (TREE_TYPE (val)))
4415	    val = decay_conversion (val, complain);
4416	}
4417
4418      if (val == error_mark_node)
4419	return -1;
4420
4421      if (type != 0)
4422	{
4423	  /* Formal parm type is specified by a function prototype.  */
4424	  tree parmval;
4425
4426	  if (!COMPLETE_TYPE_P (complete_type (type)))
4427	    {
4428              if (complain & tf_error)
4429                {
4430		  location_t loc = EXPR_LOC_OR_LOC (val, input_location);
4431                  if (fndecl)
4432		    {
4433		      auto_diagnostic_group d;
4434		      error_at (loc,
4435				"parameter %P of %qD has incomplete type %qT",
4436				i, fndecl, type);
4437		      inform (get_fndecl_argument_location (fndecl, i),
4438			      "  declared here");
4439		    }
4440                  else
4441		    error_at (loc, "parameter %P has incomplete type %qT", i,
4442			      type);
4443                }
4444	      parmval = error_mark_node;
4445	    }
4446	  else
4447	    {
4448	      parmval = convert_for_initialization
4449		(NULL_TREE, type, val, flags,
4450		 ICR_ARGPASS, fndecl, i, complain);
4451	      parmval = convert_for_arg_passing (type, parmval, complain);
4452	    }
4453
4454	  if (parmval == error_mark_node)
4455	    return -1;
4456
4457	  (**values)[i] = parmval;
4458	}
4459      else
4460	{
4461	  if (fndecl && magic_varargs_p (fndecl))
4462	    /* Don't do ellipsis conversion for __built_in_constant_p
4463	       as this will result in spurious errors for non-trivial
4464	       types.  */
4465	    val = require_complete_type_sfinae (val, complain);
4466	  else
4467	    val = convert_arg_to_ellipsis (val, complain);
4468
4469	  (**values)[i] = val;
4470	}
4471
4472      if (typetail)
4473	typetail = TREE_CHAIN (typetail);
4474    }
4475
4476  if (typetail != 0 && typetail != void_list_node)
4477    {
4478      /* See if there are default arguments that can be used.  Because
4479	 we hold default arguments in the FUNCTION_TYPE (which is so
4480	 wrong), we can see default parameters here from deduced
4481	 contexts (and via typeof) for indirect function calls.
4482	 Fortunately we know whether we have a function decl to
4483	 provide default arguments in a language conformant
4484	 manner.  */
4485      if (fndecl && TREE_PURPOSE (typetail)
4486	  && TREE_CODE (TREE_PURPOSE (typetail)) != DEFERRED_PARSE)
4487	{
4488	  for (; typetail != void_list_node; ++i)
4489	    {
4490	      /* After DR777, with explicit template args we can end up with a
4491		 default argument followed by no default argument.  */
4492	      if (!TREE_PURPOSE (typetail))
4493		break;
4494	      tree parmval
4495		= convert_default_arg (TREE_VALUE (typetail),
4496				       TREE_PURPOSE (typetail),
4497				       fndecl, i, complain);
4498
4499	      if (parmval == error_mark_node)
4500		return -1;
4501
4502	      vec_safe_push (*values, parmval);
4503	      typetail = TREE_CHAIN (typetail);
4504	      /* ends with `...'.  */
4505	      if (typetail == NULL_TREE)
4506		break;
4507	    }
4508	}
4509
4510      if (typetail && typetail != void_list_node)
4511	{
4512	  if (complain & tf_error)
4513	    error_args_num (input_location, fndecl, /*too_many_p=*/false);
4514	  return -1;
4515	}
4516    }
4517
4518  return (int) i;
4519}
4520
4521/* Build a binary-operation expression, after performing default
4522   conversions on the operands.  CODE is the kind of expression to
4523   build.  ARG1 and ARG2 are the arguments.  ARG1_CODE and ARG2_CODE
4524   are the tree codes which correspond to ARG1 and ARG2 when issuing
4525   warnings about possibly misplaced parentheses.  They may differ
4526   from the TREE_CODE of ARG1 and ARG2 if the parser has done constant
4527   folding (e.g., if the parser sees "a | 1 + 1", it may call this
4528   routine with ARG2 being an INTEGER_CST and ARG2_CODE == PLUS_EXPR).
4529   To avoid issuing any parentheses warnings, pass ARG1_CODE and/or
4530   ARG2_CODE as ERROR_MARK.  */
4531
4532tree
4533build_x_binary_op (const op_location_t &loc, enum tree_code code, tree arg1,
4534		   enum tree_code arg1_code, tree arg2,
4535		   enum tree_code arg2_code, tree lookups,
4536		   tree *overload_p, tsubst_flags_t complain)
4537{
4538  tree orig_arg1;
4539  tree orig_arg2;
4540  tree expr;
4541  tree overload = NULL_TREE;
4542
4543  orig_arg1 = arg1;
4544  orig_arg2 = arg2;
4545
4546  if (processing_template_decl)
4547    {
4548      if (type_dependent_expression_p (arg1)
4549	  || type_dependent_expression_p (arg2))
4550	{
4551	  expr = build_min_nt_loc (loc, code, arg1, arg2);
4552	  TREE_TYPE (expr)
4553	    = build_dependent_operator_type (lookups, code, false);
4554	  return expr;
4555	}
4556      arg1 = build_non_dependent_expr (arg1);
4557      arg2 = build_non_dependent_expr (arg2);
4558    }
4559
4560  if (code == DOTSTAR_EXPR)
4561    expr = build_m_component_ref (arg1, arg2, complain);
4562  else
4563    expr = build_new_op (loc, code, LOOKUP_NORMAL, arg1, arg2, NULL_TREE,
4564			 lookups, &overload, complain);
4565
4566  if (overload_p != NULL)
4567    *overload_p = overload;
4568
4569  /* Check for cases such as x+y<<z which users are likely to
4570     misinterpret.  But don't warn about obj << x + y, since that is a
4571     common idiom for I/O.  */
4572  if (warn_parentheses
4573      && (complain & tf_warning)
4574      && !processing_template_decl
4575      && !error_operand_p (arg1)
4576      && !error_operand_p (arg2)
4577      && (code != LSHIFT_EXPR
4578	  || !CLASS_TYPE_P (TREE_TYPE (arg1))))
4579    warn_about_parentheses (loc, code, arg1_code, orig_arg1,
4580			    arg2_code, orig_arg2);
4581
4582  if (processing_template_decl && expr != error_mark_node)
4583    {
4584      if (overload != NULL_TREE)
4585	return (build_min_non_dep_op_overload
4586		(code, expr, overload, orig_arg1, orig_arg2));
4587
4588      return build_min_non_dep (code, expr, orig_arg1, orig_arg2);
4589    }
4590
4591  return expr;
4592}
4593
4594/* Build and return an ARRAY_REF expression.  */
4595
4596tree
4597build_x_array_ref (location_t loc, tree arg1, tree arg2,
4598		   tsubst_flags_t complain)
4599{
4600  tree orig_arg1 = arg1;
4601  tree orig_arg2 = arg2;
4602  tree expr;
4603  tree overload = NULL_TREE;
4604
4605  if (processing_template_decl)
4606    {
4607      if (type_dependent_expression_p (arg1)
4608	  || type_dependent_expression_p (arg2))
4609	return build_min_nt_loc (loc, ARRAY_REF, arg1, arg2,
4610				 NULL_TREE, NULL_TREE);
4611      arg1 = build_non_dependent_expr (arg1);
4612      arg2 = build_non_dependent_expr (arg2);
4613    }
4614
4615  expr = build_new_op (loc, ARRAY_REF, LOOKUP_NORMAL, arg1, arg2,
4616		       NULL_TREE, NULL_TREE, &overload, complain);
4617
4618  if (processing_template_decl && expr != error_mark_node)
4619    {
4620      if (overload != NULL_TREE)
4621	return (build_min_non_dep_op_overload
4622		(ARRAY_REF, expr, overload, orig_arg1, orig_arg2));
4623
4624      return build_min_non_dep (ARRAY_REF, expr, orig_arg1, orig_arg2,
4625				NULL_TREE, NULL_TREE);
4626    }
4627  return expr;
4628}
4629
4630/* Return whether OP is an expression of enum type cast to integer
4631   type.  In C++ even unsigned enum types are cast to signed integer
4632   types.  We do not want to issue warnings about comparisons between
4633   signed and unsigned types when one of the types is an enum type.
4634   Those warnings are always false positives in practice.  */
4635
4636static bool
4637enum_cast_to_int (tree op)
4638{
4639  if (CONVERT_EXPR_P (op)
4640      && TREE_TYPE (op) == integer_type_node
4641      && TREE_CODE (TREE_TYPE (TREE_OPERAND (op, 0))) == ENUMERAL_TYPE
4642      && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (op, 0))))
4643    return true;
4644
4645  /* The cast may have been pushed into a COND_EXPR.  */
4646  if (TREE_CODE (op) == COND_EXPR)
4647    return (enum_cast_to_int (TREE_OPERAND (op, 1))
4648	    || enum_cast_to_int (TREE_OPERAND (op, 2)));
4649
4650  return false;
4651}
4652
4653/* For the c-common bits.  */
4654tree
4655build_binary_op (location_t location, enum tree_code code, tree op0, tree op1,
4656		 bool /*convert_p*/)
4657{
4658  return cp_build_binary_op (location, code, op0, op1, tf_warning_or_error);
4659}
4660
4661/* Build a vector comparison of ARG0 and ARG1 using CODE opcode
4662   into a value of TYPE type.  Comparison is done via VEC_COND_EXPR.  */
4663
4664static tree
4665build_vec_cmp (tree_code code, tree type,
4666	       tree arg0, tree arg1)
4667{
4668  tree zero_vec = build_zero_cst (type);
4669  tree minus_one_vec = build_minus_one_cst (type);
4670  tree cmp_type = truth_type_for (type);
4671  tree cmp = build2 (code, cmp_type, arg0, arg1);
4672  return build3 (VEC_COND_EXPR, type, cmp, minus_one_vec, zero_vec);
4673}
4674
4675/* Possibly warn about an address never being NULL.  */
4676
4677static void
4678warn_for_null_address (location_t location, tree op, tsubst_flags_t complain)
4679{
4680  /* Prevent warnings issued for macro expansion.  */
4681  if (!warn_address
4682      || (complain & tf_warning) == 0
4683      || c_inhibit_evaluation_warnings != 0
4684      || from_macro_expansion_at (location)
4685      || warning_suppressed_p (op, OPT_Waddress))
4686    return;
4687
4688  if (TREE_CODE (op) == NON_DEPENDENT_EXPR)
4689    op = TREE_OPERAND (op, 0);
4690
4691  tree cop = fold_for_warn (op);
4692
4693  if (TREE_CODE (cop) == NON_LVALUE_EXPR)
4694    /* Unwrap the expression for C++ 98.  */
4695    cop = TREE_OPERAND (cop, 0);
4696
4697  if (TREE_CODE (cop) == PTRMEM_CST)
4698    {
4699      /* The address of a nonstatic data member is never null.  */
4700      warning_at (location, OPT_Waddress,
4701		  "the address %qE will never be NULL",
4702		  cop);
4703      return;
4704    }
4705
4706  if (TREE_CODE (cop) == NOP_EXPR)
4707    {
4708      /* Allow casts to intptr_t to suppress the warning.  */
4709      tree type = TREE_TYPE (cop);
4710      if (TREE_CODE (type) == INTEGER_TYPE)
4711	return;
4712
4713      STRIP_NOPS (cop);
4714    }
4715
4716  bool warned = false;
4717  if (TREE_CODE (cop) == ADDR_EXPR)
4718    {
4719      cop = TREE_OPERAND (cop, 0);
4720
4721      /* Set to true in the loop below if OP dereferences its operand.
4722	 In such a case the ultimate target need not be a decl for
4723	 the null [in]equality test to be necessarily constant.  */
4724      bool deref = false;
4725
4726      /* Get the outermost array or object, or member.  */
4727      while (handled_component_p (cop))
4728	{
4729	  if (TREE_CODE (cop) == COMPONENT_REF)
4730	    {
4731	      /* Get the member (its address is never null).  */
4732	      cop = TREE_OPERAND (cop, 1);
4733	      break;
4734	    }
4735
4736	  /* Get the outer array/object to refer to in the warning.  */
4737	  cop = TREE_OPERAND (cop, 0);
4738	  deref = true;
4739	}
4740
4741      if ((!deref && !decl_with_nonnull_addr_p (cop))
4742	  || from_macro_expansion_at (location)
4743	  || warning_suppressed_p (cop, OPT_Waddress))
4744	return;
4745
4746      warned = warning_at (location, OPT_Waddress,
4747			   "the address of %qD will never be NULL", cop);
4748      op = cop;
4749    }
4750  else if (TREE_CODE (cop) == POINTER_PLUS_EXPR)
4751    {
4752      /* Adding zero to the null pointer is well-defined in C++.  When
4753	 the offset is unknown (i.e., not a constant) warn anyway since
4754	 it's less likely that the pointer operand is null than not.  */
4755      tree off = TREE_OPERAND (cop, 1);
4756      if (!integer_zerop (off)
4757	  && !warning_suppressed_p (cop, OPT_Waddress))
4758	warning_at (location, OPT_Waddress, "comparing the result of pointer "
4759		    "addition %qE and NULL", cop);
4760      return;
4761    }
4762  else if (CONVERT_EXPR_P (op)
4763	   && TYPE_REF_P (TREE_TYPE (TREE_OPERAND (op, 0))))
4764    {
4765      STRIP_NOPS (op);
4766
4767      if (TREE_CODE (op) == COMPONENT_REF)
4768	op = TREE_OPERAND (op, 1);
4769
4770      if (DECL_P (op))
4771	warned = warning_at (location, OPT_Waddress,
4772			     "the compiler can assume that the address of "
4773			     "%qD will never be NULL", op);
4774    }
4775
4776  if (warned && DECL_P (op))
4777    inform (DECL_SOURCE_LOCATION (op), "%qD declared here", op);
4778}
4779
4780/* Warn about [expr.arith.conv]/2: If one operand is of enumeration type and
4781   the other operand is of a different enumeration type or a floating-point
4782   type, this behavior is deprecated ([depr.arith.conv.enum]).  CODE is the
4783   code of the binary operation, TYPE0 and TYPE1 are the types of the operands,
4784   and LOC is the location for the whole binary expression.
4785   TODO: Consider combining this with -Wenum-compare in build_new_op_1.  */
4786
4787static void
4788do_warn_enum_conversions (location_t loc, enum tree_code code, tree type0,
4789			  tree type1)
4790{
4791  if (TREE_CODE (type0) == ENUMERAL_TYPE
4792      && TREE_CODE (type1) == ENUMERAL_TYPE
4793      && TYPE_MAIN_VARIANT (type0) != TYPE_MAIN_VARIANT (type1))
4794    {
4795      /* In C++20, -Wdeprecated-enum-enum-conversion is on by default.
4796	 Otherwise, warn if -Wenum-conversion is on.  */
4797      enum opt_code opt;
4798      if (warn_deprecated_enum_enum_conv)
4799	opt = OPT_Wdeprecated_enum_enum_conversion;
4800      else if (warn_enum_conversion)
4801	opt = OPT_Wenum_conversion;
4802      else
4803	return;
4804
4805      switch (code)
4806	{
4807	case GT_EXPR:
4808	case LT_EXPR:
4809	case GE_EXPR:
4810	case LE_EXPR:
4811	case EQ_EXPR:
4812	case NE_EXPR:
4813	  /* Comparisons are handled by -Wenum-compare.  */
4814	  return;
4815	case SPACESHIP_EXPR:
4816	  /* This is invalid, don't warn.  */
4817	  return;
4818	case BIT_AND_EXPR:
4819	case BIT_IOR_EXPR:
4820	case BIT_XOR_EXPR:
4821	  warning_at (loc, opt, "bitwise operation between different "
4822		      "enumeration types %qT and %qT is deprecated",
4823		      type0, type1);
4824	  return;
4825	default:
4826	  warning_at (loc, opt, "arithmetic between different enumeration "
4827		      "types %qT and %qT is deprecated", type0, type1);
4828	  return;
4829	}
4830    }
4831  else if ((TREE_CODE (type0) == ENUMERAL_TYPE
4832	    && TREE_CODE (type1) == REAL_TYPE)
4833	   || (TREE_CODE (type0) == REAL_TYPE
4834	       && TREE_CODE (type1) == ENUMERAL_TYPE))
4835    {
4836      const bool enum_first_p = TREE_CODE (type0) == ENUMERAL_TYPE;
4837      /* In C++20, -Wdeprecated-enum-float-conversion is on by default.
4838	 Otherwise, warn if -Wenum-conversion is on.  */
4839      enum opt_code opt;
4840      if (warn_deprecated_enum_float_conv)
4841	opt = OPT_Wdeprecated_enum_float_conversion;
4842      else if (warn_enum_conversion)
4843	opt = OPT_Wenum_conversion;
4844      else
4845	return;
4846
4847      switch (code)
4848	{
4849	case GT_EXPR:
4850	case LT_EXPR:
4851	case GE_EXPR:
4852	case LE_EXPR:
4853	case EQ_EXPR:
4854	case NE_EXPR:
4855	  if (enum_first_p)
4856	    warning_at (loc, opt, "comparison of enumeration type %qT with "
4857			"floating-point type %qT is deprecated",
4858			type0, type1);
4859	  else
4860	    warning_at (loc, opt, "comparison of floating-point type %qT "
4861			"with enumeration type %qT is deprecated",
4862			type0, type1);
4863	  return;
4864	case SPACESHIP_EXPR:
4865	  /* This is invalid, don't warn.  */
4866	  return;
4867	default:
4868	  if (enum_first_p)
4869	    warning_at (loc, opt, "arithmetic between enumeration type %qT "
4870			"and floating-point type %qT is deprecated",
4871			type0, type1);
4872	  else
4873	    warning_at (loc, opt, "arithmetic between floating-point type %qT "
4874			"and enumeration type %qT is deprecated",
4875			type0, type1);
4876	  return;
4877	}
4878    }
4879}
4880
4881/* Build a binary-operation expression without default conversions.
4882   CODE is the kind of expression to build.
4883   LOCATION is the location_t of the operator in the source code.
4884   This function differs from `build' in several ways:
4885   the data type of the result is computed and recorded in it,
4886   warnings are generated if arg data types are invalid,
4887   special handling for addition and subtraction of pointers is known,
4888   and some optimization is done (operations on narrow ints
4889   are done in the narrower type when that gives the same result).
4890   Constant folding is also done before the result is returned.
4891
4892   Note that the operands will never have enumeral types
4893   because either they have just had the default conversions performed
4894   or they have both just been converted to some other type in which
4895   the arithmetic is to be done.
4896
4897   C++: must do special pointer arithmetic when implementing
4898   multiple inheritance, and deal with pointer to member functions.  */
4899
4900tree
4901cp_build_binary_op (const op_location_t &location,
4902		    enum tree_code code, tree orig_op0, tree orig_op1,
4903		    tsubst_flags_t complain)
4904{
4905  tree op0, op1;
4906  enum tree_code code0, code1;
4907  tree type0, type1;
4908  const char *invalid_op_diag;
4909
4910  /* Expression code to give to the expression when it is built.
4911     Normally this is CODE, which is what the caller asked for,
4912     but in some special cases we change it.  */
4913  enum tree_code resultcode = code;
4914
4915  /* Data type in which the computation is to be performed.
4916     In the simplest cases this is the common type of the arguments.  */
4917  tree result_type = NULL_TREE;
4918
4919  /* Nonzero means operands have already been type-converted
4920     in whatever way is necessary.
4921     Zero means they need to be converted to RESULT_TYPE.  */
4922  int converted = 0;
4923
4924  /* Nonzero means create the expression with this type, rather than
4925     RESULT_TYPE.  */
4926  tree build_type = 0;
4927
4928  /* Nonzero means after finally constructing the expression
4929     convert it to this type.  */
4930  tree final_type = 0;
4931
4932  tree result;
4933
4934  /* Nonzero if this is an operation like MIN or MAX which can
4935     safely be computed in short if both args are promoted shorts.
4936     Also implies COMMON.
4937     -1 indicates a bitwise operation; this makes a difference
4938     in the exact conditions for when it is safe to do the operation
4939     in a narrower mode.  */
4940  int shorten = 0;
4941
4942  /* Nonzero if this is a comparison operation;
4943     if both args are promoted shorts, compare the original shorts.
4944     Also implies COMMON.  */
4945  int short_compare = 0;
4946
4947  /* Nonzero if this is a right-shift operation, which can be computed on the
4948     original short and then promoted if the operand is a promoted short.  */
4949  int short_shift = 0;
4950
4951  /* Nonzero means set RESULT_TYPE to the common type of the args.  */
4952  int common = 0;
4953
4954  /* True if both operands have arithmetic type.  */
4955  bool arithmetic_types_p;
4956
4957  /* Remember whether we're doing / or %.  */
4958  bool doing_div_or_mod = false;
4959
4960  /* Remember whether we're doing << or >>.  */
4961  bool doing_shift = false;
4962
4963  /* Tree holding instrumentation expression.  */
4964  tree instrument_expr = NULL_TREE;
4965
4966  /* Apply default conversions.  */
4967  op0 = resolve_nondeduced_context (orig_op0, complain);
4968  op1 = resolve_nondeduced_context (orig_op1, complain);
4969
4970  if (code == TRUTH_AND_EXPR || code == TRUTH_ANDIF_EXPR
4971      || code == TRUTH_OR_EXPR || code == TRUTH_ORIF_EXPR
4972      || code == TRUTH_XOR_EXPR)
4973    {
4974      if (!really_overloaded_fn (op0) && !VOID_TYPE_P (TREE_TYPE (op0)))
4975	op0 = decay_conversion (op0, complain);
4976      if (!really_overloaded_fn (op1) && !VOID_TYPE_P (TREE_TYPE (op1)))
4977	op1 = decay_conversion (op1, complain);
4978    }
4979  else
4980    {
4981      if (!really_overloaded_fn (op0) && !VOID_TYPE_P (TREE_TYPE (op0)))
4982	op0 = cp_default_conversion (op0, complain);
4983      if (!really_overloaded_fn (op1) && !VOID_TYPE_P (TREE_TYPE (op1)))
4984	op1 = cp_default_conversion (op1, complain);
4985    }
4986
4987  /* Strip NON_LVALUE_EXPRs, etc., since we aren't using as an lvalue.  */
4988  STRIP_TYPE_NOPS (op0);
4989  STRIP_TYPE_NOPS (op1);
4990
4991  /* DTRT if one side is an overloaded function, but complain about it.  */
4992  if (type_unknown_p (op0))
4993    {
4994      tree t = instantiate_type (TREE_TYPE (op1), op0, tf_none);
4995      if (t != error_mark_node)
4996	{
4997	  if (complain & tf_error)
4998	    permerror (location,
4999		       "assuming cast to type %qT from overloaded function",
5000		       TREE_TYPE (t));
5001	  op0 = t;
5002	}
5003    }
5004  if (type_unknown_p (op1))
5005    {
5006      tree t = instantiate_type (TREE_TYPE (op0), op1, tf_none);
5007      if (t != error_mark_node)
5008	{
5009	  if (complain & tf_error)
5010	    permerror (location,
5011		       "assuming cast to type %qT from overloaded function",
5012		       TREE_TYPE (t));
5013	  op1 = t;
5014	}
5015    }
5016
5017  type0 = TREE_TYPE (op0);
5018  type1 = TREE_TYPE (op1);
5019
5020  /* The expression codes of the data types of the arguments tell us
5021     whether the arguments are integers, floating, pointers, etc.  */
5022  code0 = TREE_CODE (type0);
5023  code1 = TREE_CODE (type1);
5024
5025  /* If an error was already reported for one of the arguments,
5026     avoid reporting another error.  */
5027  if (code0 == ERROR_MARK || code1 == ERROR_MARK)
5028    return error_mark_node;
5029
5030  if ((invalid_op_diag
5031       = targetm.invalid_binary_op (code, type0, type1)))
5032    {
5033      if (complain & tf_error)
5034	error (invalid_op_diag);
5035      return error_mark_node;
5036    }
5037
5038  /* Issue warnings about peculiar, but valid, uses of NULL.  */
5039  if ((null_node_p (orig_op0) || null_node_p (orig_op1))
5040      /* It's reasonable to use pointer values as operands of &&
5041	 and ||, so NULL is no exception.  */
5042      && code != TRUTH_ANDIF_EXPR && code != TRUTH_ORIF_EXPR
5043      && ( /* Both are NULL (or 0) and the operation was not a
5044	      comparison or a pointer subtraction.  */
5045	  (null_ptr_cst_p (orig_op0) && null_ptr_cst_p (orig_op1)
5046	   && code != EQ_EXPR && code != NE_EXPR && code != MINUS_EXPR)
5047	  /* Or if one of OP0 or OP1 is neither a pointer nor NULL.  */
5048	  || (!null_ptr_cst_p (orig_op0)
5049	      && !TYPE_PTR_OR_PTRMEM_P (type0))
5050	  || (!null_ptr_cst_p (orig_op1)
5051	      && !TYPE_PTR_OR_PTRMEM_P (type1)))
5052      && (complain & tf_warning))
5053    {
5054      location_t loc =
5055	expansion_point_location_if_in_system_header (input_location);
5056
5057      warning_at (loc, OPT_Wpointer_arith, "NULL used in arithmetic");
5058    }
5059
5060  /* In case when one of the operands of the binary operation is
5061     a vector and another is a scalar -- convert scalar to vector.  */
5062  if ((gnu_vector_type_p (type0) && code1 != VECTOR_TYPE)
5063      || (gnu_vector_type_p (type1) && code0 != VECTOR_TYPE))
5064    {
5065      enum stv_conv convert_flag = scalar_to_vector (location, code, op0, op1,
5066						     complain & tf_error);
5067
5068      switch (convert_flag)
5069        {
5070          case stv_error:
5071            return error_mark_node;
5072          case stv_firstarg:
5073            {
5074              op0 = convert (TREE_TYPE (type1), op0);
5075	      op0 = save_expr (op0);
5076              op0 = build_vector_from_val (type1, op0);
5077              type0 = TREE_TYPE (op0);
5078              code0 = TREE_CODE (type0);
5079              converted = 1;
5080              break;
5081            }
5082          case stv_secondarg:
5083            {
5084              op1 = convert (TREE_TYPE (type0), op1);
5085	      op1 = save_expr (op1);
5086              op1 = build_vector_from_val (type0, op1);
5087              type1 = TREE_TYPE (op1);
5088              code1 = TREE_CODE (type1);
5089              converted = 1;
5090              break;
5091            }
5092          default:
5093            break;
5094        }
5095    }
5096
5097  switch (code)
5098    {
5099    case MINUS_EXPR:
5100      /* Subtraction of two similar pointers.
5101	 We must subtract them as integers, then divide by object size.  */
5102      if (code0 == POINTER_TYPE && code1 == POINTER_TYPE
5103	  && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type0),
5104							TREE_TYPE (type1)))
5105	{
5106	  result = pointer_diff (location, op0, op1,
5107				 common_pointer_type (type0, type1), complain,
5108				 &instrument_expr);
5109	  if (instrument_expr != NULL)
5110	    result = build2 (COMPOUND_EXPR, TREE_TYPE (result),
5111			     instrument_expr, result);
5112
5113	  return result;
5114	}
5115      /* In all other cases except pointer - int, the usual arithmetic
5116	 rules apply.  */
5117      else if (!(code0 == POINTER_TYPE && code1 == INTEGER_TYPE))
5118	{
5119	  common = 1;
5120	  break;
5121	}
5122      /* The pointer - int case is just like pointer + int; fall
5123	 through.  */
5124      gcc_fallthrough ();
5125    case PLUS_EXPR:
5126      if ((code0 == POINTER_TYPE || code1 == POINTER_TYPE)
5127	  && (code0 == INTEGER_TYPE || code1 == INTEGER_TYPE))
5128	{
5129	  tree ptr_operand;
5130	  tree int_operand;
5131	  ptr_operand = ((code0 == POINTER_TYPE) ? op0 : op1);
5132	  int_operand = ((code0 == INTEGER_TYPE) ? op0 : op1);
5133	  if (processing_template_decl)
5134	    {
5135	      result_type = TREE_TYPE (ptr_operand);
5136	      break;
5137	    }
5138	  return cp_pointer_int_sum (location, code,
5139				     ptr_operand,
5140				     int_operand,
5141				     complain);
5142	}
5143      common = 1;
5144      break;
5145
5146    case MULT_EXPR:
5147      common = 1;
5148      break;
5149
5150    case TRUNC_DIV_EXPR:
5151    case CEIL_DIV_EXPR:
5152    case FLOOR_DIV_EXPR:
5153    case ROUND_DIV_EXPR:
5154    case EXACT_DIV_EXPR:
5155      if (TREE_CODE (op0) == SIZEOF_EXPR && TREE_CODE (op1) == SIZEOF_EXPR)
5156	{
5157	  tree type0 = TREE_OPERAND (op0, 0);
5158	  tree type1 = TREE_OPERAND (op1, 0);
5159	  tree first_arg = tree_strip_any_location_wrapper (type0);
5160	  if (!TYPE_P (type0))
5161	    type0 = TREE_TYPE (type0);
5162	  if (!TYPE_P (type1))
5163	    type1 = TREE_TYPE (type1);
5164	  if (INDIRECT_TYPE_P (type0) && same_type_p (TREE_TYPE (type0), type1))
5165	    {
5166	      if (!(TREE_CODE (first_arg) == PARM_DECL
5167		    && DECL_ARRAY_PARAMETER_P (first_arg)
5168		    && warn_sizeof_array_argument)
5169		  && (complain & tf_warning))
5170		{
5171		  auto_diagnostic_group d;
5172		  if (warning_at (location, OPT_Wsizeof_pointer_div,
5173				  "division %<sizeof (%T) / sizeof (%T)%> does "
5174				  "not compute the number of array elements",
5175				  type0, type1))
5176		    if (DECL_P (first_arg))
5177		      inform (DECL_SOURCE_LOCATION (first_arg),
5178			      "first %<sizeof%> operand was declared here");
5179		}
5180	    }
5181	  else if (TREE_CODE (type0) == ARRAY_TYPE
5182		   && !char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type0)))
5183		   /* Set by finish_parenthesized_expr.  */
5184		   && !warning_suppressed_p (op1, OPT_Wsizeof_array_div)
5185		   && (complain & tf_warning))
5186	    maybe_warn_sizeof_array_div (location, first_arg, type0,
5187					 op1, non_reference (type1));
5188	}
5189
5190      if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE
5191	   || code0 == COMPLEX_TYPE || code0 == VECTOR_TYPE)
5192	  && (code1 == INTEGER_TYPE || code1 == REAL_TYPE
5193	      || code1 == COMPLEX_TYPE || code1 == VECTOR_TYPE))
5194	{
5195	  enum tree_code tcode0 = code0, tcode1 = code1;
5196	  doing_div_or_mod = true;
5197	  warn_for_div_by_zero (location, fold_for_warn (op1));
5198
5199	  if (tcode0 == COMPLEX_TYPE || tcode0 == VECTOR_TYPE)
5200	    tcode0 = TREE_CODE (TREE_TYPE (TREE_TYPE (op0)));
5201	  if (tcode1 == COMPLEX_TYPE || tcode1 == VECTOR_TYPE)
5202	    tcode1 = TREE_CODE (TREE_TYPE (TREE_TYPE (op1)));
5203
5204	  if (!(tcode0 == INTEGER_TYPE && tcode1 == INTEGER_TYPE))
5205	    resultcode = RDIV_EXPR;
5206	  else
5207	    {
5208	      /* When dividing two signed integers, we have to promote to int.
5209		 unless we divide by a constant != -1.  Note that default
5210		 conversion will have been performed on the operands at this
5211		 point, so we have to dig out the original type to find out if
5212		 it was unsigned.  */
5213	      tree stripped_op1 = tree_strip_any_location_wrapper (op1);
5214	      shorten = ((TREE_CODE (op0) == NOP_EXPR
5215			  && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (op0,
5216								       0)))
5217			  && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (op0, 0)))
5218			  && (TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (op0,
5219								       0)))
5220			      < TYPE_PRECISION (type0)))
5221			 || (TREE_CODE (stripped_op1) == INTEGER_CST
5222			     && ! integer_all_onesp (stripped_op1)));
5223	    }
5224
5225	  common = 1;
5226	}
5227      break;
5228
5229    case BIT_AND_EXPR:
5230    case BIT_IOR_EXPR:
5231    case BIT_XOR_EXPR:
5232      if ((code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
5233	  || (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE
5234	      && !VECTOR_FLOAT_TYPE_P (type0)
5235	      && !VECTOR_FLOAT_TYPE_P (type1)))
5236	shorten = -1;
5237      break;
5238
5239    case TRUNC_MOD_EXPR:
5240    case FLOOR_MOD_EXPR:
5241      doing_div_or_mod = true;
5242      warn_for_div_by_zero (location, fold_for_warn (op1));
5243
5244      if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE
5245	  && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE
5246	  && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
5247	common = 1;
5248      else if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
5249	{
5250	  /* Although it would be tempting to shorten always here, that loses
5251	     on some targets, since the modulo instruction is undefined if the
5252	     quotient can't be represented in the computation mode.  We shorten
5253	     only if unsigned or if dividing by something we know != -1.  */
5254	  tree stripped_op1 = tree_strip_any_location_wrapper (op1);
5255	  shorten = ((TREE_CODE (op0) == NOP_EXPR
5256		      && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (op0, 0)))
5257		      && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (op0, 0)))
5258		      && (TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (op0, 0)))
5259			  < TYPE_PRECISION (type0)))
5260		     || (TREE_CODE (stripped_op1) == INTEGER_CST
5261			 && ! integer_all_onesp (stripped_op1)));
5262	  common = 1;
5263	}
5264      break;
5265
5266    case TRUTH_ANDIF_EXPR:
5267    case TRUTH_ORIF_EXPR:
5268    case TRUTH_AND_EXPR:
5269    case TRUTH_OR_EXPR:
5270      if (!VECTOR_TYPE_P (type0) && gnu_vector_type_p (type1))
5271	{
5272	  if (!COMPARISON_CLASS_P (op1))
5273	    op1 = cp_build_binary_op (EXPR_LOCATION (op1), NE_EXPR, op1,
5274				      build_zero_cst (type1), complain);
5275	  if (code == TRUTH_ANDIF_EXPR)
5276	    {
5277	      tree z = build_zero_cst (TREE_TYPE (op1));
5278	      return build_conditional_expr (location, op0, op1, z, complain);
5279	    }
5280	  else if (code == TRUTH_ORIF_EXPR)
5281	    {
5282	      tree m1 = build_all_ones_cst (TREE_TYPE (op1));
5283	      return build_conditional_expr (location, op0, m1, op1, complain);
5284	    }
5285	  else
5286	    gcc_unreachable ();
5287	}
5288      if (gnu_vector_type_p (type0)
5289	  && (!VECTOR_TYPE_P (type1) || gnu_vector_type_p (type1)))
5290	{
5291	  if (!COMPARISON_CLASS_P (op0))
5292	    op0 = cp_build_binary_op (EXPR_LOCATION (op0), NE_EXPR, op0,
5293				      build_zero_cst (type0), complain);
5294	  if (!VECTOR_TYPE_P (type1))
5295	    {
5296	      tree m1 = build_all_ones_cst (TREE_TYPE (op0));
5297	      tree z = build_zero_cst (TREE_TYPE (op0));
5298	      op1 = build_conditional_expr (location, op1, m1, z, complain);
5299	    }
5300	  else if (!COMPARISON_CLASS_P (op1))
5301	    op1 = cp_build_binary_op (EXPR_LOCATION (op1), NE_EXPR, op1,
5302				      build_zero_cst (type1), complain);
5303
5304	  if (code == TRUTH_ANDIF_EXPR)
5305	    code = BIT_AND_EXPR;
5306	  else if (code == TRUTH_ORIF_EXPR)
5307	    code = BIT_IOR_EXPR;
5308	  else
5309	    gcc_unreachable ();
5310
5311	  return cp_build_binary_op (location, code, op0, op1, complain);
5312	}
5313
5314      result_type = boolean_type_node;
5315      break;
5316
5317      /* Shift operations: result has same type as first operand;
5318	 always convert second operand to int.
5319	 Also set SHORT_SHIFT if shifting rightward.  */
5320
5321    case RSHIFT_EXPR:
5322      if (gnu_vector_type_p (type0)
5323	  && code1 == INTEGER_TYPE
5324	  && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE)
5325        {
5326          result_type = type0;
5327          converted = 1;
5328        }
5329      else if (gnu_vector_type_p (type0)
5330	       && gnu_vector_type_p (type1)
5331	       && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE
5332	       && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE
5333	       && known_eq (TYPE_VECTOR_SUBPARTS (type0),
5334			    TYPE_VECTOR_SUBPARTS (type1)))
5335	{
5336	  result_type = type0;
5337	  converted = 1;
5338	}
5339      else if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
5340	{
5341	  tree const_op1 = fold_for_warn (op1);
5342	  if (TREE_CODE (const_op1) != INTEGER_CST)
5343	    const_op1 = op1;
5344	  result_type = type0;
5345	  doing_shift = true;
5346	  if (TREE_CODE (const_op1) == INTEGER_CST)
5347	    {
5348	      if (tree_int_cst_lt (const_op1, integer_zero_node))
5349		{
5350		  if ((complain & tf_warning)
5351		      && c_inhibit_evaluation_warnings == 0)
5352		    warning_at (location, OPT_Wshift_count_negative,
5353				"right shift count is negative");
5354		}
5355	      else
5356		{
5357		  if (!integer_zerop (const_op1))
5358		    short_shift = 1;
5359
5360		  if (compare_tree_int (const_op1, TYPE_PRECISION (type0)) >= 0
5361		      && (complain & tf_warning)
5362		      && c_inhibit_evaluation_warnings == 0)
5363		    warning_at (location, OPT_Wshift_count_overflow,
5364				"right shift count >= width of type");
5365		}
5366	    }
5367	  /* Avoid converting op1 to result_type later.  */
5368	  converted = 1;
5369	}
5370      break;
5371
5372    case LSHIFT_EXPR:
5373      if (gnu_vector_type_p (type0)
5374	  && code1 == INTEGER_TYPE
5375          && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE)
5376        {
5377          result_type = type0;
5378          converted = 1;
5379        }
5380      else if (gnu_vector_type_p (type0)
5381	       && gnu_vector_type_p (type1)
5382	       && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE
5383	       && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE
5384	       && known_eq (TYPE_VECTOR_SUBPARTS (type0),
5385			    TYPE_VECTOR_SUBPARTS (type1)))
5386	{
5387	  result_type = type0;
5388	  converted = 1;
5389	}
5390      else if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
5391	{
5392	  tree const_op0 = fold_for_warn (op0);
5393	  if (TREE_CODE (const_op0) != INTEGER_CST)
5394	    const_op0 = op0;
5395	  tree const_op1 = fold_for_warn (op1);
5396	  if (TREE_CODE (const_op1) != INTEGER_CST)
5397	    const_op1 = op1;
5398	  result_type = type0;
5399	  doing_shift = true;
5400	  if (TREE_CODE (const_op0) == INTEGER_CST
5401	      && tree_int_cst_sgn (const_op0) < 0
5402	      && !TYPE_OVERFLOW_WRAPS (type0)
5403	      && (complain & tf_warning)
5404	      && c_inhibit_evaluation_warnings == 0)
5405	    warning_at (location, OPT_Wshift_negative_value,
5406			"left shift of negative value");
5407	  if (TREE_CODE (const_op1) == INTEGER_CST)
5408	    {
5409	      if (tree_int_cst_lt (const_op1, integer_zero_node))
5410		{
5411		  if ((complain & tf_warning)
5412		      && c_inhibit_evaluation_warnings == 0)
5413		    warning_at (location, OPT_Wshift_count_negative,
5414				"left shift count is negative");
5415		}
5416	      else if (compare_tree_int (const_op1,
5417					 TYPE_PRECISION (type0)) >= 0)
5418		{
5419		  if ((complain & tf_warning)
5420		      && c_inhibit_evaluation_warnings == 0)
5421		    warning_at (location, OPT_Wshift_count_overflow,
5422				"left shift count >= width of type");
5423		}
5424	      else if (TREE_CODE (const_op0) == INTEGER_CST
5425		       && (complain & tf_warning))
5426		maybe_warn_shift_overflow (location, const_op0, const_op1);
5427	    }
5428	  /* Avoid converting op1 to result_type later.  */
5429	  converted = 1;
5430	}
5431      break;
5432
5433    case EQ_EXPR:
5434    case NE_EXPR:
5435      if (gnu_vector_type_p (type0) && gnu_vector_type_p (type1))
5436	goto vector_compare;
5437      if ((complain & tf_warning)
5438	  && c_inhibit_evaluation_warnings == 0
5439	  && (FLOAT_TYPE_P (type0) || FLOAT_TYPE_P (type1)))
5440	warning_at (location, OPT_Wfloat_equal,
5441		    "comparing floating-point with %<==%> "
5442		    "or %<!=%> is unsafe");
5443      if (complain & tf_warning)
5444	{
5445	  tree stripped_orig_op0 = tree_strip_any_location_wrapper (orig_op0);
5446	  tree stripped_orig_op1 = tree_strip_any_location_wrapper (orig_op1);
5447	  if ((TREE_CODE (stripped_orig_op0) == STRING_CST
5448	       && !integer_zerop (cp_fully_fold (op1)))
5449	      || (TREE_CODE (stripped_orig_op1) == STRING_CST
5450		  && !integer_zerop (cp_fully_fold (op0))))
5451	    warning_at (location, OPT_Waddress,
5452			"comparison with string literal results in "
5453			"unspecified behavior");
5454	  else if (warn_array_compare
5455		   && TREE_CODE (TREE_TYPE (orig_op0)) == ARRAY_TYPE
5456		   && TREE_CODE (TREE_TYPE (orig_op1)) == ARRAY_TYPE)
5457	    do_warn_array_compare (location, code, stripped_orig_op0,
5458				   stripped_orig_op1);
5459	}
5460
5461      build_type = boolean_type_node;
5462      if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE
5463	   || code0 == COMPLEX_TYPE || code0 == ENUMERAL_TYPE)
5464	  && (code1 == INTEGER_TYPE || code1 == REAL_TYPE
5465	      || code1 == COMPLEX_TYPE || code1 == ENUMERAL_TYPE))
5466	short_compare = 1;
5467      else if (((code0 == POINTER_TYPE || TYPE_PTRDATAMEM_P (type0))
5468		&& null_ptr_cst_p (orig_op1))
5469	       /* Handle, eg, (void*)0 (c++/43906), and more.  */
5470	       || (code0 == POINTER_TYPE
5471		   && TYPE_PTR_P (type1) && integer_zerop (op1)))
5472	{
5473	  if (TYPE_PTR_P (type1))
5474	    result_type = composite_pointer_type (location,
5475						  type0, type1, op0, op1,
5476						  CPO_COMPARISON, complain);
5477	  else
5478	    result_type = type0;
5479
5480	  if (char_type_p (TREE_TYPE (orig_op1)))
5481	    {
5482	      auto_diagnostic_group d;
5483	      if (warning_at (location, OPT_Wpointer_compare,
5484			      "comparison between pointer and zero character "
5485			      "constant"))
5486		inform (location,
5487			"did you mean to dereference the pointer?");
5488	    }
5489	  warn_for_null_address (location, op0, complain);
5490	}
5491      else if (((code1 == POINTER_TYPE || TYPE_PTRDATAMEM_P (type1))
5492		&& null_ptr_cst_p (orig_op0))
5493	       /* Handle, eg, (void*)0 (c++/43906), and more.  */
5494	       || (code1 == POINTER_TYPE
5495		   && TYPE_PTR_P (type0) && integer_zerop (op0)))
5496	{
5497	  if (TYPE_PTR_P (type0))
5498	    result_type = composite_pointer_type (location,
5499						  type0, type1, op0, op1,
5500						  CPO_COMPARISON, complain);
5501	  else
5502	    result_type = type1;
5503
5504	  if (char_type_p (TREE_TYPE (orig_op0)))
5505	    {
5506	      auto_diagnostic_group d;
5507	      if (warning_at (location, OPT_Wpointer_compare,
5508			     "comparison between pointer and zero character "
5509			     "constant"))
5510		inform (location,
5511			"did you mean to dereference the pointer?");
5512	    }
5513	  warn_for_null_address (location, op1, complain);
5514	}
5515      else if ((code0 == POINTER_TYPE && code1 == POINTER_TYPE)
5516	       || (TYPE_PTRDATAMEM_P (type0) && TYPE_PTRDATAMEM_P (type1)))
5517	result_type = composite_pointer_type (location,
5518					      type0, type1, op0, op1,
5519					      CPO_COMPARISON, complain);
5520      else if (null_ptr_cst_p (orig_op0) && null_ptr_cst_p (orig_op1))
5521	/* One of the operands must be of nullptr_t type.  */
5522        result_type = TREE_TYPE (nullptr_node);
5523      else if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE)
5524	{
5525	  result_type = type0;
5526	  if (complain & tf_error)
5527	    permerror (location, "ISO C++ forbids comparison between "
5528		       "pointer and integer");
5529          else
5530            return error_mark_node;
5531	}
5532      else if (code0 == INTEGER_TYPE && code1 == POINTER_TYPE)
5533	{
5534	  result_type = type1;
5535	  if (complain & tf_error)
5536	    permerror (location, "ISO C++ forbids comparison between "
5537		       "pointer and integer");
5538          else
5539            return error_mark_node;
5540	}
5541      else if (TYPE_PTRMEMFUNC_P (type0) && null_ptr_cst_p (orig_op1))
5542	{
5543	  if (TARGET_PTRMEMFUNC_VBIT_LOCATION
5544	      == ptrmemfunc_vbit_in_delta)
5545	    {
5546	      tree pfn0, delta0, e1, e2;
5547
5548	      if (TREE_SIDE_EFFECTS (op0))
5549		op0 = cp_save_expr (op0);
5550
5551	      pfn0 = pfn_from_ptrmemfunc (op0);
5552	      delta0 = delta_from_ptrmemfunc (op0);
5553	      e1 = cp_build_binary_op (location,
5554				       EQ_EXPR,
5555	  			       pfn0,
5556				       build_zero_cst (TREE_TYPE (pfn0)),
5557				       complain);
5558	      e2 = cp_build_binary_op (location,
5559				       BIT_AND_EXPR,
5560				       delta0,
5561				       integer_one_node,
5562				       complain);
5563
5564	      if (complain & tf_warning)
5565		maybe_warn_zero_as_null_pointer_constant (op1, input_location);
5566
5567	      e2 = cp_build_binary_op (location,
5568				       EQ_EXPR, e2, integer_zero_node,
5569				       complain);
5570	      op0 = cp_build_binary_op (location,
5571					TRUTH_ANDIF_EXPR, e1, e2,
5572					complain);
5573	      op1 = cp_convert (TREE_TYPE (op0), integer_one_node, complain);
5574	    }
5575     	  else
5576	    {
5577	      op0 = build_ptrmemfunc_access_expr (op0, pfn_identifier);
5578	      op1 = cp_convert (TREE_TYPE (op0), op1, complain);
5579	    }
5580	  result_type = TREE_TYPE (op0);
5581
5582	  warn_for_null_address (location, orig_op0, complain);
5583	}
5584      else if (TYPE_PTRMEMFUNC_P (type1) && null_ptr_cst_p (orig_op0))
5585	return cp_build_binary_op (location, code, op1, op0, complain);
5586      else if (TYPE_PTRMEMFUNC_P (type0) && TYPE_PTRMEMFUNC_P (type1))
5587	{
5588	  tree type;
5589	  /* E will be the final comparison.  */
5590	  tree e;
5591	  /* E1 and E2 are for scratch.  */
5592	  tree e1;
5593	  tree e2;
5594	  tree pfn0;
5595	  tree pfn1;
5596	  tree delta0;
5597	  tree delta1;
5598
5599	  type = composite_pointer_type (location, type0, type1, op0, op1,
5600					 CPO_COMPARISON, complain);
5601
5602	  if (!same_type_p (TREE_TYPE (op0), type))
5603	    op0 = cp_convert_and_check (type, op0, complain);
5604	  if (!same_type_p (TREE_TYPE (op1), type))
5605	    op1 = cp_convert_and_check (type, op1, complain);
5606
5607	  if (op0 == error_mark_node || op1 == error_mark_node)
5608	    return error_mark_node;
5609
5610	  if (TREE_SIDE_EFFECTS (op0))
5611	    op0 = save_expr (op0);
5612	  if (TREE_SIDE_EFFECTS (op1))
5613	    op1 = save_expr (op1);
5614
5615	  pfn0 = pfn_from_ptrmemfunc (op0);
5616	  pfn0 = cp_fully_fold (pfn0);
5617	  /* Avoid -Waddress warnings (c++/64877).  */
5618	  if (TREE_CODE (pfn0) == ADDR_EXPR)
5619	    suppress_warning (pfn0, OPT_Waddress);
5620	  pfn1 = pfn_from_ptrmemfunc (op1);
5621	  pfn1 = cp_fully_fold (pfn1);
5622	  delta0 = delta_from_ptrmemfunc (op0);
5623	  delta1 = delta_from_ptrmemfunc (op1);
5624	  if (TARGET_PTRMEMFUNC_VBIT_LOCATION
5625	      == ptrmemfunc_vbit_in_delta)
5626	    {
5627	      /* We generate:
5628
5629		 (op0.pfn == op1.pfn
5630		  && ((op0.delta == op1.delta)
5631     		       || (!op0.pfn && op0.delta & 1 == 0
5632			   && op1.delta & 1 == 0))
5633
5634	         The reason for the `!op0.pfn' bit is that a NULL
5635	         pointer-to-member is any member with a zero PFN and
5636	         LSB of the DELTA field is 0.  */
5637
5638	      e1 = cp_build_binary_op (location, BIT_AND_EXPR,
5639				       delta0,
5640				       integer_one_node,
5641				       complain);
5642	      e1 = cp_build_binary_op (location,
5643				       EQ_EXPR, e1, integer_zero_node,
5644				       complain);
5645	      e2 = cp_build_binary_op (location, BIT_AND_EXPR,
5646				       delta1,
5647				       integer_one_node,
5648				       complain);
5649	      e2 = cp_build_binary_op (location,
5650				       EQ_EXPR, e2, integer_zero_node,
5651				       complain);
5652	      e1 = cp_build_binary_op (location,
5653				       TRUTH_ANDIF_EXPR, e2, e1,
5654				       complain);
5655	      e2 = cp_build_binary_op (location, EQ_EXPR,
5656				       pfn0,
5657				       build_zero_cst (TREE_TYPE (pfn0)),
5658				       complain);
5659	      e2 = cp_build_binary_op (location,
5660				       TRUTH_ANDIF_EXPR, e2, e1, complain);
5661	      e1 = cp_build_binary_op (location,
5662				       EQ_EXPR, delta0, delta1, complain);
5663	      e1 = cp_build_binary_op (location,
5664				       TRUTH_ORIF_EXPR, e1, e2, complain);
5665	    }
5666	  else
5667	    {
5668	      /* We generate:
5669
5670	         (op0.pfn == op1.pfn
5671	         && (!op0.pfn || op0.delta == op1.delta))
5672
5673	         The reason for the `!op0.pfn' bit is that a NULL
5674	         pointer-to-member is any member with a zero PFN; the
5675	         DELTA field is unspecified.  */
5676
5677    	      e1 = cp_build_binary_op (location,
5678				       EQ_EXPR, delta0, delta1, complain);
5679	      e2 = cp_build_binary_op (location,
5680				       EQ_EXPR,
5681		      		       pfn0,
5682			   	       build_zero_cst (TREE_TYPE (pfn0)),
5683				       complain);
5684	      e1 = cp_build_binary_op (location,
5685				       TRUTH_ORIF_EXPR, e1, e2, complain);
5686	    }
5687	  e2 = build2 (EQ_EXPR, boolean_type_node, pfn0, pfn1);
5688	  e = cp_build_binary_op (location,
5689				  TRUTH_ANDIF_EXPR, e2, e1, complain);
5690	  if (code == EQ_EXPR)
5691	    return e;
5692	  return cp_build_binary_op (location,
5693				     EQ_EXPR, e, integer_zero_node, complain);
5694	}
5695      else
5696	{
5697	  gcc_assert (!TYPE_PTRMEMFUNC_P (type0)
5698		      || !same_type_p (TYPE_PTRMEMFUNC_FN_TYPE (type0),
5699				       type1));
5700	  gcc_assert (!TYPE_PTRMEMFUNC_P (type1)
5701		      || !same_type_p (TYPE_PTRMEMFUNC_FN_TYPE (type1),
5702				       type0));
5703	}
5704
5705      break;
5706
5707    case MAX_EXPR:
5708    case MIN_EXPR:
5709      if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE)
5710	   && (code1 == INTEGER_TYPE || code1 == REAL_TYPE))
5711	shorten = 1;
5712      else if (code0 == POINTER_TYPE && code1 == POINTER_TYPE)
5713	result_type = composite_pointer_type (location,
5714					      type0, type1, op0, op1,
5715					      CPO_COMPARISON, complain);
5716      break;
5717
5718    case LE_EXPR:
5719    case GE_EXPR:
5720    case LT_EXPR:
5721    case GT_EXPR:
5722    case SPACESHIP_EXPR:
5723      if (TREE_CODE (orig_op0) == STRING_CST
5724	  || TREE_CODE (orig_op1) == STRING_CST)
5725	{
5726	  if (complain & tf_warning)
5727	    warning_at (location, OPT_Waddress,
5728			"comparison with string literal results "
5729			"in unspecified behavior");
5730	}
5731      else if (warn_array_compare
5732	       && TREE_CODE (TREE_TYPE (orig_op0)) == ARRAY_TYPE
5733	       && TREE_CODE (TREE_TYPE (orig_op1)) == ARRAY_TYPE
5734	       && code != SPACESHIP_EXPR
5735	       && (complain & tf_warning))
5736	do_warn_array_compare (location, code,
5737			       tree_strip_any_location_wrapper (orig_op0),
5738			       tree_strip_any_location_wrapper (orig_op1));
5739
5740      if (gnu_vector_type_p (type0) && gnu_vector_type_p (type1))
5741	{
5742	vector_compare:
5743	  tree intt;
5744	  if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type0),
5745							  TREE_TYPE (type1))
5746	      && !vector_types_compatible_elements_p (type0, type1))
5747	    {
5748	      if (complain & tf_error)
5749		{
5750		  error_at (location, "comparing vectors with different "
5751				      "element types");
5752		  inform (location, "operand types are %qT and %qT",
5753			  type0, type1);
5754		}
5755	      return error_mark_node;
5756	    }
5757
5758	  if (maybe_ne (TYPE_VECTOR_SUBPARTS (type0),
5759			TYPE_VECTOR_SUBPARTS (type1)))
5760	    {
5761	      if (complain & tf_error)
5762		{
5763		  error_at (location, "comparing vectors with different "
5764				      "number of elements");
5765		  inform (location, "operand types are %qT and %qT",
5766			  type0, type1);
5767		}
5768	      return error_mark_node;
5769	    }
5770
5771	  /* It's not precisely specified how the usual arithmetic
5772	     conversions apply to the vector types.  Here, we use
5773	     the unsigned type if one of the operands is signed and
5774	     the other one is unsigned.  */
5775	  if (TYPE_UNSIGNED (type0) != TYPE_UNSIGNED (type1))
5776	    {
5777	      if (!TYPE_UNSIGNED (type0))
5778		op0 = build1 (VIEW_CONVERT_EXPR, type1, op0);
5779	      else
5780		op1 = build1 (VIEW_CONVERT_EXPR, type0, op1);
5781	      warning_at (location, OPT_Wsign_compare, "comparison between "
5782			  "types %qT and %qT", type0, type1);
5783	    }
5784
5785	  if (resultcode == SPACESHIP_EXPR)
5786	    {
5787	      if (complain & tf_error)
5788		sorry_at (location, "three-way comparison of vectors");
5789	      return error_mark_node;
5790	    }
5791
5792	  /* Always construct signed integer vector type.  */
5793	  intt = c_common_type_for_size
5794	    (GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (type0))), 0);
5795	  if (!intt)
5796	    {
5797	      if (complain & tf_error)
5798		error_at (location, "could not find an integer type "
5799			  "of the same size as %qT", TREE_TYPE (type0));
5800	      return error_mark_node;
5801	    }
5802	  result_type = build_opaque_vector_type (intt,
5803						  TYPE_VECTOR_SUBPARTS (type0));
5804	  return build_vec_cmp (resultcode, result_type, op0, op1);
5805	}
5806      build_type = boolean_type_node;
5807      if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE
5808	   || code0 == ENUMERAL_TYPE)
5809	   && (code1 == INTEGER_TYPE || code1 == REAL_TYPE
5810	       || code1 == ENUMERAL_TYPE))
5811	short_compare = 1;
5812      else if (code0 == POINTER_TYPE && code1 == POINTER_TYPE)
5813	result_type = composite_pointer_type (location,
5814					      type0, type1, op0, op1,
5815					      CPO_COMPARISON, complain);
5816      else if ((code0 == POINTER_TYPE && null_ptr_cst_p (orig_op1))
5817	       || (code1 == POINTER_TYPE && null_ptr_cst_p (orig_op0))
5818	       || (null_ptr_cst_p (orig_op0) && null_ptr_cst_p (orig_op1)))
5819	{
5820	  /* Core Issue 1512 made this ill-formed.  */
5821	  if (complain & tf_error)
5822	    error_at (location, "ordered comparison of pointer with "
5823		      "integer zero (%qT and %qT)", type0, type1);
5824	  return error_mark_node;
5825	}
5826      else if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE)
5827	{
5828	  result_type = type0;
5829	  if (complain & tf_error)
5830	    permerror (location, "ISO C++ forbids comparison between "
5831		       "pointer and integer");
5832	  else
5833            return error_mark_node;
5834	}
5835      else if (code0 == INTEGER_TYPE && code1 == POINTER_TYPE)
5836	{
5837	  result_type = type1;
5838	  if (complain & tf_error)
5839	    permerror (location, "ISO C++ forbids comparison between "
5840		       "pointer and integer");
5841	  else
5842            return error_mark_node;
5843	}
5844
5845      if ((code0 == POINTER_TYPE || code1 == POINTER_TYPE)
5846	  && !processing_template_decl
5847	  && sanitize_flags_p (SANITIZE_POINTER_COMPARE))
5848	{
5849	  op0 = save_expr (op0);
5850	  op1 = save_expr (op1);
5851
5852	  tree tt = builtin_decl_explicit (BUILT_IN_ASAN_POINTER_COMPARE);
5853	  instrument_expr = build_call_expr_loc (location, tt, 2, op0, op1);
5854	}
5855
5856      break;
5857
5858    case UNORDERED_EXPR:
5859    case ORDERED_EXPR:
5860    case UNLT_EXPR:
5861    case UNLE_EXPR:
5862    case UNGT_EXPR:
5863    case UNGE_EXPR:
5864    case UNEQ_EXPR:
5865      build_type = integer_type_node;
5866      if (code0 != REAL_TYPE || code1 != REAL_TYPE)
5867	{
5868	  if (complain & tf_error)
5869	    error ("unordered comparison on non-floating-point argument");
5870	  return error_mark_node;
5871	}
5872      common = 1;
5873      break;
5874
5875    default:
5876      break;
5877    }
5878
5879  if (((code0 == INTEGER_TYPE || code0 == REAL_TYPE || code0 == COMPLEX_TYPE
5880	|| code0 == ENUMERAL_TYPE)
5881       && (code1 == INTEGER_TYPE || code1 == REAL_TYPE
5882	   || code1 == COMPLEX_TYPE || code1 == ENUMERAL_TYPE)))
5883    arithmetic_types_p = 1;
5884  else
5885    {
5886      arithmetic_types_p = 0;
5887      /* Vector arithmetic is only allowed when both sides are vectors.  */
5888      if (gnu_vector_type_p (type0) && gnu_vector_type_p (type1))
5889	{
5890	  if (!tree_int_cst_equal (TYPE_SIZE (type0), TYPE_SIZE (type1))
5891	      || !vector_types_compatible_elements_p (type0, type1))
5892	    {
5893	      if (complain & tf_error)
5894		{
5895		  /* "location" already embeds the locations of the
5896		     operands, so we don't need to add them separately
5897		     to richloc.  */
5898		  rich_location richloc (line_table, location);
5899		  binary_op_error (&richloc, code, type0, type1);
5900		}
5901	      return error_mark_node;
5902	    }
5903	  arithmetic_types_p = 1;
5904	}
5905    }
5906  /* Determine the RESULT_TYPE, if it is not already known.  */
5907  if (!result_type
5908      && arithmetic_types_p
5909      && (shorten || common || short_compare))
5910    {
5911      result_type = cp_common_type (type0, type1);
5912      if (complain & tf_warning)
5913	{
5914	  do_warn_double_promotion (result_type, type0, type1,
5915				    "implicit conversion from %qH to %qI "
5916				    "to match other operand of binary "
5917				    "expression",
5918				    location);
5919	  do_warn_enum_conversions (location, code, TREE_TYPE (orig_op0),
5920				    TREE_TYPE (orig_op1));
5921	}
5922    }
5923
5924  if (code == SPACESHIP_EXPR)
5925    {
5926      iloc_sentinel s (location);
5927
5928      tree orig_type0 = TREE_TYPE (orig_op0);
5929      tree_code orig_code0 = TREE_CODE (orig_type0);
5930      tree orig_type1 = TREE_TYPE (orig_op1);
5931      tree_code orig_code1 = TREE_CODE (orig_type1);
5932      if (!result_type || result_type == error_mark_node)
5933	/* Nope.  */
5934	result_type = NULL_TREE;
5935      else if ((orig_code0 == BOOLEAN_TYPE) != (orig_code1 == BOOLEAN_TYPE))
5936	/* "If one of the operands is of type bool and the other is not, the
5937	   program is ill-formed."  */
5938	result_type = NULL_TREE;
5939      else if (code0 == POINTER_TYPE && orig_code0 != POINTER_TYPE
5940	       && code1 == POINTER_TYPE && orig_code1 != POINTER_TYPE)
5941	/* We only do array/function-to-pointer conversion if "at least one of
5942	   the operands is of pointer type".  */
5943	result_type = NULL_TREE;
5944      else if (TYPE_PTRFN_P (result_type) || NULLPTR_TYPE_P (result_type))
5945	/* <=> no longer supports equality relations.  */
5946	result_type = NULL_TREE;
5947      else if (orig_code0 == ENUMERAL_TYPE && orig_code1 == ENUMERAL_TYPE
5948	       && !(same_type_ignoring_top_level_qualifiers_p
5949		    (orig_type0, orig_type1)))
5950	/* "If both operands have arithmetic types, or one operand has integral
5951	   type and the other operand has unscoped enumeration type, the usual
5952	   arithmetic conversions are applied to the operands."  So we don't do
5953	   arithmetic conversions if the operands both have enumeral type.  */
5954	result_type = NULL_TREE;
5955      else if ((orig_code0 == ENUMERAL_TYPE && orig_code1 == REAL_TYPE)
5956	       || (orig_code0 == REAL_TYPE && orig_code1 == ENUMERAL_TYPE))
5957	/* [depr.arith.conv.enum]: Three-way comparisons between such operands
5958	   [where one is of enumeration type and the other is of a different
5959	   enumeration type or a floating-point type] are ill-formed.  */
5960	result_type = NULL_TREE;
5961
5962      if (result_type)
5963	{
5964	  build_type = spaceship_type (result_type, complain);
5965	  if (build_type == error_mark_node)
5966	    return error_mark_node;
5967	}
5968
5969      if (result_type && arithmetic_types_p)
5970	{
5971	  /* If a narrowing conversion is required, other than from an integral
5972	     type to a floating point type, the program is ill-formed.  */
5973	  bool ok = true;
5974	  if (TREE_CODE (result_type) == REAL_TYPE
5975	      && CP_INTEGRAL_TYPE_P (orig_type0))
5976	    /* OK */;
5977	  else if (!check_narrowing (result_type, orig_op0, complain))
5978	    ok = false;
5979	  if (TREE_CODE (result_type) == REAL_TYPE
5980	      && CP_INTEGRAL_TYPE_P (orig_type1))
5981	    /* OK */;
5982	  else if (!check_narrowing (result_type, orig_op1, complain))
5983	    ok = false;
5984	  if (!ok && !(complain & tf_error))
5985	    return error_mark_node;
5986	}
5987    }
5988
5989  if (!result_type)
5990    {
5991      if (complain & tf_error)
5992	{
5993	  binary_op_rich_location richloc (location,
5994					   orig_op0, orig_op1, true);
5995	  error_at (&richloc,
5996		    "invalid operands of types %qT and %qT to binary %qO",
5997		    TREE_TYPE (orig_op0), TREE_TYPE (orig_op1), code);
5998	}
5999      return error_mark_node;
6000    }
6001
6002  /* If we're in a template, the only thing we need to know is the
6003     RESULT_TYPE.  */
6004  if (processing_template_decl)
6005    {
6006      /* Since the middle-end checks the type when doing a build2, we
6007	 need to build the tree in pieces.  This built tree will never
6008	 get out of the front-end as we replace it when instantiating
6009	 the template.  */
6010      tree tmp = build2 (resultcode,
6011			 build_type ? build_type : result_type,
6012			 NULL_TREE, op1);
6013      TREE_OPERAND (tmp, 0) = op0;
6014      return tmp;
6015    }
6016
6017  /* Remember the original type; RESULT_TYPE might be changed later on
6018     by shorten_binary_op.  */
6019  tree orig_type = result_type;
6020
6021  if (arithmetic_types_p)
6022    {
6023      bool first_complex = (code0 == COMPLEX_TYPE);
6024      bool second_complex = (code1 == COMPLEX_TYPE);
6025      int none_complex = (!first_complex && !second_complex);
6026
6027      /* Adapted from patch for c/24581.  */
6028      if (first_complex != second_complex
6029	  && (code == PLUS_EXPR
6030	      || code == MINUS_EXPR
6031	      || code == MULT_EXPR
6032	      || (code == TRUNC_DIV_EXPR && first_complex))
6033	  && TREE_CODE (TREE_TYPE (result_type)) == REAL_TYPE
6034	  && flag_signed_zeros)
6035	{
6036	  /* An operation on mixed real/complex operands must be
6037	     handled specially, but the language-independent code can
6038	     more easily optimize the plain complex arithmetic if
6039	     -fno-signed-zeros.  */
6040	  tree real_type = TREE_TYPE (result_type);
6041	  tree real, imag;
6042	  if (first_complex)
6043	    {
6044	      if (TREE_TYPE (op0) != result_type)
6045		op0 = cp_convert_and_check (result_type, op0, complain);
6046	      if (TREE_TYPE (op1) != real_type)
6047		op1 = cp_convert_and_check (real_type, op1, complain);
6048	    }
6049	  else
6050	    {
6051	      if (TREE_TYPE (op0) != real_type)
6052		op0 = cp_convert_and_check (real_type, op0, complain);
6053	      if (TREE_TYPE (op1) != result_type)
6054		op1 = cp_convert_and_check (result_type, op1, complain);
6055	    }
6056	  if (TREE_CODE (op0) == ERROR_MARK || TREE_CODE (op1) == ERROR_MARK)
6057	    return error_mark_node;
6058	  if (first_complex)
6059	    {
6060	      op0 = save_expr (op0);
6061	      real = cp_build_unary_op (REALPART_EXPR, op0, true, complain);
6062	      imag = cp_build_unary_op (IMAGPART_EXPR, op0, true, complain);
6063	      switch (code)
6064		{
6065		case MULT_EXPR:
6066		case TRUNC_DIV_EXPR:
6067		  op1 = save_expr (op1);
6068		  imag = build2 (resultcode, real_type, imag, op1);
6069		  /* Fall through.  */
6070		case PLUS_EXPR:
6071		case MINUS_EXPR:
6072		  real = build2 (resultcode, real_type, real, op1);
6073		  break;
6074		default:
6075		  gcc_unreachable();
6076		}
6077	    }
6078	  else
6079	    {
6080	      op1 = save_expr (op1);
6081	      real = cp_build_unary_op (REALPART_EXPR, op1, true, complain);
6082	      imag = cp_build_unary_op (IMAGPART_EXPR, op1, true, complain);
6083	      switch (code)
6084		{
6085		case MULT_EXPR:
6086		  op0 = save_expr (op0);
6087		  imag = build2 (resultcode, real_type, op0, imag);
6088		  /* Fall through.  */
6089		case PLUS_EXPR:
6090		  real = build2 (resultcode, real_type, op0, real);
6091		  break;
6092		case MINUS_EXPR:
6093		  real = build2 (resultcode, real_type, op0, real);
6094		  imag = build1 (NEGATE_EXPR, real_type, imag);
6095		  break;
6096		default:
6097		  gcc_unreachable();
6098		}
6099	    }
6100	  result = build2 (COMPLEX_EXPR, result_type, real, imag);
6101	  return result;
6102	}
6103
6104      /* For certain operations (which identify themselves by shorten != 0)
6105	 if both args were extended from the same smaller type,
6106	 do the arithmetic in that type and then extend.
6107
6108	 shorten !=0 and !=1 indicates a bitwise operation.
6109	 For them, this optimization is safe only if
6110	 both args are zero-extended or both are sign-extended.
6111	 Otherwise, we might change the result.
6112	 E.g., (short)-1 | (unsigned short)-1 is (int)-1
6113	 but calculated in (unsigned short) it would be (unsigned short)-1.  */
6114
6115      if (shorten && none_complex)
6116	{
6117	  final_type = result_type;
6118	  result_type = shorten_binary_op (result_type, op0, op1,
6119					   shorten == -1);
6120	}
6121
6122      /* Shifts can be shortened if shifting right.  */
6123
6124      if (short_shift)
6125	{
6126	  int unsigned_arg;
6127	  tree arg0 = get_narrower (op0, &unsigned_arg);
6128	  /* We're not really warning here but when we set short_shift we
6129	     used fold_for_warn to fold the operand.  */
6130	  tree const_op1 = fold_for_warn (op1);
6131
6132	  final_type = result_type;
6133
6134	  if (arg0 == op0 && final_type == TREE_TYPE (op0))
6135	    unsigned_arg = TYPE_UNSIGNED (TREE_TYPE (op0));
6136
6137	  if (TYPE_PRECISION (TREE_TYPE (arg0)) < TYPE_PRECISION (result_type)
6138	      && tree_int_cst_sgn (const_op1) > 0
6139	      /* We can shorten only if the shift count is less than the
6140		 number of bits in the smaller type size.  */
6141	      && compare_tree_int (const_op1,
6142				   TYPE_PRECISION (TREE_TYPE (arg0))) < 0
6143	      /* We cannot drop an unsigned shift after sign-extension.  */
6144	      && (!TYPE_UNSIGNED (final_type) || unsigned_arg))
6145	    {
6146	      /* Do an unsigned shift if the operand was zero-extended.  */
6147	      result_type
6148		= c_common_signed_or_unsigned_type (unsigned_arg,
6149						    TREE_TYPE (arg0));
6150	      /* Convert value-to-be-shifted to that type.  */
6151	      if (TREE_TYPE (op0) != result_type)
6152		op0 = convert (result_type, op0);
6153	      converted = 1;
6154	    }
6155	}
6156
6157      /* Comparison operations are shortened too but differently.
6158	 They identify themselves by setting short_compare = 1.  */
6159
6160      if (short_compare)
6161	{
6162	  /* We call shorten_compare only for diagnostics.  */
6163	  tree xop0 = fold_simple (op0);
6164	  tree xop1 = fold_simple (op1);
6165	  tree xresult_type = result_type;
6166	  enum tree_code xresultcode = resultcode;
6167	  shorten_compare (location, &xop0, &xop1, &xresult_type,
6168			   &xresultcode);
6169	}
6170
6171      if ((short_compare || code == MIN_EXPR || code == MAX_EXPR)
6172	  && warn_sign_compare
6173	  /* Do not warn until the template is instantiated; we cannot
6174	     bound the ranges of the arguments until that point.  */
6175	  && !processing_template_decl
6176          && (complain & tf_warning)
6177	  && c_inhibit_evaluation_warnings == 0
6178	  /* Even unsigned enum types promote to signed int.  We don't
6179	     want to issue -Wsign-compare warnings for this case.  */
6180	  && !enum_cast_to_int (orig_op0)
6181	  && !enum_cast_to_int (orig_op1))
6182	{
6183	  warn_for_sign_compare (location, orig_op0, orig_op1, op0, op1,
6184				 result_type, resultcode);
6185	}
6186    }
6187
6188  /* If CONVERTED is zero, both args will be converted to type RESULT_TYPE.
6189     Then the expression will be built.
6190     It will be given type FINAL_TYPE if that is nonzero;
6191     otherwise, it will be given type RESULT_TYPE.  */
6192  if (! converted)
6193    {
6194      warning_sentinel w (warn_sign_conversion, short_compare);
6195      if (!same_type_p (TREE_TYPE (op0), result_type))
6196	op0 = cp_convert_and_check (result_type, op0, complain);
6197      if (!same_type_p (TREE_TYPE (op1), result_type))
6198	op1 = cp_convert_and_check (result_type, op1, complain);
6199
6200      if (op0 == error_mark_node || op1 == error_mark_node)
6201	return error_mark_node;
6202    }
6203
6204  if (build_type == NULL_TREE)
6205    build_type = result_type;
6206
6207  if (doing_shift
6208      && flag_strong_eval_order == 2
6209      && TREE_SIDE_EFFECTS (op1)
6210      && !processing_template_decl)
6211    {
6212      /* In C++17, in both op0 << op1 and op0 >> op1 op0 is sequenced before
6213	 op1, so if op1 has side-effects, use SAVE_EXPR around op0.  */
6214      op0 = cp_save_expr (op0);
6215      instrument_expr = op0;
6216    }
6217
6218  if (sanitize_flags_p ((SANITIZE_SHIFT
6219			 | SANITIZE_DIVIDE
6220			 | SANITIZE_FLOAT_DIVIDE
6221			 | SANITIZE_SI_OVERFLOW))
6222      && current_function_decl != NULL_TREE
6223      && !processing_template_decl
6224      && (doing_div_or_mod || doing_shift))
6225    {
6226      /* OP0 and/or OP1 might have side-effects.  */
6227      op0 = cp_save_expr (op0);
6228      op1 = cp_save_expr (op1);
6229      op0 = fold_non_dependent_expr (op0, complain);
6230      op1 = fold_non_dependent_expr (op1, complain);
6231      tree instrument_expr1 = NULL_TREE;
6232      if (doing_div_or_mod
6233	  && sanitize_flags_p (SANITIZE_DIVIDE
6234			       | SANITIZE_FLOAT_DIVIDE
6235			       | SANITIZE_SI_OVERFLOW))
6236	{
6237	  /* For diagnostics we want to use the promoted types without
6238	     shorten_binary_op.  So convert the arguments to the
6239	     original result_type.  */
6240	  tree cop0 = op0;
6241	  tree cop1 = op1;
6242	  if (TREE_TYPE (cop0) != orig_type)
6243	    cop0 = cp_convert (orig_type, op0, complain);
6244	  if (TREE_TYPE (cop1) != orig_type)
6245	    cop1 = cp_convert (orig_type, op1, complain);
6246	  instrument_expr1 = ubsan_instrument_division (location, cop0, cop1);
6247	}
6248      else if (doing_shift && sanitize_flags_p (SANITIZE_SHIFT))
6249	instrument_expr1 = ubsan_instrument_shift (location, code, op0, op1);
6250      if (instrument_expr != NULL)
6251	instrument_expr = add_stmt_to_compound (instrument_expr,
6252						instrument_expr1);
6253      else
6254	instrument_expr = instrument_expr1;
6255    }
6256
6257  result = build2_loc (location, resultcode, build_type, op0, op1);
6258  if (final_type != 0)
6259    result = cp_convert (final_type, result, complain);
6260
6261  if (instrument_expr != NULL)
6262    result = build2 (COMPOUND_EXPR, TREE_TYPE (result),
6263		     instrument_expr, result);
6264
6265  if (resultcode == SPACESHIP_EXPR && !processing_template_decl)
6266    result = get_target_expr_sfinae (result, complain);
6267
6268  if (!c_inhibit_evaluation_warnings)
6269    {
6270      if (!processing_template_decl)
6271	{
6272	  op0 = cp_fully_fold (op0);
6273	  /* Only consider the second argument if the first isn't overflowed.  */
6274	  if (!CONSTANT_CLASS_P (op0) || TREE_OVERFLOW_P (op0))
6275	    return result;
6276	  op1 = cp_fully_fold (op1);
6277	  if (!CONSTANT_CLASS_P (op1) || TREE_OVERFLOW_P (op1))
6278	    return result;
6279	}
6280      else if (!CONSTANT_CLASS_P (op0) || !CONSTANT_CLASS_P (op1)
6281	       || TREE_OVERFLOW_P (op0) || TREE_OVERFLOW_P (op1))
6282	return result;
6283
6284      tree result_ovl = fold_build2 (resultcode, build_type, op0, op1);
6285      if (TREE_OVERFLOW_P (result_ovl))
6286	overflow_warning (location, result_ovl);
6287    }
6288
6289  return result;
6290}
6291
6292/* Build a VEC_PERM_EXPR.
6293   This is a simple wrapper for c_build_vec_perm_expr.  */
6294tree
6295build_x_vec_perm_expr (location_t loc,
6296			tree arg0, tree arg1, tree arg2,
6297			tsubst_flags_t complain)
6298{
6299  tree orig_arg0 = arg0;
6300  tree orig_arg1 = arg1;
6301  tree orig_arg2 = arg2;
6302  if (processing_template_decl)
6303    {
6304      if (type_dependent_expression_p (arg0)
6305	  || type_dependent_expression_p (arg1)
6306	  || type_dependent_expression_p (arg2))
6307	return build_min_nt_loc (loc, VEC_PERM_EXPR, arg0, arg1, arg2);
6308      arg0 = build_non_dependent_expr (arg0);
6309      if (arg1)
6310	arg1 = build_non_dependent_expr (arg1);
6311      arg2 = build_non_dependent_expr (arg2);
6312    }
6313  tree exp = c_build_vec_perm_expr (loc, arg0, arg1, arg2, complain & tf_error);
6314  if (processing_template_decl && exp != error_mark_node)
6315    return build_min_non_dep (VEC_PERM_EXPR, exp, orig_arg0,
6316			      orig_arg1, orig_arg2);
6317  return exp;
6318}
6319
6320/* Build a VEC_PERM_EXPR.
6321   This is a simple wrapper for c_build_shufflevector.  */
6322tree
6323build_x_shufflevector (location_t loc, vec<tree, va_gc> *args,
6324		       tsubst_flags_t complain)
6325{
6326  tree arg0 = (*args)[0];
6327  tree arg1 = (*args)[1];
6328  if (processing_template_decl)
6329    {
6330      for (unsigned i = 0; i < args->length (); ++i)
6331	if (i <= 1
6332	    ? type_dependent_expression_p ((*args)[i])
6333	    : instantiation_dependent_expression_p ((*args)[i]))
6334	  {
6335	    tree exp = build_min_nt_call_vec (NULL, args);
6336	    CALL_EXPR_IFN (exp) = IFN_SHUFFLEVECTOR;
6337	    return exp;
6338	  }
6339      arg0 = build_non_dependent_expr (arg0);
6340      arg1 = build_non_dependent_expr (arg1);
6341      /* ???  Nothing needed for the index arguments?  */
6342    }
6343  auto_vec<tree, 16> mask;
6344  for (unsigned i = 2; i < args->length (); ++i)
6345    {
6346      tree idx = fold_non_dependent_expr ((*args)[i], complain);
6347      mask.safe_push (idx);
6348    }
6349  tree exp = c_build_shufflevector (loc, arg0, arg1, mask, complain & tf_error);
6350  if (processing_template_decl && exp != error_mark_node)
6351    {
6352      exp = build_min_non_dep_call_vec (exp, NULL, args);
6353      CALL_EXPR_IFN (exp) = IFN_SHUFFLEVECTOR;
6354    }
6355  return exp;
6356}
6357
6358/* Return a tree for the sum or difference (RESULTCODE says which)
6359   of pointer PTROP and integer INTOP.  */
6360
6361static tree
6362cp_pointer_int_sum (location_t loc, enum tree_code resultcode, tree ptrop,
6363		    tree intop, tsubst_flags_t complain)
6364{
6365  tree res_type = TREE_TYPE (ptrop);
6366
6367  /* pointer_int_sum() uses size_in_bytes() on the TREE_TYPE(res_type)
6368     in certain circumstance (when it's valid to do so).  So we need
6369     to make sure it's complete.  We don't need to check here, if we
6370     can actually complete it at all, as those checks will be done in
6371     pointer_int_sum() anyway.  */
6372  complete_type (TREE_TYPE (res_type));
6373
6374  return pointer_int_sum (loc, resultcode, ptrop,
6375			  intop, complain & tf_warning_or_error);
6376}
6377
6378/* Return a tree for the difference of pointers OP0 and OP1.
6379   The resulting tree has type int.  If POINTER_SUBTRACT sanitization is
6380   enabled, assign to INSTRUMENT_EXPR call to libsanitizer.  */
6381
6382static tree
6383pointer_diff (location_t loc, tree op0, tree op1, tree ptrtype,
6384	      tsubst_flags_t complain, tree *instrument_expr)
6385{
6386  tree result, inttype;
6387  tree restype = ptrdiff_type_node;
6388  tree target_type = TREE_TYPE (ptrtype);
6389
6390  if (!complete_type_or_maybe_complain (target_type, NULL_TREE, complain))
6391    return error_mark_node;
6392
6393  if (VOID_TYPE_P (target_type))
6394    {
6395      if (complain & tf_error)
6396	permerror (loc, "ISO C++ forbids using pointer of "
6397		   "type %<void *%> in subtraction");
6398      else
6399	return error_mark_node;
6400    }
6401  if (TREE_CODE (target_type) == FUNCTION_TYPE)
6402    {
6403      if (complain & tf_error)
6404	permerror (loc, "ISO C++ forbids using pointer to "
6405		   "a function in subtraction");
6406      else
6407	return error_mark_node;
6408    }
6409  if (TREE_CODE (target_type) == METHOD_TYPE)
6410    {
6411      if (complain & tf_error)
6412	permerror (loc, "ISO C++ forbids using pointer to "
6413		   "a method in subtraction");
6414      else
6415	return error_mark_node;
6416    }
6417  else if (!verify_type_context (loc, TCTX_POINTER_ARITH,
6418				 TREE_TYPE (TREE_TYPE (op0)),
6419				 !(complain & tf_error))
6420	   || !verify_type_context (loc, TCTX_POINTER_ARITH,
6421				    TREE_TYPE (TREE_TYPE (op1)),
6422				    !(complain & tf_error)))
6423    return error_mark_node;
6424
6425  /* Determine integer type result of the subtraction.  This will usually
6426     be the same as the result type (ptrdiff_t), but may need to be a wider
6427     type if pointers for the address space are wider than ptrdiff_t.  */
6428  if (TYPE_PRECISION (restype) < TYPE_PRECISION (TREE_TYPE (op0)))
6429    inttype = c_common_type_for_size (TYPE_PRECISION (TREE_TYPE (op0)), 0);
6430  else
6431    inttype = restype;
6432
6433  if (!processing_template_decl
6434      && sanitize_flags_p (SANITIZE_POINTER_SUBTRACT))
6435    {
6436      op0 = save_expr (op0);
6437      op1 = save_expr (op1);
6438
6439      tree tt = builtin_decl_explicit (BUILT_IN_ASAN_POINTER_SUBTRACT);
6440      *instrument_expr = build_call_expr_loc (loc, tt, 2, op0, op1);
6441    }
6442
6443  /* First do the subtraction, then build the divide operator
6444     and only convert at the very end.
6445     Do not do default conversions in case restype is a short type.  */
6446
6447  /* POINTER_DIFF_EXPR requires a signed integer type of the same size as
6448     pointers.  If some platform cannot provide that, or has a larger
6449     ptrdiff_type to support differences larger than half the address
6450     space, cast the pointers to some larger integer type and do the
6451     computations in that type.  */
6452  if (TYPE_PRECISION (inttype) > TYPE_PRECISION (TREE_TYPE (op0)))
6453    op0 = cp_build_binary_op (loc,
6454			      MINUS_EXPR,
6455			      cp_convert (inttype, op0, complain),
6456			      cp_convert (inttype, op1, complain),
6457			      complain);
6458  else
6459    op0 = build2_loc (loc, POINTER_DIFF_EXPR, inttype, op0, op1);
6460
6461  /* This generates an error if op1 is a pointer to an incomplete type.  */
6462  if (!COMPLETE_TYPE_P (TREE_TYPE (TREE_TYPE (op1))))
6463    {
6464      if (complain & tf_error)
6465	error_at (loc, "invalid use of a pointer to an incomplete type in "
6466		  "pointer arithmetic");
6467      else
6468	return error_mark_node;
6469    }
6470
6471  if (pointer_to_zero_sized_aggr_p (TREE_TYPE (op1)))
6472    {
6473      if (complain & tf_error)
6474	error_at (loc, "arithmetic on pointer to an empty aggregate");
6475      else
6476	return error_mark_node;
6477    }
6478
6479  op1 = (TYPE_PTROB_P (ptrtype)
6480	 ? size_in_bytes_loc (loc, target_type)
6481	 : integer_one_node);
6482
6483  /* Do the division.  */
6484
6485  result = build2_loc (loc, EXACT_DIV_EXPR, inttype, op0,
6486		       cp_convert (inttype, op1, complain));
6487  return cp_convert (restype, result, complain);
6488}
6489
6490/* Construct and perhaps optimize a tree representation
6491   for a unary operation.  CODE, a tree_code, specifies the operation
6492   and XARG is the operand.  */
6493
6494tree
6495build_x_unary_op (location_t loc, enum tree_code code, cp_expr xarg,
6496		  tree lookups, tsubst_flags_t complain)
6497{
6498  tree orig_expr = xarg;
6499  tree exp;
6500  int ptrmem = 0;
6501  tree overload = NULL_TREE;
6502
6503  if (processing_template_decl)
6504    {
6505      if (type_dependent_expression_p (xarg))
6506	{
6507	  tree e = build_min_nt_loc (loc, code, xarg.get_value (), NULL_TREE);
6508	  TREE_TYPE (e) = build_dependent_operator_type (lookups, code, false);
6509	  return e;
6510	}
6511
6512      xarg = build_non_dependent_expr (xarg);
6513    }
6514
6515  exp = NULL_TREE;
6516
6517  /* [expr.unary.op] says:
6518
6519       The address of an object of incomplete type can be taken.
6520
6521     (And is just the ordinary address operator, not an overloaded
6522     "operator &".)  However, if the type is a template
6523     specialization, we must complete the type at this point so that
6524     an overloaded "operator &" will be available if required.  */
6525  if (code == ADDR_EXPR
6526      && TREE_CODE (xarg) != TEMPLATE_ID_EXPR
6527      && ((CLASS_TYPE_P (TREE_TYPE (xarg))
6528	   && !COMPLETE_TYPE_P (complete_type (TREE_TYPE (xarg))))
6529	  || (TREE_CODE (xarg) == OFFSET_REF)))
6530    /* Don't look for a function.  */;
6531  else
6532    exp = build_new_op (loc, code, LOOKUP_NORMAL, xarg, NULL_TREE,
6533			NULL_TREE, lookups, &overload, complain);
6534
6535  if (!exp && code == ADDR_EXPR)
6536    {
6537      if (is_overloaded_fn (xarg))
6538	{
6539	  tree fn = get_first_fn (xarg);
6540	  if (DECL_CONSTRUCTOR_P (fn) || DECL_DESTRUCTOR_P (fn))
6541	    {
6542	      if (complain & tf_error)
6543		error_at (loc, DECL_CONSTRUCTOR_P (fn)
6544			  ? G_("taking address of constructor %qD")
6545			  : G_("taking address of destructor %qD"),
6546			  fn);
6547	      return error_mark_node;
6548	    }
6549	}
6550
6551      /* A pointer to member-function can be formed only by saying
6552	 &X::mf.  */
6553      if (!flag_ms_extensions && TREE_CODE (TREE_TYPE (xarg)) == METHOD_TYPE
6554	  && (TREE_CODE (xarg) != OFFSET_REF || !PTRMEM_OK_P (xarg)))
6555	{
6556	  if (TREE_CODE (xarg) != OFFSET_REF
6557	      || !TYPE_P (TREE_OPERAND (xarg, 0)))
6558	    {
6559	      if (complain & tf_error)
6560		{
6561		  error_at (loc, "invalid use of %qE to form a "
6562			    "pointer-to-member-function", xarg.get_value ());
6563		  if (TREE_CODE (xarg) != OFFSET_REF)
6564		    inform (loc, "  a qualified-id is required");
6565		}
6566	      return error_mark_node;
6567	    }
6568	  else
6569	    {
6570	      if (complain & tf_error)
6571		error_at (loc, "parentheses around %qE cannot be used to "
6572			  "form a pointer-to-member-function",
6573			  xarg.get_value ());
6574	      else
6575		return error_mark_node;
6576	      PTRMEM_OK_P (xarg) = 1;
6577	    }
6578	}
6579
6580      if (TREE_CODE (xarg) == OFFSET_REF)
6581	{
6582	  ptrmem = PTRMEM_OK_P (xarg);
6583
6584	  if (!ptrmem && !flag_ms_extensions
6585	      && TREE_CODE (TREE_TYPE (TREE_OPERAND (xarg, 1))) == METHOD_TYPE)
6586	    {
6587	      /* A single non-static member, make sure we don't allow a
6588		 pointer-to-member.  */
6589	      xarg = build2 (OFFSET_REF, TREE_TYPE (xarg),
6590			     TREE_OPERAND (xarg, 0),
6591			     ovl_make (TREE_OPERAND (xarg, 1)));
6592	      PTRMEM_OK_P (xarg) = ptrmem;
6593	    }
6594	}
6595
6596      exp = cp_build_addr_expr_strict (xarg, complain);
6597
6598      if (TREE_CODE (exp) == PTRMEM_CST)
6599	PTRMEM_CST_LOCATION (exp) = loc;
6600      else
6601	protected_set_expr_location (exp, loc);
6602    }
6603
6604  if (processing_template_decl && exp != error_mark_node)
6605    {
6606      if (overload != NULL_TREE)
6607	return (build_min_non_dep_op_overload
6608		(code, exp, overload, orig_expr, integer_zero_node));
6609
6610      exp = build_min_non_dep (code, exp, orig_expr,
6611			       /*For {PRE,POST}{INC,DEC}REMENT_EXPR*/NULL_TREE);
6612    }
6613  if (TREE_CODE (exp) == ADDR_EXPR)
6614    PTRMEM_OK_P (exp) = ptrmem;
6615  return exp;
6616}
6617
6618/* Construct and perhaps optimize a tree representation
6619   for __builtin_addressof operation.  ARG specifies the operand.  */
6620
6621tree
6622cp_build_addressof (location_t loc, tree arg, tsubst_flags_t complain)
6623{
6624  tree orig_expr = arg;
6625
6626  if (processing_template_decl)
6627    {
6628      if (type_dependent_expression_p (arg))
6629	return build_min_nt_loc (loc, ADDRESSOF_EXPR, arg, NULL_TREE);
6630
6631      arg = build_non_dependent_expr (arg);
6632    }
6633
6634  tree exp = cp_build_addr_expr_strict (arg, complain);
6635
6636  if (processing_template_decl && exp != error_mark_node)
6637    exp = build_min_non_dep (ADDRESSOF_EXPR, exp, orig_expr, NULL_TREE);
6638  return exp;
6639}
6640
6641/* Like c_common_truthvalue_conversion, but handle pointer-to-member
6642   constants, where a null value is represented by an INTEGER_CST of
6643   -1.  */
6644
6645tree
6646cp_truthvalue_conversion (tree expr, tsubst_flags_t complain)
6647{
6648  tree type = TREE_TYPE (expr);
6649  location_t loc = cp_expr_loc_or_input_loc (expr);
6650  if (TYPE_PTR_OR_PTRMEM_P (type)
6651      /* Avoid ICE on invalid use of non-static member function.  */
6652      || TREE_CODE (expr) == FUNCTION_DECL)
6653    return cp_build_binary_op (loc, NE_EXPR, expr, nullptr_node, complain);
6654  else
6655    return c_common_truthvalue_conversion (loc, expr);
6656}
6657
6658/* Returns EXPR contextually converted to bool.  */
6659
6660tree
6661contextual_conv_bool (tree expr, tsubst_flags_t complain)
6662{
6663  return perform_implicit_conversion_flags (boolean_type_node, expr,
6664					    complain, LOOKUP_NORMAL);
6665}
6666
6667/* Just like cp_truthvalue_conversion, but we want a CLEANUP_POINT_EXPR.  This
6668   is a low-level function; most callers should use maybe_convert_cond.  */
6669
6670tree
6671condition_conversion (tree expr)
6672{
6673  tree t = contextual_conv_bool (expr, tf_warning_or_error);
6674  if (!processing_template_decl)
6675    t = fold_build_cleanup_point_expr (boolean_type_node, t);
6676  return t;
6677}
6678
6679/* Returns the address of T.  This function will fold away
6680   ADDR_EXPR of INDIRECT_REF.  This is only for low-level usage;
6681   most places should use cp_build_addr_expr instead.  */
6682
6683tree
6684build_address (tree t)
6685{
6686  if (error_operand_p (t) || !cxx_mark_addressable (t))
6687    return error_mark_node;
6688  gcc_checking_assert (TREE_CODE (t) != CONSTRUCTOR
6689		       || processing_template_decl);
6690  t = build_fold_addr_expr_loc (EXPR_LOCATION (t), t);
6691  if (TREE_CODE (t) != ADDR_EXPR)
6692    t = rvalue (t);
6693  return t;
6694}
6695
6696/* Return a NOP_EXPR converting EXPR to TYPE.  */
6697
6698tree
6699build_nop (tree type, tree expr)
6700{
6701  if (type == error_mark_node || error_operand_p (expr))
6702    return expr;
6703  return build1_loc (EXPR_LOCATION (expr), NOP_EXPR, type, expr);
6704}
6705
6706/* Take the address of ARG, whatever that means under C++ semantics.
6707   If STRICT_LVALUE is true, require an lvalue; otherwise, allow xvalues
6708   and class rvalues as well.
6709
6710   Nothing should call this function directly; instead, callers should use
6711   cp_build_addr_expr or cp_build_addr_expr_strict.  */
6712
6713static tree
6714cp_build_addr_expr_1 (tree arg, bool strict_lvalue, tsubst_flags_t complain)
6715{
6716  tree argtype;
6717  tree val;
6718
6719  if (!arg || error_operand_p (arg))
6720    return error_mark_node;
6721
6722  arg = mark_lvalue_use (arg);
6723  if (error_operand_p (arg))
6724    return error_mark_node;
6725
6726  argtype = lvalue_type (arg);
6727  location_t loc = cp_expr_loc_or_input_loc (arg);
6728
6729  gcc_assert (!(identifier_p (arg) && IDENTIFIER_ANY_OP_P (arg)));
6730
6731  if (TREE_CODE (arg) == COMPONENT_REF && type_unknown_p (arg)
6732      && !really_overloaded_fn (arg))
6733    {
6734      /* They're trying to take the address of a unique non-static
6735	 member function.  This is ill-formed (except in MS-land),
6736	 but let's try to DTRT.
6737	 Note: We only handle unique functions here because we don't
6738	 want to complain if there's a static overload; non-unique
6739	 cases will be handled by instantiate_type.  But we need to
6740	 handle this case here to allow casts on the resulting PMF.
6741	 We could defer this in non-MS mode, but it's easier to give
6742	 a useful error here.  */
6743
6744      /* Inside constant member functions, the `this' pointer
6745	 contains an extra const qualifier.  TYPE_MAIN_VARIANT
6746	 is used here to remove this const from the diagnostics
6747	 and the created OFFSET_REF.  */
6748      tree base = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (arg, 0)));
6749      tree fn = get_first_fn (TREE_OPERAND (arg, 1));
6750      if (!mark_used (fn, complain) && !(complain & tf_error))
6751	return error_mark_node;
6752
6753      if (! flag_ms_extensions)
6754	{
6755	  tree name = DECL_NAME (fn);
6756	  if (!(complain & tf_error))
6757	    return error_mark_node;
6758	  else if (current_class_type
6759		   && TREE_OPERAND (arg, 0) == current_class_ref)
6760	    /* An expression like &memfn.  */
6761	    permerror (loc,
6762		       "ISO C++ forbids taking the address of an unqualified"
6763		       " or parenthesized non-static member function to form"
6764		       " a pointer to member function.  Say %<&%T::%D%>",
6765		       base, name);
6766	  else
6767	    permerror (loc,
6768		       "ISO C++ forbids taking the address of a bound member"
6769		       " function to form a pointer to member function."
6770		       "  Say %<&%T::%D%>",
6771		       base, name);
6772	}
6773      arg = build_offset_ref (base, fn, /*address_p=*/true, complain);
6774    }
6775
6776  /* Uninstantiated types are all functions.  Taking the
6777     address of a function is a no-op, so just return the
6778     argument.  */
6779  if (type_unknown_p (arg))
6780    return build1 (ADDR_EXPR, unknown_type_node, arg);
6781
6782  if (TREE_CODE (arg) == OFFSET_REF)
6783    /* We want a pointer to member; bypass all the code for actually taking
6784       the address of something.  */
6785    goto offset_ref;
6786
6787  /* Anything not already handled and not a true memory reference
6788     is an error.  */
6789  if (!FUNC_OR_METHOD_TYPE_P (argtype))
6790    {
6791      cp_lvalue_kind kind = lvalue_kind (arg);
6792      if (kind == clk_none)
6793	{
6794	  if (complain & tf_error)
6795	    lvalue_error (loc, lv_addressof);
6796	  return error_mark_node;
6797	}
6798      if (strict_lvalue && (kind & (clk_rvalueref|clk_class)))
6799	{
6800	  if (!(complain & tf_error))
6801	    return error_mark_node;
6802	  /* Make this a permerror because we used to accept it.  */
6803	  permerror (loc, "taking address of rvalue");
6804	}
6805    }
6806
6807  if (TYPE_REF_P (argtype))
6808    {
6809      tree type = build_pointer_type (TREE_TYPE (argtype));
6810      arg = build1 (CONVERT_EXPR, type, arg);
6811      return arg;
6812    }
6813  else if (pedantic && DECL_MAIN_P (tree_strip_any_location_wrapper (arg)))
6814    {
6815      /* ARM $3.4 */
6816      /* Apparently a lot of autoconf scripts for C++ packages do this,
6817	 so only complain if -Wpedantic.  */
6818      if (complain & (flag_pedantic_errors ? tf_error : tf_warning))
6819	pedwarn (loc, OPT_Wpedantic,
6820		 "ISO C++ forbids taking address of function %<::main%>");
6821      else if (flag_pedantic_errors)
6822	return error_mark_node;
6823    }
6824
6825  /* Let &* cancel out to simplify resulting code.  */
6826  if (INDIRECT_REF_P (arg))
6827    {
6828      arg = TREE_OPERAND (arg, 0);
6829      if (TYPE_REF_P (TREE_TYPE (arg)))
6830	{
6831	  tree type = build_pointer_type (TREE_TYPE (TREE_TYPE (arg)));
6832	  arg = build1 (CONVERT_EXPR, type, arg);
6833	}
6834      else
6835	/* Don't let this be an lvalue.  */
6836	arg = rvalue (arg);
6837      return arg;
6838    }
6839
6840  /* Handle complex lvalues (when permitted)
6841     by reduction to simpler cases.  */
6842  val = unary_complex_lvalue (ADDR_EXPR, arg);
6843  if (val != 0)
6844    return val;
6845
6846  switch (TREE_CODE (arg))
6847    {
6848    CASE_CONVERT:
6849    case FLOAT_EXPR:
6850    case FIX_TRUNC_EXPR:
6851      /* We should have handled this above in the lvalue_kind check.  */
6852      gcc_unreachable ();
6853      break;
6854
6855    case BASELINK:
6856      arg = BASELINK_FUNCTIONS (arg);
6857      /* Fall through.  */
6858
6859    case OVERLOAD:
6860      arg = OVL_FIRST (arg);
6861      break;
6862
6863    case OFFSET_REF:
6864    offset_ref:
6865      /* Turn a reference to a non-static data member into a
6866	 pointer-to-member.  */
6867      {
6868	tree type;
6869	tree t;
6870
6871	gcc_assert (PTRMEM_OK_P (arg));
6872
6873	t = TREE_OPERAND (arg, 1);
6874	if (TYPE_REF_P (TREE_TYPE (t)))
6875	  {
6876	    if (complain & tf_error)
6877	      error_at (loc,
6878			"cannot create pointer to reference member %qD", t);
6879	    return error_mark_node;
6880	  }
6881
6882	/* Forming a pointer-to-member is a use of non-pure-virtual fns.  */
6883	if (TREE_CODE (t) == FUNCTION_DECL
6884	    && !DECL_PURE_VIRTUAL_P (t)
6885	    && !mark_used (t, complain) && !(complain & tf_error))
6886	  return error_mark_node;
6887
6888	type = build_ptrmem_type (context_for_name_lookup (t),
6889				  TREE_TYPE (t));
6890	t = make_ptrmem_cst (type, t);
6891	return t;
6892      }
6893
6894    default:
6895      break;
6896    }
6897
6898  if (argtype != error_mark_node)
6899    argtype = build_pointer_type (argtype);
6900
6901  if (bitfield_p (arg))
6902    {
6903      if (complain & tf_error)
6904	error_at (loc, "attempt to take address of bit-field");
6905      return error_mark_node;
6906    }
6907
6908  /* In a template, we are processing a non-dependent expression
6909     so we can just form an ADDR_EXPR with the correct type.  */
6910  if (processing_template_decl || TREE_CODE (arg) != COMPONENT_REF)
6911    {
6912      if (!mark_single_function (arg, complain))
6913	return error_mark_node;
6914      val = build_address (arg);
6915      if (TREE_CODE (arg) == OFFSET_REF)
6916	PTRMEM_OK_P (val) = PTRMEM_OK_P (arg);
6917    }
6918  else if (BASELINK_P (TREE_OPERAND (arg, 1)))
6919    {
6920      tree fn = BASELINK_FUNCTIONS (TREE_OPERAND (arg, 1));
6921
6922      /* We can only get here with a single static member
6923	 function.  */
6924      gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
6925		  && DECL_STATIC_FUNCTION_P (fn));
6926      if (!mark_used (fn, complain) && !(complain & tf_error))
6927	return error_mark_node;
6928      val = build_address (fn);
6929      if (TREE_SIDE_EFFECTS (TREE_OPERAND (arg, 0)))
6930	/* Do not lose object's side effects.  */
6931	val = build2 (COMPOUND_EXPR, TREE_TYPE (val),
6932		      TREE_OPERAND (arg, 0), val);
6933    }
6934  else
6935    {
6936      tree object = TREE_OPERAND (arg, 0);
6937      tree field = TREE_OPERAND (arg, 1);
6938      gcc_assert (same_type_ignoring_top_level_qualifiers_p
6939		  (TREE_TYPE (object), decl_type_context (field)));
6940      val = build_address (arg);
6941    }
6942
6943  if (TYPE_PTR_P (argtype)
6944      && TREE_CODE (TREE_TYPE (argtype)) == METHOD_TYPE)
6945    {
6946      build_ptrmemfunc_type (argtype);
6947      val = build_ptrmemfunc (argtype, val, 0,
6948			      /*c_cast_p=*/false,
6949			      complain);
6950    }
6951
6952  /* For addresses of immediate functions ensure we have EXPR_LOCATION
6953     set for possible later diagnostics.  */
6954  if (TREE_CODE (val) == ADDR_EXPR
6955      && TREE_CODE (TREE_OPERAND (val, 0)) == FUNCTION_DECL
6956      && DECL_IMMEDIATE_FUNCTION_P (TREE_OPERAND (val, 0)))
6957    SET_EXPR_LOCATION (val, input_location);
6958
6959  return val;
6960}
6961
6962/* Take the address of ARG if it has one, even if it's an rvalue.  */
6963
6964tree
6965cp_build_addr_expr (tree arg, tsubst_flags_t complain)
6966{
6967  return cp_build_addr_expr_1 (arg, 0, complain);
6968}
6969
6970/* Take the address of ARG, but only if it's an lvalue.  */
6971
6972static tree
6973cp_build_addr_expr_strict (tree arg, tsubst_flags_t complain)
6974{
6975  return cp_build_addr_expr_1 (arg, 1, complain);
6976}
6977
6978/* C++: Must handle pointers to members.
6979
6980   Perhaps type instantiation should be extended to handle conversion
6981   from aggregates to types we don't yet know we want?  (Or are those
6982   cases typically errors which should be reported?)
6983
6984   NOCONVERT suppresses the default promotions (such as from short to int).  */
6985
6986tree
6987cp_build_unary_op (enum tree_code code, tree xarg, bool noconvert,
6988                   tsubst_flags_t complain)
6989{
6990  /* No default_conversion here.  It causes trouble for ADDR_EXPR.  */
6991  tree arg = xarg;
6992  location_t location = cp_expr_loc_or_input_loc (arg);
6993  tree argtype = 0;
6994  const char *errstring = NULL;
6995  tree val;
6996  const char *invalid_op_diag;
6997
6998  if (!arg || error_operand_p (arg))
6999    return error_mark_node;
7000
7001  arg = resolve_nondeduced_context (arg, complain);
7002
7003  if ((invalid_op_diag
7004       = targetm.invalid_unary_op ((code == UNARY_PLUS_EXPR
7005				    ? CONVERT_EXPR
7006				    : code),
7007				   TREE_TYPE (arg))))
7008    {
7009      if (complain & tf_error)
7010	error (invalid_op_diag);
7011      return error_mark_node;
7012    }
7013
7014  switch (code)
7015    {
7016    case UNARY_PLUS_EXPR:
7017    case NEGATE_EXPR:
7018      {
7019	int flags = WANT_ARITH | WANT_ENUM;
7020	/* Unary plus (but not unary minus) is allowed on pointers.  */
7021	if (code == UNARY_PLUS_EXPR)
7022	  flags |= WANT_POINTER;
7023	arg = build_expr_type_conversion (flags, arg, true);
7024	if (!arg)
7025	  errstring = (code == NEGATE_EXPR
7026		       ? _("wrong type argument to unary minus")
7027		       : _("wrong type argument to unary plus"));
7028	else
7029	  {
7030	    if (!noconvert && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (arg)))
7031	      arg = cp_perform_integral_promotions (arg, complain);
7032
7033	    /* Make sure the result is not an lvalue: a unary plus or minus
7034	       expression is always a rvalue.  */
7035	    arg = rvalue (arg);
7036	  }
7037      }
7038      break;
7039
7040    case BIT_NOT_EXPR:
7041      if (TREE_CODE (TREE_TYPE (arg)) == COMPLEX_TYPE)
7042	{
7043	  code = CONJ_EXPR;
7044	  if (!noconvert)
7045	    {
7046	      arg = cp_default_conversion (arg, complain);
7047	      if (arg == error_mark_node)
7048		return error_mark_node;
7049	    }
7050	}
7051      else if (!(arg = build_expr_type_conversion (WANT_INT | WANT_ENUM
7052						   | WANT_VECTOR_OR_COMPLEX,
7053						   arg, true)))
7054	errstring = _("wrong type argument to bit-complement");
7055      else if (!noconvert && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (arg)))
7056	{
7057	  /* Warn if the expression has boolean value.  */
7058	  if (TREE_CODE (TREE_TYPE (arg)) == BOOLEAN_TYPE
7059	      && (complain & tf_warning)
7060	      && warning_at (location, OPT_Wbool_operation,
7061			     "%<~%> on an expression of type %<bool%>"))
7062	    inform (location, "did you mean to use logical not (%<!%>)?");
7063	  arg = cp_perform_integral_promotions (arg, complain);
7064	}
7065      else if (!noconvert && VECTOR_TYPE_P (TREE_TYPE (arg)))
7066	arg = mark_rvalue_use (arg);
7067      break;
7068
7069    case ABS_EXPR:
7070      if (!(arg = build_expr_type_conversion (WANT_ARITH | WANT_ENUM, arg, true)))
7071	errstring = _("wrong type argument to abs");
7072      else if (!noconvert)
7073	{
7074	  arg = cp_default_conversion (arg, complain);
7075	  if (arg == error_mark_node)
7076	    return error_mark_node;
7077	}
7078      break;
7079
7080    case CONJ_EXPR:
7081      /* Conjugating a real value is a no-op, but allow it anyway.  */
7082      if (!(arg = build_expr_type_conversion (WANT_ARITH | WANT_ENUM, arg, true)))
7083	errstring = _("wrong type argument to conjugation");
7084      else if (!noconvert)
7085	{
7086	  arg = cp_default_conversion (arg, complain);
7087	  if (arg == error_mark_node)
7088	    return error_mark_node;
7089	}
7090      break;
7091
7092    case TRUTH_NOT_EXPR:
7093      if (gnu_vector_type_p (TREE_TYPE (arg)))
7094	return cp_build_binary_op (input_location, EQ_EXPR, arg,
7095				   build_zero_cst (TREE_TYPE (arg)), complain);
7096      arg = perform_implicit_conversion (boolean_type_node, arg,
7097					 complain);
7098      if (arg != error_mark_node)
7099	{
7100	  val = invert_truthvalue_loc (location, arg);
7101	  if (obvalue_p (val))
7102	    val = non_lvalue_loc (location, val);
7103	  return val;
7104	}
7105      errstring = _("in argument to unary !");
7106      break;
7107
7108    case NOP_EXPR:
7109      break;
7110
7111    case REALPART_EXPR:
7112    case IMAGPART_EXPR:
7113      arg = build_real_imag_expr (input_location, code, arg);
7114      return arg;
7115
7116    case PREINCREMENT_EXPR:
7117    case POSTINCREMENT_EXPR:
7118    case PREDECREMENT_EXPR:
7119    case POSTDECREMENT_EXPR:
7120      /* Handle complex lvalues (when permitted)
7121	 by reduction to simpler cases.  */
7122
7123      val = unary_complex_lvalue (code, arg);
7124      if (val != 0)
7125	return val;
7126
7127      arg = mark_lvalue_use (arg);
7128
7129      /* Increment or decrement the real part of the value,
7130	 and don't change the imaginary part.  */
7131      if (TREE_CODE (TREE_TYPE (arg)) == COMPLEX_TYPE)
7132	{
7133	  tree real, imag;
7134
7135	  arg = cp_stabilize_reference (arg);
7136	  real = cp_build_unary_op (REALPART_EXPR, arg, true, complain);
7137	  imag = cp_build_unary_op (IMAGPART_EXPR, arg, true, complain);
7138	  real = cp_build_unary_op (code, real, true, complain);
7139	  if (real == error_mark_node || imag == error_mark_node)
7140	    return error_mark_node;
7141	  return build2 (COMPLEX_EXPR, TREE_TYPE (arg),
7142			 real, imag);
7143	}
7144
7145      /* Report invalid types.  */
7146
7147      if (!(arg = build_expr_type_conversion (WANT_ARITH | WANT_POINTER,
7148					      arg, true)))
7149	{
7150	  if (code == PREINCREMENT_EXPR)
7151	    errstring = _("no pre-increment operator for type");
7152	  else if (code == POSTINCREMENT_EXPR)
7153	    errstring = _("no post-increment operator for type");
7154	  else if (code == PREDECREMENT_EXPR)
7155	    errstring = _("no pre-decrement operator for type");
7156	  else
7157	    errstring = _("no post-decrement operator for type");
7158	  break;
7159	}
7160      else if (arg == error_mark_node)
7161	return error_mark_node;
7162
7163      /* Report something read-only.  */
7164
7165      if (CP_TYPE_CONST_P (TREE_TYPE (arg))
7166	  || TREE_READONLY (arg))
7167        {
7168          if (complain & tf_error)
7169	    cxx_readonly_error (location, arg,
7170				((code == PREINCREMENT_EXPR
7171				  || code == POSTINCREMENT_EXPR)
7172				 ? lv_increment : lv_decrement));
7173          else
7174            return error_mark_node;
7175        }
7176
7177      {
7178	tree inc;
7179	tree declared_type = unlowered_expr_type (arg);
7180
7181	argtype = TREE_TYPE (arg);
7182
7183	/* ARM $5.2.5 last annotation says this should be forbidden.  */
7184	if (TREE_CODE (argtype) == ENUMERAL_TYPE)
7185          {
7186            if (complain & tf_error)
7187              permerror (location, (code == PREINCREMENT_EXPR
7188				    || code == POSTINCREMENT_EXPR)
7189                         ? G_("ISO C++ forbids incrementing an enum")
7190                         : G_("ISO C++ forbids decrementing an enum"));
7191            else
7192              return error_mark_node;
7193          }
7194
7195	/* Compute the increment.  */
7196
7197	if (TYPE_PTR_P (argtype))
7198	  {
7199	    tree type = complete_type (TREE_TYPE (argtype));
7200
7201	    if (!COMPLETE_OR_VOID_TYPE_P (type))
7202              {
7203                if (complain & tf_error)
7204                  error_at (location, ((code == PREINCREMENT_EXPR
7205					|| code == POSTINCREMENT_EXPR))
7206			    ? G_("cannot increment a pointer to incomplete "
7207				 "type %qT")
7208			    : G_("cannot decrement a pointer to incomplete "
7209				 "type %qT"),
7210			    TREE_TYPE (argtype));
7211                else
7212                  return error_mark_node;
7213              }
7214	    else if (!TYPE_PTROB_P (argtype))
7215              {
7216                if (complain & tf_error)
7217                  pedwarn (location, OPT_Wpointer_arith,
7218			   (code == PREINCREMENT_EXPR
7219                              || code == POSTINCREMENT_EXPR)
7220			   ? G_("ISO C++ forbids incrementing a pointer "
7221				"of type %qT")
7222			   : G_("ISO C++ forbids decrementing a pointer "
7223				"of type %qT"),
7224			   argtype);
7225                else
7226                  return error_mark_node;
7227              }
7228	    else if (!verify_type_context (location, TCTX_POINTER_ARITH,
7229					   TREE_TYPE (argtype),
7230					   !(complain & tf_error)))
7231	      return error_mark_node;
7232
7233	    inc = cxx_sizeof_nowarn (TREE_TYPE (argtype));
7234	  }
7235	else
7236	  inc = VECTOR_TYPE_P (argtype)
7237	    ? build_one_cst (argtype)
7238	    : integer_one_node;
7239
7240	inc = cp_convert (argtype, inc, complain);
7241
7242	/* If 'arg' is an Objective-C PROPERTY_REF expression, then we
7243	   need to ask Objective-C to build the increment or decrement
7244	   expression for it.  */
7245	if (objc_is_property_ref (arg))
7246	  return objc_build_incr_expr_for_property_ref (input_location, code,
7247							arg, inc);
7248
7249	/* Complain about anything else that is not a true lvalue.  */
7250	if (!lvalue_or_else (arg, ((code == PREINCREMENT_EXPR
7251				    || code == POSTINCREMENT_EXPR)
7252				   ? lv_increment : lv_decrement),
7253                             complain))
7254	  return error_mark_node;
7255
7256	/* [depr.volatile.type] "Postfix ++ and -- expressions and
7257	   prefix ++ and -- expressions of volatile-qualified arithmetic
7258	   and pointer types are deprecated."  */
7259	if (TREE_THIS_VOLATILE (arg) || CP_TYPE_VOLATILE_P (TREE_TYPE (arg)))
7260	  warning_at (location, OPT_Wvolatile,
7261		      "%qs expression of %<volatile%>-qualified type is "
7262		      "deprecated",
7263		      ((code == PREINCREMENT_EXPR
7264			|| code == POSTINCREMENT_EXPR)
7265		       ? "++" : "--"));
7266
7267	/* Forbid using -- or ++ in C++17 on `bool'.  */
7268	if (TREE_CODE (declared_type) == BOOLEAN_TYPE)
7269	  {
7270	    if (code == POSTDECREMENT_EXPR || code == PREDECREMENT_EXPR)
7271	      {
7272                if (complain & tf_error)
7273		  error_at (location,
7274			    "use of an operand of type %qT in %<operator--%> "
7275			    "is forbidden", boolean_type_node);
7276		return error_mark_node;
7277	      }
7278	    else
7279	      {
7280		if (cxx_dialect >= cxx17)
7281		  {
7282		    if (complain & tf_error)
7283		      error_at (location,
7284				"use of an operand of type %qT in "
7285				"%<operator++%> is forbidden in C++17",
7286				boolean_type_node);
7287		    return error_mark_node;
7288		  }
7289		/* Otherwise, [depr.incr.bool] says this is deprecated.  */
7290		else
7291		  warning_at (location, OPT_Wdeprecated,
7292			      "use of an operand of type %qT "
7293			      "in %<operator++%> is deprecated",
7294			      boolean_type_node);
7295	      }
7296	    val = boolean_increment (code, arg);
7297	  }
7298	else if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
7299	  /* An rvalue has no cv-qualifiers.  */
7300	  val = build2 (code, cv_unqualified (TREE_TYPE (arg)), arg, inc);
7301	else
7302	  val = build2 (code, TREE_TYPE (arg), arg, inc);
7303
7304	TREE_SIDE_EFFECTS (val) = 1;
7305	return val;
7306      }
7307
7308    case ADDR_EXPR:
7309      /* Note that this operation never does default_conversion
7310	 regardless of NOCONVERT.  */
7311      return cp_build_addr_expr (arg, complain);
7312
7313    default:
7314      break;
7315    }
7316
7317  if (!errstring)
7318    {
7319      if (argtype == 0)
7320	argtype = TREE_TYPE (arg);
7321      return build1 (code, argtype, arg);
7322    }
7323
7324  if (complain & tf_error)
7325    error_at (location, "%s", errstring);
7326  return error_mark_node;
7327}
7328
7329/* Hook for the c-common bits that build a unary op.  */
7330tree
7331build_unary_op (location_t /*location*/,
7332		enum tree_code code, tree xarg, bool noconvert)
7333{
7334  return cp_build_unary_op (code, xarg, noconvert, tf_warning_or_error);
7335}
7336
7337/* Adjust LVALUE, an MODIFY_EXPR, PREINCREMENT_EXPR or PREDECREMENT_EXPR,
7338   so that it is a valid lvalue even for GENERIC by replacing
7339   (lhs = rhs) with ((lhs = rhs), lhs)
7340   (--lhs) with ((--lhs), lhs)
7341   (++lhs) with ((++lhs), lhs)
7342   and if lhs has side-effects, calling cp_stabilize_reference on it, so
7343   that it can be evaluated multiple times.  */
7344
7345tree
7346genericize_compound_lvalue (tree lvalue)
7347{
7348  if (TREE_SIDE_EFFECTS (TREE_OPERAND (lvalue, 0)))
7349    lvalue = build2 (TREE_CODE (lvalue), TREE_TYPE (lvalue),
7350		     cp_stabilize_reference (TREE_OPERAND (lvalue, 0)),
7351		     TREE_OPERAND (lvalue, 1));
7352  return build2 (COMPOUND_EXPR, TREE_TYPE (TREE_OPERAND (lvalue, 0)),
7353		 lvalue, TREE_OPERAND (lvalue, 0));
7354}
7355
7356/* Apply unary lvalue-demanding operator CODE to the expression ARG
7357   for certain kinds of expressions which are not really lvalues
7358   but which we can accept as lvalues.
7359
7360   If ARG is not a kind of expression we can handle, return
7361   NULL_TREE.  */
7362
7363tree
7364unary_complex_lvalue (enum tree_code code, tree arg)
7365{
7366  /* Inside a template, making these kinds of adjustments is
7367     pointless; we are only concerned with the type of the
7368     expression.  */
7369  if (processing_template_decl)
7370    return NULL_TREE;
7371
7372  /* Handle (a, b) used as an "lvalue".  */
7373  if (TREE_CODE (arg) == COMPOUND_EXPR)
7374    {
7375      tree real_result = cp_build_unary_op (code, TREE_OPERAND (arg, 1), false,
7376                                            tf_warning_or_error);
7377      return build2 (COMPOUND_EXPR, TREE_TYPE (real_result),
7378		     TREE_OPERAND (arg, 0), real_result);
7379    }
7380
7381  /* Handle (a ? b : c) used as an "lvalue".  */
7382  if (TREE_CODE (arg) == COND_EXPR
7383      || TREE_CODE (arg) == MIN_EXPR || TREE_CODE (arg) == MAX_EXPR)
7384    return rationalize_conditional_expr (code, arg, tf_warning_or_error);
7385
7386  /* Handle (a = b), (++a), and (--a) used as an "lvalue".  */
7387  if (TREE_CODE (arg) == MODIFY_EXPR
7388      || TREE_CODE (arg) == PREINCREMENT_EXPR
7389      || TREE_CODE (arg) == PREDECREMENT_EXPR)
7390    return unary_complex_lvalue (code, genericize_compound_lvalue (arg));
7391
7392  if (code != ADDR_EXPR)
7393    return NULL_TREE;
7394
7395  /* Handle (a = b) used as an "lvalue" for `&'.  */
7396  if (TREE_CODE (arg) == MODIFY_EXPR
7397      || TREE_CODE (arg) == INIT_EXPR)
7398    {
7399      tree real_result = cp_build_unary_op (code, TREE_OPERAND (arg, 0), false,
7400                                            tf_warning_or_error);
7401      arg = build2 (COMPOUND_EXPR, TREE_TYPE (real_result),
7402		    arg, real_result);
7403      suppress_warning (arg /* What warning? */);
7404      return arg;
7405    }
7406
7407  if (FUNC_OR_METHOD_TYPE_P (TREE_TYPE (arg))
7408      || TREE_CODE (arg) == OFFSET_REF)
7409    return NULL_TREE;
7410
7411  /* We permit compiler to make function calls returning
7412     objects of aggregate type look like lvalues.  */
7413  {
7414    tree targ = arg;
7415
7416    if (TREE_CODE (targ) == SAVE_EXPR)
7417      targ = TREE_OPERAND (targ, 0);
7418
7419    if (TREE_CODE (targ) == CALL_EXPR && MAYBE_CLASS_TYPE_P (TREE_TYPE (targ)))
7420      {
7421	if (TREE_CODE (arg) == SAVE_EXPR)
7422	  targ = arg;
7423	else
7424	  targ = build_cplus_new (TREE_TYPE (arg), arg, tf_warning_or_error);
7425	return build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (arg)), targ);
7426      }
7427
7428    if (TREE_CODE (arg) == SAVE_EXPR && INDIRECT_REF_P (targ))
7429      return build3 (SAVE_EXPR, build_pointer_type (TREE_TYPE (arg)),
7430		     TREE_OPERAND (targ, 0), current_function_decl, NULL);
7431  }
7432
7433  /* Don't let anything else be handled specially.  */
7434  return NULL_TREE;
7435}
7436
7437/* Mark EXP saying that we need to be able to take the
7438   address of it; it should not be allocated in a register.
7439   Value is true if successful.  ARRAY_REF_P is true if this
7440   is for ARRAY_REF construction - in that case we don't want
7441   to look through VIEW_CONVERT_EXPR from VECTOR_TYPE to ARRAY_TYPE,
7442   it is fine to use ARRAY_REFs for vector subscripts on vector
7443   register variables.
7444
7445   C++: we do not allow `current_class_ptr' to be addressable.  */
7446
7447bool
7448cxx_mark_addressable (tree exp, bool array_ref_p)
7449{
7450  tree x = exp;
7451
7452  while (1)
7453    switch (TREE_CODE (x))
7454      {
7455      case VIEW_CONVERT_EXPR:
7456	if (array_ref_p
7457	    && TREE_CODE (TREE_TYPE (x)) == ARRAY_TYPE
7458	    && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (x, 0))))
7459	  return true;
7460	x = TREE_OPERAND (x, 0);
7461	break;
7462
7463      case COMPONENT_REF:
7464	if (bitfield_p (x))
7465	  error ("attempt to take address of bit-field");
7466	/* FALLTHRU */
7467      case ADDR_EXPR:
7468      case ARRAY_REF:
7469      case REALPART_EXPR:
7470      case IMAGPART_EXPR:
7471	x = TREE_OPERAND (x, 0);
7472	break;
7473
7474      case PARM_DECL:
7475	if (x == current_class_ptr)
7476	  {
7477	    error ("cannot take the address of %<this%>, which is an rvalue expression");
7478	    TREE_ADDRESSABLE (x) = 1; /* so compiler doesn't die later.  */
7479	    return true;
7480	  }
7481	/* Fall through.  */
7482
7483      case VAR_DECL:
7484	/* Caller should not be trying to mark initialized
7485	   constant fields addressable.  */
7486	gcc_assert (DECL_LANG_SPECIFIC (x) == 0
7487		    || DECL_IN_AGGR_P (x) == 0
7488		    || TREE_STATIC (x)
7489		    || DECL_EXTERNAL (x));
7490	/* Fall through.  */
7491
7492      case RESULT_DECL:
7493	if (DECL_REGISTER (x) && !TREE_ADDRESSABLE (x)
7494	    && !DECL_ARTIFICIAL (x))
7495	  {
7496	    if (VAR_P (x) && DECL_HARD_REGISTER (x))
7497	      {
7498		error
7499		  ("address of explicit register variable %qD requested", x);
7500		return false;
7501	      }
7502	    else if (extra_warnings)
7503	      warning
7504		(OPT_Wextra, "address requested for %qD, which is declared %<register%>", x);
7505	  }
7506	TREE_ADDRESSABLE (x) = 1;
7507	return true;
7508
7509      case CONST_DECL:
7510      case FUNCTION_DECL:
7511	TREE_ADDRESSABLE (x) = 1;
7512	return true;
7513
7514      case CONSTRUCTOR:
7515	TREE_ADDRESSABLE (x) = 1;
7516	return true;
7517
7518      case TARGET_EXPR:
7519	TREE_ADDRESSABLE (x) = 1;
7520	cxx_mark_addressable (TREE_OPERAND (x, 0));
7521	return true;
7522
7523      default:
7524	return true;
7525    }
7526}
7527
7528/* Build and return a conditional expression IFEXP ? OP1 : OP2.  */
7529
7530tree
7531build_x_conditional_expr (location_t loc, tree ifexp, tree op1, tree op2,
7532                          tsubst_flags_t complain)
7533{
7534  tree orig_ifexp = ifexp;
7535  tree orig_op1 = op1;
7536  tree orig_op2 = op2;
7537  tree expr;
7538
7539  if (processing_template_decl)
7540    {
7541      /* The standard says that the expression is type-dependent if
7542	 IFEXP is type-dependent, even though the eventual type of the
7543	 expression doesn't dependent on IFEXP.  */
7544      if (type_dependent_expression_p (ifexp)
7545	  /* As a GNU extension, the middle operand may be omitted.  */
7546	  || (op1 && type_dependent_expression_p (op1))
7547	  || type_dependent_expression_p (op2))
7548	return build_min_nt_loc (loc, COND_EXPR, ifexp, op1, op2);
7549      ifexp = build_non_dependent_expr (ifexp);
7550      if (op1)
7551	op1 = build_non_dependent_expr (op1);
7552      op2 = build_non_dependent_expr (op2);
7553    }
7554
7555  expr = build_conditional_expr (loc, ifexp, op1, op2, complain);
7556  if (processing_template_decl && expr != error_mark_node)
7557    {
7558      tree min = build_min_non_dep (COND_EXPR, expr,
7559				    orig_ifexp, orig_op1, orig_op2);
7560      expr = convert_from_reference (min);
7561    }
7562  return expr;
7563}
7564
7565/* Given a list of expressions, return a compound expression
7566   that performs them all and returns the value of the last of them.  */
7567
7568tree
7569build_x_compound_expr_from_list (tree list, expr_list_kind exp,
7570				 tsubst_flags_t complain)
7571{
7572  tree expr = TREE_VALUE (list);
7573
7574  if (BRACE_ENCLOSED_INITIALIZER_P (expr)
7575      && !CONSTRUCTOR_IS_DIRECT_INIT (expr))
7576    {
7577      if (complain & tf_error)
7578	pedwarn (cp_expr_loc_or_input_loc (expr), 0,
7579		 "list-initializer for non-class type must not "
7580		 "be parenthesized");
7581      else
7582	return error_mark_node;
7583    }
7584
7585  if (TREE_CHAIN (list))
7586    {
7587      if (complain & tf_error)
7588	switch (exp)
7589	  {
7590	  case ELK_INIT:
7591	    permerror (input_location, "expression list treated as compound "
7592				       "expression in initializer");
7593	    break;
7594	  case ELK_MEM_INIT:
7595	    permerror (input_location, "expression list treated as compound "
7596				       "expression in mem-initializer");
7597	    break;
7598	  case ELK_FUNC_CAST:
7599	    permerror (input_location, "expression list treated as compound "
7600				       "expression in functional cast");
7601	    break;
7602	  default:
7603	    gcc_unreachable ();
7604	  }
7605      else
7606	return error_mark_node;
7607
7608      for (list = TREE_CHAIN (list); list; list = TREE_CHAIN (list))
7609	expr = build_x_compound_expr (EXPR_LOCATION (TREE_VALUE (list)),
7610				      expr, TREE_VALUE (list), NULL_TREE,
7611				      complain);
7612    }
7613
7614  return expr;
7615}
7616
7617/* Like build_x_compound_expr_from_list, but using a VEC.  */
7618
7619tree
7620build_x_compound_expr_from_vec (vec<tree, va_gc> *vec, const char *msg,
7621				tsubst_flags_t complain)
7622{
7623  if (vec_safe_is_empty (vec))
7624    return NULL_TREE;
7625  else if (vec->length () == 1)
7626    return (*vec)[0];
7627  else
7628    {
7629      tree expr;
7630      unsigned int ix;
7631      tree t;
7632
7633      if (msg != NULL)
7634	{
7635	  if (complain & tf_error)
7636	    permerror (input_location,
7637		       "%s expression list treated as compound expression",
7638		       msg);
7639	  else
7640	    return error_mark_node;
7641	}
7642
7643      expr = (*vec)[0];
7644      for (ix = 1; vec->iterate (ix, &t); ++ix)
7645	expr = build_x_compound_expr (EXPR_LOCATION (t), expr,
7646				      t, NULL_TREE, complain);
7647
7648      return expr;
7649    }
7650}
7651
7652/* Handle overloading of the ',' operator when needed.  */
7653
7654tree
7655build_x_compound_expr (location_t loc, tree op1, tree op2,
7656		       tree lookups, tsubst_flags_t complain)
7657{
7658  tree result;
7659  tree orig_op1 = op1;
7660  tree orig_op2 = op2;
7661  tree overload = NULL_TREE;
7662
7663  if (processing_template_decl)
7664    {
7665      if (type_dependent_expression_p (op1)
7666	  || type_dependent_expression_p (op2))
7667	{
7668	  result = build_min_nt_loc (loc, COMPOUND_EXPR, op1, op2);
7669	  TREE_TYPE (result)
7670	    = build_dependent_operator_type (lookups, COMPOUND_EXPR, false);
7671	  return result;
7672	}
7673      op1 = build_non_dependent_expr (op1);
7674      op2 = build_non_dependent_expr (op2);
7675    }
7676
7677  result = build_new_op (loc, COMPOUND_EXPR, LOOKUP_NORMAL, op1, op2,
7678			 NULL_TREE, lookups, &overload, complain);
7679  if (!result)
7680    result = cp_build_compound_expr (op1, op2, complain);
7681
7682  if (processing_template_decl && result != error_mark_node)
7683    {
7684      if (overload != NULL_TREE)
7685	return (build_min_non_dep_op_overload
7686		(COMPOUND_EXPR, result, overload, orig_op1, orig_op2));
7687
7688      return build_min_non_dep (COMPOUND_EXPR, result, orig_op1, orig_op2);
7689    }
7690
7691  return result;
7692}
7693
7694/* Like cp_build_compound_expr, but for the c-common bits.  */
7695
7696tree
7697build_compound_expr (location_t /*loc*/, tree lhs, tree rhs)
7698{
7699  return cp_build_compound_expr (lhs, rhs, tf_warning_or_error);
7700}
7701
7702/* Build a compound expression.  */
7703
7704tree
7705cp_build_compound_expr (tree lhs, tree rhs, tsubst_flags_t complain)
7706{
7707  lhs = convert_to_void (lhs, ICV_LEFT_OF_COMMA, complain);
7708
7709  if (lhs == error_mark_node || rhs == error_mark_node)
7710    return error_mark_node;
7711
7712  if (TREE_CODE (rhs) == TARGET_EXPR)
7713    {
7714      /* If the rhs is a TARGET_EXPR, then build the compound
7715	 expression inside the target_expr's initializer. This
7716	 helps the compiler to eliminate unnecessary temporaries.  */
7717      tree init = TREE_OPERAND (rhs, 1);
7718
7719      init = build2 (COMPOUND_EXPR, TREE_TYPE (init), lhs, init);
7720      TREE_OPERAND (rhs, 1) = init;
7721
7722      return rhs;
7723    }
7724
7725  if (type_unknown_p (rhs))
7726    {
7727      if (complain & tf_error)
7728	error_at (cp_expr_loc_or_input_loc (rhs),
7729		  "no context to resolve type of %qE", rhs);
7730      return error_mark_node;
7731    }
7732
7733  return build2 (COMPOUND_EXPR, TREE_TYPE (rhs), lhs, rhs);
7734}
7735
7736/* Issue a diagnostic message if casting from SRC_TYPE to DEST_TYPE
7737   casts away constness.  CAST gives the type of cast.  Returns true
7738   if the cast is ill-formed, false if it is well-formed.
7739
7740   ??? This function warns for casting away any qualifier not just
7741   const.  We would like to specify exactly what qualifiers are casted
7742   away.
7743*/
7744
7745static bool
7746check_for_casting_away_constness (location_t loc, tree src_type,
7747				  tree dest_type, enum tree_code cast,
7748				  tsubst_flags_t complain)
7749{
7750  /* C-style casts are allowed to cast away constness.  With
7751     WARN_CAST_QUAL, we still want to issue a warning.  */
7752  if (cast == CAST_EXPR && !warn_cast_qual)
7753    return false;
7754
7755  if (!casts_away_constness (src_type, dest_type, complain))
7756    return false;
7757
7758  switch (cast)
7759    {
7760    case CAST_EXPR:
7761      if (complain & tf_warning)
7762	warning_at (loc, OPT_Wcast_qual,
7763		    "cast from type %qT to type %qT casts away qualifiers",
7764		    src_type, dest_type);
7765      return false;
7766
7767    case STATIC_CAST_EXPR:
7768      if (complain & tf_error)
7769	error_at (loc, "%<static_cast%> from type %qT to type %qT casts "
7770		  "away qualifiers",
7771		  src_type, dest_type);
7772      return true;
7773
7774    case REINTERPRET_CAST_EXPR:
7775      if (complain & tf_error)
7776	error_at (loc, "%<reinterpret_cast%> from type %qT to type %qT "
7777		  "casts away qualifiers",
7778		  src_type, dest_type);
7779      return true;
7780
7781    default:
7782      gcc_unreachable();
7783    }
7784}
7785
7786/* Warns if the cast from expression EXPR to type TYPE is useless.  */
7787void
7788maybe_warn_about_useless_cast (location_t loc, tree type, tree expr,
7789			       tsubst_flags_t complain)
7790{
7791  if (warn_useless_cast
7792      && complain & tf_warning)
7793    {
7794      if ((TYPE_REF_P (type)
7795	   && (TYPE_REF_IS_RVALUE (type)
7796	       ? xvalue_p (expr) : lvalue_p (expr))
7797	   && same_type_p (TREE_TYPE (expr), TREE_TYPE (type)))
7798	  || same_type_p (TREE_TYPE (expr), type))
7799	warning_at (loc, OPT_Wuseless_cast,
7800		    "useless cast to type %q#T", type);
7801    }
7802}
7803
7804/* Warns if the cast ignores cv-qualifiers on TYPE.  */
7805static void
7806maybe_warn_about_cast_ignoring_quals (location_t loc, tree type,
7807				      tsubst_flags_t complain)
7808{
7809  if (warn_ignored_qualifiers
7810      && complain & tf_warning
7811      && !CLASS_TYPE_P (type)
7812      && (cp_type_quals (type) & (TYPE_QUAL_CONST|TYPE_QUAL_VOLATILE)))
7813    warning_at (loc, OPT_Wignored_qualifiers,
7814		"type qualifiers ignored on cast result type");
7815}
7816
7817/* Convert EXPR (an expression with pointer-to-member type) to TYPE
7818   (another pointer-to-member type in the same hierarchy) and return
7819   the converted expression.  If ALLOW_INVERSE_P is permitted, a
7820   pointer-to-derived may be converted to pointer-to-base; otherwise,
7821   only the other direction is permitted.  If C_CAST_P is true, this
7822   conversion is taking place as part of a C-style cast.  */
7823
7824tree
7825convert_ptrmem (tree type, tree expr, bool allow_inverse_p,
7826		bool c_cast_p, tsubst_flags_t complain)
7827{
7828  if (same_type_p (type, TREE_TYPE (expr)))
7829    return expr;
7830
7831  if (TYPE_PTRDATAMEM_P (type))
7832    {
7833      tree obase = TYPE_PTRMEM_CLASS_TYPE (TREE_TYPE (expr));
7834      tree nbase = TYPE_PTRMEM_CLASS_TYPE (type);
7835      tree delta = (get_delta_difference
7836		    (obase, nbase,
7837		     allow_inverse_p, c_cast_p, complain));
7838
7839      if (delta == error_mark_node)
7840	return error_mark_node;
7841
7842      if (!same_type_p (obase, nbase))
7843	{
7844	  if (TREE_CODE (expr) == PTRMEM_CST)
7845	    expr = cplus_expand_constant (expr);
7846
7847	  tree cond = cp_build_binary_op (input_location, EQ_EXPR, expr,
7848					  build_int_cst (TREE_TYPE (expr), -1),
7849					  complain);
7850	  tree op1 = build_nop (ptrdiff_type_node, expr);
7851	  tree op2 = cp_build_binary_op (input_location, PLUS_EXPR, op1, delta,
7852					 complain);
7853
7854	  expr = fold_build3_loc (input_location,
7855				  COND_EXPR, ptrdiff_type_node, cond, op1, op2);
7856	}
7857
7858      return build_nop (type, expr);
7859    }
7860  else
7861    return build_ptrmemfunc (TYPE_PTRMEMFUNC_FN_TYPE (type), expr,
7862			     allow_inverse_p, c_cast_p, complain);
7863}
7864
7865/* Perform a static_cast from EXPR to TYPE.  When C_CAST_P is true,
7866   this static_cast is being attempted as one of the possible casts
7867   allowed by a C-style cast.  (In that case, accessibility of base
7868   classes is not considered, and it is OK to cast away
7869   constness.)  Return the result of the cast.  *VALID_P is set to
7870   indicate whether or not the cast was valid.  */
7871
7872static tree
7873build_static_cast_1 (location_t loc, tree type, tree expr, bool c_cast_p,
7874		     bool *valid_p, tsubst_flags_t complain)
7875{
7876  tree intype;
7877  tree result;
7878  cp_lvalue_kind clk;
7879
7880  /* Assume the cast is valid.  */
7881  *valid_p = true;
7882
7883  intype = unlowered_expr_type (expr);
7884
7885  /* Save casted types in the function's used types hash table.  */
7886  used_types_insert (type);
7887
7888  /* A prvalue of non-class type is cv-unqualified.  */
7889  if (!CLASS_TYPE_P (type))
7890    type = cv_unqualified (type);
7891
7892  /* [expr.static.cast]
7893
7894     An lvalue of type "cv1 B", where B is a class type, can be cast
7895     to type "reference to cv2 D", where D is a class derived (clause
7896     _class.derived_) from B, if a valid standard conversion from
7897     "pointer to D" to "pointer to B" exists (_conv.ptr_), cv2 is the
7898     same cv-qualification as, or greater cv-qualification than, cv1,
7899     and B is not a virtual base class of D.  */
7900  /* We check this case before checking the validity of "TYPE t =
7901     EXPR;" below because for this case:
7902
7903       struct B {};
7904       struct D : public B { D(const B&); };
7905       extern B& b;
7906       void f() { static_cast<const D&>(b); }
7907
7908     we want to avoid constructing a new D.  The standard is not
7909     completely clear about this issue, but our interpretation is
7910     consistent with other compilers.  */
7911  if (TYPE_REF_P (type)
7912      && CLASS_TYPE_P (TREE_TYPE (type))
7913      && CLASS_TYPE_P (intype)
7914      && (TYPE_REF_IS_RVALUE (type) || lvalue_p (expr))
7915      && DERIVED_FROM_P (intype, TREE_TYPE (type))
7916      && can_convert (build_pointer_type (TYPE_MAIN_VARIANT (intype)),
7917		      build_pointer_type (TYPE_MAIN_VARIANT
7918					  (TREE_TYPE (type))),
7919		      complain)
7920      && (c_cast_p
7921	  || at_least_as_qualified_p (TREE_TYPE (type), intype)))
7922    {
7923      tree base;
7924
7925      if (processing_template_decl)
7926	return expr;
7927
7928      /* There is a standard conversion from "D*" to "B*" even if "B"
7929	 is ambiguous or inaccessible.  If this is really a
7930	 static_cast, then we check both for inaccessibility and
7931	 ambiguity.  However, if this is a static_cast being performed
7932	 because the user wrote a C-style cast, then accessibility is
7933	 not considered.  */
7934      base = lookup_base (TREE_TYPE (type), intype,
7935			  c_cast_p ? ba_unique : ba_check,
7936			  NULL, complain);
7937      expr = cp_build_addr_expr (expr, complain);
7938
7939      if (sanitize_flags_p (SANITIZE_VPTR))
7940	{
7941	  tree ubsan_check
7942	    = cp_ubsan_maybe_instrument_downcast (loc, type,
7943						  intype, expr);
7944	  if (ubsan_check)
7945	    expr = ubsan_check;
7946	}
7947
7948      /* Convert from "B*" to "D*".  This function will check that "B"
7949	 is not a virtual base of "D".  Even if we don't have a guarantee
7950	 that expr is NULL, if the static_cast is to a reference type,
7951	 it is UB if it would be NULL, so omit the non-NULL check.  */
7952      expr = build_base_path (MINUS_EXPR, expr, base,
7953			      /*nonnull=*/flag_delete_null_pointer_checks,
7954			      complain);
7955
7956      /* Convert the pointer to a reference -- but then remember that
7957	 there are no expressions with reference type in C++.
7958
7959         We call rvalue so that there's an actual tree code
7960         (NON_LVALUE_EXPR) for the static_cast; otherwise, if the operand
7961         is a variable with the same type, the conversion would get folded
7962         away, leaving just the variable and causing lvalue_kind to give
7963         the wrong answer.  */
7964      expr = cp_fold_convert (type, expr);
7965
7966      /* When -fsanitize=null, make sure to diagnose reference binding to
7967	 NULL even when the reference is converted to pointer later on.  */
7968      if (sanitize_flags_p (SANITIZE_NULL)
7969	  && TREE_CODE (expr) == COND_EXPR
7970	  && TREE_OPERAND (expr, 2)
7971	  && TREE_CODE (TREE_OPERAND (expr, 2)) == INTEGER_CST
7972	  && TREE_TYPE (TREE_OPERAND (expr, 2)) == type)
7973	ubsan_maybe_instrument_reference (&TREE_OPERAND (expr, 2));
7974
7975      return convert_from_reference (rvalue (expr));
7976    }
7977
7978  /* "A glvalue of type cv1 T1 can be cast to type rvalue reference to
7979     cv2 T2 if cv2 T2 is reference-compatible with cv1 T1 (8.5.3)."  */
7980  if (TYPE_REF_P (type)
7981      && TYPE_REF_IS_RVALUE (type)
7982      && (clk = real_lvalue_p (expr))
7983      && reference_compatible_p (TREE_TYPE (type), intype)
7984      && (c_cast_p || at_least_as_qualified_p (TREE_TYPE (type), intype)))
7985    {
7986      if (processing_template_decl)
7987	return expr;
7988      if (clk == clk_ordinary)
7989	{
7990	  /* Handle the (non-bit-field) lvalue case here by casting to
7991	     lvalue reference and then changing it to an rvalue reference.
7992	     Casting an xvalue to rvalue reference will be handled by the
7993	     main code path.  */
7994	  tree lref = cp_build_reference_type (TREE_TYPE (type), false);
7995	  result = (perform_direct_initialization_if_possible
7996		    (lref, expr, c_cast_p, complain));
7997	  result = build1 (NON_LVALUE_EXPR, type, result);
7998	  return convert_from_reference (result);
7999	}
8000      else
8001	/* For a bit-field or packed field, bind to a temporary.  */
8002	expr = rvalue (expr);
8003    }
8004
8005  /* Resolve overloaded address here rather than once in
8006     implicit_conversion and again in the inverse code below.  */
8007  if (TYPE_PTRMEMFUNC_P (type) && type_unknown_p (expr))
8008    {
8009      expr = instantiate_type (type, expr, complain);
8010      intype = TREE_TYPE (expr);
8011    }
8012
8013  /* [expr.static.cast]
8014
8015     Any expression can be explicitly converted to type cv void.  */
8016  if (VOID_TYPE_P (type))
8017    return convert_to_void (expr, ICV_CAST, complain);
8018
8019  /* [class.abstract]
8020     An abstract class shall not be used ... as the type of an explicit
8021     conversion.  */
8022  if (abstract_virtuals_error_sfinae (ACU_CAST, type, complain))
8023    return error_mark_node;
8024
8025  /* [expr.static.cast]
8026
8027     An expression e can be explicitly converted to a type T using a
8028     static_cast of the form static_cast<T>(e) if the declaration T
8029     t(e);" is well-formed, for some invented temporary variable
8030     t.  */
8031  result = perform_direct_initialization_if_possible (type, expr,
8032						      c_cast_p, complain);
8033  /* P1975 allows static_cast<Aggr>(42), as well as static_cast<T[5]>(42),
8034     which initialize the first element of the aggregate.  We need to handle
8035     the array case specifically.  */
8036  if (result == NULL_TREE
8037      && cxx_dialect >= cxx20
8038      && TREE_CODE (type) == ARRAY_TYPE)
8039    {
8040      /* Create { EXPR } and perform direct-initialization from it.  */
8041      tree e = build_constructor_single (init_list_type_node, NULL_TREE, expr);
8042      CONSTRUCTOR_IS_DIRECT_INIT (e) = true;
8043      CONSTRUCTOR_IS_PAREN_INIT (e) = true;
8044      result = perform_direct_initialization_if_possible (type, e, c_cast_p,
8045							  complain);
8046    }
8047  if (result)
8048    {
8049      if (processing_template_decl)
8050	return expr;
8051
8052      result = convert_from_reference (result);
8053
8054      /* [expr.static.cast]
8055
8056	 If T is a reference type, the result is an lvalue; otherwise,
8057	 the result is an rvalue.  */
8058      if (!TYPE_REF_P (type))
8059	{
8060	  result = rvalue (result);
8061
8062	  if (result == expr && SCALAR_TYPE_P (type))
8063	    /* Leave some record of the cast.  */
8064	    result = build_nop (type, expr);
8065	}
8066      return result;
8067    }
8068
8069  /* [expr.static.cast]
8070
8071     The inverse of any standard conversion sequence (clause _conv_),
8072     other than the lvalue-to-rvalue (_conv.lval_), array-to-pointer
8073     (_conv.array_), function-to-pointer (_conv.func_), and boolean
8074     (_conv.bool_) conversions, can be performed explicitly using
8075     static_cast subject to the restriction that the explicit
8076     conversion does not cast away constness (_expr.const.cast_), and
8077     the following additional rules for specific cases:  */
8078  /* For reference, the conversions not excluded are: integral
8079     promotions, floating-point promotion, integral conversions,
8080     floating-point conversions, floating-integral conversions,
8081     pointer conversions, and pointer to member conversions.  */
8082  /* DR 128
8083
8084     A value of integral _or enumeration_ type can be explicitly
8085     converted to an enumeration type.  */
8086  /* The effect of all that is that any conversion between any two
8087     types which are integral, floating, or enumeration types can be
8088     performed.  */
8089  if ((INTEGRAL_OR_ENUMERATION_TYPE_P (type)
8090       || SCALAR_FLOAT_TYPE_P (type))
8091      && (INTEGRAL_OR_ENUMERATION_TYPE_P (intype)
8092	  || SCALAR_FLOAT_TYPE_P (intype)))
8093    {
8094      if (processing_template_decl)
8095	return expr;
8096      return ocp_convert (type, expr, CONV_C_CAST, LOOKUP_NORMAL, complain);
8097    }
8098
8099  if (TYPE_PTR_P (type) && TYPE_PTR_P (intype)
8100      && CLASS_TYPE_P (TREE_TYPE (type))
8101      && CLASS_TYPE_P (TREE_TYPE (intype))
8102      && can_convert (build_pointer_type (TYPE_MAIN_VARIANT
8103					  (TREE_TYPE (intype))),
8104		      build_pointer_type (TYPE_MAIN_VARIANT
8105					  (TREE_TYPE (type))),
8106		      complain))
8107    {
8108      tree base;
8109
8110      if (processing_template_decl)
8111	return expr;
8112
8113      if (!c_cast_p
8114	  && check_for_casting_away_constness (loc, intype, type,
8115					       STATIC_CAST_EXPR,
8116					       complain))
8117	return error_mark_node;
8118      base = lookup_base (TREE_TYPE (type), TREE_TYPE (intype),
8119			  c_cast_p ? ba_unique : ba_check,
8120			  NULL, complain);
8121      expr = build_base_path (MINUS_EXPR, expr, base, /*nonnull=*/false,
8122			      complain);
8123
8124      if (sanitize_flags_p (SANITIZE_VPTR))
8125	{
8126	  tree ubsan_check
8127	    = cp_ubsan_maybe_instrument_downcast (loc, type,
8128						  intype, expr);
8129	  if (ubsan_check)
8130	    expr = ubsan_check;
8131	}
8132
8133      return cp_fold_convert (type, expr);
8134    }
8135
8136  if ((TYPE_PTRDATAMEM_P (type) && TYPE_PTRDATAMEM_P (intype))
8137      || (TYPE_PTRMEMFUNC_P (type) && TYPE_PTRMEMFUNC_P (intype)))
8138    {
8139      tree c1;
8140      tree c2;
8141      tree t1;
8142      tree t2;
8143
8144      c1 = TYPE_PTRMEM_CLASS_TYPE (intype);
8145      c2 = TYPE_PTRMEM_CLASS_TYPE (type);
8146
8147      if (TYPE_PTRDATAMEM_P (type))
8148	{
8149	  t1 = (build_ptrmem_type
8150		(c1,
8151		 TYPE_MAIN_VARIANT (TYPE_PTRMEM_POINTED_TO_TYPE (intype))));
8152	  t2 = (build_ptrmem_type
8153		(c2,
8154		 TYPE_MAIN_VARIANT (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
8155	}
8156      else
8157	{
8158	  t1 = intype;
8159	  t2 = type;
8160	}
8161      if (can_convert (t1, t2, complain) || can_convert (t2, t1, complain))
8162	{
8163	  if (!c_cast_p
8164	      && check_for_casting_away_constness (loc, intype, type,
8165						   STATIC_CAST_EXPR,
8166						   complain))
8167	    return error_mark_node;
8168	  if (processing_template_decl)
8169	    return expr;
8170	  return convert_ptrmem (type, expr, /*allow_inverse_p=*/1,
8171				 c_cast_p, complain);
8172	}
8173    }
8174
8175  /* [expr.static.cast]
8176
8177     An rvalue of type "pointer to cv void" can be explicitly
8178     converted to a pointer to object type.  A value of type pointer
8179     to object converted to "pointer to cv void" and back to the
8180     original pointer type will have its original value.  */
8181  if (TYPE_PTR_P (intype)
8182      && VOID_TYPE_P (TREE_TYPE (intype))
8183      && TYPE_PTROB_P (type))
8184    {
8185      if (!c_cast_p
8186	  && check_for_casting_away_constness (loc, intype, type,
8187					       STATIC_CAST_EXPR,
8188					       complain))
8189	return error_mark_node;
8190      if (processing_template_decl)
8191	return expr;
8192      return build_nop (type, expr);
8193    }
8194
8195  *valid_p = false;
8196  return error_mark_node;
8197}
8198
8199/* Return an expression representing static_cast<TYPE>(EXPR).  */
8200
8201tree
8202build_static_cast (location_t loc, tree type, tree oexpr,
8203		   tsubst_flags_t complain)
8204{
8205  tree expr = oexpr;
8206  tree result;
8207  bool valid_p;
8208
8209  if (type == error_mark_node || expr == error_mark_node)
8210    return error_mark_node;
8211
8212  bool dependent = (dependent_type_p (type)
8213		    || type_dependent_expression_p (expr));
8214  if (dependent)
8215    {
8216    tmpl:
8217      expr = build_min (STATIC_CAST_EXPR, type, oexpr);
8218      /* We don't know if it will or will not have side effects.  */
8219      TREE_SIDE_EFFECTS (expr) = 1;
8220      result = convert_from_reference (expr);
8221      protected_set_expr_location (result, loc);
8222      return result;
8223    }
8224  else if (processing_template_decl)
8225    expr = build_non_dependent_expr (expr);
8226
8227  /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
8228     Strip such NOP_EXPRs if VALUE is being used in non-lvalue context.  */
8229  if (!TYPE_REF_P (type)
8230      && TREE_CODE (expr) == NOP_EXPR
8231      && TREE_TYPE (expr) == TREE_TYPE (TREE_OPERAND (expr, 0)))
8232    expr = TREE_OPERAND (expr, 0);
8233
8234  result = build_static_cast_1 (loc, type, expr, /*c_cast_p=*/false,
8235				&valid_p, complain);
8236  if (valid_p)
8237    {
8238      if (result != error_mark_node)
8239	{
8240	  maybe_warn_about_useless_cast (loc, type, expr, complain);
8241	  maybe_warn_about_cast_ignoring_quals (loc, type, complain);
8242	}
8243      if (processing_template_decl)
8244	goto tmpl;
8245      protected_set_expr_location (result, loc);
8246      return result;
8247    }
8248
8249  if (complain & tf_error)
8250    {
8251      error_at (loc, "invalid %<static_cast%> from type %qT to type %qT",
8252		TREE_TYPE (expr), type);
8253      if ((TYPE_PTR_P (type) || TYPE_REF_P (type))
8254	  && CLASS_TYPE_P (TREE_TYPE (type))
8255	    && !COMPLETE_TYPE_P (TREE_TYPE (type)))
8256	inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (TREE_TYPE (type))),
8257		"class type %qT is incomplete", TREE_TYPE (type));
8258      tree expr_type = TREE_TYPE (expr);
8259      if (TYPE_PTR_P (expr_type))
8260	expr_type = TREE_TYPE (expr_type);
8261      if (CLASS_TYPE_P (expr_type) && !COMPLETE_TYPE_P (expr_type))
8262	inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (expr_type)),
8263		"class type %qT is incomplete", expr_type);
8264    }
8265  return error_mark_node;
8266}
8267
8268/* EXPR is an expression with member function or pointer-to-member
8269   function type.  TYPE is a pointer type.  Converting EXPR to TYPE is
8270   not permitted by ISO C++, but we accept it in some modes.  If we
8271   are not in one of those modes, issue a diagnostic.  Return the
8272   converted expression.  */
8273
8274tree
8275convert_member_func_to_ptr (tree type, tree expr, tsubst_flags_t complain)
8276{
8277  tree intype;
8278  tree decl;
8279
8280  intype = TREE_TYPE (expr);
8281  gcc_assert (TYPE_PTRMEMFUNC_P (intype)
8282	      || TREE_CODE (intype) == METHOD_TYPE);
8283
8284  if (!(complain & tf_warning_or_error))
8285    return error_mark_node;
8286
8287  location_t loc = cp_expr_loc_or_input_loc (expr);
8288
8289  if (pedantic || warn_pmf2ptr)
8290    pedwarn (loc, pedantic ? OPT_Wpedantic : OPT_Wpmf_conversions,
8291	     "converting from %qH to %qI", intype, type);
8292
8293  STRIP_ANY_LOCATION_WRAPPER (expr);
8294
8295  if (TREE_CODE (intype) == METHOD_TYPE)
8296    expr = build_addr_func (expr, complain);
8297  else if (TREE_CODE (expr) == PTRMEM_CST)
8298    expr = build_address (PTRMEM_CST_MEMBER (expr));
8299  else
8300    {
8301      decl = maybe_dummy_object (TYPE_PTRMEM_CLASS_TYPE (intype), 0);
8302      decl = build_address (decl);
8303      expr = get_member_function_from_ptrfunc (&decl, expr, complain);
8304    }
8305
8306  if (expr == error_mark_node)
8307    return error_mark_node;
8308
8309  expr = build_nop (type, expr);
8310  SET_EXPR_LOCATION (expr, loc);
8311  return expr;
8312}
8313
8314/* Build a NOP_EXPR to TYPE, but mark it as a reinterpret_cast so that
8315   constexpr evaluation knows to reject it.  */
8316
8317static tree
8318build_nop_reinterpret (tree type, tree expr)
8319{
8320  tree ret = build_nop (type, expr);
8321  if (ret != expr)
8322    REINTERPRET_CAST_P (ret) = true;
8323  return ret;
8324}
8325
8326/* Return a representation for a reinterpret_cast from EXPR to TYPE.
8327   If C_CAST_P is true, this reinterpret cast is being done as part of
8328   a C-style cast.  If VALID_P is non-NULL, *VALID_P is set to
8329   indicate whether or not reinterpret_cast was valid.  */
8330
8331static tree
8332build_reinterpret_cast_1 (location_t loc, tree type, tree expr,
8333			  bool c_cast_p, bool *valid_p,
8334			  tsubst_flags_t complain)
8335{
8336  tree intype;
8337
8338  /* Assume the cast is invalid.  */
8339  if (valid_p)
8340    *valid_p = true;
8341
8342  if (type == error_mark_node || error_operand_p (expr))
8343    return error_mark_node;
8344
8345  intype = TREE_TYPE (expr);
8346
8347  /* Save casted types in the function's used types hash table.  */
8348  used_types_insert (type);
8349
8350  /* A prvalue of non-class type is cv-unqualified.  */
8351  if (!CLASS_TYPE_P (type))
8352    type = cv_unqualified (type);
8353
8354  /* [expr.reinterpret.cast]
8355     A glvalue of type T1, designating an object x, can be cast to the type
8356     "reference to T2" if an expression of type "pointer to T1" can be
8357     explicitly converted to the type "pointer to T2" using a reinterpret_cast.
8358     The result is that of *reinterpret_cast<T2 *>(p) where p is a pointer to x
8359     of type "pointer to T1". No temporary is created, no copy is made, and no
8360     constructors (11.4.4) or conversion functions (11.4.7) are called.  */
8361  if (TYPE_REF_P (type))
8362    {
8363      if (!glvalue_p (expr))
8364	{
8365          if (complain & tf_error)
8366	    error_at (loc, "invalid cast of a prvalue expression of type "
8367		      "%qT to type %qT",
8368		      intype, type);
8369	  return error_mark_node;
8370	}
8371
8372      /* Warn about a reinterpret_cast from "A*" to "B&" if "A" and
8373	 "B" are related class types; the reinterpret_cast does not
8374	 adjust the pointer.  */
8375      if (TYPE_PTR_P (intype)
8376          && (complain & tf_warning)
8377	  && (comptypes (TREE_TYPE (intype), TREE_TYPE (type),
8378			 COMPARE_BASE | COMPARE_DERIVED)))
8379	warning_at (loc, 0, "casting %qT to %qT does not dereference pointer",
8380		    intype, type);
8381
8382      expr = cp_build_addr_expr (expr, complain);
8383
8384      if (warn_strict_aliasing > 2)
8385	cp_strict_aliasing_warning (EXPR_LOCATION (expr), type, expr);
8386
8387      if (expr != error_mark_node)
8388	expr = build_reinterpret_cast_1
8389	  (loc, build_pointer_type (TREE_TYPE (type)), expr, c_cast_p,
8390	   valid_p, complain);
8391      if (expr != error_mark_node)
8392	/* cp_build_indirect_ref isn't right for rvalue refs.  */
8393	expr = convert_from_reference (fold_convert (type, expr));
8394      return expr;
8395    }
8396
8397  /* As a G++ extension, we consider conversions from member
8398     functions, and pointers to member functions to
8399     pointer-to-function and pointer-to-void types.  If
8400     -Wno-pmf-conversions has not been specified,
8401     convert_member_func_to_ptr will issue an error message.  */
8402  if ((TYPE_PTRMEMFUNC_P (intype)
8403       || TREE_CODE (intype) == METHOD_TYPE)
8404      && TYPE_PTR_P (type)
8405      && (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE
8406	  || VOID_TYPE_P (TREE_TYPE (type))))
8407    return convert_member_func_to_ptr (type, expr, complain);
8408
8409  /* If the cast is not to a reference type, the lvalue-to-rvalue,
8410     array-to-pointer, and function-to-pointer conversions are
8411     performed.  */
8412  expr = decay_conversion (expr, complain);
8413
8414  /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
8415     Strip such NOP_EXPRs if VALUE is being used in non-lvalue context.  */
8416  if (TREE_CODE (expr) == NOP_EXPR
8417      && TREE_TYPE (expr) == TREE_TYPE (TREE_OPERAND (expr, 0)))
8418    expr = TREE_OPERAND (expr, 0);
8419
8420  if (error_operand_p (expr))
8421    return error_mark_node;
8422
8423  intype = TREE_TYPE (expr);
8424
8425  /* [expr.reinterpret.cast]
8426     A pointer can be converted to any integral type large enough to
8427     hold it. ... A value of type std::nullptr_t can be converted to
8428     an integral type; the conversion has the same meaning and
8429     validity as a conversion of (void*)0 to the integral type.  */
8430  if (CP_INTEGRAL_TYPE_P (type)
8431      && (TYPE_PTR_P (intype) || NULLPTR_TYPE_P (intype)))
8432    {
8433      if (TYPE_PRECISION (type) < TYPE_PRECISION (intype))
8434        {
8435          if (complain & tf_error)
8436            permerror (loc, "cast from %qH to %qI loses precision",
8437                       intype, type);
8438          else
8439            return error_mark_node;
8440        }
8441      if (NULLPTR_TYPE_P (intype))
8442        return build_int_cst (type, 0);
8443    }
8444  /* [expr.reinterpret.cast]
8445     A value of integral or enumeration type can be explicitly
8446     converted to a pointer.  */
8447  else if (TYPE_PTR_P (type) && INTEGRAL_OR_ENUMERATION_TYPE_P (intype))
8448    /* OK */
8449    ;
8450  else if ((INTEGRAL_OR_ENUMERATION_TYPE_P (type)
8451	    || TYPE_PTR_OR_PTRMEM_P (type))
8452	   && same_type_p (type, intype))
8453    /* DR 799 */
8454    return rvalue (expr);
8455  else if (TYPE_PTRFN_P (type) && TYPE_PTRFN_P (intype))
8456    {
8457      if ((complain & tf_warning)
8458	  && !cxx_safe_function_type_cast_p (TREE_TYPE (type),
8459					     TREE_TYPE (intype)))
8460	warning_at (loc, OPT_Wcast_function_type,
8461		    "cast between incompatible function types"
8462		    " from %qH to %qI", intype, type);
8463      return build_nop_reinterpret (type, expr);
8464    }
8465  else if (TYPE_PTRMEMFUNC_P (type) && TYPE_PTRMEMFUNC_P (intype))
8466    {
8467      if ((complain & tf_warning)
8468	  && !cxx_safe_function_type_cast_p
8469		(TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE_RAW (type)),
8470		 TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE_RAW (intype))))
8471	warning_at (loc, OPT_Wcast_function_type,
8472		    "cast between incompatible pointer to member types"
8473		    " from %qH to %qI", intype, type);
8474      return build_nop_reinterpret (type, expr);
8475    }
8476  else if ((TYPE_PTRDATAMEM_P (type) && TYPE_PTRDATAMEM_P (intype))
8477	   || (TYPE_PTROBV_P (type) && TYPE_PTROBV_P (intype)))
8478    {
8479      if (!c_cast_p
8480	  && check_for_casting_away_constness (loc, intype, type,
8481					       REINTERPRET_CAST_EXPR,
8482					       complain))
8483	return error_mark_node;
8484      /* Warn about possible alignment problems.  */
8485      if ((STRICT_ALIGNMENT || warn_cast_align == 2)
8486	  && (complain & tf_warning)
8487	  && !VOID_TYPE_P (type)
8488	  && TREE_CODE (TREE_TYPE (intype)) != FUNCTION_TYPE
8489	  && COMPLETE_TYPE_P (TREE_TYPE (type))
8490	  && COMPLETE_TYPE_P (TREE_TYPE (intype))
8491	  && min_align_of_type (TREE_TYPE (type))
8492	     > min_align_of_type (TREE_TYPE (intype)))
8493	warning_at (loc, OPT_Wcast_align, "cast from %qH to %qI "
8494		    "increases required alignment of target type",
8495		    intype, type);
8496
8497      if (warn_strict_aliasing <= 2)
8498	/* strict_aliasing_warning STRIP_NOPs its expr.  */
8499	cp_strict_aliasing_warning (EXPR_LOCATION (expr), type, expr);
8500
8501      return build_nop_reinterpret (type, expr);
8502    }
8503  else if ((TYPE_PTRFN_P (type) && TYPE_PTROBV_P (intype))
8504	   || (TYPE_PTRFN_P (intype) && TYPE_PTROBV_P (type)))
8505    {
8506      if (complain & tf_warning)
8507	/* C++11 5.2.10 p8 says that "Converting a function pointer to an
8508	   object pointer type or vice versa is conditionally-supported."  */
8509	warning_at (loc, OPT_Wconditionally_supported,
8510		    "casting between pointer-to-function and "
8511		    "pointer-to-object is conditionally-supported");
8512      return build_nop_reinterpret (type, expr);
8513    }
8514  else if (gnu_vector_type_p (type) && scalarish_type_p (intype))
8515    return convert_to_vector (type, rvalue (expr));
8516  else if (gnu_vector_type_p (intype)
8517	   && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
8518    return convert_to_integer_nofold (type, expr);
8519  else
8520    {
8521      if (valid_p)
8522	*valid_p = false;
8523      if (complain & tf_error)
8524        error_at (loc, "invalid cast from type %qT to type %qT",
8525		  intype, type);
8526      return error_mark_node;
8527    }
8528
8529  expr = cp_convert (type, expr, complain);
8530  if (TREE_CODE (expr) == NOP_EXPR)
8531    /* Mark any nop_expr that created as a reintepret_cast.  */
8532    REINTERPRET_CAST_P (expr) = true;
8533  return expr;
8534}
8535
8536tree
8537build_reinterpret_cast (location_t loc, tree type, tree expr,
8538			tsubst_flags_t complain)
8539{
8540  tree r;
8541
8542  if (type == error_mark_node || expr == error_mark_node)
8543    return error_mark_node;
8544
8545  if (processing_template_decl)
8546    {
8547      tree t = build_min (REINTERPRET_CAST_EXPR, type, expr);
8548
8549      if (!TREE_SIDE_EFFECTS (t)
8550	  && type_dependent_expression_p (expr))
8551	/* There might turn out to be side effects inside expr.  */
8552	TREE_SIDE_EFFECTS (t) = 1;
8553      r = convert_from_reference (t);
8554      protected_set_expr_location (r, loc);
8555      return r;
8556    }
8557
8558  r = build_reinterpret_cast_1 (loc, type, expr, /*c_cast_p=*/false,
8559				/*valid_p=*/NULL, complain);
8560  if (r != error_mark_node)
8561    {
8562      maybe_warn_about_useless_cast (loc, type, expr, complain);
8563      maybe_warn_about_cast_ignoring_quals (loc, type, complain);
8564    }
8565  protected_set_expr_location (r, loc);
8566  return r;
8567}
8568
8569/* Perform a const_cast from EXPR to TYPE.  If the cast is valid,
8570   return an appropriate expression.  Otherwise, return
8571   error_mark_node.  If the cast is not valid, and COMPLAIN is true,
8572   then a diagnostic will be issued.  If VALID_P is non-NULL, we are
8573   performing a C-style cast, its value upon return will indicate
8574   whether or not the conversion succeeded.  */
8575
8576static tree
8577build_const_cast_1 (location_t loc, tree dst_type, tree expr,
8578		    tsubst_flags_t complain, bool *valid_p)
8579{
8580  tree src_type;
8581  tree reference_type;
8582
8583  /* Callers are responsible for handling error_mark_node as a
8584     destination type.  */
8585  gcc_assert (dst_type != error_mark_node);
8586  /* In a template, callers should be building syntactic
8587     representations of casts, not using this machinery.  */
8588  gcc_assert (!processing_template_decl);
8589
8590  /* Assume the conversion is invalid.  */
8591  if (valid_p)
8592    *valid_p = false;
8593
8594  if (!INDIRECT_TYPE_P (dst_type) && !TYPE_PTRDATAMEM_P (dst_type))
8595    {
8596      if (complain & tf_error)
8597	error_at (loc, "invalid use of %<const_cast%> with type %qT, "
8598		  "which is not a pointer, reference, "
8599		  "nor a pointer-to-data-member type", dst_type);
8600      return error_mark_node;
8601    }
8602
8603  if (TREE_CODE (TREE_TYPE (dst_type)) == FUNCTION_TYPE)
8604    {
8605      if (complain & tf_error)
8606	error_at (loc, "invalid use of %<const_cast%> with type %qT, "
8607		  "which is a pointer or reference to a function type",
8608		  dst_type);
8609       return error_mark_node;
8610    }
8611
8612  /* A prvalue of non-class type is cv-unqualified.  */
8613  dst_type = cv_unqualified (dst_type);
8614
8615  /* Save casted types in the function's used types hash table.  */
8616  used_types_insert (dst_type);
8617
8618  src_type = TREE_TYPE (expr);
8619  /* Expressions do not really have reference types.  */
8620  if (TYPE_REF_P (src_type))
8621    src_type = TREE_TYPE (src_type);
8622
8623  /* [expr.const.cast]
8624
8625     For two object types T1 and T2, if a pointer to T1 can be explicitly
8626     converted to the type "pointer to T2" using a const_cast, then the
8627     following conversions can also be made:
8628
8629     -- an lvalue of type T1 can be explicitly converted to an lvalue of
8630     type T2 using the cast const_cast<T2&>;
8631
8632     -- a glvalue of type T1 can be explicitly converted to an xvalue of
8633     type T2 using the cast const_cast<T2&&>; and
8634
8635     -- if T1 is a class type, a prvalue of type T1 can be explicitly
8636     converted to an xvalue of type T2 using the cast const_cast<T2&&>.  */
8637
8638  if (TYPE_REF_P (dst_type))
8639    {
8640      reference_type = dst_type;
8641      if (!TYPE_REF_IS_RVALUE (dst_type)
8642	  ? lvalue_p (expr)
8643	  : obvalue_p (expr))
8644	/* OK.  */;
8645      else
8646	{
8647	  if (complain & tf_error)
8648	    error_at (loc, "invalid %<const_cast%> of an rvalue of type %qT "
8649		      "to type %qT",
8650		      src_type, dst_type);
8651 	  return error_mark_node;
8652	}
8653      dst_type = build_pointer_type (TREE_TYPE (dst_type));
8654      src_type = build_pointer_type (src_type);
8655    }
8656  else
8657    {
8658      reference_type = NULL_TREE;
8659      /* If the destination type is not a reference type, the
8660	 lvalue-to-rvalue, array-to-pointer, and function-to-pointer
8661	 conversions are performed.  */
8662      src_type = type_decays_to (src_type);
8663      if (src_type == error_mark_node)
8664	return error_mark_node;
8665    }
8666
8667  if (TYPE_PTR_P (src_type) || TYPE_PTRDATAMEM_P (src_type))
8668    {
8669      if (comp_ptr_ttypes_const (dst_type, src_type, bounds_none))
8670	{
8671	  if (valid_p)
8672	    {
8673	      *valid_p = true;
8674	      /* This cast is actually a C-style cast.  Issue a warning if
8675		 the user is making a potentially unsafe cast.  */
8676	      check_for_casting_away_constness (loc, src_type, dst_type,
8677						CAST_EXPR, complain);
8678	      /* ??? comp_ptr_ttypes_const ignores TYPE_ALIGN.  */
8679	      if ((STRICT_ALIGNMENT || warn_cast_align == 2)
8680		  && (complain & tf_warning)
8681		  && min_align_of_type (TREE_TYPE (dst_type))
8682		     > min_align_of_type (TREE_TYPE (src_type)))
8683		warning_at (loc, OPT_Wcast_align, "cast from %qH to %qI "
8684			    "increases required alignment of target type",
8685			    src_type, dst_type);
8686	    }
8687	  if (reference_type)
8688	    {
8689	      expr = cp_build_addr_expr (expr, complain);
8690	      if (expr == error_mark_node)
8691		return error_mark_node;
8692	      expr = build_nop (reference_type, expr);
8693	      return convert_from_reference (expr);
8694	    }
8695	  else
8696	    {
8697	      expr = decay_conversion (expr, complain);
8698	      if (expr == error_mark_node)
8699		return error_mark_node;
8700
8701	      /* build_c_cast puts on a NOP_EXPR to make the result not an
8702		 lvalue.  Strip such NOP_EXPRs if VALUE is being used in
8703		 non-lvalue context.  */
8704	      if (TREE_CODE (expr) == NOP_EXPR
8705		  && TREE_TYPE (expr) == TREE_TYPE (TREE_OPERAND (expr, 0)))
8706		expr = TREE_OPERAND (expr, 0);
8707	      return build_nop (dst_type, expr);
8708	    }
8709	}
8710      else if (valid_p
8711	       && !at_least_as_qualified_p (TREE_TYPE (dst_type),
8712					    TREE_TYPE (src_type)))
8713	check_for_casting_away_constness (loc, src_type, dst_type,
8714					  CAST_EXPR, complain);
8715    }
8716
8717  if (complain & tf_error)
8718    error_at (loc, "invalid %<const_cast%> from type %qT to type %qT",
8719	      src_type, dst_type);
8720  return error_mark_node;
8721}
8722
8723tree
8724build_const_cast (location_t loc, tree type, tree expr,
8725		  tsubst_flags_t complain)
8726{
8727  tree r;
8728
8729  if (type == error_mark_node || error_operand_p (expr))
8730    return error_mark_node;
8731
8732  if (processing_template_decl)
8733    {
8734      tree t = build_min (CONST_CAST_EXPR, type, expr);
8735
8736      if (!TREE_SIDE_EFFECTS (t)
8737	  && type_dependent_expression_p (expr))
8738	/* There might turn out to be side effects inside expr.  */
8739	TREE_SIDE_EFFECTS (t) = 1;
8740      r = convert_from_reference (t);
8741      protected_set_expr_location (r, loc);
8742      return r;
8743    }
8744
8745  r = build_const_cast_1 (loc, type, expr, complain, /*valid_p=*/NULL);
8746  if (r != error_mark_node)
8747    {
8748      maybe_warn_about_useless_cast (loc, type, expr, complain);
8749      maybe_warn_about_cast_ignoring_quals (loc, type, complain);
8750    }
8751  protected_set_expr_location (r, loc);
8752  return r;
8753}
8754
8755/* Like cp_build_c_cast, but for the c-common bits.  */
8756
8757tree
8758build_c_cast (location_t loc, tree type, tree expr)
8759{
8760  return cp_build_c_cast (loc, type, expr, tf_warning_or_error);
8761}
8762
8763/* Like the "build_c_cast" used for c-common, but using cp_expr to
8764   preserve location information even for tree nodes that don't
8765   support it.  */
8766
8767cp_expr
8768build_c_cast (location_t loc, tree type, cp_expr expr)
8769{
8770  cp_expr result = cp_build_c_cast (loc, type, expr, tf_warning_or_error);
8771  result.set_location (loc);
8772  return result;
8773}
8774
8775/* Build an expression representing an explicit C-style cast to type
8776   TYPE of expression EXPR.  */
8777
8778tree
8779cp_build_c_cast (location_t loc, tree type, tree expr,
8780		 tsubst_flags_t complain)
8781{
8782  tree value = expr;
8783  tree result;
8784  bool valid_p;
8785
8786  if (type == error_mark_node || error_operand_p (expr))
8787    return error_mark_node;
8788
8789  if (processing_template_decl)
8790    {
8791      tree t = build_min (CAST_EXPR, type,
8792			  tree_cons (NULL_TREE, value, NULL_TREE));
8793      /* We don't know if it will or will not have side effects.  */
8794      TREE_SIDE_EFFECTS (t) = 1;
8795      return convert_from_reference (t);
8796    }
8797
8798  /* Casts to a (pointer to a) specific ObjC class (or 'id' or
8799     'Class') should always be retained, because this information aids
8800     in method lookup.  */
8801  if (objc_is_object_ptr (type)
8802      && objc_is_object_ptr (TREE_TYPE (expr)))
8803    return build_nop (type, expr);
8804
8805  /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
8806     Strip such NOP_EXPRs if VALUE is being used in non-lvalue context.  */
8807  if (!TYPE_REF_P (type)
8808      && TREE_CODE (value) == NOP_EXPR
8809      && TREE_TYPE (value) == TREE_TYPE (TREE_OPERAND (value, 0)))
8810    value = TREE_OPERAND (value, 0);
8811
8812  if (TREE_CODE (type) == ARRAY_TYPE)
8813    {
8814      /* Allow casting from T1* to T2[] because Cfront allows it.
8815	 NIHCL uses it. It is not valid ISO C++ however.  */
8816      if (TYPE_PTR_P (TREE_TYPE (expr)))
8817	{
8818          if (complain & tf_error)
8819            permerror (loc, "ISO C++ forbids casting to an array type %qT",
8820		       type);
8821          else
8822            return error_mark_node;
8823	  type = build_pointer_type (TREE_TYPE (type));
8824	}
8825      else
8826	{
8827          if (complain & tf_error)
8828            error_at (loc, "ISO C++ forbids casting to an array type %qT",
8829		      type);
8830	  return error_mark_node;
8831	}
8832    }
8833
8834  if (FUNC_OR_METHOD_TYPE_P (type))
8835    {
8836      if (complain & tf_error)
8837        error_at (loc, "invalid cast to function type %qT", type);
8838      return error_mark_node;
8839    }
8840
8841  if (TYPE_PTR_P (type)
8842      && TREE_CODE (TREE_TYPE (value)) == INTEGER_TYPE
8843      /* Casting to an integer of smaller size is an error detected elsewhere.  */
8844      && TYPE_PRECISION (type) > TYPE_PRECISION (TREE_TYPE (value))
8845      /* Don't warn about converting any constant.  */
8846      && !TREE_CONSTANT (value))
8847    warning_at (loc, OPT_Wint_to_pointer_cast,
8848		"cast to pointer from integer of different size");
8849
8850  /* A C-style cast can be a const_cast.  */
8851  result = build_const_cast_1 (loc, type, value, complain & tf_warning,
8852			       &valid_p);
8853  if (valid_p)
8854    {
8855      if (result != error_mark_node)
8856	{
8857	  maybe_warn_about_useless_cast (loc, type, value, complain);
8858	  maybe_warn_about_cast_ignoring_quals (loc, type, complain);
8859	}
8860      return result;
8861    }
8862
8863  /* Or a static cast.  */
8864  result = build_static_cast_1 (loc, type, value, /*c_cast_p=*/true,
8865				&valid_p, complain);
8866  /* Or a reinterpret_cast.  */
8867  if (!valid_p)
8868    result = build_reinterpret_cast_1 (loc, type, value, /*c_cast_p=*/true,
8869				       &valid_p, complain);
8870  /* The static_cast or reinterpret_cast may be followed by a
8871     const_cast.  */
8872  if (valid_p
8873      /* A valid cast may result in errors if, for example, a
8874	 conversion to an ambiguous base class is required.  */
8875      && !error_operand_p (result))
8876    {
8877      tree result_type;
8878
8879      maybe_warn_about_useless_cast (loc, type, value, complain);
8880      maybe_warn_about_cast_ignoring_quals (loc, type, complain);
8881
8882      /* Non-class rvalues always have cv-unqualified type.  */
8883      if (!CLASS_TYPE_P (type))
8884	type = TYPE_MAIN_VARIANT (type);
8885      result_type = TREE_TYPE (result);
8886      if (!CLASS_TYPE_P (result_type) && !TYPE_REF_P (type))
8887	result_type = TYPE_MAIN_VARIANT (result_type);
8888      /* If the type of RESULT does not match TYPE, perform a
8889	 const_cast to make it match.  If the static_cast or
8890	 reinterpret_cast succeeded, we will differ by at most
8891	 cv-qualification, so the follow-on const_cast is guaranteed
8892	 to succeed.  */
8893      if (!same_type_p (non_reference (type), non_reference (result_type)))
8894	{
8895	  result = build_const_cast_1 (loc, type, result, false, &valid_p);
8896	  gcc_assert (valid_p);
8897	}
8898      return result;
8899    }
8900
8901  return error_mark_node;
8902}
8903
8904/* For use from the C common bits.  */
8905tree
8906build_modify_expr (location_t location,
8907		   tree lhs, tree /*lhs_origtype*/,
8908		   enum tree_code modifycode,
8909		   location_t /*rhs_location*/, tree rhs,
8910		   tree /*rhs_origtype*/)
8911{
8912  return cp_build_modify_expr (location, lhs, modifycode, rhs,
8913			       tf_warning_or_error);
8914}
8915
8916/* Build an assignment expression of lvalue LHS from value RHS.
8917   MODIFYCODE is the code for a binary operator that we use
8918   to combine the old value of LHS with RHS to get the new value.
8919   Or else MODIFYCODE is NOP_EXPR meaning do a simple assignment.
8920
8921   C++: If MODIFYCODE is INIT_EXPR, then leave references unbashed.  */
8922
8923tree
8924cp_build_modify_expr (location_t loc, tree lhs, enum tree_code modifycode,
8925		      tree rhs, tsubst_flags_t complain)
8926{
8927  lhs = mark_lvalue_use_nonread (lhs);
8928
8929  tree result = NULL_TREE;
8930  tree newrhs = rhs;
8931  tree lhstype = TREE_TYPE (lhs);
8932  tree olhs = lhs;
8933  tree olhstype = lhstype;
8934  bool plain_assign = (modifycode == NOP_EXPR);
8935  bool compound_side_effects_p = false;
8936  tree preeval = NULL_TREE;
8937
8938  /* Avoid duplicate error messages from operands that had errors.  */
8939  if (error_operand_p (lhs) || error_operand_p (rhs))
8940    return error_mark_node;
8941
8942  while (TREE_CODE (lhs) == COMPOUND_EXPR)
8943    {
8944      if (TREE_SIDE_EFFECTS (TREE_OPERAND (lhs, 0)))
8945	compound_side_effects_p = true;
8946      lhs = TREE_OPERAND (lhs, 1);
8947    }
8948
8949  /* Handle control structure constructs used as "lvalues".  Note that we
8950     leave COMPOUND_EXPR on the LHS because it is sequenced after the RHS.  */
8951  switch (TREE_CODE (lhs))
8952    {
8953      /* Handle --foo = 5; as these are valid constructs in C++.  */
8954    case PREDECREMENT_EXPR:
8955    case PREINCREMENT_EXPR:
8956      if (compound_side_effects_p)
8957	newrhs = rhs = stabilize_expr (rhs, &preeval);
8958      lhs = genericize_compound_lvalue (lhs);
8959    maybe_add_compound:
8960      /* If we had (bar, --foo) = 5; or (bar, (baz, --foo)) = 5;
8961	 and looked through the COMPOUND_EXPRs, readd them now around
8962	 the resulting lhs.  */
8963      if (TREE_CODE (olhs) == COMPOUND_EXPR)
8964	{
8965	  lhs = build2 (COMPOUND_EXPR, lhstype, TREE_OPERAND (olhs, 0), lhs);
8966	  tree *ptr = &TREE_OPERAND (lhs, 1);
8967	  for (olhs = TREE_OPERAND (olhs, 1);
8968	       TREE_CODE (olhs) == COMPOUND_EXPR;
8969	       olhs = TREE_OPERAND (olhs, 1))
8970	    {
8971	      *ptr = build2 (COMPOUND_EXPR, lhstype,
8972			     TREE_OPERAND (olhs, 0), *ptr);
8973	      ptr = &TREE_OPERAND (*ptr, 1);
8974	    }
8975	}
8976      break;
8977
8978    case MODIFY_EXPR:
8979      if (compound_side_effects_p)
8980	newrhs = rhs = stabilize_expr (rhs, &preeval);
8981      lhs = genericize_compound_lvalue (lhs);
8982      goto maybe_add_compound;
8983
8984    case MIN_EXPR:
8985    case MAX_EXPR:
8986      /* MIN_EXPR and MAX_EXPR are currently only permitted as lvalues,
8987	 when neither operand has side-effects.  */
8988      if (!lvalue_or_else (lhs, lv_assign, complain))
8989	return error_mark_node;
8990
8991      gcc_assert (!TREE_SIDE_EFFECTS (TREE_OPERAND (lhs, 0))
8992		  && !TREE_SIDE_EFFECTS (TREE_OPERAND (lhs, 1)));
8993
8994      lhs = build3 (COND_EXPR, TREE_TYPE (lhs),
8995		    build2 (TREE_CODE (lhs) == MIN_EXPR ? LE_EXPR : GE_EXPR,
8996			    boolean_type_node,
8997			    TREE_OPERAND (lhs, 0),
8998			    TREE_OPERAND (lhs, 1)),
8999		    TREE_OPERAND (lhs, 0),
9000		    TREE_OPERAND (lhs, 1));
9001      gcc_fallthrough ();
9002
9003      /* Handle (a ? b : c) used as an "lvalue".  */
9004    case COND_EXPR:
9005      {
9006	/* Produce (a ? (b = rhs) : (c = rhs))
9007	   except that the RHS goes through a save-expr
9008	   so the code to compute it is only emitted once.  */
9009	if (VOID_TYPE_P (TREE_TYPE (rhs)))
9010	  {
9011	    if (complain & tf_error)
9012	      error_at (cp_expr_loc_or_loc (rhs, loc),
9013			"void value not ignored as it ought to be");
9014	    return error_mark_node;
9015	  }
9016
9017	rhs = stabilize_expr (rhs, &preeval);
9018
9019	/* Check this here to avoid odd errors when trying to convert
9020	   a throw to the type of the COND_EXPR.  */
9021	if (!lvalue_or_else (lhs, lv_assign, complain))
9022	  return error_mark_node;
9023
9024	tree op1 = TREE_OPERAND (lhs, 1);
9025	if (TREE_CODE (op1) != THROW_EXPR)
9026	  op1 = cp_build_modify_expr (loc, op1, modifycode, rhs, complain);
9027	/* When sanitizing undefined behavior, even when rhs doesn't need
9028	   stabilization at this point, the sanitization might add extra
9029	   SAVE_EXPRs in there and so make sure there is no tree sharing
9030	   in the rhs, otherwise those SAVE_EXPRs will have initialization
9031	   only in one of the two branches.  */
9032	if (sanitize_flags_p (SANITIZE_UNDEFINED
9033			      | SANITIZE_UNDEFINED_NONDEFAULT))
9034	  rhs = unshare_expr (rhs);
9035	tree op2 = TREE_OPERAND (lhs, 2);
9036	if (TREE_CODE (op2) != THROW_EXPR)
9037	  op2 = cp_build_modify_expr (loc, op2, modifycode, rhs, complain);
9038	tree cond = build_conditional_expr (input_location,
9039					    TREE_OPERAND (lhs, 0), op1, op2,
9040					    complain);
9041
9042	if (cond == error_mark_node)
9043	  return cond;
9044	/* If we had (e, (a ? b : c)) = d; or (e, (f, (a ? b : c))) = d;
9045	   and looked through the COMPOUND_EXPRs, readd them now around
9046	   the resulting cond before adding the preevaluated rhs.  */
9047	if (TREE_CODE (olhs) == COMPOUND_EXPR)
9048	  {
9049	    cond = build2 (COMPOUND_EXPR, TREE_TYPE (cond),
9050			   TREE_OPERAND (olhs, 0), cond);
9051	    tree *ptr = &TREE_OPERAND (cond, 1);
9052	    for (olhs = TREE_OPERAND (olhs, 1);
9053		 TREE_CODE (olhs) == COMPOUND_EXPR;
9054		 olhs = TREE_OPERAND (olhs, 1))
9055	      {
9056		*ptr = build2 (COMPOUND_EXPR, TREE_TYPE (cond),
9057			       TREE_OPERAND (olhs, 0), *ptr);
9058		ptr = &TREE_OPERAND (*ptr, 1);
9059	      }
9060	  }
9061	/* Make sure the code to compute the rhs comes out
9062	   before the split.  */
9063	result = cond;
9064	goto ret;
9065      }
9066
9067    default:
9068      lhs = olhs;
9069      break;
9070    }
9071
9072  if (modifycode == INIT_EXPR)
9073    {
9074      if (BRACE_ENCLOSED_INITIALIZER_P (rhs))
9075	/* Do the default thing.  */;
9076      else if (TREE_CODE (rhs) == CONSTRUCTOR)
9077	{
9078	  /* Compound literal.  */
9079	  if (! same_type_p (TREE_TYPE (rhs), lhstype))
9080	    /* Call convert to generate an error; see PR 11063.  */
9081	    rhs = convert (lhstype, rhs);
9082	  result = build2 (INIT_EXPR, lhstype, lhs, rhs);
9083	  TREE_SIDE_EFFECTS (result) = 1;
9084	  goto ret;
9085	}
9086      else if (! MAYBE_CLASS_TYPE_P (lhstype))
9087	/* Do the default thing.  */;
9088      else
9089	{
9090	  releasing_vec rhs_vec = make_tree_vector_single (rhs);
9091	  result = build_special_member_call (lhs, complete_ctor_identifier,
9092					      &rhs_vec, lhstype, LOOKUP_NORMAL,
9093                                              complain);
9094	  if (result == NULL_TREE)
9095	    return error_mark_node;
9096	  goto ret;
9097	}
9098    }
9099  else
9100    {
9101      lhs = require_complete_type_sfinae (lhs, complain);
9102      if (lhs == error_mark_node)
9103	return error_mark_node;
9104
9105      if (modifycode == NOP_EXPR)
9106	{
9107	  if (c_dialect_objc ())
9108	    {
9109	      result = objc_maybe_build_modify_expr (lhs, rhs);
9110	      if (result)
9111		goto ret;
9112	    }
9113
9114	  /* `operator=' is not an inheritable operator.  */
9115	  if (! MAYBE_CLASS_TYPE_P (lhstype))
9116	    /* Do the default thing.  */;
9117	  else
9118	    {
9119	      result = build_new_op (input_location, MODIFY_EXPR,
9120				     LOOKUP_NORMAL, lhs, rhs,
9121				     make_node (NOP_EXPR), NULL_TREE,
9122				     /*overload=*/NULL, complain);
9123	      if (result == NULL_TREE)
9124		return error_mark_node;
9125	      goto ret;
9126	    }
9127	  lhstype = olhstype;
9128	}
9129      else
9130	{
9131	  tree init = NULL_TREE;
9132
9133	  /* A binary op has been requested.  Combine the old LHS
9134	     value with the RHS producing the value we should actually
9135	     store into the LHS.  */
9136	  gcc_assert (!((TYPE_REF_P (lhstype)
9137			 && MAYBE_CLASS_TYPE_P (TREE_TYPE (lhstype)))
9138			|| MAYBE_CLASS_TYPE_P (lhstype)));
9139
9140	  /* An expression of the form E1 op= E2.  [expr.ass] says:
9141	     "Such expressions are deprecated if E1 has volatile-qualified
9142	     type and op is not one of the bitwise operators |, &, ^."
9143	     We warn here rather than in cp_genericize_r because
9144	     for compound assignments we are supposed to warn even if the
9145	     assignment is a discarded-value expression.  */
9146	  if (modifycode != BIT_AND_EXPR
9147	      && modifycode != BIT_IOR_EXPR
9148	      && modifycode != BIT_XOR_EXPR
9149	      && (TREE_THIS_VOLATILE (lhs) || CP_TYPE_VOLATILE_P (lhstype)))
9150	    warning_at (loc, OPT_Wvolatile,
9151			"compound assignment with %<volatile%>-qualified left "
9152			"operand is deprecated");
9153	  /* Preevaluate the RHS to make sure its evaluation is complete
9154	     before the lvalue-to-rvalue conversion of the LHS:
9155
9156	     [expr.ass] With respect to an indeterminately-sequenced
9157	     function call, the operation of a compound assignment is a
9158	     single evaluation. [ Note: Therefore, a function call shall
9159	     not intervene between the lvalue-to-rvalue conversion and the
9160	     side effect associated with any single compound assignment
9161	     operator. -- end note ]  */
9162	  lhs = cp_stabilize_reference (lhs);
9163	  rhs = decay_conversion (rhs, complain);
9164	  if (rhs == error_mark_node)
9165	    return error_mark_node;
9166	  rhs = stabilize_expr (rhs, &init);
9167	  newrhs = cp_build_binary_op (loc, modifycode, lhs, rhs, complain);
9168	  if (newrhs == error_mark_node)
9169	    {
9170	      if (complain & tf_error)
9171		inform (loc, "  in evaluation of %<%Q(%#T, %#T)%>",
9172			modifycode, TREE_TYPE (lhs), TREE_TYPE (rhs));
9173	      return error_mark_node;
9174	    }
9175
9176	  if (init)
9177	    newrhs = build2 (COMPOUND_EXPR, TREE_TYPE (newrhs), init, newrhs);
9178
9179	  /* Now it looks like a plain assignment.  */
9180	  modifycode = NOP_EXPR;
9181	  if (c_dialect_objc ())
9182	    {
9183	      result = objc_maybe_build_modify_expr (lhs, newrhs);
9184	      if (result)
9185		goto ret;
9186	    }
9187	}
9188      gcc_assert (!TYPE_REF_P (lhstype));
9189      gcc_assert (!TYPE_REF_P (TREE_TYPE (newrhs)));
9190    }
9191
9192  /* The left-hand side must be an lvalue.  */
9193  if (!lvalue_or_else (lhs, lv_assign, complain))
9194    return error_mark_node;
9195
9196  /* Warn about modifying something that is `const'.  Don't warn if
9197     this is initialization.  */
9198  if (modifycode != INIT_EXPR
9199      && (TREE_READONLY (lhs) || CP_TYPE_CONST_P (lhstype)
9200	  /* Functions are not modifiable, even though they are
9201	     lvalues.  */
9202	  || FUNC_OR_METHOD_TYPE_P (TREE_TYPE (lhs))
9203	  /* If it's an aggregate and any field is const, then it is
9204	     effectively const.  */
9205	  || (CLASS_TYPE_P (lhstype)
9206	      && C_TYPE_FIELDS_READONLY (lhstype))))
9207    {
9208      if (complain & tf_error)
9209	cxx_readonly_error (loc, lhs, lv_assign);
9210      return error_mark_node;
9211    }
9212
9213  /* If storing into a structure or union member, it may have been given a
9214     lowered bitfield type.  We need to convert to the declared type first,
9215     so retrieve it now.  */
9216
9217  olhstype = unlowered_expr_type (lhs);
9218
9219  /* Convert new value to destination type.  */
9220
9221  if (TREE_CODE (lhstype) == ARRAY_TYPE)
9222    {
9223      int from_array;
9224
9225      if (BRACE_ENCLOSED_INITIALIZER_P (newrhs))
9226	{
9227	  if (modifycode != INIT_EXPR)
9228	    {
9229	      if (complain & tf_error)
9230		error_at (loc,
9231			  "assigning to an array from an initializer list");
9232	      return error_mark_node;
9233	    }
9234	  if (check_array_initializer (lhs, lhstype, newrhs))
9235	    return error_mark_node;
9236	  newrhs = digest_init (lhstype, newrhs, complain);
9237	  if (newrhs == error_mark_node)
9238	    return error_mark_node;
9239	}
9240
9241      /* C++11 8.5/17: "If the destination type is an array of characters,
9242	 an array of char16_t, an array of char32_t, or an array of wchar_t,
9243	 and the initializer is a string literal...".  */
9244      else if ((TREE_CODE (tree_strip_any_location_wrapper (newrhs))
9245		== STRING_CST)
9246	       && char_type_p (TREE_TYPE (TYPE_MAIN_VARIANT (lhstype)))
9247	       && modifycode == INIT_EXPR)
9248	{
9249	  newrhs = digest_init (lhstype, newrhs, complain);
9250	  if (newrhs == error_mark_node)
9251	    return error_mark_node;
9252	}
9253
9254      else if (!same_or_base_type_p (TYPE_MAIN_VARIANT (lhstype),
9255				     TYPE_MAIN_VARIANT (TREE_TYPE (newrhs))))
9256	{
9257	  if (complain & tf_error)
9258	    error_at (loc, "incompatible types in assignment of %qT to %qT",
9259		      TREE_TYPE (rhs), lhstype);
9260	  return error_mark_node;
9261	}
9262
9263      /* Allow array assignment in compiler-generated code.  */
9264      else if (DECL_P (lhs) && DECL_ARTIFICIAL (lhs))
9265	/* OK, used by coroutines (co-await-initlist1.C).  */;
9266      else if (!current_function_decl
9267	       || !DECL_DEFAULTED_FN (current_function_decl))
9268	{
9269          /* This routine is used for both initialization and assignment.
9270             Make sure the diagnostic message differentiates the context.  */
9271	  if (complain & tf_error)
9272	    {
9273	      if (modifycode == INIT_EXPR)
9274		error_at (loc, "array used as initializer");
9275	      else
9276		error_at (loc, "invalid array assignment");
9277	    }
9278	  return error_mark_node;
9279	}
9280
9281      from_array = TREE_CODE (TREE_TYPE (newrhs)) == ARRAY_TYPE
9282		   ? 1 + (modifycode != INIT_EXPR): 0;
9283      result = build_vec_init (lhs, NULL_TREE, newrhs,
9284			       /*explicit_value_init_p=*/false,
9285			       from_array, complain);
9286      goto ret;
9287    }
9288
9289  if (modifycode == INIT_EXPR)
9290    /* Calls with INIT_EXPR are all direct-initialization, so don't set
9291       LOOKUP_ONLYCONVERTING.  */
9292    newrhs = convert_for_initialization (lhs, olhstype, newrhs, LOOKUP_NORMAL,
9293					 ICR_INIT, NULL_TREE, 0,
9294					 complain | tf_no_cleanup);
9295  else
9296    newrhs = convert_for_assignment (olhstype, newrhs, ICR_ASSIGN,
9297				     NULL_TREE, 0, complain, LOOKUP_IMPLICIT);
9298
9299  if (!same_type_p (lhstype, olhstype))
9300    newrhs = cp_convert_and_check (lhstype, newrhs, complain);
9301
9302  if (modifycode != INIT_EXPR)
9303    {
9304      if (TREE_CODE (newrhs) == CALL_EXPR
9305	  && TYPE_NEEDS_CONSTRUCTING (lhstype))
9306	newrhs = build_cplus_new (lhstype, newrhs, complain);
9307
9308      /* Can't initialize directly from a TARGET_EXPR, since that would
9309	 cause the lhs to be constructed twice, and possibly result in
9310	 accidental self-initialization.  So we force the TARGET_EXPR to be
9311	 expanded without a target.  */
9312      if (TREE_CODE (newrhs) == TARGET_EXPR)
9313	newrhs = build2 (COMPOUND_EXPR, TREE_TYPE (newrhs), newrhs,
9314			 TREE_OPERAND (newrhs, 0));
9315    }
9316
9317  if (newrhs == error_mark_node)
9318    return error_mark_node;
9319
9320  if (c_dialect_objc () && flag_objc_gc)
9321    {
9322      result = objc_generate_write_barrier (lhs, modifycode, newrhs);
9323
9324      if (result)
9325	goto ret;
9326    }
9327
9328  result = build2_loc (loc, modifycode == NOP_EXPR ? MODIFY_EXPR : INIT_EXPR,
9329		       lhstype, lhs, newrhs);
9330
9331  TREE_SIDE_EFFECTS (result) = 1;
9332  if (!plain_assign)
9333    suppress_warning (result, OPT_Wparentheses);
9334
9335 ret:
9336  if (preeval)
9337    result = build2 (COMPOUND_EXPR, TREE_TYPE (result), preeval, result);
9338  return result;
9339}
9340
9341cp_expr
9342build_x_modify_expr (location_t loc, tree lhs, enum tree_code modifycode,
9343		     tree rhs, tree lookups, tsubst_flags_t complain)
9344{
9345  tree orig_lhs = lhs;
9346  tree orig_rhs = rhs;
9347  tree overload = NULL_TREE;
9348
9349  if (lhs == error_mark_node || rhs == error_mark_node)
9350    return cp_expr (error_mark_node, loc);
9351
9352  if (processing_template_decl)
9353    {
9354      if (modifycode == NOP_EXPR
9355	  || type_dependent_expression_p (lhs)
9356	  || type_dependent_expression_p (rhs))
9357	{
9358	  tree op = build_min_nt_loc (loc, modifycode, NULL_TREE, NULL_TREE);
9359	  tree rval = build_min_nt_loc (loc, MODOP_EXPR, lhs, op, rhs);
9360	  if (modifycode != NOP_EXPR)
9361	    TREE_TYPE (rval)
9362	      = build_dependent_operator_type (lookups, modifycode, true);
9363	  return rval;
9364	}
9365
9366      lhs = build_non_dependent_expr (lhs);
9367      rhs = build_non_dependent_expr (rhs);
9368    }
9369
9370  if (modifycode != NOP_EXPR)
9371    {
9372      tree op = build_nt (modifycode, NULL_TREE, NULL_TREE);
9373      tree rval = build_new_op (loc, MODIFY_EXPR, LOOKUP_NORMAL,
9374				lhs, rhs, op, lookups, &overload, complain);
9375      if (rval)
9376	{
9377	  if (rval == error_mark_node)
9378	    return rval;
9379	  suppress_warning (rval /* What warning? */);
9380	  if (processing_template_decl)
9381	    {
9382	      if (overload != NULL_TREE)
9383		return (build_min_non_dep_op_overload
9384			(MODIFY_EXPR, rval, overload, orig_lhs, orig_rhs));
9385
9386	      return (build_min_non_dep
9387		      (MODOP_EXPR, rval, orig_lhs, op, orig_rhs));
9388	    }
9389	  return rval;
9390	}
9391    }
9392  return cp_build_modify_expr (loc, lhs, modifycode, rhs, complain);
9393}
9394
9395/* Helper function for get_delta_difference which assumes FROM is a base
9396   class of TO.  Returns a delta for the conversion of pointer-to-member
9397   of FROM to pointer-to-member of TO.  If the conversion is invalid and
9398   tf_error is not set in COMPLAIN returns error_mark_node, otherwise
9399   returns zero.  If FROM is not a base class of TO, returns NULL_TREE.
9400   If C_CAST_P is true, this conversion is taking place as part of a
9401   C-style cast.  */
9402
9403static tree
9404get_delta_difference_1 (tree from, tree to, bool c_cast_p,
9405			tsubst_flags_t complain)
9406{
9407  tree binfo;
9408  base_kind kind;
9409
9410  binfo = lookup_base (to, from, c_cast_p ? ba_unique : ba_check,
9411		       &kind, complain);
9412
9413  if (binfo == error_mark_node)
9414    {
9415      if (!(complain & tf_error))
9416	return error_mark_node;
9417
9418      inform (input_location, "   in pointer to member function conversion");
9419      return size_zero_node;
9420    }
9421  else if (binfo)
9422    {
9423      if (kind != bk_via_virtual)
9424	return BINFO_OFFSET (binfo);
9425      else
9426	/* FROM is a virtual base class of TO.  Issue an error or warning
9427	   depending on whether or not this is a reinterpret cast.  */
9428	{
9429	  if (!(complain & tf_error))
9430	    return error_mark_node;
9431
9432	  error ("pointer to member conversion via virtual base %qT",
9433		 BINFO_TYPE (binfo_from_vbase (binfo)));
9434
9435	  return size_zero_node;
9436	}
9437      }
9438  else
9439    return NULL_TREE;
9440}
9441
9442/* Get difference in deltas for different pointer to member function
9443   types.  If the conversion is invalid and tf_error is not set in
9444   COMPLAIN, returns error_mark_node, otherwise returns an integer
9445   constant of type PTRDIFF_TYPE_NODE and its value is zero if the
9446   conversion is invalid.  If ALLOW_INVERSE_P is true, then allow reverse
9447   conversions as well.  If C_CAST_P is true this conversion is taking
9448   place as part of a C-style cast.
9449
9450   Note that the naming of FROM and TO is kind of backwards; the return
9451   value is what we add to a TO in order to get a FROM.  They are named
9452   this way because we call this function to find out how to convert from
9453   a pointer to member of FROM to a pointer to member of TO.  */
9454
9455static tree
9456get_delta_difference (tree from, tree to,
9457		      bool allow_inverse_p,
9458		      bool c_cast_p, tsubst_flags_t complain)
9459{
9460  tree result;
9461
9462  if (same_type_ignoring_top_level_qualifiers_p (from, to))
9463    /* Pointer to member of incomplete class is permitted*/
9464    result = size_zero_node;
9465  else
9466    result = get_delta_difference_1 (from, to, c_cast_p, complain);
9467
9468  if (result == error_mark_node)
9469    return error_mark_node;
9470
9471  if (!result)
9472  {
9473    if (!allow_inverse_p)
9474      {
9475	if (!(complain & tf_error))
9476	  return error_mark_node;
9477
9478	error_not_base_type (from, to);
9479	inform (input_location, "   in pointer to member conversion");
9480      	result = size_zero_node;
9481      }
9482    else
9483      {
9484	result = get_delta_difference_1 (to, from, c_cast_p, complain);
9485
9486	if (result == error_mark_node)
9487	  return error_mark_node;
9488
9489	if (result)
9490	  result = size_diffop_loc (input_location,
9491				    size_zero_node, result);
9492	else
9493	  {
9494	    if (!(complain & tf_error))
9495	      return error_mark_node;
9496
9497	    error_not_base_type (from, to);
9498	    inform (input_location, "   in pointer to member conversion");
9499	    result = size_zero_node;
9500	  }
9501      }
9502  }
9503
9504  return convert_to_integer (ptrdiff_type_node, result);
9505}
9506
9507/* Return a constructor for the pointer-to-member-function TYPE using
9508   the other components as specified.  */
9509
9510tree
9511build_ptrmemfunc1 (tree type, tree delta, tree pfn)
9512{
9513  tree u = NULL_TREE;
9514  tree delta_field;
9515  tree pfn_field;
9516  vec<constructor_elt, va_gc> *v;
9517
9518  /* Pull the FIELD_DECLs out of the type.  */
9519  pfn_field = TYPE_FIELDS (type);
9520  delta_field = DECL_CHAIN (pfn_field);
9521
9522  /* Make sure DELTA has the type we want.  */
9523  delta = convert_and_check (input_location, delta_type_node, delta);
9524
9525  /* Convert to the correct target type if necessary.  */
9526  pfn = fold_convert (TREE_TYPE (pfn_field), pfn);
9527
9528  /* Finish creating the initializer.  */
9529  vec_alloc (v, 2);
9530  CONSTRUCTOR_APPEND_ELT(v, pfn_field, pfn);
9531  CONSTRUCTOR_APPEND_ELT(v, delta_field, delta);
9532  u = build_constructor (type, v);
9533  TREE_CONSTANT (u) = TREE_CONSTANT (pfn) & TREE_CONSTANT (delta);
9534  TREE_STATIC (u) = (TREE_CONSTANT (u)
9535		     && (initializer_constant_valid_p (pfn, TREE_TYPE (pfn))
9536			 != NULL_TREE)
9537		     && (initializer_constant_valid_p (delta, TREE_TYPE (delta))
9538			 != NULL_TREE));
9539  return u;
9540}
9541
9542/* Build a constructor for a pointer to member function.  It can be
9543   used to initialize global variables, local variable, or used
9544   as a value in expressions.  TYPE is the POINTER to METHOD_TYPE we
9545   want to be.
9546
9547   If FORCE is nonzero, then force this conversion, even if
9548   we would rather not do it.  Usually set when using an explicit
9549   cast.  A C-style cast is being processed iff C_CAST_P is true.
9550
9551   Return error_mark_node, if something goes wrong.  */
9552
9553tree
9554build_ptrmemfunc (tree type, tree pfn, int force, bool c_cast_p,
9555		  tsubst_flags_t complain)
9556{
9557  tree fn;
9558  tree pfn_type;
9559  tree to_type;
9560
9561  if (error_operand_p (pfn))
9562    return error_mark_node;
9563
9564  pfn_type = TREE_TYPE (pfn);
9565  to_type = build_ptrmemfunc_type (type);
9566
9567  /* Handle multiple conversions of pointer to member functions.  */
9568  if (TYPE_PTRMEMFUNC_P (pfn_type))
9569    {
9570      tree delta = NULL_TREE;
9571      tree npfn = NULL_TREE;
9572      tree n;
9573
9574      if (!force
9575	  && !can_convert_arg (to_type, TREE_TYPE (pfn), pfn,
9576			       LOOKUP_NORMAL, complain))
9577	{
9578	  if (complain & tf_error)
9579	    error ("invalid conversion to type %qT from type %qT",
9580		   to_type, pfn_type);
9581	  else
9582	    return error_mark_node;
9583	}
9584
9585      n = get_delta_difference (TYPE_PTRMEMFUNC_OBJECT_TYPE (pfn_type),
9586				TYPE_PTRMEMFUNC_OBJECT_TYPE (to_type),
9587				force,
9588				c_cast_p, complain);
9589      if (n == error_mark_node)
9590	return error_mark_node;
9591
9592      STRIP_ANY_LOCATION_WRAPPER (pfn);
9593
9594      /* We don't have to do any conversion to convert a
9595	 pointer-to-member to its own type.  But, we don't want to
9596	 just return a PTRMEM_CST if there's an explicit cast; that
9597	 cast should make the expression an invalid template argument.  */
9598      if (TREE_CODE (pfn) != PTRMEM_CST
9599	  && same_type_p (to_type, pfn_type))
9600	return pfn;
9601
9602      if (TREE_SIDE_EFFECTS (pfn))
9603	pfn = save_expr (pfn);
9604
9605      /* Obtain the function pointer and the current DELTA.  */
9606      if (TREE_CODE (pfn) == PTRMEM_CST)
9607	expand_ptrmemfunc_cst (pfn, &delta, &npfn);
9608      else
9609	{
9610	  npfn = build_ptrmemfunc_access_expr (pfn, pfn_identifier);
9611	  delta = build_ptrmemfunc_access_expr (pfn, delta_identifier);
9612	}
9613
9614      /* Just adjust the DELTA field.  */
9615      gcc_assert  (same_type_ignoring_top_level_qualifiers_p
9616		   (TREE_TYPE (delta), ptrdiff_type_node));
9617      if (!integer_zerop (n))
9618	{
9619	  if (TARGET_PTRMEMFUNC_VBIT_LOCATION == ptrmemfunc_vbit_in_delta)
9620	    n = cp_build_binary_op (input_location,
9621				    LSHIFT_EXPR, n, integer_one_node,
9622				    complain);
9623	  delta = cp_build_binary_op (input_location,
9624				      PLUS_EXPR, delta, n, complain);
9625	}
9626      return build_ptrmemfunc1 (to_type, delta, npfn);
9627    }
9628
9629  /* Handle null pointer to member function conversions.  */
9630  if (null_ptr_cst_p (pfn))
9631    {
9632      pfn = cp_build_c_cast (input_location,
9633			     TYPE_PTRMEMFUNC_FN_TYPE_RAW (to_type),
9634			     pfn, complain);
9635      return build_ptrmemfunc1 (to_type,
9636				integer_zero_node,
9637				pfn);
9638    }
9639
9640  if (type_unknown_p (pfn))
9641    return instantiate_type (type, pfn, complain);
9642
9643  fn = TREE_OPERAND (pfn, 0);
9644  gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
9645	      /* In a template, we will have preserved the
9646		 OFFSET_REF.  */
9647	      || (processing_template_decl && TREE_CODE (fn) == OFFSET_REF));
9648  return make_ptrmem_cst (to_type, fn);
9649}
9650
9651/* Return the DELTA, IDX, PFN, and DELTA2 values for the PTRMEM_CST
9652   given by CST.
9653
9654   ??? There is no consistency as to the types returned for the above
9655   values.  Some code acts as if it were a sizetype and some as if it were
9656   integer_type_node.  */
9657
9658void
9659expand_ptrmemfunc_cst (tree cst, tree *delta, tree *pfn)
9660{
9661  tree type = TREE_TYPE (cst);
9662  tree fn = PTRMEM_CST_MEMBER (cst);
9663  tree ptr_class, fn_class;
9664
9665  gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
9666
9667  /* The class that the function belongs to.  */
9668  fn_class = DECL_CONTEXT (fn);
9669
9670  /* The class that we're creating a pointer to member of.  */
9671  ptr_class = TYPE_PTRMEMFUNC_OBJECT_TYPE (type);
9672
9673  /* First, calculate the adjustment to the function's class.  */
9674  *delta = get_delta_difference (fn_class, ptr_class, /*force=*/0,
9675				 /*c_cast_p=*/0, tf_warning_or_error);
9676
9677  if (!DECL_VIRTUAL_P (fn))
9678    {
9679      tree t = build_addr_func (fn, tf_warning_or_error);
9680      if (TREE_CODE (t) == ADDR_EXPR)
9681	SET_EXPR_LOCATION (t, PTRMEM_CST_LOCATION (cst));
9682      *pfn = convert (TYPE_PTRMEMFUNC_FN_TYPE (type), t);
9683    }
9684  else
9685    {
9686      /* If we're dealing with a virtual function, we have to adjust 'this'
9687	 again, to point to the base which provides the vtable entry for
9688	 fn; the call will do the opposite adjustment.  */
9689      tree orig_class = DECL_CONTEXT (fn);
9690      tree binfo = binfo_or_else (orig_class, fn_class);
9691      *delta = fold_build2 (PLUS_EXPR, TREE_TYPE (*delta),
9692			    *delta, BINFO_OFFSET (binfo));
9693
9694      /* We set PFN to the vtable offset at which the function can be
9695	 found, plus one (unless ptrmemfunc_vbit_in_delta, in which
9696	 case delta is shifted left, and then incremented).  */
9697      *pfn = DECL_VINDEX (fn);
9698      *pfn = fold_build2 (MULT_EXPR, integer_type_node, *pfn,
9699			  TYPE_SIZE_UNIT (vtable_entry_type));
9700
9701      switch (TARGET_PTRMEMFUNC_VBIT_LOCATION)
9702	{
9703	case ptrmemfunc_vbit_in_pfn:
9704	  *pfn = fold_build2 (PLUS_EXPR, integer_type_node, *pfn,
9705			      integer_one_node);
9706	  break;
9707
9708	case ptrmemfunc_vbit_in_delta:
9709	  *delta = fold_build2 (LSHIFT_EXPR, TREE_TYPE (*delta),
9710				*delta, integer_one_node);
9711	  *delta = fold_build2 (PLUS_EXPR, TREE_TYPE (*delta),
9712				*delta, integer_one_node);
9713	  break;
9714
9715	default:
9716	  gcc_unreachable ();
9717	}
9718
9719      *pfn = fold_convert (TYPE_PTRMEMFUNC_FN_TYPE (type), *pfn);
9720    }
9721}
9722
9723/* Return an expression for PFN from the pointer-to-member function
9724   given by T.  */
9725
9726static tree
9727pfn_from_ptrmemfunc (tree t)
9728{
9729  if (TREE_CODE (t) == PTRMEM_CST)
9730    {
9731      tree delta;
9732      tree pfn;
9733
9734      expand_ptrmemfunc_cst (t, &delta, &pfn);
9735      if (pfn)
9736	return pfn;
9737    }
9738
9739  return build_ptrmemfunc_access_expr (t, pfn_identifier);
9740}
9741
9742/* Return an expression for DELTA from the pointer-to-member function
9743   given by T.  */
9744
9745static tree
9746delta_from_ptrmemfunc (tree t)
9747{
9748  if (TREE_CODE (t) == PTRMEM_CST)
9749    {
9750      tree delta;
9751      tree pfn;
9752
9753      expand_ptrmemfunc_cst (t, &delta, &pfn);
9754      if (delta)
9755	return delta;
9756    }
9757
9758  return build_ptrmemfunc_access_expr (t, delta_identifier);
9759}
9760
9761/* Convert value RHS to type TYPE as preparation for an assignment to
9762   an lvalue of type TYPE.  ERRTYPE indicates what kind of error the
9763   implicit conversion is.  If FNDECL is non-NULL, we are doing the
9764   conversion in order to pass the PARMNUMth argument of FNDECL.
9765   If FNDECL is NULL, we are doing the conversion in function pointer
9766   argument passing, conversion in initialization, etc. */
9767
9768static tree
9769convert_for_assignment (tree type, tree rhs,
9770			impl_conv_rhs errtype, tree fndecl, int parmnum,
9771			tsubst_flags_t complain, int flags)
9772{
9773  tree rhstype;
9774  enum tree_code coder;
9775
9776  location_t rhs_loc = cp_expr_loc_or_input_loc (rhs);
9777  bool has_loc = EXPR_LOCATION (rhs) != UNKNOWN_LOCATION;
9778  /* Strip NON_LVALUE_EXPRs since we aren't using as an lvalue,
9779     but preserve location wrappers.  */
9780  if (TREE_CODE (rhs) == NON_LVALUE_EXPR
9781      && !location_wrapper_p (rhs))
9782    rhs = TREE_OPERAND (rhs, 0);
9783
9784  /* Handle [dcl.init.list] direct-list-initialization from
9785     single element of enumeration with a fixed underlying type.  */
9786  if (is_direct_enum_init (type, rhs))
9787    {
9788      tree elt = CONSTRUCTOR_ELT (rhs, 0)->value;
9789      if (check_narrowing (ENUM_UNDERLYING_TYPE (type), elt, complain))
9790	{
9791	  warning_sentinel w (warn_useless_cast);
9792	  warning_sentinel w2 (warn_ignored_qualifiers);
9793	  rhs = cp_build_c_cast (rhs_loc, type, elt, complain);
9794	}
9795      else
9796	rhs = error_mark_node;
9797    }
9798
9799  rhstype = TREE_TYPE (rhs);
9800  coder = TREE_CODE (rhstype);
9801
9802  if (VECTOR_TYPE_P (type) && coder == VECTOR_TYPE
9803      && vector_types_convertible_p (type, rhstype, true))
9804    {
9805      rhs = mark_rvalue_use (rhs);
9806      return convert (type, rhs);
9807    }
9808
9809  if (rhs == error_mark_node || rhstype == error_mark_node)
9810    return error_mark_node;
9811  if (TREE_CODE (rhs) == TREE_LIST && TREE_VALUE (rhs) == error_mark_node)
9812    return error_mark_node;
9813
9814  /* The RHS of an assignment cannot have void type.  */
9815  if (coder == VOID_TYPE)
9816    {
9817      if (complain & tf_error)
9818	error_at (rhs_loc, "void value not ignored as it ought to be");
9819      return error_mark_node;
9820    }
9821
9822  if (c_dialect_objc ())
9823    {
9824      int parmno;
9825      tree selector;
9826      tree rname = fndecl;
9827
9828      switch (errtype)
9829        {
9830	  case ICR_ASSIGN:
9831	    parmno = -1;
9832	    break;
9833	  case ICR_INIT:
9834	    parmno = -2;
9835	    break;
9836	  default:
9837	    selector = objc_message_selector ();
9838	    parmno = parmnum;
9839	    if (selector && parmno > 1)
9840	      {
9841		rname = selector;
9842		parmno -= 1;
9843	      }
9844	}
9845
9846      if (objc_compare_types (type, rhstype, parmno, rname))
9847	{
9848	  rhs = mark_rvalue_use (rhs);
9849	  return convert (type, rhs);
9850	}
9851    }
9852
9853  /* [expr.ass]
9854
9855     The expression is implicitly converted (clause _conv_) to the
9856     cv-unqualified type of the left operand.
9857
9858     We allow bad conversions here because by the time we get to this point
9859     we are committed to doing the conversion.  If we end up doing a bad
9860     conversion, convert_like will complain.  */
9861  if (!can_convert_arg_bad (type, rhstype, rhs, flags, complain))
9862    {
9863      /* When -Wno-pmf-conversions is use, we just silently allow
9864	 conversions from pointers-to-members to plain pointers.  If
9865	 the conversion doesn't work, cp_convert will complain.  */
9866      if (!warn_pmf2ptr
9867	  && TYPE_PTR_P (type)
9868	  && TYPE_PTRMEMFUNC_P (rhstype))
9869	rhs = cp_convert (strip_top_quals (type), rhs, complain);
9870      else
9871	{
9872	  if (complain & tf_error)
9873	    {
9874	      /* If the right-hand side has unknown type, then it is an
9875		 overloaded function.  Call instantiate_type to get error
9876		 messages.  */
9877	      if (rhstype == unknown_type_node)
9878		{
9879		  tree r = instantiate_type (type, rhs, tf_warning_or_error);
9880		  /* -fpermissive might allow this; recurse.  */
9881		  if (!seen_error ())
9882		    return convert_for_assignment (type, r, errtype, fndecl,
9883						   parmnum, complain, flags);
9884		}
9885	      else if (fndecl)
9886		complain_about_bad_argument (rhs_loc,
9887					     rhstype, type,
9888					     fndecl, parmnum);
9889	      else
9890		{
9891		  range_label_for_type_mismatch label (rhstype, type);
9892		  gcc_rich_location richloc (rhs_loc, has_loc ? &label : NULL);
9893		  switch (errtype)
9894		    {
9895		    case ICR_DEFAULT_ARGUMENT:
9896		      error_at (&richloc,
9897				"cannot convert %qH to %qI in default argument",
9898				rhstype, type);
9899		      break;
9900		    case ICR_ARGPASS:
9901		      error_at (&richloc,
9902				"cannot convert %qH to %qI in argument passing",
9903				rhstype, type);
9904		      break;
9905		    case ICR_CONVERTING:
9906		      error_at (&richloc, "cannot convert %qH to %qI",
9907				rhstype, type);
9908		      break;
9909		    case ICR_INIT:
9910		      error_at (&richloc,
9911				"cannot convert %qH to %qI in initialization",
9912				rhstype, type);
9913		      break;
9914		    case ICR_RETURN:
9915		      error_at (&richloc, "cannot convert %qH to %qI in return",
9916				rhstype, type);
9917		      break;
9918		    case ICR_ASSIGN:
9919		      error_at (&richloc,
9920				"cannot convert %qH to %qI in assignment",
9921				rhstype, type);
9922		      break;
9923		    default:
9924		      gcc_unreachable();
9925		  }
9926		}
9927	      if (TYPE_PTR_P (rhstype)
9928		  && TYPE_PTR_P (type)
9929		  && CLASS_TYPE_P (TREE_TYPE (rhstype))
9930		  && CLASS_TYPE_P (TREE_TYPE (type))
9931		  && !COMPLETE_TYPE_P (TREE_TYPE (rhstype)))
9932		inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL
9933					      (TREE_TYPE (rhstype))),
9934			"class type %qT is incomplete", TREE_TYPE (rhstype));
9935	    }
9936	  return error_mark_node;
9937	}
9938    }
9939  if (warn_suggest_attribute_format)
9940    {
9941      const enum tree_code codel = TREE_CODE (type);
9942      if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
9943	  && coder == codel
9944	  && check_missing_format_attribute (type, rhstype)
9945	  && (complain & tf_warning))
9946	switch (errtype)
9947	  {
9948	    case ICR_ARGPASS:
9949	    case ICR_DEFAULT_ARGUMENT:
9950	      if (fndecl)
9951		warning (OPT_Wsuggest_attribute_format,
9952			 "parameter %qP of %qD might be a candidate "
9953			 "for a format attribute", parmnum, fndecl);
9954	      else
9955		warning (OPT_Wsuggest_attribute_format,
9956			 "parameter might be a candidate "
9957			 "for a format attribute");
9958	      break;
9959	    case ICR_CONVERTING:
9960	      warning (OPT_Wsuggest_attribute_format,
9961		       "target of conversion might be a candidate "
9962		       "for a format attribute");
9963	      break;
9964	    case ICR_INIT:
9965	      warning (OPT_Wsuggest_attribute_format,
9966		       "target of initialization might be a candidate "
9967		       "for a format attribute");
9968	      break;
9969	    case ICR_RETURN:
9970	      warning (OPT_Wsuggest_attribute_format,
9971		       "return type might be a candidate "
9972		       "for a format attribute");
9973	      break;
9974	    case ICR_ASSIGN:
9975	      warning (OPT_Wsuggest_attribute_format,
9976		       "left-hand side of assignment might be a candidate "
9977		       "for a format attribute");
9978	      break;
9979	    default:
9980	      gcc_unreachable();
9981	  }
9982    }
9983
9984  /* If -Wparentheses, warn about a = b = c when a has type bool and b
9985     does not.  */
9986  if (warn_parentheses
9987      && TREE_CODE (type) == BOOLEAN_TYPE
9988      && TREE_CODE (rhs) == MODIFY_EXPR
9989      && !warning_suppressed_p (rhs, OPT_Wparentheses)
9990      && TREE_CODE (TREE_TYPE (rhs)) != BOOLEAN_TYPE
9991      && (complain & tf_warning)
9992      && warning_at (rhs_loc, OPT_Wparentheses,
9993		     "suggest parentheses around assignment used as "
9994		     "truth value"))
9995    suppress_warning (rhs, OPT_Wparentheses);
9996
9997  if (complain & tf_warning)
9998    warn_for_address_or_pointer_of_packed_member (type, rhs);
9999
10000  return perform_implicit_conversion_flags (strip_top_quals (type), rhs,
10001					    complain, flags);
10002}
10003
10004/* Convert RHS to be of type TYPE.
10005   If EXP is nonzero, it is the target of the initialization.
10006   ERRTYPE indicates what kind of error the implicit conversion is.
10007
10008   Two major differences between the behavior of
10009   `convert_for_assignment' and `convert_for_initialization'
10010   are that references are bashed in the former, while
10011   copied in the latter, and aggregates are assigned in
10012   the former (operator=) while initialized in the
10013   latter (X(X&)).
10014
10015   If using constructor make sure no conversion operator exists, if one does
10016   exist, an ambiguity exists.  */
10017
10018tree
10019convert_for_initialization (tree exp, tree type, tree rhs, int flags,
10020			    impl_conv_rhs errtype, tree fndecl, int parmnum,
10021                            tsubst_flags_t complain)
10022{
10023  enum tree_code codel = TREE_CODE (type);
10024  tree rhstype;
10025  enum tree_code coder;
10026
10027  /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
10028     Strip such NOP_EXPRs, since RHS is used in non-lvalue context.  */
10029  if (TREE_CODE (rhs) == NOP_EXPR
10030      && TREE_TYPE (rhs) == TREE_TYPE (TREE_OPERAND (rhs, 0))
10031      && codel != REFERENCE_TYPE)
10032    rhs = TREE_OPERAND (rhs, 0);
10033
10034  if (type == error_mark_node
10035      || rhs == error_mark_node
10036      || (TREE_CODE (rhs) == TREE_LIST && TREE_VALUE (rhs) == error_mark_node))
10037    return error_mark_node;
10038
10039  if (MAYBE_CLASS_TYPE_P (non_reference (type)))
10040    ;
10041  else if ((TREE_CODE (TREE_TYPE (rhs)) == ARRAY_TYPE
10042	    && TREE_CODE (type) != ARRAY_TYPE
10043	    && (!TYPE_REF_P (type)
10044		|| TREE_CODE (TREE_TYPE (type)) != ARRAY_TYPE))
10045	   || (TREE_CODE (TREE_TYPE (rhs)) == FUNCTION_TYPE
10046	       && !TYPE_REFFN_P (type))
10047	   || TREE_CODE (TREE_TYPE (rhs)) == METHOD_TYPE)
10048    rhs = decay_conversion (rhs, complain);
10049
10050  rhstype = TREE_TYPE (rhs);
10051  coder = TREE_CODE (rhstype);
10052
10053  if (coder == ERROR_MARK)
10054    return error_mark_node;
10055
10056  /* We accept references to incomplete types, so we can
10057     return here before checking if RHS is of complete type.  */
10058
10059  if (codel == REFERENCE_TYPE)
10060    {
10061      auto_diagnostic_group d;
10062      /* This should eventually happen in convert_arguments.  */
10063      int savew = 0, savee = 0;
10064
10065      if (fndecl)
10066	savew = warningcount + werrorcount, savee = errorcount;
10067      rhs = initialize_reference (type, rhs, flags, complain);
10068
10069      if (fndecl
10070	  && (warningcount + werrorcount > savew || errorcount > savee))
10071	inform (get_fndecl_argument_location (fndecl, parmnum),
10072		"in passing argument %P of %qD", parmnum, fndecl);
10073      return rhs;
10074    }
10075
10076  if (exp != 0)
10077    exp = require_complete_type_sfinae (exp, complain);
10078  if (exp == error_mark_node)
10079    return error_mark_node;
10080
10081  type = complete_type (type);
10082
10083  if (DIRECT_INIT_EXPR_P (type, rhs))
10084    /* Don't try to do copy-initialization if we already have
10085       direct-initialization.  */
10086    return rhs;
10087
10088  if (MAYBE_CLASS_TYPE_P (type))
10089    return perform_implicit_conversion_flags (type, rhs, complain, flags);
10090
10091  return convert_for_assignment (type, rhs, errtype, fndecl, parmnum,
10092				 complain, flags);
10093}
10094
10095/* If RETVAL is the address of, or a reference to, a local variable or
10096   temporary give an appropriate warning and return true.  */
10097
10098static bool
10099maybe_warn_about_returning_address_of_local (tree retval, location_t loc)
10100{
10101  tree valtype = TREE_TYPE (DECL_RESULT (current_function_decl));
10102  tree whats_returned = fold_for_warn (retval);
10103  if (!loc)
10104    loc = cp_expr_loc_or_input_loc (retval);
10105
10106  for (;;)
10107    {
10108      if (TREE_CODE (whats_returned) == COMPOUND_EXPR)
10109	whats_returned = TREE_OPERAND (whats_returned, 1);
10110      else if (CONVERT_EXPR_P (whats_returned)
10111	       || TREE_CODE (whats_returned) == NON_LVALUE_EXPR)
10112	whats_returned = TREE_OPERAND (whats_returned, 0);
10113      else
10114	break;
10115    }
10116
10117  if (TREE_CODE (whats_returned) == TARGET_EXPR
10118      && is_std_init_list (TREE_TYPE (whats_returned)))
10119    {
10120      tree init = TARGET_EXPR_INITIAL (whats_returned);
10121      if (TREE_CODE (init) == CONSTRUCTOR)
10122	/* Pull out the array address.  */
10123	whats_returned = CONSTRUCTOR_ELT (init, 0)->value;
10124      else if (TREE_CODE (init) == INDIRECT_REF)
10125	/* The source of a trivial copy looks like *(T*)&var.  */
10126	whats_returned = TREE_OPERAND (init, 0);
10127      else
10128	return false;
10129      STRIP_NOPS (whats_returned);
10130    }
10131
10132  /* As a special case, we handle a call to std::move or std::forward.  */
10133  if (TREE_CODE (whats_returned) == CALL_EXPR
10134      && (is_std_move_p (whats_returned)
10135	  || is_std_forward_p (whats_returned)))
10136    {
10137      tree arg = CALL_EXPR_ARG (whats_returned, 0);
10138      return maybe_warn_about_returning_address_of_local (arg, loc);
10139    }
10140
10141  if (TREE_CODE (whats_returned) != ADDR_EXPR)
10142    return false;
10143  whats_returned = TREE_OPERAND (whats_returned, 0);
10144
10145  while (TREE_CODE (whats_returned) == COMPONENT_REF
10146	 || TREE_CODE (whats_returned) == ARRAY_REF)
10147    whats_returned = TREE_OPERAND (whats_returned, 0);
10148
10149  if (TREE_CODE (whats_returned) == AGGR_INIT_EXPR
10150      || TREE_CODE (whats_returned) == TARGET_EXPR)
10151    {
10152      if (TYPE_REF_P (valtype))
10153	warning_at (loc, OPT_Wreturn_local_addr,
10154		    "returning reference to temporary");
10155      else if (is_std_init_list (valtype))
10156	warning_at (loc, OPT_Winit_list_lifetime,
10157		    "returning temporary %<initializer_list%> does not extend "
10158		    "the lifetime of the underlying array");
10159      return true;
10160    }
10161
10162  STRIP_ANY_LOCATION_WRAPPER (whats_returned);
10163
10164  if (DECL_P (whats_returned)
10165      && DECL_NAME (whats_returned)
10166      && DECL_FUNCTION_SCOPE_P (whats_returned)
10167      && !is_capture_proxy (whats_returned)
10168      && !(TREE_STATIC (whats_returned)
10169	   || TREE_PUBLIC (whats_returned)))
10170    {
10171      if (VAR_P (whats_returned)
10172	  && DECL_DECOMPOSITION_P (whats_returned)
10173	  && DECL_DECOMP_BASE (whats_returned)
10174	  && DECL_HAS_VALUE_EXPR_P (whats_returned))
10175	{
10176	  /* When returning address of a structured binding, if the structured
10177	     binding is not a reference, continue normally, if it is a
10178	     reference, recurse on the initializer of the structured
10179	     binding.  */
10180	  tree base = DECL_DECOMP_BASE (whats_returned);
10181	  if (TYPE_REF_P (TREE_TYPE (base)))
10182	    {
10183	      if (tree init = DECL_INITIAL (base))
10184		return maybe_warn_about_returning_address_of_local (init, loc);
10185	      else
10186		return false;
10187	    }
10188	}
10189      bool w = false;
10190      auto_diagnostic_group d;
10191      if (TYPE_REF_P (valtype))
10192	w = warning_at (loc, OPT_Wreturn_local_addr,
10193			"reference to local variable %qD returned",
10194			whats_returned);
10195      else if (is_std_init_list (valtype))
10196	w = warning_at (loc, OPT_Winit_list_lifetime,
10197			"returning local %<initializer_list%> variable %qD "
10198			"does not extend the lifetime of the underlying array",
10199			whats_returned);
10200      else if (POINTER_TYPE_P (valtype)
10201	       && TREE_CODE (whats_returned) == LABEL_DECL)
10202	w = warning_at (loc, OPT_Wreturn_local_addr,
10203			"address of label %qD returned",
10204			whats_returned);
10205      else if (POINTER_TYPE_P (valtype))
10206	w = warning_at (loc, OPT_Wreturn_local_addr,
10207			"address of local variable %qD returned",
10208			whats_returned);
10209      if (w)
10210	inform (DECL_SOURCE_LOCATION (whats_returned),
10211		"declared here");
10212      return true;
10213    }
10214
10215  return false;
10216}
10217
10218/* Returns true if DECL is in the std namespace.  */
10219
10220bool
10221decl_in_std_namespace_p (tree decl)
10222{
10223  while (decl)
10224    {
10225      decl = decl_namespace_context (decl);
10226      if (DECL_NAMESPACE_STD_P (decl))
10227	return true;
10228      /* Allow inline namespaces inside of std namespace, e.g. with
10229	 --enable-symvers=gnu-versioned-namespace std::forward would be
10230	 actually std::_8::forward.  */
10231      if (!DECL_NAMESPACE_INLINE_P (decl))
10232	return false;
10233      decl = CP_DECL_CONTEXT (decl);
10234    }
10235  return false;
10236}
10237
10238/* Returns true if FN, a CALL_EXPR, is a call to std::forward.  */
10239
10240static bool
10241is_std_forward_p (tree fn)
10242{
10243  /* std::forward only takes one argument.  */
10244  if (call_expr_nargs (fn) != 1)
10245    return false;
10246
10247  tree fndecl = cp_get_callee_fndecl_nofold (fn);
10248  if (!decl_in_std_namespace_p (fndecl))
10249    return false;
10250
10251  tree name = DECL_NAME (fndecl);
10252  return name && id_equal (name, "forward");
10253}
10254
10255/* Returns true if FN, a CALL_EXPR, is a call to std::move.  */
10256
10257static bool
10258is_std_move_p (tree fn)
10259{
10260  /* std::move only takes one argument.  */
10261  if (call_expr_nargs (fn) != 1)
10262    return false;
10263
10264  tree fndecl = cp_get_callee_fndecl_nofold (fn);
10265  if (!decl_in_std_namespace_p (fndecl))
10266    return false;
10267
10268  tree name = DECL_NAME (fndecl);
10269  return name && id_equal (name, "move");
10270}
10271
10272/* Returns true if RETVAL is a good candidate for the NRVO as per
10273   [class.copy.elision].  FUNCTYPE is the type the function is declared
10274   to return.  */
10275
10276static bool
10277can_do_nrvo_p (tree retval, tree functype)
10278{
10279  if (functype == error_mark_node)
10280    return false;
10281  if (retval)
10282    STRIP_ANY_LOCATION_WRAPPER (retval);
10283  tree result = DECL_RESULT (current_function_decl);
10284  return (retval != NULL_TREE
10285	  && !processing_template_decl
10286	  /* Must be a local, automatic variable.  */
10287	  && VAR_P (retval)
10288	  && DECL_CONTEXT (retval) == current_function_decl
10289	  && !TREE_STATIC (retval)
10290	  /* And not a lambda or anonymous union proxy.  */
10291	  && !DECL_HAS_VALUE_EXPR_P (retval)
10292	  && (DECL_ALIGN (retval) <= DECL_ALIGN (result))
10293	  /* The cv-unqualified type of the returned value must be the
10294	     same as the cv-unqualified return type of the
10295	     function.  */
10296	  && same_type_p ((TYPE_MAIN_VARIANT (TREE_TYPE (retval))),
10297			  (TYPE_MAIN_VARIANT (functype)))
10298	  /* And the returned value must be non-volatile.  */
10299	  && !TYPE_VOLATILE (TREE_TYPE (retval)));
10300}
10301
10302/* If we should treat RETVAL, an expression being returned, as if it were
10303   designated by an rvalue, returns it adjusted accordingly; otherwise, returns
10304   NULL_TREE.  See [class.copy.elision].  RETURN_P is true if this is a return
10305   context (rather than throw).  */
10306
10307tree
10308treat_lvalue_as_rvalue_p (tree expr, bool return_p)
10309{
10310  if (cxx_dialect == cxx98)
10311    return NULL_TREE;
10312
10313  tree retval = expr;
10314  STRIP_ANY_LOCATION_WRAPPER (retval);
10315  if (REFERENCE_REF_P (retval))
10316    retval = TREE_OPERAND (retval, 0);
10317
10318  /* An implicitly movable entity is a variable of automatic storage duration
10319     that is either a non-volatile object or (C++20) an rvalue reference to a
10320     non-volatile object type.  */
10321  if (!(((VAR_P (retval) && !DECL_HAS_VALUE_EXPR_P (retval))
10322	 || TREE_CODE (retval) == PARM_DECL)
10323	&& !TREE_STATIC (retval)
10324	&& !CP_TYPE_VOLATILE_P (non_reference (TREE_TYPE (retval)))
10325	&& (TREE_CODE (TREE_TYPE (retval)) != REFERENCE_TYPE
10326	    || (cxx_dialect >= cxx20
10327		&& TYPE_REF_IS_RVALUE (TREE_TYPE (retval))))))
10328    return NULL_TREE;
10329
10330  /* If the expression in a return or co_return statement is a (possibly
10331     parenthesized) id-expression that names an implicitly movable entity
10332     declared in the body or parameter-declaration-clause of the innermost
10333     enclosing function or lambda-expression, */
10334  if (DECL_CONTEXT (retval) != current_function_decl)
10335    return NULL_TREE;
10336  if (return_p)
10337    return set_implicit_rvalue_p (move (expr));
10338
10339  /* if the operand of a throw-expression is a (possibly parenthesized)
10340     id-expression that names an implicitly movable entity whose scope does not
10341     extend beyond the compound-statement of the innermost try-block or
10342     function-try-block (if any) whose compound-statement or ctor-initializer
10343     encloses the throw-expression, */
10344
10345  /* C++20 added move on throw of parms.  */
10346  if (TREE_CODE (retval) == PARM_DECL && cxx_dialect < cxx20)
10347    return NULL_TREE;
10348
10349  for (cp_binding_level *b = current_binding_level;
10350       ; b = b->level_chain)
10351    {
10352      for (tree decl = b->names; decl; decl = TREE_CHAIN (decl))
10353	if (decl == retval)
10354	  return set_implicit_rvalue_p (move (expr));
10355      if (b->kind == sk_function_parms || b->kind == sk_try)
10356	return NULL_TREE;
10357    }
10358}
10359
10360/* Warn about wrong usage of std::move in a return statement.  RETVAL
10361   is the expression we are returning; FUNCTYPE is the type the function
10362   is declared to return.  */
10363
10364static void
10365maybe_warn_pessimizing_move (tree retval, tree functype)
10366{
10367  if (!(warn_pessimizing_move || warn_redundant_move))
10368    return;
10369
10370  location_t loc = cp_expr_loc_or_input_loc (retval);
10371
10372  /* C++98 doesn't know move.  */
10373  if (cxx_dialect < cxx11)
10374    return;
10375
10376  /* Wait until instantiation time, since we can't gauge if we should do
10377     the NRVO until then.  */
10378  if (processing_template_decl)
10379    return;
10380
10381  /* This is only interesting for class types.  */
10382  if (!CLASS_TYPE_P (functype))
10383    return;
10384
10385  /* We're looking for *std::move<T&> ((T &) &arg).  */
10386  if (REFERENCE_REF_P (retval)
10387      && TREE_CODE (TREE_OPERAND (retval, 0)) == CALL_EXPR)
10388    {
10389      tree fn = TREE_OPERAND (retval, 0);
10390      if (is_std_move_p (fn))
10391	{
10392	  tree arg = CALL_EXPR_ARG (fn, 0);
10393	  tree moved;
10394	  if (TREE_CODE (arg) != NOP_EXPR)
10395	    return;
10396	  arg = TREE_OPERAND (arg, 0);
10397	  if (TREE_CODE (arg) != ADDR_EXPR)
10398	    return;
10399	  arg = TREE_OPERAND (arg, 0);
10400	  arg = convert_from_reference (arg);
10401	  /* Warn if we could do copy elision were it not for the move.  */
10402	  if (can_do_nrvo_p (arg, functype))
10403	    {
10404	      auto_diagnostic_group d;
10405	      if (warning_at (loc, OPT_Wpessimizing_move,
10406			      "moving a local object in a return statement "
10407			      "prevents copy elision"))
10408		inform (loc, "remove %<std::move%> call");
10409	    }
10410	  /* Warn if the move is redundant.  It is redundant when we would
10411	     do maybe-rvalue overload resolution even without std::move.  */
10412	  else if (warn_redundant_move
10413		   && (moved = treat_lvalue_as_rvalue_p (arg, /*return*/true)))
10414	    {
10415	      /* Make sure that the overload resolution would actually succeed
10416		 if we removed the std::move call.  */
10417	      tree t = convert_for_initialization (NULL_TREE, functype,
10418						   moved,
10419						   (LOOKUP_NORMAL
10420						    | LOOKUP_ONLYCONVERTING
10421						    | LOOKUP_PREFER_RVALUE),
10422						   ICR_RETURN, NULL_TREE, 0,
10423						   tf_none);
10424	      /* If this worked, implicit rvalue would work, so the call to
10425		 std::move is redundant.  */
10426	      if (t != error_mark_node)
10427		{
10428		  auto_diagnostic_group d;
10429		  if (warning_at (loc, OPT_Wredundant_move,
10430				  "redundant move in return statement"))
10431		    inform (loc, "remove %<std::move%> call");
10432		}
10433	    }
10434	}
10435    }
10436}
10437
10438/* Check that returning RETVAL from the current function is valid.
10439   Return an expression explicitly showing all conversions required to
10440   change RETVAL into the function return type, and to assign it to
10441   the DECL_RESULT for the function.  Set *NO_WARNING to true if
10442   code reaches end of non-void function warning shouldn't be issued
10443   on this RETURN_EXPR.  */
10444
10445tree
10446check_return_expr (tree retval, bool *no_warning)
10447{
10448  tree result;
10449  /* The type actually returned by the function.  */
10450  tree valtype;
10451  /* The type the function is declared to return, or void if
10452     the declared type is incomplete.  */
10453  tree functype;
10454  int fn_returns_value_p;
10455  location_t loc = cp_expr_loc_or_input_loc (retval);
10456
10457  *no_warning = false;
10458
10459  /* A `volatile' function is one that isn't supposed to return, ever.
10460     (This is a G++ extension, used to get better code for functions
10461     that call the `volatile' function.)  */
10462  if (TREE_THIS_VOLATILE (current_function_decl))
10463    warning (0, "function declared %<noreturn%> has a %<return%> statement");
10464
10465  /* Check for various simple errors.  */
10466  if (DECL_DESTRUCTOR_P (current_function_decl))
10467    {
10468      if (retval)
10469	error_at (loc, "returning a value from a destructor");
10470      return NULL_TREE;
10471    }
10472  else if (DECL_CONSTRUCTOR_P (current_function_decl))
10473    {
10474      if (in_function_try_handler)
10475	/* If a return statement appears in a handler of the
10476	   function-try-block of a constructor, the program is ill-formed.  */
10477	error ("cannot return from a handler of a function-try-block of a constructor");
10478      else if (retval)
10479	/* You can't return a value from a constructor.  */
10480	error_at (loc, "returning a value from a constructor");
10481      return NULL_TREE;
10482    }
10483
10484  const tree saved_retval = retval;
10485
10486  if (processing_template_decl)
10487    {
10488      current_function_returns_value = 1;
10489
10490      if (check_for_bare_parameter_packs (retval))
10491	return error_mark_node;
10492
10493      /* If one of the types might be void, we can't tell whether we're
10494	 returning a value.  */
10495      if ((WILDCARD_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl)))
10496	   && !FNDECL_USED_AUTO (current_function_decl))
10497	  || (retval != NULL_TREE
10498	      && (TREE_TYPE (retval) == NULL_TREE
10499		  || WILDCARD_TYPE_P (TREE_TYPE (retval)))))
10500	goto dependent;
10501    }
10502
10503  functype = TREE_TYPE (TREE_TYPE (current_function_decl));
10504
10505  /* Deduce auto return type from a return statement.  */
10506  if (FNDECL_USED_AUTO (current_function_decl))
10507    {
10508      tree pattern = DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl);
10509      tree auto_node;
10510      tree type;
10511
10512      if (!retval && !is_auto (pattern))
10513	{
10514	  /* Give a helpful error message.  */
10515	  error ("return-statement with no value, in function returning %qT",
10516		 pattern);
10517	  inform (input_location, "only plain %<auto%> return type can be "
10518		  "deduced to %<void%>");
10519	  type = error_mark_node;
10520	}
10521      else if (retval && BRACE_ENCLOSED_INITIALIZER_P (retval))
10522	{
10523	  error ("returning initializer list");
10524	  type = error_mark_node;
10525	}
10526      else
10527	{
10528	  if (!retval)
10529	    retval = void_node;
10530	  auto_node = type_uses_auto (pattern);
10531	  type = do_auto_deduction (pattern, retval, auto_node,
10532				    tf_warning_or_error, adc_return_type);
10533	}
10534
10535      if (type == error_mark_node)
10536	/* Leave it.  */;
10537      else if (functype == pattern)
10538	apply_deduced_return_type (current_function_decl, type);
10539      else if (!same_type_p (type, functype))
10540	{
10541	  if (LAMBDA_FUNCTION_P (current_function_decl))
10542	    error_at (loc, "inconsistent types %qT and %qT deduced for "
10543		      "lambda return type", functype, type);
10544	  else
10545	    error_at (loc, "inconsistent deduction for auto return type: "
10546		      "%qT and then %qT", functype, type);
10547	}
10548      functype = type;
10549    }
10550
10551  result = DECL_RESULT (current_function_decl);
10552  valtype = TREE_TYPE (result);
10553  gcc_assert (valtype != NULL_TREE);
10554  fn_returns_value_p = !VOID_TYPE_P (valtype);
10555
10556  /* Check for a return statement with no return value in a function
10557     that's supposed to return a value.  */
10558  if (!retval && fn_returns_value_p)
10559    {
10560      if (functype != error_mark_node)
10561	permerror (input_location, "return-statement with no value, in "
10562		   "function returning %qT", valtype);
10563      /* Remember that this function did return.  */
10564      current_function_returns_value = 1;
10565      /* And signal caller that TREE_NO_WARNING should be set on the
10566	 RETURN_EXPR to avoid control reaches end of non-void function
10567	 warnings in tree-cfg.cc.  */
10568      *no_warning = true;
10569    }
10570  /* Check for a return statement with a value in a function that
10571     isn't supposed to return a value.  */
10572  else if (retval && !fn_returns_value_p)
10573    {
10574      if (VOID_TYPE_P (TREE_TYPE (retval)))
10575	/* You can return a `void' value from a function of `void'
10576	   type.  In that case, we have to evaluate the expression for
10577	   its side-effects.  */
10578	finish_expr_stmt (retval);
10579      else if (retval != error_mark_node)
10580	permerror (loc, "return-statement with a value, in function "
10581		   "returning %qT", valtype);
10582      current_function_returns_null = 1;
10583
10584      /* There's really no value to return, after all.  */
10585      return NULL_TREE;
10586    }
10587  else if (!retval)
10588    /* Remember that this function can sometimes return without a
10589       value.  */
10590    current_function_returns_null = 1;
10591  else
10592    /* Remember that this function did return a value.  */
10593    current_function_returns_value = 1;
10594
10595  /* Check for erroneous operands -- but after giving ourselves a
10596     chance to provide an error about returning a value from a void
10597     function.  */
10598  if (error_operand_p (retval))
10599    {
10600      current_function_return_value = error_mark_node;
10601      return error_mark_node;
10602    }
10603
10604  /* Only operator new(...) throw(), can return NULL [expr.new/13].  */
10605  if (IDENTIFIER_NEW_OP_P (DECL_NAME (current_function_decl))
10606      && !TYPE_NOTHROW_P (TREE_TYPE (current_function_decl))
10607      && ! flag_check_new
10608      && retval && null_ptr_cst_p (retval))
10609    warning (0, "%<operator new%> must not return NULL unless it is "
10610	     "declared %<throw()%> (or %<-fcheck-new%> is in effect)");
10611
10612  /* Effective C++ rule 15.  See also start_function.  */
10613  if (warn_ecpp
10614      && DECL_NAME (current_function_decl) == assign_op_identifier
10615      && !type_dependent_expression_p (retval))
10616    {
10617      bool warn = true;
10618
10619      /* The function return type must be a reference to the current
10620	class.  */
10621      if (TYPE_REF_P (valtype)
10622	  && same_type_ignoring_top_level_qualifiers_p
10623	      (TREE_TYPE (valtype), TREE_TYPE (current_class_ref)))
10624	{
10625	  /* Returning '*this' is obviously OK.  */
10626	  if (retval == current_class_ref)
10627	    warn = false;
10628	  /* If we are calling a function whose return type is the same of
10629	     the current class reference, it is ok.  */
10630	  else if (INDIRECT_REF_P (retval)
10631		   && TREE_CODE (TREE_OPERAND (retval, 0)) == CALL_EXPR)
10632	    warn = false;
10633	}
10634
10635      if (warn)
10636	warning_at (loc, OPT_Weffc__,
10637		    "%<operator=%> should return a reference to %<*this%>");
10638    }
10639
10640  if (dependent_type_p (functype)
10641      || type_dependent_expression_p (retval))
10642    {
10643    dependent:
10644      /* We should not have changed the return value.  */
10645      gcc_assert (retval == saved_retval);
10646      /* We don't know if this is an lvalue or rvalue use, but
10647	 either way we can mark it as read.  */
10648      mark_exp_read (retval);
10649      return retval;
10650    }
10651
10652  /* The fabled Named Return Value optimization, as per [class.copy]/15:
10653
10654     [...]      For  a function with a class return type, if the expression
10655     in the return statement is the name of a local  object,  and  the  cv-
10656     unqualified  type  of  the  local  object  is the same as the function
10657     return type, an implementation is permitted to omit creating the  tem-
10658     porary  object  to  hold  the function return value [...]
10659
10660     So, if this is a value-returning function that always returns the same
10661     local variable, remember it.
10662
10663     It might be nice to be more flexible, and choose the first suitable
10664     variable even if the function sometimes returns something else, but
10665     then we run the risk of clobbering the variable we chose if the other
10666     returned expression uses the chosen variable somehow.  And people expect
10667     this restriction, anyway.  (jason 2000-11-19)
10668
10669     See finish_function and finalize_nrv for the rest of this optimization.  */
10670  tree bare_retval = NULL_TREE;
10671  if (retval)
10672    {
10673      retval = maybe_undo_parenthesized_ref (retval);
10674      bare_retval = tree_strip_any_location_wrapper (retval);
10675    }
10676
10677  bool named_return_value_okay_p = can_do_nrvo_p (bare_retval, functype);
10678  if (fn_returns_value_p && flag_elide_constructors)
10679    {
10680      if (named_return_value_okay_p
10681          && (current_function_return_value == NULL_TREE
10682	      || current_function_return_value == bare_retval))
10683	current_function_return_value = bare_retval;
10684      else
10685	current_function_return_value = error_mark_node;
10686    }
10687
10688  /* We don't need to do any conversions when there's nothing being
10689     returned.  */
10690  if (!retval)
10691    return NULL_TREE;
10692
10693  if (!named_return_value_okay_p)
10694    maybe_warn_pessimizing_move (retval, functype);
10695
10696  /* Do any required conversions.  */
10697  if (bare_retval == result || DECL_CONSTRUCTOR_P (current_function_decl))
10698    /* No conversions are required.  */
10699    ;
10700  else
10701    {
10702      int flags = LOOKUP_NORMAL | LOOKUP_ONLYCONVERTING;
10703
10704      /* The functype's return type will have been set to void, if it
10705	 was an incomplete type.  Just treat this as 'return;' */
10706      if (VOID_TYPE_P (functype))
10707	return error_mark_node;
10708
10709      if (processing_template_decl)
10710	retval = build_non_dependent_expr (retval);
10711
10712      /* Under C++11 [12.8/32 class.copy], a returned lvalue is sometimes
10713	 treated as an rvalue for the purposes of overload resolution to
10714	 favor move constructors over copy constructors.
10715
10716         Note that these conditions are similar to, but not as strict as,
10717	 the conditions for the named return value optimization.  */
10718      bool converted = false;
10719      tree moved;
10720      /* This is only interesting for class type.  */
10721      if (CLASS_TYPE_P (functype)
10722	  && (moved = treat_lvalue_as_rvalue_p (retval, /*return*/true)))
10723	{
10724	  if (cxx_dialect < cxx20)
10725	    {
10726	      moved = convert_for_initialization
10727		(NULL_TREE, functype, moved, flags|LOOKUP_PREFER_RVALUE,
10728		 ICR_RETURN, NULL_TREE, 0, tf_none);
10729	      if (moved != error_mark_node)
10730		{
10731		  retval = moved;
10732		  converted = true;
10733		}
10734	    }
10735	  else
10736	    /* In C++20 we just treat the return value as an rvalue that
10737	       can bind to lvalue refs.  */
10738	    retval = moved;
10739	}
10740
10741      /* The call in a (lambda) thunk needs no conversions.  */
10742      if (TREE_CODE (retval) == CALL_EXPR
10743	  && call_from_lambda_thunk_p (retval))
10744	converted = true;
10745
10746      /* First convert the value to the function's return type, then
10747	 to the type of return value's location to handle the
10748	 case that functype is smaller than the valtype.  */
10749      if (!converted)
10750	retval = convert_for_initialization
10751	  (NULL_TREE, functype, retval, flags, ICR_RETURN, NULL_TREE, 0,
10752	   tf_warning_or_error);
10753      retval = convert (valtype, retval);
10754
10755      /* If the conversion failed, treat this just like `return;'.  */
10756      if (retval == error_mark_node)
10757	return retval;
10758      /* We can't initialize a register from a AGGR_INIT_EXPR.  */
10759      else if (! cfun->returns_struct
10760	       && TREE_CODE (retval) == TARGET_EXPR
10761	       && TREE_CODE (TREE_OPERAND (retval, 1)) == AGGR_INIT_EXPR)
10762	retval = build2 (COMPOUND_EXPR, TREE_TYPE (retval), retval,
10763			 TREE_OPERAND (retval, 0));
10764      else if (!processing_template_decl
10765	       && maybe_warn_about_returning_address_of_local (retval, loc)
10766	       && INDIRECT_TYPE_P (valtype))
10767	retval = build2 (COMPOUND_EXPR, TREE_TYPE (retval), retval,
10768			 build_zero_cst (TREE_TYPE (retval)));
10769    }
10770
10771  if (processing_template_decl)
10772    return saved_retval;
10773
10774  /* Actually copy the value returned into the appropriate location.  */
10775  if (retval && retval != result)
10776    retval = build2 (INIT_EXPR, TREE_TYPE (result), result, retval);
10777
10778  if (tree set = maybe_set_retval_sentinel ())
10779    retval = build2 (COMPOUND_EXPR, void_type_node, retval, set);
10780
10781  return retval;
10782}
10783
10784
10785/* Returns nonzero if the pointer-type FROM can be converted to the
10786   pointer-type TO via a qualification conversion.  If CONSTP is -1,
10787   then we return nonzero if the pointers are similar, and the
10788   cv-qualification signature of FROM is a proper subset of that of TO.
10789
10790   If CONSTP is positive, then all outer pointers have been
10791   const-qualified.  */
10792
10793static bool
10794comp_ptr_ttypes_real (tree to, tree from, int constp)
10795{
10796  bool to_more_cv_qualified = false;
10797  bool is_opaque_pointer = false;
10798
10799  for (; ; to = TREE_TYPE (to), from = TREE_TYPE (from))
10800    {
10801      if (TREE_CODE (to) != TREE_CODE (from))
10802	return false;
10803
10804      if (TREE_CODE (from) == OFFSET_TYPE
10805	  && !same_type_p (TYPE_OFFSET_BASETYPE (from),
10806			   TYPE_OFFSET_BASETYPE (to)))
10807	return false;
10808
10809      /* Const and volatile mean something different for function and
10810	 array types, so the usual checks are not appropriate.  We'll
10811	 check the array type elements in further iterations.  */
10812      if (!FUNC_OR_METHOD_TYPE_P (to) && TREE_CODE (to) != ARRAY_TYPE)
10813	{
10814	  if (!at_least_as_qualified_p (to, from))
10815	    return false;
10816
10817	  if (!at_least_as_qualified_p (from, to))
10818	    {
10819	      if (constp == 0)
10820		return false;
10821	      to_more_cv_qualified = true;
10822	    }
10823
10824	  if (constp > 0)
10825	    constp &= TYPE_READONLY (to);
10826	}
10827
10828      if (VECTOR_TYPE_P (to))
10829	is_opaque_pointer = vector_targets_convertible_p (to, from);
10830
10831      /* P0388R4 allows a conversion from int[N] to int[] but not the
10832	 other way round.  When both arrays have bounds but they do
10833	 not match, then no conversion is possible.  */
10834      if (TREE_CODE (to) == ARRAY_TYPE
10835	  && !comp_array_types (to, from, bounds_first, /*strict=*/false))
10836	return false;
10837
10838      if (!TYPE_PTR_P (to)
10839	  && !TYPE_PTRDATAMEM_P (to)
10840	  /* CWG 330 says we need to look through arrays.  */
10841	  && TREE_CODE (to) != ARRAY_TYPE)
10842	return ((constp >= 0 || to_more_cv_qualified)
10843		&& (is_opaque_pointer
10844		    || same_type_ignoring_top_level_qualifiers_p (to, from)));
10845    }
10846}
10847
10848/* When comparing, say, char ** to char const **, this function takes
10849   the 'char *' and 'char const *'.  Do not pass non-pointer/reference
10850   types to this function.  */
10851
10852int
10853comp_ptr_ttypes (tree to, tree from)
10854{
10855  return comp_ptr_ttypes_real (to, from, 1);
10856}
10857
10858/* Returns true iff FNTYPE is a non-class type that involves
10859   error_mark_node.  We can get FUNCTION_TYPE with buried error_mark_node
10860   if a parameter type is ill-formed.  */
10861
10862bool
10863error_type_p (const_tree type)
10864{
10865  tree t;
10866
10867  switch (TREE_CODE (type))
10868    {
10869    case ERROR_MARK:
10870      return true;
10871
10872    case POINTER_TYPE:
10873    case REFERENCE_TYPE:
10874    case OFFSET_TYPE:
10875      return error_type_p (TREE_TYPE (type));
10876
10877    case FUNCTION_TYPE:
10878    case METHOD_TYPE:
10879      if (error_type_p (TREE_TYPE (type)))
10880	return true;
10881      for (t = TYPE_ARG_TYPES (type); t; t = TREE_CHAIN (t))
10882	if (error_type_p (TREE_VALUE (t)))
10883	  return true;
10884      return false;
10885
10886    case RECORD_TYPE:
10887      if (TYPE_PTRMEMFUNC_P (type))
10888	return error_type_p (TYPE_PTRMEMFUNC_FN_TYPE (type));
10889      return false;
10890
10891    default:
10892      return false;
10893    }
10894}
10895
10896/* Returns true if to and from are (possibly multi-level) pointers to the same
10897   type or inheritance-related types, regardless of cv-quals.  */
10898
10899bool
10900ptr_reasonably_similar (const_tree to, const_tree from)
10901{
10902  for (; ; to = TREE_TYPE (to), from = TREE_TYPE (from))
10903    {
10904      /* Any target type is similar enough to void.  */
10905      if (VOID_TYPE_P (to))
10906	return !error_type_p (from);
10907      if (VOID_TYPE_P (from))
10908	return !error_type_p (to);
10909
10910      if (TREE_CODE (to) != TREE_CODE (from))
10911	return false;
10912
10913      if (TREE_CODE (from) == OFFSET_TYPE
10914	  && comptypes (TYPE_OFFSET_BASETYPE (to),
10915			TYPE_OFFSET_BASETYPE (from),
10916			COMPARE_BASE | COMPARE_DERIVED))
10917	continue;
10918
10919      if (VECTOR_TYPE_P (to)
10920	  && vector_types_convertible_p (to, from, false))
10921	return true;
10922
10923      if (TREE_CODE (to) == INTEGER_TYPE
10924	  && TYPE_PRECISION (to) == TYPE_PRECISION (from))
10925	return true;
10926
10927      if (TREE_CODE (to) == FUNCTION_TYPE)
10928	return !error_type_p (to) && !error_type_p (from);
10929
10930      if (!TYPE_PTR_P (to))
10931	{
10932	  /* When either type is incomplete avoid DERIVED_FROM_P,
10933	     which may call complete_type (c++/57942).  */
10934	  bool b = !COMPLETE_TYPE_P (to) || !COMPLETE_TYPE_P (from);
10935	  return comptypes
10936	    (TYPE_MAIN_VARIANT (to), TYPE_MAIN_VARIANT (from),
10937	     b ? COMPARE_STRICT : COMPARE_BASE | COMPARE_DERIVED);
10938	}
10939    }
10940}
10941
10942/* Return true if TO and FROM (both of which are POINTER_TYPEs or
10943   pointer-to-member types) are the same, ignoring cv-qualification at
10944   all levels.  CB says how we should behave when comparing array bounds.  */
10945
10946bool
10947comp_ptr_ttypes_const (tree to, tree from, compare_bounds_t cb)
10948{
10949  bool is_opaque_pointer = false;
10950
10951  for (; ; to = TREE_TYPE (to), from = TREE_TYPE (from))
10952    {
10953      if (TREE_CODE (to) != TREE_CODE (from))
10954	return false;
10955
10956      if (TREE_CODE (from) == OFFSET_TYPE
10957	  && same_type_p (TYPE_OFFSET_BASETYPE (from),
10958			  TYPE_OFFSET_BASETYPE (to)))
10959	  continue;
10960
10961      if (VECTOR_TYPE_P (to))
10962	is_opaque_pointer = vector_targets_convertible_p (to, from);
10963
10964      if (TREE_CODE (to) == ARRAY_TYPE
10965	  /* Ignore cv-qualification, but if we see e.g. int[3] and int[4],
10966	     we must fail.  */
10967	  && !comp_array_types (to, from, cb, /*strict=*/false))
10968	return false;
10969
10970      /* CWG 330 says we need to look through arrays.  */
10971      if (!TYPE_PTR_P (to) && TREE_CODE (to) != ARRAY_TYPE)
10972	return (is_opaque_pointer
10973		|| same_type_ignoring_top_level_qualifiers_p (to, from));
10974    }
10975}
10976
10977/* Returns the type qualifiers for this type, including the qualifiers on the
10978   elements for an array type.  */
10979
10980int
10981cp_type_quals (const_tree type)
10982{
10983  int quals;
10984  /* This CONST_CAST is okay because strip_array_types returns its
10985     argument unmodified and we assign it to a const_tree.  */
10986  type = strip_array_types (CONST_CAST_TREE (type));
10987  if (type == error_mark_node
10988      /* Quals on a FUNCTION_TYPE are memfn quals.  */
10989      || TREE_CODE (type) == FUNCTION_TYPE)
10990    return TYPE_UNQUALIFIED;
10991  quals = TYPE_QUALS (type);
10992  /* METHOD and REFERENCE_TYPEs should never have quals.  */
10993  gcc_assert ((TREE_CODE (type) != METHOD_TYPE
10994	       && !TYPE_REF_P (type))
10995	      || ((quals & (TYPE_QUAL_CONST|TYPE_QUAL_VOLATILE))
10996		  == TYPE_UNQUALIFIED));
10997  return quals;
10998}
10999
11000/* Returns the function-ref-qualifier for TYPE */
11001
11002cp_ref_qualifier
11003type_memfn_rqual (const_tree type)
11004{
11005  gcc_assert (FUNC_OR_METHOD_TYPE_P (type));
11006
11007  if (!FUNCTION_REF_QUALIFIED (type))
11008    return REF_QUAL_NONE;
11009  else if (FUNCTION_RVALUE_QUALIFIED (type))
11010    return REF_QUAL_RVALUE;
11011  else
11012    return REF_QUAL_LVALUE;
11013}
11014
11015/* Returns the function-cv-quals for TYPE, which must be a FUNCTION_TYPE or
11016   METHOD_TYPE.  */
11017
11018int
11019type_memfn_quals (const_tree type)
11020{
11021  if (TREE_CODE (type) == FUNCTION_TYPE)
11022    return TYPE_QUALS (type);
11023  else if (TREE_CODE (type) == METHOD_TYPE)
11024    return cp_type_quals (class_of_this_parm (type));
11025  else
11026    gcc_unreachable ();
11027}
11028
11029/* Returns the FUNCTION_TYPE TYPE with its function-cv-quals changed to
11030   MEMFN_QUALS and its ref-qualifier to RQUAL. */
11031
11032tree
11033apply_memfn_quals (tree type, cp_cv_quals memfn_quals, cp_ref_qualifier rqual)
11034{
11035  /* Could handle METHOD_TYPE here if necessary.  */
11036  gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
11037  if (TYPE_QUALS (type) == memfn_quals
11038      && type_memfn_rqual (type) == rqual)
11039    return type;
11040
11041  /* This should really have a different TYPE_MAIN_VARIANT, but that gets
11042     complex.  */
11043  tree result = build_qualified_type (type, memfn_quals);
11044  return build_ref_qualified_type (result, rqual);
11045}
11046
11047/* Returns nonzero if TYPE is const or volatile.  */
11048
11049bool
11050cv_qualified_p (const_tree type)
11051{
11052  int quals = cp_type_quals (type);
11053  return (quals & (TYPE_QUAL_CONST|TYPE_QUAL_VOLATILE)) != 0;
11054}
11055
11056/* Returns nonzero if the TYPE contains a mutable member.  */
11057
11058bool
11059cp_has_mutable_p (const_tree type)
11060{
11061  /* This CONST_CAST is okay because strip_array_types returns its
11062     argument unmodified and we assign it to a const_tree.  */
11063  type = strip_array_types (CONST_CAST_TREE(type));
11064
11065  return CLASS_TYPE_P (type) && CLASSTYPE_HAS_MUTABLE (type);
11066}
11067
11068/* Set TREE_READONLY and TREE_VOLATILE on DECL as indicated by the
11069   TYPE_QUALS.  For a VAR_DECL, this may be an optimistic
11070   approximation.  In particular, consider:
11071
11072     int f();
11073     struct S { int i; };
11074     const S s = { f(); }
11075
11076   Here, we will make "s" as TREE_READONLY (because it is declared
11077   "const") -- only to reverse ourselves upon seeing that the
11078   initializer is non-constant.  */
11079
11080void
11081cp_apply_type_quals_to_decl (int type_quals, tree decl)
11082{
11083  tree type = TREE_TYPE (decl);
11084
11085  if (type == error_mark_node)
11086    return;
11087
11088  if (TREE_CODE (decl) == TYPE_DECL)
11089    return;
11090
11091  gcc_assert (!(TREE_CODE (type) == FUNCTION_TYPE
11092		&& type_quals != TYPE_UNQUALIFIED));
11093
11094  /* Avoid setting TREE_READONLY incorrectly.  */
11095  /* We used to check TYPE_NEEDS_CONSTRUCTING here, but now a constexpr
11096     constructor can produce constant init, so rely on cp_finish_decl to
11097     clear TREE_READONLY if the variable has non-constant init.  */
11098
11099  /* If the type has (or might have) a mutable component, that component
11100     might be modified.  */
11101  if (TYPE_HAS_MUTABLE_P (type) || !COMPLETE_TYPE_P (type))
11102    type_quals &= ~TYPE_QUAL_CONST;
11103
11104  c_apply_type_quals_to_decl (type_quals, decl);
11105}
11106
11107/* Subroutine of casts_away_constness.  Make T1 and T2 point at
11108   exemplar types such that casting T1 to T2 is casting away constness
11109   if and only if there is no implicit conversion from T1 to T2.  */
11110
11111static void
11112casts_away_constness_r (tree *t1, tree *t2, tsubst_flags_t complain)
11113{
11114  int quals1;
11115  int quals2;
11116
11117  /* [expr.const.cast]
11118
11119     For multi-level pointer to members and multi-level mixed pointers
11120     and pointers to members (conv.qual), the "member" aspect of a
11121     pointer to member level is ignored when determining if a const
11122     cv-qualifier has been cast away.  */
11123  /* [expr.const.cast]
11124
11125     For  two  pointer types:
11126
11127	    X1 is T1cv1,1 * ... cv1,N *   where T1 is not a pointer type
11128	    X2 is T2cv2,1 * ... cv2,M *   where T2 is not a pointer type
11129	    K is min(N,M)
11130
11131     casting from X1 to X2 casts away constness if, for a non-pointer
11132     type T there does not exist an implicit conversion (clause
11133     _conv_) from:
11134
11135	    Tcv1,(N-K+1) * cv1,(N-K+2) * ... cv1,N *
11136
11137     to
11138
11139	    Tcv2,(M-K+1) * cv2,(M-K+2) * ... cv2,M *.  */
11140  if ((!TYPE_PTR_P (*t1) && !TYPE_PTRDATAMEM_P (*t1))
11141      || (!TYPE_PTR_P (*t2) && !TYPE_PTRDATAMEM_P (*t2)))
11142    {
11143      *t1 = cp_build_qualified_type (void_type_node,
11144				     cp_type_quals (*t1));
11145      *t2 = cp_build_qualified_type (void_type_node,
11146				     cp_type_quals (*t2));
11147      return;
11148    }
11149
11150  quals1 = cp_type_quals (*t1);
11151  quals2 = cp_type_quals (*t2);
11152
11153  if (TYPE_PTRDATAMEM_P (*t1))
11154    *t1 = TYPE_PTRMEM_POINTED_TO_TYPE (*t1);
11155  else
11156    *t1 = TREE_TYPE (*t1);
11157  if (TYPE_PTRDATAMEM_P (*t2))
11158    *t2 = TYPE_PTRMEM_POINTED_TO_TYPE (*t2);
11159  else
11160    *t2 = TREE_TYPE (*t2);
11161
11162  casts_away_constness_r (t1, t2, complain);
11163  *t1 = build_pointer_type (*t1);
11164  *t2 = build_pointer_type (*t2);
11165  *t1 = cp_build_qualified_type (*t1, quals1);
11166  *t2 = cp_build_qualified_type (*t2, quals2);
11167}
11168
11169/* Returns nonzero if casting from TYPE1 to TYPE2 casts away
11170   constness.
11171
11172   ??? This function returns non-zero if casting away qualifiers not
11173   just const.  We would like to return to the caller exactly which
11174   qualifiers are casted away to give more accurate diagnostics.
11175*/
11176
11177static bool
11178casts_away_constness (tree t1, tree t2, tsubst_flags_t complain)
11179{
11180  if (TYPE_REF_P (t2))
11181    {
11182      /* [expr.const.cast]
11183
11184	 Casting from an lvalue of type T1 to an lvalue of type T2
11185	 using a reference cast casts away constness if a cast from an
11186	 rvalue of type "pointer to T1" to the type "pointer to T2"
11187	 casts away constness.  */
11188      t1 = (TYPE_REF_P (t1) ? TREE_TYPE (t1) : t1);
11189      return casts_away_constness (build_pointer_type (t1),
11190				   build_pointer_type (TREE_TYPE (t2)),
11191				   complain);
11192    }
11193
11194  if (TYPE_PTRDATAMEM_P (t1) && TYPE_PTRDATAMEM_P (t2))
11195    /* [expr.const.cast]
11196
11197       Casting from an rvalue of type "pointer to data member of X
11198       of type T1" to the type "pointer to data member of Y of type
11199       T2" casts away constness if a cast from an rvalue of type
11200       "pointer to T1" to the type "pointer to T2" casts away
11201       constness.  */
11202    return casts_away_constness
11203      (build_pointer_type (TYPE_PTRMEM_POINTED_TO_TYPE (t1)),
11204       build_pointer_type (TYPE_PTRMEM_POINTED_TO_TYPE (t2)),
11205       complain);
11206
11207  /* Casting away constness is only something that makes sense for
11208     pointer or reference types.  */
11209  if (!TYPE_PTR_P (t1) || !TYPE_PTR_P (t2))
11210    return false;
11211
11212  /* Top-level qualifiers don't matter.  */
11213  t1 = TYPE_MAIN_VARIANT (t1);
11214  t2 = TYPE_MAIN_VARIANT (t2);
11215  casts_away_constness_r (&t1, &t2, complain);
11216  if (!can_convert (t2, t1, complain))
11217    return true;
11218
11219  return false;
11220}
11221
11222/* If T is a REFERENCE_TYPE return the type to which T refers.
11223   Otherwise, return T itself.  */
11224
11225tree
11226non_reference (tree t)
11227{
11228  if (t && TYPE_REF_P (t))
11229    t = TREE_TYPE (t);
11230  return t;
11231}
11232
11233
11234/* Return nonzero if REF is an lvalue valid for this language;
11235   otherwise, print an error message and return zero.  USE says
11236   how the lvalue is being used and so selects the error message.  */
11237
11238int
11239lvalue_or_else (tree ref, enum lvalue_use use, tsubst_flags_t complain)
11240{
11241  cp_lvalue_kind kind = lvalue_kind (ref);
11242
11243  if (kind == clk_none)
11244    {
11245      if (complain & tf_error)
11246	lvalue_error (cp_expr_loc_or_input_loc (ref), use);
11247      return 0;
11248    }
11249  else if (kind & (clk_rvalueref|clk_class))
11250    {
11251      if (!(complain & tf_error))
11252	return 0;
11253      /* Make this a permerror because we used to accept it.  */
11254      permerror (cp_expr_loc_or_input_loc (ref),
11255		 "using rvalue as lvalue");
11256    }
11257  return 1;
11258}
11259
11260/* Return true if a user-defined literal operator is a raw operator.  */
11261
11262bool
11263check_raw_literal_operator (const_tree decl)
11264{
11265  tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
11266  tree argtype;
11267  int arity;
11268  bool maybe_raw_p = false;
11269
11270  /* Count the number and type of arguments and check for ellipsis.  */
11271  for (argtype = argtypes, arity = 0;
11272       argtype && argtype != void_list_node;
11273       ++arity, argtype = TREE_CHAIN (argtype))
11274    {
11275      tree t = TREE_VALUE (argtype);
11276
11277      if (same_type_p (t, const_string_type_node))
11278	maybe_raw_p = true;
11279    }
11280  if (!argtype)
11281    return false; /* Found ellipsis.  */
11282
11283  if (!maybe_raw_p || arity != 1)
11284    return false;
11285
11286  return true;
11287}
11288
11289
11290/* Return true if a user-defined literal operator has one of the allowed
11291   argument types.  */
11292
11293bool
11294check_literal_operator_args (const_tree decl,
11295			     bool *long_long_unsigned_p, bool *long_double_p)
11296{
11297  tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
11298
11299  *long_long_unsigned_p = false;
11300  *long_double_p = false;
11301  if (processing_template_decl || processing_specialization)
11302    return argtypes == void_list_node;
11303  else
11304    {
11305      tree argtype;
11306      int arity;
11307      int max_arity = 2;
11308
11309      /* Count the number and type of arguments and check for ellipsis.  */
11310      for (argtype = argtypes, arity = 0;
11311	   argtype && argtype != void_list_node;
11312	   argtype = TREE_CHAIN (argtype))
11313	{
11314	  tree t = TREE_VALUE (argtype);
11315	  ++arity;
11316
11317	  if (TYPE_PTR_P (t))
11318	    {
11319	      bool maybe_raw_p = false;
11320	      t = TREE_TYPE (t);
11321	      if (cp_type_quals (t) != TYPE_QUAL_CONST)
11322		return false;
11323	      t = TYPE_MAIN_VARIANT (t);
11324	      if ((maybe_raw_p = same_type_p (t, char_type_node))
11325		  || same_type_p (t, wchar_type_node)
11326		  || same_type_p (t, char8_type_node)
11327		  || same_type_p (t, char16_type_node)
11328		  || same_type_p (t, char32_type_node))
11329		{
11330		  argtype = TREE_CHAIN (argtype);
11331		  if (!argtype)
11332		    return false;
11333		  t = TREE_VALUE (argtype);
11334		  if (maybe_raw_p && argtype == void_list_node)
11335		    return true;
11336		  else if (same_type_p (t, size_type_node))
11337		    {
11338		      ++arity;
11339		      continue;
11340		    }
11341		  else
11342		    return false;
11343		}
11344	    }
11345	  else if (same_type_p (t, long_long_unsigned_type_node))
11346	    {
11347	      max_arity = 1;
11348	      *long_long_unsigned_p = true;
11349	    }
11350	  else if (same_type_p (t, long_double_type_node))
11351	    {
11352	      max_arity = 1;
11353	      *long_double_p = true;
11354	    }
11355	  else if (same_type_p (t, char_type_node))
11356	    max_arity = 1;
11357	  else if (same_type_p (t, wchar_type_node))
11358	    max_arity = 1;
11359	  else if (same_type_p (t, char8_type_node))
11360	    max_arity = 1;
11361	  else if (same_type_p (t, char16_type_node))
11362	    max_arity = 1;
11363	  else if (same_type_p (t, char32_type_node))
11364	    max_arity = 1;
11365	  else
11366	    return false;
11367	}
11368      if (!argtype)
11369	return false; /* Found ellipsis.  */
11370
11371      if (arity != max_arity)
11372	return false;
11373
11374      return true;
11375    }
11376}
11377
11378/* Always returns false since unlike C90, C++ has no concept of implicit
11379   function declarations.  */
11380
11381bool
11382c_decl_implicit (const_tree)
11383{
11384  return false;
11385}
11386