1 /* Functions related to invoking -*- C++ -*- methods and overloaded functions.
2    Copyright (C) 1987-2021 Free Software Foundation, Inc.
3    Contributed by Michael Tiemann (tiemann@cygnus.com) and
4    modified by Brendan Kehoe (brendan@cygnus.com).
5 
6 This file is part of GCC.
7 
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12 
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17 
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21 
22 
23 /* High-level class interface.  */
24 
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "target.h"
29 #include "cp-tree.h"
30 #include "timevar.h"
31 #include "stringpool.h"
32 #include "cgraph.h"
33 #include "stor-layout.h"
34 #include "trans-mem.h"
35 #include "flags.h"
36 #include "toplev.h"
37 #include "intl.h"
38 #include "convert.h"
39 #include "langhooks.h"
40 #include "c-family/c-objc.h"
41 #include "internal-fn.h"
42 #include "stringpool.h"
43 #include "attribs.h"
44 #include "gcc-rich-location.h"
45 
46 /* The various kinds of conversion.  */
47 
48 enum conversion_kind {
49   ck_identity,
50   ck_lvalue,
51   ck_fnptr,
52   ck_qual,
53   ck_std,
54   ck_ptr,
55   ck_pmem,
56   ck_base,
57   ck_ref_bind,
58   ck_user,
59   ck_ambig,
60   ck_list,
61   ck_aggr,
62   ck_rvalue
63 };
64 
65 /* The rank of the conversion.  Order of the enumerals matters; better
66    conversions should come earlier in the list.  */
67 
68 enum conversion_rank {
69   cr_identity,
70   cr_exact,
71   cr_promotion,
72   cr_std,
73   cr_pbool,
74   cr_user,
75   cr_ellipsis,
76   cr_bad
77 };
78 
79 /* An implicit conversion sequence, in the sense of [over.best.ics].
80    The first conversion to be performed is at the end of the chain.
81    That conversion is always a cr_identity conversion.  */
82 
83 struct conversion {
84   /* The kind of conversion represented by this step.  */
85   conversion_kind kind;
86   /* The rank of this conversion.  */
87   conversion_rank rank;
88   BOOL_BITFIELD user_conv_p : 1;
89   BOOL_BITFIELD ellipsis_p : 1;
90   BOOL_BITFIELD this_p : 1;
91   /* True if this conversion would be permitted with a bending of
92      language standards, e.g. disregarding pointer qualifiers or
93      converting integers to pointers.  */
94   BOOL_BITFIELD bad_p : 1;
95   /* If KIND is ck_ref_bind or ck_base, true to indicate that a
96      temporary should be created to hold the result of the
97      conversion.  If KIND is ck_ambig or ck_user, true means force
98      copy-initialization.  */
99   BOOL_BITFIELD need_temporary_p : 1;
100   /* If KIND is ck_ptr or ck_pmem, true to indicate that a conversion
101      from a pointer-to-derived to pointer-to-base is being performed.  */
102   BOOL_BITFIELD base_p : 1;
103   /* If KIND is ck_ref_bind, true when either an lvalue reference is
104      being bound to an lvalue expression or an rvalue reference is
105      being bound to an rvalue expression.  If KIND is ck_rvalue or ck_base,
106      true when we are treating an lvalue as an rvalue (12.8p33).  If
107      ck_identity, we will be binding a reference directly or decaying to
108      a pointer.  */
109   BOOL_BITFIELD rvaluedness_matches_p: 1;
110   BOOL_BITFIELD check_narrowing: 1;
111   /* Whether check_narrowing should only check TREE_CONSTANTs; used
112      in build_converted_constant_expr.  */
113   BOOL_BITFIELD check_narrowing_const_only: 1;
114   /* True if this conversion is taking place in a copy-initialization context
115      and we should only consider converting constructors.  Only set in
116      ck_base and ck_rvalue.  */
117   BOOL_BITFIELD copy_init_p : 1;
118   /* The type of the expression resulting from the conversion.  */
119   tree type;
120   union {
121     /* The next conversion in the chain.  Since the conversions are
122        arranged from outermost to innermost, the NEXT conversion will
123        actually be performed before this conversion.  This variant is
124        used only when KIND is neither ck_identity, ck_aggr, ck_ambig nor
125        ck_list.  Please use the next_conversion function instead
126        of using this field directly.  */
127     conversion *next;
128     /* The expression at the beginning of the conversion chain.  This
129        variant is used only if KIND is ck_identity, ck_aggr, or ck_ambig.
130        You can use conv_get_original_expr to get this expression.  */
131     tree expr;
132     /* The array of conversions for an initializer_list, so this
133        variant is used only when KIN D is ck_list.  */
134     conversion **list;
135   } u;
136   /* The function candidate corresponding to this conversion
137      sequence.  This field is only used if KIND is ck_user.  */
138   struct z_candidate *cand;
139 };
140 
141 #define CONVERSION_RANK(NODE)			\
142   ((NODE)->bad_p ? cr_bad			\
143    : (NODE)->ellipsis_p ? cr_ellipsis		\
144    : (NODE)->user_conv_p ? cr_user		\
145    : (NODE)->rank)
146 
147 #define BAD_CONVERSION_RANK(NODE)		\
148   ((NODE)->ellipsis_p ? cr_ellipsis		\
149    : (NODE)->user_conv_p ? cr_user		\
150    : (NODE)->rank)
151 
152 static struct obstack conversion_obstack;
153 static bool conversion_obstack_initialized;
154 struct rejection_reason;
155 
156 static struct z_candidate * tourney (struct z_candidate *, tsubst_flags_t);
157 static int equal_functions (tree, tree);
158 static int joust (struct z_candidate *, struct z_candidate *, bool,
159 		  tsubst_flags_t);
160 static int compare_ics (conversion *, conversion *);
161 static void maybe_warn_class_memaccess (location_t, tree,
162 					const vec<tree, va_gc> *);
163 static tree build_over_call (struct z_candidate *, int, tsubst_flags_t);
164 static tree convert_like (conversion *, tree, tsubst_flags_t);
165 static tree convert_like_with_context (conversion *, tree, tree, int,
166 				       tsubst_flags_t);
167 static void op_error (const op_location_t &, enum tree_code, enum tree_code,
168 		      tree, tree, tree, bool);
169 static struct z_candidate *build_user_type_conversion_1 (tree, tree, int,
170 							 tsubst_flags_t);
171 static void print_z_candidate (location_t, const char *, struct z_candidate *);
172 static void print_z_candidates (location_t, struct z_candidate *);
173 static tree build_this (tree);
174 static struct z_candidate *splice_viable (struct z_candidate *, bool, bool *);
175 static bool any_strictly_viable (struct z_candidate *);
176 static struct z_candidate *add_template_candidate
177 	(struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
178 	 tree, tree, tree, int, unification_kind_t, bool, tsubst_flags_t);
179 static struct z_candidate *add_template_candidate_real
180 	(struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
181 	 tree, tree, tree, int, tree, unification_kind_t, bool, tsubst_flags_t);
182 static bool is_complete (tree);
183 static struct z_candidate *add_conv_candidate
184 	(struct z_candidate **, tree, tree, const vec<tree, va_gc> *, tree,
185 	 tree, tsubst_flags_t);
186 static struct z_candidate *add_function_candidate
187 	(struct z_candidate **, tree, tree, tree, const vec<tree, va_gc> *, tree,
188 	 tree, int, conversion**, bool, tsubst_flags_t);
189 static conversion *implicit_conversion (tree, tree, tree, bool, int,
190 					tsubst_flags_t);
191 static conversion *reference_binding (tree, tree, tree, bool, int,
192 				      tsubst_flags_t);
193 static conversion *build_conv (conversion_kind, tree, conversion *);
194 static conversion *build_list_conv (tree, tree, int, tsubst_flags_t);
195 static conversion *next_conversion (conversion *);
196 static bool is_subseq (conversion *, conversion *);
197 static conversion *maybe_handle_ref_bind (conversion **);
198 static void maybe_handle_implicit_object (conversion **);
199 static struct z_candidate *add_candidate
200 	(struct z_candidate **, tree, tree, const vec<tree, va_gc> *, size_t,
201 	 conversion **, tree, tree, int, struct rejection_reason *, int);
202 static tree source_type (conversion *);
203 static void add_warning (struct z_candidate *, struct z_candidate *);
204 static conversion *direct_reference_binding (tree, conversion *);
205 static bool promoted_arithmetic_type_p (tree);
206 static conversion *conditional_conversion (tree, tree, tsubst_flags_t);
207 static char *name_as_c_string (tree, tree, bool *);
208 static tree prep_operand (tree);
209 static void add_candidates (tree, tree, const vec<tree, va_gc> *, tree, tree,
210 			    bool, tree, tree, int, struct z_candidate **,
211 			    tsubst_flags_t);
212 static conversion *merge_conversion_sequences (conversion *, conversion *);
213 static tree build_temp (tree, tree, int, diagnostic_t *, tsubst_flags_t);
214 static conversion *build_identity_conv (tree, tree);
215 static inline bool conv_binds_to_array_of_unknown_bound (conversion *);
216 static bool conv_is_prvalue (conversion *);
217 static tree prevent_lifetime_extension (tree);
218 
219 /* Returns nonzero iff the destructor name specified in NAME matches BASETYPE.
220    NAME can take many forms...  */
221 
222 bool
check_dtor_name(tree basetype,tree name)223 check_dtor_name (tree basetype, tree name)
224 {
225   /* Just accept something we've already complained about.  */
226   if (name == error_mark_node)
227     return true;
228 
229   if (TREE_CODE (name) == TYPE_DECL)
230     name = TREE_TYPE (name);
231   else if (TYPE_P (name))
232     /* OK */;
233   else if (identifier_p (name))
234     {
235       if ((MAYBE_CLASS_TYPE_P (basetype)
236 	   || TREE_CODE (basetype) == ENUMERAL_TYPE)
237 	  && name == constructor_name (basetype))
238 	return true;
239 
240       /* Otherwise lookup the name, it could be an unrelated typedef
241 	 of the correct type.  */
242       name = lookup_name (name, LOOK_want::TYPE);
243       if (!name)
244 	return false;
245       name = TREE_TYPE (name);
246       if (name == error_mark_node)
247 	return false;
248     }
249   else
250     {
251       /* In the case of:
252 
253 	 template <class T> struct S { ~S(); };
254 	 int i;
255 	 i.~S();
256 
257 	 NAME will be a class template.  */
258       gcc_assert (DECL_CLASS_TEMPLATE_P (name));
259       return false;
260     }
261 
262   return same_type_p (TYPE_MAIN_VARIANT (basetype), TYPE_MAIN_VARIANT (name));
263 }
264 
265 /* We want the address of a function or method.  We avoid creating a
266    pointer-to-member function.  */
267 
268 tree
build_addr_func(tree function,tsubst_flags_t complain)269 build_addr_func (tree function, tsubst_flags_t complain)
270 {
271   tree type = TREE_TYPE (function);
272 
273   /* We have to do these by hand to avoid real pointer to member
274      functions.  */
275   if (TREE_CODE (type) == METHOD_TYPE)
276     {
277       if (TREE_CODE (function) == OFFSET_REF)
278 	{
279 	  tree object = build_address (TREE_OPERAND (function, 0));
280 	  return get_member_function_from_ptrfunc (&object,
281 						   TREE_OPERAND (function, 1),
282 						   complain);
283 	}
284       function = build_address (function);
285     }
286   else if (TREE_CODE (function) == FUNCTION_DECL
287 	   && DECL_IMMEDIATE_FUNCTION_P (function))
288     function = build_address (function);
289   else
290     function = decay_conversion (function, complain, /*reject_builtin=*/false);
291 
292   return function;
293 }
294 
295 /* Build a CALL_EXPR, we can handle FUNCTION_TYPEs, METHOD_TYPEs, or
296    POINTER_TYPE to those.  Note, pointer to member function types
297    (TYPE_PTRMEMFUNC_P) must be handled by our callers.  There are
298    two variants.  build_call_a is the primitive taking an array of
299    arguments, while build_call_n is a wrapper that handles varargs.  */
300 
301 tree
build_call_n(tree function,int n,...)302 build_call_n (tree function, int n, ...)
303 {
304   if (n == 0)
305     return build_call_a (function, 0, NULL);
306   else
307     {
308       tree *argarray = XALLOCAVEC (tree, n);
309       va_list ap;
310       int i;
311 
312       va_start (ap, n);
313       for (i = 0; i < n; i++)
314 	argarray[i] = va_arg (ap, tree);
315       va_end (ap);
316       return build_call_a (function, n, argarray);
317     }
318 }
319 
320 /* Update various flags in cfun and the call itself based on what is being
321    called.  Split out of build_call_a so that bot_manip can use it too.  */
322 
323 void
set_flags_from_callee(tree call)324 set_flags_from_callee (tree call)
325 {
326   /* Handle both CALL_EXPRs and AGGR_INIT_EXPRs.  */
327   tree decl = cp_get_callee_fndecl_nofold (call);
328 
329   /* We check both the decl and the type; a function may be known not to
330      throw without being declared throw().  */
331   bool nothrow = decl && TREE_NOTHROW (decl);
332   tree callee = cp_get_callee (call);
333   if (callee)
334     nothrow |= TYPE_NOTHROW_P (TREE_TYPE (TREE_TYPE (callee)));
335   else if (TREE_CODE (call) == CALL_EXPR
336 	   && internal_fn_flags (CALL_EXPR_IFN (call)) & ECF_NOTHROW)
337     nothrow = true;
338 
339   if (cfun && cp_function_chain && !cp_unevaluated_operand)
340     {
341       if (!nothrow && at_function_scope_p ())
342 	cp_function_chain->can_throw = 1;
343 
344       if (decl && TREE_THIS_VOLATILE (decl))
345 	current_function_returns_abnormally = 1;
346     }
347 
348   TREE_NOTHROW (call) = nothrow;
349 }
350 
351 tree
build_call_a(tree function,int n,tree * argarray)352 build_call_a (tree function, int n, tree *argarray)
353 {
354   tree decl;
355   tree result_type;
356   tree fntype;
357   int i;
358 
359   function = build_addr_func (function, tf_warning_or_error);
360 
361   gcc_assert (TYPE_PTR_P (TREE_TYPE (function)));
362   fntype = TREE_TYPE (TREE_TYPE (function));
363   gcc_assert (FUNC_OR_METHOD_TYPE_P (fntype));
364   result_type = TREE_TYPE (fntype);
365   /* An rvalue has no cv-qualifiers.  */
366   if (SCALAR_TYPE_P (result_type) || VOID_TYPE_P (result_type))
367     result_type = cv_unqualified (result_type);
368 
369   function = build_call_array_loc (input_location,
370 				   result_type, function, n, argarray);
371   set_flags_from_callee (function);
372 
373   decl = get_callee_fndecl (function);
374 
375   if (decl && !TREE_USED (decl))
376     {
377       /* We invoke build_call directly for several library
378 	 functions.  These may have been declared normally if
379 	 we're building libgcc, so we can't just check
380 	 DECL_ARTIFICIAL.  */
381       gcc_assert (DECL_ARTIFICIAL (decl)
382 		  || !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)),
383 			       "__", 2));
384       mark_used (decl);
385     }
386 
387   require_complete_eh_spec_types (fntype, decl);
388 
389   TREE_HAS_CONSTRUCTOR (function) = (decl && DECL_CONSTRUCTOR_P (decl));
390 
391   /* Don't pass empty class objects by value.  This is useful
392      for tags in STL, which are used to control overload resolution.
393      We don't need to handle other cases of copying empty classes.  */
394   if (!decl || !fndecl_built_in_p (decl))
395     for (i = 0; i < n; i++)
396       {
397 	tree arg = CALL_EXPR_ARG (function, i);
398 	if (is_empty_class (TREE_TYPE (arg))
399 	    && simple_empty_class_p (TREE_TYPE (arg), arg, INIT_EXPR))
400 	  {
401 	    while (TREE_CODE (arg) == TARGET_EXPR)
402 	      /* We're disconnecting the initializer from its target,
403 		 don't create a temporary.  */
404 	      arg = TARGET_EXPR_INITIAL (arg);
405 	    tree t = build0 (EMPTY_CLASS_EXPR, TREE_TYPE (arg));
406 	    arg = build2 (COMPOUND_EXPR, TREE_TYPE (t), arg, t);
407 	    CALL_EXPR_ARG (function, i) = arg;
408 	  }
409       }
410 
411   return function;
412 }
413 
414 /* New overloading code.  */
415 
416 struct z_candidate;
417 
418 struct candidate_warning {
419   z_candidate *loser;
420   candidate_warning *next;
421 };
422 
423 /* Information for providing diagnostics about why overloading failed.  */
424 
425 enum rejection_reason_code {
426   rr_none,
427   rr_arity,
428   rr_explicit_conversion,
429   rr_template_conversion,
430   rr_arg_conversion,
431   rr_bad_arg_conversion,
432   rr_template_unification,
433   rr_invalid_copy,
434   rr_inherited_ctor,
435   rr_constraint_failure
436 };
437 
438 struct conversion_info {
439   /* The index of the argument, 0-based.  */
440   int n_arg;
441   /* The actual argument or its type.  */
442   tree from;
443   /* The type of the parameter.  */
444   tree to_type;
445   /* The location of the argument.  */
446   location_t loc;
447 };
448 
449 struct rejection_reason {
450   enum rejection_reason_code code;
451   union {
452     /* Information about an arity mismatch.  */
453     struct {
454       /* The expected number of arguments.  */
455       int expected;
456       /* The actual number of arguments in the call.  */
457       int actual;
458       /* Whether EXPECTED should be treated as a lower bound.  */
459       bool least_p;
460     } arity;
461     /* Information about an argument conversion mismatch.  */
462     struct conversion_info conversion;
463     /* Same, but for bad argument conversions.  */
464     struct conversion_info bad_conversion;
465     /* Information about template unification failures.  These are the
466        parameters passed to fn_type_unification.  */
467     struct {
468       tree tmpl;
469       tree explicit_targs;
470       int num_targs;
471       const tree *args;
472       unsigned int nargs;
473       tree return_type;
474       unification_kind_t strict;
475       int flags;
476     } template_unification;
477     /* Information about template instantiation failures.  These are the
478        parameters passed to instantiate_template.  */
479     struct {
480       tree tmpl;
481       tree targs;
482     } template_instantiation;
483   } u;
484 };
485 
486 struct z_candidate {
487   /* The FUNCTION_DECL that will be called if this candidate is
488      selected by overload resolution.  */
489   tree fn;
490   /* If not NULL_TREE, the first argument to use when calling this
491      function.  */
492   tree first_arg;
493   /* The rest of the arguments to use when calling this function.  If
494      there are no further arguments this may be NULL or it may be an
495      empty vector.  */
496   const vec<tree, va_gc> *args;
497   /* The implicit conversion sequences for each of the arguments to
498      FN.  */
499   conversion **convs;
500   /* The number of implicit conversion sequences.  */
501   size_t num_convs;
502   /* If FN is a user-defined conversion, the standard conversion
503      sequence from the type returned by FN to the desired destination
504      type.  */
505   conversion *second_conv;
506   struct rejection_reason *reason;
507   /* If FN is a member function, the binfo indicating the path used to
508      qualify the name of FN at the call site.  This path is used to
509      determine whether or not FN is accessible if it is selected by
510      overload resolution.  The DECL_CONTEXT of FN will always be a
511      (possibly improper) base of this binfo.  */
512   tree access_path;
513   /* If FN is a non-static member function, the binfo indicating the
514      subobject to which the `this' pointer should be converted if FN
515      is selected by overload resolution.  The type pointed to by
516      the `this' pointer must correspond to the most derived class
517      indicated by the CONVERSION_PATH.  */
518   tree conversion_path;
519   tree template_decl;
520   tree explicit_targs;
521   candidate_warning *warnings;
522   z_candidate *next;
523   int viable;
524 
525   /* The flags active in add_candidate.  */
526   int flags;
527 
rewrittenz_candidate528   bool rewritten () const { return (flags & LOOKUP_REWRITTEN); }
reversedz_candidate529   bool reversed () const { return (flags & LOOKUP_REVERSED); }
530 };
531 
532 /* Returns true iff T is a null pointer constant in the sense of
533    [conv.ptr].  */
534 
535 bool
null_ptr_cst_p(tree t)536 null_ptr_cst_p (tree t)
537 {
538   tree type = TREE_TYPE (t);
539 
540   /* [conv.ptr]
541 
542      A null pointer constant is an integer literal ([lex.icon]) with value
543      zero or a prvalue of type std::nullptr_t.  */
544   if (NULLPTR_TYPE_P (type))
545     return true;
546 
547   if (cxx_dialect >= cxx11)
548     {
549       STRIP_ANY_LOCATION_WRAPPER (t);
550 
551       /* Core issue 903 says only literal 0 is a null pointer constant.  */
552       if (TREE_CODE (t) == INTEGER_CST
553 	  && !TREE_OVERFLOW (t)
554 	  && TREE_CODE (type) == INTEGER_TYPE
555 	  && integer_zerop (t)
556 	  && !char_type_p (type))
557 	return true;
558     }
559   else if (CP_INTEGRAL_TYPE_P (type))
560     {
561       t = fold_non_dependent_expr (t, tf_none);
562       STRIP_NOPS (t);
563       if (integer_zerop (t) && !TREE_OVERFLOW (t))
564 	return true;
565     }
566 
567   return false;
568 }
569 
570 /* Returns true iff T is a null member pointer value (4.11).  */
571 
572 bool
null_member_pointer_value_p(tree t)573 null_member_pointer_value_p (tree t)
574 {
575   tree type = TREE_TYPE (t);
576   if (!type)
577     return false;
578   else if (TYPE_PTRMEMFUNC_P (type))
579     return (TREE_CODE (t) == CONSTRUCTOR
580 	    && CONSTRUCTOR_NELTS (t)
581 	    && integer_zerop (CONSTRUCTOR_ELT (t, 0)->value));
582   else if (TYPE_PTRDATAMEM_P (type))
583     return integer_all_onesp (t);
584   else
585     return false;
586 }
587 
588 /* Returns nonzero if PARMLIST consists of only default parms,
589    ellipsis, and/or undeduced parameter packs.  */
590 
591 bool
sufficient_parms_p(const_tree parmlist)592 sufficient_parms_p (const_tree parmlist)
593 {
594   for (; parmlist && parmlist != void_list_node;
595        parmlist = TREE_CHAIN (parmlist))
596     if (!TREE_PURPOSE (parmlist)
597 	&& !PACK_EXPANSION_P (TREE_VALUE (parmlist)))
598       return false;
599   return true;
600 }
601 
602 /* Allocate N bytes of memory from the conversion obstack.  The memory
603    is zeroed before being returned.  */
604 
605 static void *
conversion_obstack_alloc(size_t n)606 conversion_obstack_alloc (size_t n)
607 {
608   void *p;
609   if (!conversion_obstack_initialized)
610     {
611       gcc_obstack_init (&conversion_obstack);
612       conversion_obstack_initialized = true;
613     }
614   p = obstack_alloc (&conversion_obstack, n);
615   memset (p, 0, n);
616   return p;
617 }
618 
619 /* Allocate rejection reasons.  */
620 
621 static struct rejection_reason *
alloc_rejection(enum rejection_reason_code code)622 alloc_rejection (enum rejection_reason_code code)
623 {
624   struct rejection_reason *p;
625   p = (struct rejection_reason *) conversion_obstack_alloc (sizeof *p);
626   p->code = code;
627   return p;
628 }
629 
630 static struct rejection_reason *
631 arity_rejection (tree first_arg, int expected, int actual, bool least_p = false)
632 {
633   struct rejection_reason *r = alloc_rejection (rr_arity);
634   int adjust = first_arg != NULL_TREE;
635   r->u.arity.expected = expected - adjust;
636   r->u.arity.actual = actual - adjust;
637   r->u.arity.least_p = least_p;
638   return r;
639 }
640 
641 static struct rejection_reason *
arg_conversion_rejection(tree first_arg,int n_arg,tree from,tree to,location_t loc)642 arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
643 			  location_t loc)
644 {
645   struct rejection_reason *r = alloc_rejection (rr_arg_conversion);
646   int adjust = first_arg != NULL_TREE;
647   r->u.conversion.n_arg = n_arg - adjust;
648   r->u.conversion.from = from;
649   r->u.conversion.to_type = to;
650   r->u.conversion.loc = loc;
651   return r;
652 }
653 
654 static struct rejection_reason *
bad_arg_conversion_rejection(tree first_arg,int n_arg,tree from,tree to,location_t loc)655 bad_arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
656 			      location_t loc)
657 {
658   struct rejection_reason *r = alloc_rejection (rr_bad_arg_conversion);
659   int adjust = first_arg != NULL_TREE;
660   r->u.bad_conversion.n_arg = n_arg - adjust;
661   r->u.bad_conversion.from = from;
662   r->u.bad_conversion.to_type = to;
663   r->u.bad_conversion.loc = loc;
664   return r;
665 }
666 
667 static struct rejection_reason *
explicit_conversion_rejection(tree from,tree to)668 explicit_conversion_rejection (tree from, tree to)
669 {
670   struct rejection_reason *r = alloc_rejection (rr_explicit_conversion);
671   r->u.conversion.n_arg = 0;
672   r->u.conversion.from = from;
673   r->u.conversion.to_type = to;
674   r->u.conversion.loc = UNKNOWN_LOCATION;
675   return r;
676 }
677 
678 static struct rejection_reason *
template_conversion_rejection(tree from,tree to)679 template_conversion_rejection (tree from, tree to)
680 {
681   struct rejection_reason *r = alloc_rejection (rr_template_conversion);
682   r->u.conversion.n_arg = 0;
683   r->u.conversion.from = from;
684   r->u.conversion.to_type = to;
685   r->u.conversion.loc = UNKNOWN_LOCATION;
686   return r;
687 }
688 
689 static struct rejection_reason *
template_unification_rejection(tree tmpl,tree explicit_targs,tree targs,const tree * args,unsigned int nargs,tree return_type,unification_kind_t strict,int flags)690 template_unification_rejection (tree tmpl, tree explicit_targs, tree targs,
691 				const tree *args, unsigned int nargs,
692 				tree return_type, unification_kind_t strict,
693 				int flags)
694 {
695   size_t args_n_bytes = sizeof (*args) * nargs;
696   tree *args1 = (tree *) conversion_obstack_alloc (args_n_bytes);
697   struct rejection_reason *r = alloc_rejection (rr_template_unification);
698   r->u.template_unification.tmpl = tmpl;
699   r->u.template_unification.explicit_targs = explicit_targs;
700   r->u.template_unification.num_targs = TREE_VEC_LENGTH (targs);
701   /* Copy args to our own storage.  */
702   memcpy (args1, args, args_n_bytes);
703   r->u.template_unification.args = args1;
704   r->u.template_unification.nargs = nargs;
705   r->u.template_unification.return_type = return_type;
706   r->u.template_unification.strict = strict;
707   r->u.template_unification.flags = flags;
708   return r;
709 }
710 
711 static struct rejection_reason *
template_unification_error_rejection(void)712 template_unification_error_rejection (void)
713 {
714   return alloc_rejection (rr_template_unification);
715 }
716 
717 static struct rejection_reason *
invalid_copy_with_fn_template_rejection(void)718 invalid_copy_with_fn_template_rejection (void)
719 {
720   struct rejection_reason *r = alloc_rejection (rr_invalid_copy);
721   return r;
722 }
723 
724 static struct rejection_reason *
inherited_ctor_rejection(void)725 inherited_ctor_rejection (void)
726 {
727   struct rejection_reason *r = alloc_rejection (rr_inherited_ctor);
728   return r;
729 }
730 
731 /* Build a constraint failure record.  */
732 
733 static struct rejection_reason *
constraint_failure(void)734 constraint_failure (void)
735 {
736   struct rejection_reason *r = alloc_rejection (rr_constraint_failure);
737   return r;
738 }
739 
740 /* Dynamically allocate a conversion.  */
741 
742 static conversion *
alloc_conversion(conversion_kind kind)743 alloc_conversion (conversion_kind kind)
744 {
745   conversion *c;
746   c = (conversion *) conversion_obstack_alloc (sizeof (conversion));
747   c->kind = kind;
748   return c;
749 }
750 
751 /* Make sure that all memory on the conversion obstack has been
752    freed.  */
753 
754 void
validate_conversion_obstack(void)755 validate_conversion_obstack (void)
756 {
757   if (conversion_obstack_initialized)
758     gcc_assert ((obstack_next_free (&conversion_obstack)
759 		 == obstack_base (&conversion_obstack)));
760 }
761 
762 /* Dynamically allocate an array of N conversions.  */
763 
764 static conversion **
alloc_conversions(size_t n)765 alloc_conversions (size_t n)
766 {
767   return (conversion **) conversion_obstack_alloc (n * sizeof (conversion *));
768 }
769 
770 /* True iff the active member of conversion::u for code CODE is NEXT.  */
771 
772 static inline bool
has_next(conversion_kind code)773 has_next (conversion_kind code)
774 {
775   return !(code == ck_identity
776 	   || code == ck_ambig
777 	   || code == ck_list
778 	   || code == ck_aggr);
779 }
780 
781 static conversion *
build_conv(conversion_kind code,tree type,conversion * from)782 build_conv (conversion_kind code, tree type, conversion *from)
783 {
784   conversion *t;
785   conversion_rank rank = CONVERSION_RANK (from);
786 
787   /* Only call this function for conversions that use u.next.  */
788   gcc_assert (from == NULL || has_next (code));
789 
790   /* Note that the caller is responsible for filling in t->cand for
791      user-defined conversions.  */
792   t = alloc_conversion (code);
793   t->type = type;
794   t->u.next = from;
795 
796   switch (code)
797     {
798     case ck_ptr:
799     case ck_pmem:
800     case ck_base:
801     case ck_std:
802       if (rank < cr_std)
803 	rank = cr_std;
804       break;
805 
806     case ck_qual:
807     case ck_fnptr:
808       if (rank < cr_exact)
809 	rank = cr_exact;
810       break;
811 
812     default:
813       break;
814     }
815   t->rank = rank;
816   t->user_conv_p = (code == ck_user || from->user_conv_p);
817   t->bad_p = from->bad_p;
818   t->base_p = false;
819   return t;
820 }
821 
822 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
823    specialization of std::initializer_list<T>, if such a conversion is
824    possible.  */
825 
826 static conversion *
build_list_conv(tree type,tree ctor,int flags,tsubst_flags_t complain)827 build_list_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
828 {
829   tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (type), 0);
830   unsigned len = CONSTRUCTOR_NELTS (ctor);
831   conversion **subconvs = alloc_conversions (len);
832   conversion *t;
833   unsigned i;
834   tree val;
835 
836   /* Within a list-initialization we can have more user-defined
837      conversions.  */
838   flags &= ~LOOKUP_NO_CONVERSION;
839   /* But no narrowing conversions.  */
840   flags |= LOOKUP_NO_NARROWING;
841 
842   /* Can't make an array of these types.  */
843   if (TYPE_REF_P (elttype)
844       || TREE_CODE (elttype) == FUNCTION_TYPE
845       || VOID_TYPE_P (elttype))
846     return NULL;
847 
848   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
849     {
850       conversion *sub
851 	= implicit_conversion (elttype, TREE_TYPE (val), val,
852 			       false, flags, complain);
853       if (sub == NULL)
854 	return NULL;
855 
856       subconvs[i] = sub;
857     }
858 
859   t = alloc_conversion (ck_list);
860   t->type = type;
861   t->u.list = subconvs;
862   t->rank = cr_exact;
863 
864   for (i = 0; i < len; ++i)
865     {
866       conversion *sub = subconvs[i];
867       if (sub->rank > t->rank)
868 	t->rank = sub->rank;
869       if (sub->user_conv_p)
870 	t->user_conv_p = true;
871       if (sub->bad_p)
872 	t->bad_p = true;
873     }
874 
875   return t;
876 }
877 
878 /* Return the next conversion of the conversion chain (if applicable),
879    or NULL otherwise.  Please use this function instead of directly
880    accessing fields of struct conversion.  */
881 
882 static conversion *
next_conversion(conversion * conv)883 next_conversion (conversion *conv)
884 {
885   if (conv == NULL
886       || !has_next (conv->kind))
887     return NULL;
888   return conv->u.next;
889 }
890 
891 /* Strip to the first ck_user, ck_ambig, ck_list, ck_aggr or ck_identity
892    encountered.  */
893 
894 static conversion *
strip_standard_conversion(conversion * conv)895 strip_standard_conversion (conversion *conv)
896 {
897   while (conv
898 	 && conv->kind != ck_user
899 	 && has_next (conv->kind))
900     conv = next_conversion (conv);
901   return conv;
902 }
903 
904 /* Subroutine of build_aggr_conv: check whether FROM is a valid aggregate
905    initializer for array type ATYPE.  */
906 
907 static bool
can_convert_array(tree atype,tree from,int flags,tsubst_flags_t complain)908 can_convert_array (tree atype, tree from, int flags, tsubst_flags_t complain)
909 {
910   tree elttype = TREE_TYPE (atype);
911   unsigned i;
912 
913   if (TREE_CODE (from) == CONSTRUCTOR)
914     {
915       for (i = 0; i < CONSTRUCTOR_NELTS (from); ++i)
916 	{
917 	  tree val = CONSTRUCTOR_ELT (from, i)->value;
918 	  bool ok;
919 	  if (TREE_CODE (elttype) == ARRAY_TYPE)
920 	    ok = can_convert_array (elttype, val, flags, complain);
921 	  else
922 	    ok = can_convert_arg (elttype, TREE_TYPE (val), val, flags,
923 				  complain);
924 	  if (!ok)
925 	    return false;
926 	}
927       return true;
928     }
929 
930   if (char_type_p (TYPE_MAIN_VARIANT (elttype))
931       && TREE_CODE (tree_strip_any_location_wrapper (from)) == STRING_CST)
932     return array_string_literal_compatible_p (atype, from);
933 
934   /* No other valid way to aggregate initialize an array.  */
935   return false;
936 }
937 
938 /* Helper for build_aggr_conv.  Return true if FIELD is in PSET, or if
939    FIELD has ANON_AGGR_TYPE_P and any initializable field in there recursively
940    is in PSET.  */
941 
942 static bool
field_in_pset(hash_set<tree,true> & pset,tree field)943 field_in_pset (hash_set<tree, true> &pset, tree field)
944 {
945   if (pset.contains (field))
946     return true;
947   if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
948     for (field = TYPE_FIELDS (TREE_TYPE (field));
949 	 field; field = DECL_CHAIN (field))
950       {
951 	field = next_initializable_field (field);
952 	if (field == NULL_TREE)
953 	  break;
954 	if (field_in_pset (pset, field))
955 	  return true;
956       }
957   return false;
958 }
959 
960 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
961    aggregate class, if such a conversion is possible.  */
962 
963 static conversion *
build_aggr_conv(tree type,tree ctor,int flags,tsubst_flags_t complain)964 build_aggr_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
965 {
966   unsigned HOST_WIDE_INT i = 0;
967   conversion *c;
968   tree field = next_initializable_field (TYPE_FIELDS (type));
969   tree empty_ctor = NULL_TREE;
970   hash_set<tree, true> pset;
971 
972   /* We already called reshape_init in implicit_conversion.  */
973 
974   /* The conversions within the init-list aren't affected by the enclosing
975      context; they're always simple copy-initialization.  */
976   flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
977 
978   /* For designated initializers, verify that each initializer is convertible
979      to corresponding TREE_TYPE (ce->index) and mark those FIELD_DECLs as
980      visited.  In the following loop then ignore already visited
981      FIELD_DECLs.  */
982   if (CONSTRUCTOR_IS_DESIGNATED_INIT (ctor))
983     {
984       tree idx, val;
985       FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, idx, val)
986 	{
987 	  if (idx && TREE_CODE (idx) == FIELD_DECL)
988 	    {
989 	      tree ftype = TREE_TYPE (idx);
990 	      bool ok;
991 
992 	      if (TREE_CODE (ftype) == ARRAY_TYPE)
993 		ok = can_convert_array (ftype, val, flags, complain);
994 	      else
995 		ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
996 				      complain);
997 
998 	      if (!ok)
999 		return NULL;
1000 	      /* For unions, there should be just one initializer.  */
1001 	      if (TREE_CODE (type) == UNION_TYPE)
1002 		{
1003 		  field = NULL_TREE;
1004 		  i = 1;
1005 		  break;
1006 		}
1007 	      pset.add (idx);
1008 	    }
1009 	  else
1010 	    return NULL;
1011 	}
1012     }
1013 
1014   for (; field; field = next_initializable_field (DECL_CHAIN (field)))
1015     {
1016       tree ftype = TREE_TYPE (field);
1017       tree val;
1018       bool ok;
1019 
1020       if (!pset.is_empty () && field_in_pset (pset, field))
1021 	continue;
1022       if (i < CONSTRUCTOR_NELTS (ctor))
1023 	{
1024 	  val = CONSTRUCTOR_ELT (ctor, i)->value;
1025 	  ++i;
1026 	}
1027       else if (DECL_INITIAL (field))
1028 	val = get_nsdmi (field, /*ctor*/false, complain);
1029       else if (TYPE_REF_P (ftype))
1030 	/* Value-initialization of reference is ill-formed.  */
1031 	return NULL;
1032       else
1033 	{
1034 	  if (empty_ctor == NULL_TREE)
1035 	    empty_ctor = build_constructor (init_list_type_node, NULL);
1036 	  val = empty_ctor;
1037 	}
1038 
1039       if (TREE_CODE (ftype) == ARRAY_TYPE)
1040 	ok = can_convert_array (ftype, val, flags, complain);
1041       else
1042 	ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1043 			      complain);
1044 
1045       if (!ok)
1046 	return NULL;
1047 
1048       if (TREE_CODE (type) == UNION_TYPE)
1049 	break;
1050     }
1051 
1052   if (i < CONSTRUCTOR_NELTS (ctor))
1053     return NULL;
1054 
1055   c = alloc_conversion (ck_aggr);
1056   c->type = type;
1057   c->rank = cr_exact;
1058   c->user_conv_p = true;
1059   c->check_narrowing = true;
1060   c->u.expr = ctor;
1061   return c;
1062 }
1063 
1064 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
1065    array type, if such a conversion is possible.  */
1066 
1067 static conversion *
build_array_conv(tree type,tree ctor,int flags,tsubst_flags_t complain)1068 build_array_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
1069 {
1070   conversion *c;
1071   unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1072   tree elttype = TREE_TYPE (type);
1073   bool bad = false;
1074   bool user = false;
1075   enum conversion_rank rank = cr_exact;
1076 
1077   /* We might need to propagate the size from the element to the array.  */
1078   complete_type (type);
1079 
1080   if (TYPE_DOMAIN (type)
1081       && !variably_modified_type_p (TYPE_DOMAIN (type), NULL_TREE))
1082     {
1083       unsigned HOST_WIDE_INT alen = tree_to_uhwi (array_type_nelts_top (type));
1084       if (alen < len)
1085 	return NULL;
1086     }
1087 
1088   flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1089 
1090   for (auto &e: CONSTRUCTOR_ELTS (ctor))
1091     {
1092       conversion *sub
1093 	= implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1094 			       false, flags, complain);
1095       if (sub == NULL)
1096 	return NULL;
1097 
1098       if (sub->rank > rank)
1099 	rank = sub->rank;
1100       if (sub->user_conv_p)
1101 	user = true;
1102       if (sub->bad_p)
1103 	bad = true;
1104     }
1105 
1106   c = alloc_conversion (ck_aggr);
1107   c->type = type;
1108   c->rank = rank;
1109   c->user_conv_p = user;
1110   c->bad_p = bad;
1111   c->u.expr = ctor;
1112   return c;
1113 }
1114 
1115 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
1116    complex type, if such a conversion is possible.  */
1117 
1118 static conversion *
build_complex_conv(tree type,tree ctor,int flags,tsubst_flags_t complain)1119 build_complex_conv (tree type, tree ctor, int flags,
1120 		    tsubst_flags_t complain)
1121 {
1122   conversion *c;
1123   unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1124   tree elttype = TREE_TYPE (type);
1125   bool bad = false;
1126   bool user = false;
1127   enum conversion_rank rank = cr_exact;
1128 
1129   if (len != 2)
1130     return NULL;
1131 
1132   flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1133 
1134   for (auto &e: CONSTRUCTOR_ELTS (ctor))
1135     {
1136       conversion *sub
1137 	= implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1138 			       false, flags, complain);
1139       if (sub == NULL)
1140 	return NULL;
1141 
1142       if (sub->rank > rank)
1143 	rank = sub->rank;
1144       if (sub->user_conv_p)
1145 	user = true;
1146       if (sub->bad_p)
1147 	bad = true;
1148     }
1149 
1150   c = alloc_conversion (ck_aggr);
1151   c->type = type;
1152   c->rank = rank;
1153   c->user_conv_p = user;
1154   c->bad_p = bad;
1155   c->u.expr = ctor;
1156   return c;
1157 }
1158 
1159 /* Build a representation of the identity conversion from EXPR to
1160    itself.  The TYPE should match the type of EXPR, if EXPR is non-NULL.  */
1161 
1162 static conversion *
build_identity_conv(tree type,tree expr)1163 build_identity_conv (tree type, tree expr)
1164 {
1165   conversion *c;
1166 
1167   c = alloc_conversion (ck_identity);
1168   c->type = type;
1169   c->u.expr = expr;
1170 
1171   return c;
1172 }
1173 
1174 /* Converting from EXPR to TYPE was ambiguous in the sense that there
1175    were multiple user-defined conversions to accomplish the job.
1176    Build a conversion that indicates that ambiguity.  */
1177 
1178 static conversion *
build_ambiguous_conv(tree type,tree expr)1179 build_ambiguous_conv (tree type, tree expr)
1180 {
1181   conversion *c;
1182 
1183   c = alloc_conversion (ck_ambig);
1184   c->type = type;
1185   c->u.expr = expr;
1186 
1187   return c;
1188 }
1189 
1190 tree
strip_top_quals(tree t)1191 strip_top_quals (tree t)
1192 {
1193   if (TREE_CODE (t) == ARRAY_TYPE)
1194     return t;
1195   return cp_build_qualified_type (t, 0);
1196 }
1197 
1198 /* Returns the standard conversion path (see [conv]) from type FROM to type
1199    TO, if any.  For proper handling of null pointer constants, you must
1200    also pass the expression EXPR to convert from.  If C_CAST_P is true,
1201    this conversion is coming from a C-style cast.  */
1202 
1203 static conversion *
standard_conversion(tree to,tree from,tree expr,bool c_cast_p,int flags,tsubst_flags_t complain)1204 standard_conversion (tree to, tree from, tree expr, bool c_cast_p,
1205 		     int flags, tsubst_flags_t complain)
1206 {
1207   enum tree_code fcode, tcode;
1208   conversion *conv;
1209   bool fromref = false;
1210   tree qualified_to;
1211 
1212   to = non_reference (to);
1213   if (TYPE_REF_P (from))
1214     {
1215       fromref = true;
1216       from = TREE_TYPE (from);
1217     }
1218   qualified_to = to;
1219   to = strip_top_quals (to);
1220   from = strip_top_quals (from);
1221 
1222   if (expr && type_unknown_p (expr))
1223     {
1224       if (TYPE_PTRFN_P (to) || TYPE_PTRMEMFUNC_P (to))
1225 	{
1226 	  tsubst_flags_t tflags = tf_conv;
1227 	  expr = instantiate_type (to, expr, tflags);
1228 	  if (expr == error_mark_node)
1229 	    return NULL;
1230 	  from = TREE_TYPE (expr);
1231 	}
1232       else if (TREE_CODE (to) == BOOLEAN_TYPE)
1233 	{
1234 	  /* Necessary for eg, TEMPLATE_ID_EXPRs (c++/50961).  */
1235 	  expr = resolve_nondeduced_context (expr, complain);
1236 	  from = TREE_TYPE (expr);
1237 	}
1238     }
1239 
1240   fcode = TREE_CODE (from);
1241   tcode = TREE_CODE (to);
1242 
1243   conv = build_identity_conv (from, expr);
1244   if (fcode == FUNCTION_TYPE || fcode == ARRAY_TYPE)
1245     {
1246       from = type_decays_to (from);
1247       fcode = TREE_CODE (from);
1248       /* Tell convert_like that we're using the address.  */
1249       conv->rvaluedness_matches_p = true;
1250       conv = build_conv (ck_lvalue, from, conv);
1251     }
1252   /* Wrapping a ck_rvalue around a class prvalue (as a result of using
1253      obvalue_p) seems odd, since it's already a prvalue, but that's how we
1254      express the copy constructor call required by copy-initialization.  */
1255   else if (fromref || (expr && obvalue_p (expr)))
1256     {
1257       if (expr)
1258 	{
1259 	  tree bitfield_type;
1260 	  bitfield_type = is_bitfield_expr_with_lowered_type (expr);
1261 	  if (bitfield_type)
1262 	    {
1263 	      from = strip_top_quals (bitfield_type);
1264 	      fcode = TREE_CODE (from);
1265 	    }
1266 	}
1267       conv = build_conv (ck_rvalue, from, conv);
1268       if (flags & LOOKUP_PREFER_RVALUE)
1269 	/* Tell convert_like to set LOOKUP_PREFER_RVALUE.  */
1270 	conv->rvaluedness_matches_p = true;
1271       /* If we're performing copy-initialization, remember to skip
1272 	 explicit constructors.  */
1273       if (flags & LOOKUP_ONLYCONVERTING)
1274 	conv->copy_init_p = true;
1275     }
1276 
1277    /* Allow conversion between `__complex__' data types.  */
1278   if (tcode == COMPLEX_TYPE && fcode == COMPLEX_TYPE)
1279     {
1280       /* The standard conversion sequence to convert FROM to TO is
1281 	 the standard conversion sequence to perform componentwise
1282 	 conversion.  */
1283       conversion *part_conv = standard_conversion
1284 	(TREE_TYPE (to), TREE_TYPE (from), NULL_TREE, c_cast_p, flags,
1285 	 complain);
1286 
1287       if (!part_conv)
1288 	conv = NULL;
1289       else if (part_conv->kind == ck_identity)
1290 	/* Leave conv alone.  */;
1291       else
1292 	{
1293 	  conv = build_conv (part_conv->kind, to, conv);
1294 	  conv->rank = part_conv->rank;
1295 	}
1296 
1297       return conv;
1298     }
1299 
1300   if (same_type_p (from, to))
1301     {
1302       if (CLASS_TYPE_P (to) && conv->kind == ck_rvalue)
1303 	conv->type = qualified_to;
1304       return conv;
1305     }
1306 
1307   /* [conv.ptr]
1308      A null pointer constant can be converted to a pointer type; ... A
1309      null pointer constant of integral type can be converted to an
1310      rvalue of type std::nullptr_t. */
1311   if ((tcode == POINTER_TYPE || TYPE_PTRMEM_P (to)
1312        || NULLPTR_TYPE_P (to))
1313       && ((expr && null_ptr_cst_p (expr))
1314 	  || NULLPTR_TYPE_P (from)))
1315     conv = build_conv (ck_std, to, conv);
1316   else if ((tcode == INTEGER_TYPE && fcode == POINTER_TYPE)
1317 	   || (tcode == POINTER_TYPE && fcode == INTEGER_TYPE))
1318     {
1319       /* For backwards brain damage compatibility, allow interconversion of
1320 	 pointers and integers with a pedwarn.  */
1321       conv = build_conv (ck_std, to, conv);
1322       conv->bad_p = true;
1323     }
1324   else if (UNSCOPED_ENUM_P (to) && fcode == INTEGER_TYPE)
1325     {
1326       /* For backwards brain damage compatibility, allow interconversion of
1327 	 enums and integers with a pedwarn.  */
1328       conv = build_conv (ck_std, to, conv);
1329       conv->bad_p = true;
1330     }
1331   else if ((tcode == POINTER_TYPE && fcode == POINTER_TYPE)
1332 	   || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from)))
1333     {
1334       tree to_pointee;
1335       tree from_pointee;
1336 
1337       if (tcode == POINTER_TYPE)
1338 	{
1339 	  to_pointee = TREE_TYPE (to);
1340 	  from_pointee = TREE_TYPE (from);
1341 
1342 	  /* Since this is the target of a pointer, it can't have function
1343 	     qualifiers, so any TYPE_QUALS must be for attributes const or
1344 	     noreturn.  Strip them.  */
1345 	  if (TREE_CODE (to_pointee) == FUNCTION_TYPE
1346 	      && TYPE_QUALS (to_pointee))
1347 	    to_pointee = build_qualified_type (to_pointee, TYPE_UNQUALIFIED);
1348 	  if (TREE_CODE (from_pointee) == FUNCTION_TYPE
1349 	      && TYPE_QUALS (from_pointee))
1350 	    from_pointee = build_qualified_type (from_pointee, TYPE_UNQUALIFIED);
1351 	}
1352       else
1353 	{
1354 	  to_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (to);
1355 	  from_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (from);
1356 	}
1357 
1358       if (tcode == POINTER_TYPE
1359 	  && same_type_ignoring_top_level_qualifiers_p (from_pointee,
1360 							to_pointee))
1361 	;
1362       else if (VOID_TYPE_P (to_pointee)
1363 	       && !TYPE_PTRDATAMEM_P (from)
1364 	       && TREE_CODE (from_pointee) != FUNCTION_TYPE)
1365 	{
1366 	  tree nfrom = TREE_TYPE (from);
1367 	  /* Don't try to apply restrict to void.  */
1368 	  int quals = cp_type_quals (nfrom) & ~TYPE_QUAL_RESTRICT;
1369 	  from_pointee = cp_build_qualified_type (void_type_node, quals);
1370 	  from = build_pointer_type (from_pointee);
1371 	  conv = build_conv (ck_ptr, from, conv);
1372 	}
1373       else if (TYPE_PTRDATAMEM_P (from))
1374 	{
1375 	  tree fbase = TYPE_PTRMEM_CLASS_TYPE (from);
1376 	  tree tbase = TYPE_PTRMEM_CLASS_TYPE (to);
1377 
1378 	  if (same_type_p (fbase, tbase))
1379 	    /* No base conversion needed.  */;
1380 	  else if (DERIVED_FROM_P (fbase, tbase)
1381 		   && (same_type_ignoring_top_level_qualifiers_p
1382 		       (from_pointee, to_pointee)))
1383 	    {
1384 	      from = build_ptrmem_type (tbase, from_pointee);
1385 	      conv = build_conv (ck_pmem, from, conv);
1386 	    }
1387 	  else
1388 	    return NULL;
1389 	}
1390       else if (CLASS_TYPE_P (from_pointee)
1391 	       && CLASS_TYPE_P (to_pointee)
1392 	       /* [conv.ptr]
1393 
1394 		  An rvalue of type "pointer to cv D," where D is a
1395 		  class type, can be converted to an rvalue of type
1396 		  "pointer to cv B," where B is a base class (clause
1397 		  _class.derived_) of D.  If B is an inaccessible
1398 		  (clause _class.access_) or ambiguous
1399 		  (_class.member.lookup_) base class of D, a program
1400 		  that necessitates this conversion is ill-formed.
1401 		  Therefore, we use DERIVED_FROM_P, and do not check
1402 		  access or uniqueness.  */
1403 	       && DERIVED_FROM_P (to_pointee, from_pointee))
1404 	{
1405 	  from_pointee
1406 	    = cp_build_qualified_type (to_pointee,
1407 				       cp_type_quals (from_pointee));
1408 	  from = build_pointer_type (from_pointee);
1409 	  conv = build_conv (ck_ptr, from, conv);
1410 	  conv->base_p = true;
1411 	}
1412 
1413       if (same_type_p (from, to))
1414 	/* OK */;
1415       else if (c_cast_p && comp_ptr_ttypes_const (to, from, bounds_either))
1416 	/* In a C-style cast, we ignore CV-qualification because we
1417 	   are allowed to perform a static_cast followed by a
1418 	   const_cast.  */
1419 	conv = build_conv (ck_qual, to, conv);
1420       else if (!c_cast_p && comp_ptr_ttypes (to_pointee, from_pointee))
1421 	conv = build_conv (ck_qual, to, conv);
1422       else if (expr && string_conv_p (to, expr, 0))
1423 	/* converting from string constant to char *.  */
1424 	conv = build_conv (ck_qual, to, conv);
1425       else if (fnptr_conv_p (to, from))
1426 	conv = build_conv (ck_fnptr, to, conv);
1427       /* Allow conversions among compatible ObjC pointer types (base
1428 	 conversions have been already handled above).  */
1429       else if (c_dialect_objc ()
1430 	       && objc_compare_types (to, from, -4, NULL_TREE))
1431 	conv = build_conv (ck_ptr, to, conv);
1432       else if (ptr_reasonably_similar (to_pointee, from_pointee))
1433 	{
1434 	  conv = build_conv (ck_ptr, to, conv);
1435 	  conv->bad_p = true;
1436 	}
1437       else
1438 	return NULL;
1439 
1440       from = to;
1441     }
1442   else if (TYPE_PTRMEMFUNC_P (to) && TYPE_PTRMEMFUNC_P (from))
1443     {
1444       tree fromfn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (from));
1445       tree tofn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (to));
1446       tree fbase = class_of_this_parm (fromfn);
1447       tree tbase = class_of_this_parm (tofn);
1448 
1449       /* If FBASE and TBASE are equivalent but incomplete, DERIVED_FROM_P
1450 	 yields false.  But a pointer to member of incomplete class is OK.  */
1451       if (!same_type_p (fbase, tbase) && !DERIVED_FROM_P (fbase, tbase))
1452 	return NULL;
1453 
1454       tree fstat = static_fn_type (fromfn);
1455       tree tstat = static_fn_type (tofn);
1456       if (same_type_p (tstat, fstat)
1457 	  || fnptr_conv_p (tstat, fstat))
1458 	/* OK */;
1459       else
1460 	return NULL;
1461 
1462       if (!same_type_p (fbase, tbase))
1463 	{
1464 	  from = build_memfn_type (fstat,
1465 				   tbase,
1466 				   cp_type_quals (tbase),
1467 				   type_memfn_rqual (tofn));
1468 	  from = build_ptrmemfunc_type (build_pointer_type (from));
1469 	  conv = build_conv (ck_pmem, from, conv);
1470 	  conv->base_p = true;
1471 	}
1472       if (fnptr_conv_p (tstat, fstat))
1473 	conv = build_conv (ck_fnptr, to, conv);
1474     }
1475   else if (tcode == BOOLEAN_TYPE)
1476     {
1477       /* [conv.bool]
1478 
1479 	  A prvalue of arithmetic, unscoped enumeration, pointer, or pointer
1480 	  to member type can be converted to a prvalue of type bool. ...
1481 	  For direct-initialization (8.5 [dcl.init]), a prvalue of type
1482 	  std::nullptr_t can be converted to a prvalue of type bool;  */
1483       if (ARITHMETIC_TYPE_P (from)
1484 	  || UNSCOPED_ENUM_P (from)
1485 	  || fcode == POINTER_TYPE
1486 	  || TYPE_PTRMEM_P (from)
1487 	  || NULLPTR_TYPE_P (from))
1488 	{
1489 	  conv = build_conv (ck_std, to, conv);
1490 	  if (fcode == POINTER_TYPE
1491 	      || TYPE_PTRDATAMEM_P (from)
1492 	      || (TYPE_PTRMEMFUNC_P (from)
1493 		  && conv->rank < cr_pbool)
1494 	      || NULLPTR_TYPE_P (from))
1495 	    conv->rank = cr_pbool;
1496 	  if (NULLPTR_TYPE_P (from) && (flags & LOOKUP_ONLYCONVERTING))
1497 	    conv->bad_p = true;
1498 	  if (flags & LOOKUP_NO_NARROWING)
1499 	    conv->check_narrowing = true;
1500 	  return conv;
1501 	}
1502 
1503       return NULL;
1504     }
1505   /* We don't check for ENUMERAL_TYPE here because there are no standard
1506      conversions to enum type.  */
1507   /* As an extension, allow conversion to complex type.  */
1508   else if (ARITHMETIC_TYPE_P (to))
1509     {
1510       if (! (INTEGRAL_CODE_P (fcode)
1511 	     || (fcode == REAL_TYPE && !(flags & LOOKUP_NO_NON_INTEGRAL)))
1512           || SCOPED_ENUM_P (from))
1513 	return NULL;
1514 
1515       /* If we're parsing an enum with no fixed underlying type, we're
1516 	 dealing with an incomplete type, which renders the conversion
1517 	 ill-formed.  */
1518       if (!COMPLETE_TYPE_P (from))
1519 	return NULL;
1520 
1521       conv = build_conv (ck_std, to, conv);
1522 
1523       tree underlying_type = NULL_TREE;
1524       if (TREE_CODE (from) == ENUMERAL_TYPE
1525 	  && ENUM_FIXED_UNDERLYING_TYPE_P (from))
1526 	underlying_type = ENUM_UNDERLYING_TYPE (from);
1527 
1528       /* Give this a better rank if it's a promotion.
1529 
1530 	 To handle CWG 1601, also bump the rank if we are converting
1531 	 an enumeration with a fixed underlying type to the underlying
1532 	 type.  */
1533       if ((same_type_p (to, type_promotes_to (from))
1534 	   || (underlying_type && same_type_p (to, underlying_type)))
1535 	  && next_conversion (conv)->rank <= cr_promotion)
1536 	conv->rank = cr_promotion;
1537     }
1538   else if (fcode == VECTOR_TYPE && tcode == VECTOR_TYPE
1539 	   && vector_types_convertible_p (from, to, false))
1540     return build_conv (ck_std, to, conv);
1541   else if (MAYBE_CLASS_TYPE_P (to) && MAYBE_CLASS_TYPE_P (from)
1542 	   && is_properly_derived_from (from, to))
1543     {
1544       if (conv->kind == ck_rvalue)
1545 	conv = next_conversion (conv);
1546       conv = build_conv (ck_base, to, conv);
1547       /* The derived-to-base conversion indicates the initialization
1548 	 of a parameter with base type from an object of a derived
1549 	 type.  A temporary object is created to hold the result of
1550 	 the conversion unless we're binding directly to a reference.  */
1551       conv->need_temporary_p = !(flags & LOOKUP_NO_TEMP_BIND);
1552       if (flags & LOOKUP_PREFER_RVALUE)
1553 	/* Tell convert_like to set LOOKUP_PREFER_RVALUE.  */
1554 	conv->rvaluedness_matches_p = true;
1555       /* If we're performing copy-initialization, remember to skip
1556 	 explicit constructors.  */
1557       if (flags & LOOKUP_ONLYCONVERTING)
1558 	conv->copy_init_p = true;
1559     }
1560   else
1561     return NULL;
1562 
1563   if (flags & LOOKUP_NO_NARROWING)
1564     conv->check_narrowing = true;
1565 
1566   return conv;
1567 }
1568 
1569 /* Returns nonzero if T1 is reference-related to T2.  */
1570 
1571 bool
reference_related_p(tree t1,tree t2)1572 reference_related_p (tree t1, tree t2)
1573 {
1574   if (t1 == error_mark_node || t2 == error_mark_node)
1575     return false;
1576 
1577   t1 = TYPE_MAIN_VARIANT (t1);
1578   t2 = TYPE_MAIN_VARIANT (t2);
1579 
1580   /* [dcl.init.ref]
1581 
1582      Given types "cv1 T1" and "cv2 T2," "cv1 T1" is reference-related
1583      to "cv2 T2" if T1 is similar to T2, or T1 is a base class of T2.  */
1584   return (similar_type_p (t1, t2)
1585 	  || (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
1586 	      && DERIVED_FROM_P (t1, t2)));
1587 }
1588 
1589 /* Returns nonzero if T1 is reference-compatible with T2.  */
1590 
1591 bool
reference_compatible_p(tree t1,tree t2)1592 reference_compatible_p (tree t1, tree t2)
1593 {
1594   /* [dcl.init.ref]
1595 
1596      "cv1 T1" is reference compatible with "cv2 T2" if
1597      a prvalue of type "pointer to cv2 T2" can be converted to the type
1598      "pointer to cv1 T1" via a standard conversion sequence.  */
1599   tree ptype1 = build_pointer_type (t1);
1600   tree ptype2 = build_pointer_type (t2);
1601   conversion *conv = standard_conversion (ptype1, ptype2, NULL_TREE,
1602 					  /*c_cast_p=*/false, 0, tf_none);
1603   if (!conv || conv->bad_p)
1604     return false;
1605   return true;
1606 }
1607 
1608 /* Return true if converting FROM to TO would involve a qualification
1609    conversion.  */
1610 
1611 static bool
involves_qualification_conversion_p(tree to,tree from)1612 involves_qualification_conversion_p (tree to, tree from)
1613 {
1614   /* If we're not convering a pointer to another one, we won't get
1615      a qualification conversion.  */
1616   if (!((TYPE_PTR_P (to) && TYPE_PTR_P (from))
1617 	|| (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from))))
1618     return false;
1619 
1620   conversion *conv = standard_conversion (to, from, NULL_TREE,
1621 					  /*c_cast_p=*/false, 0, tf_none);
1622   for (conversion *t = conv; t; t = next_conversion (t))
1623     if (t->kind == ck_qual)
1624       return true;
1625 
1626   return false;
1627 }
1628 
1629 /* A reference of the indicated TYPE is being bound directly to the
1630    expression represented by the implicit conversion sequence CONV.
1631    Return a conversion sequence for this binding.  */
1632 
1633 static conversion *
direct_reference_binding(tree type,conversion * conv)1634 direct_reference_binding (tree type, conversion *conv)
1635 {
1636   tree t;
1637 
1638   gcc_assert (TYPE_REF_P (type));
1639   gcc_assert (!TYPE_REF_P (conv->type));
1640 
1641   t = TREE_TYPE (type);
1642 
1643   if (conv->kind == ck_identity)
1644     /* Mark the identity conv as to not decay to rvalue.  */
1645     conv->rvaluedness_matches_p = true;
1646 
1647   /* [over.ics.rank]
1648 
1649      When a parameter of reference type binds directly
1650      (_dcl.init.ref_) to an argument expression, the implicit
1651      conversion sequence is the identity conversion, unless the
1652      argument expression has a type that is a derived class of the
1653      parameter type, in which case the implicit conversion sequence is
1654      a derived-to-base Conversion.
1655 
1656      If the parameter binds directly to the result of applying a
1657      conversion function to the argument expression, the implicit
1658      conversion sequence is a user-defined conversion sequence
1659      (_over.ics.user_), with the second standard conversion sequence
1660      either an identity conversion or, if the conversion function
1661      returns an entity of a type that is a derived class of the
1662      parameter type, a derived-to-base conversion.  */
1663   if (is_properly_derived_from (conv->type, t))
1664     {
1665       /* Represent the derived-to-base conversion.  */
1666       conv = build_conv (ck_base, t, conv);
1667       /* We will actually be binding to the base-class subobject in
1668 	 the derived class, so we mark this conversion appropriately.
1669 	 That way, convert_like knows not to generate a temporary.  */
1670       conv->need_temporary_p = false;
1671     }
1672   else if (involves_qualification_conversion_p (t, conv->type))
1673     /* Represent the qualification conversion.  After DR 2352
1674        #1 and #2 were indistinguishable conversion sequences:
1675 
1676 	 void f(int*); // #1
1677 	 void f(const int* const &); // #2
1678 	 void g(int* p) { f(p); }
1679 
1680        because the types "int *" and "const int *const" are
1681        reference-related and we were binding both directly and they
1682        had the same rank.  To break it up, we add a ck_qual under the
1683        ck_ref_bind so that conversion sequence ranking chooses #1.  */
1684     conv = build_conv (ck_qual, t, conv);
1685 
1686   return build_conv (ck_ref_bind, type, conv);
1687 }
1688 
1689 /* Returns the conversion path from type FROM to reference type TO for
1690    purposes of reference binding.  For lvalue binding, either pass a
1691    reference type to FROM or an lvalue expression to EXPR.  If the
1692    reference will be bound to a temporary, NEED_TEMPORARY_P is set for
1693    the conversion returned.  If C_CAST_P is true, this
1694    conversion is coming from a C-style cast.  */
1695 
1696 static conversion *
reference_binding(tree rto,tree rfrom,tree expr,bool c_cast_p,int flags,tsubst_flags_t complain)1697 reference_binding (tree rto, tree rfrom, tree expr, bool c_cast_p, int flags,
1698 		   tsubst_flags_t complain)
1699 {
1700   conversion *conv = NULL;
1701   tree to = TREE_TYPE (rto);
1702   tree from = rfrom;
1703   tree tfrom;
1704   bool related_p;
1705   bool compatible_p;
1706   cp_lvalue_kind gl_kind;
1707   bool is_lvalue;
1708 
1709   if (TREE_CODE (to) == FUNCTION_TYPE && expr && type_unknown_p (expr))
1710     {
1711       expr = instantiate_type (to, expr, tf_none);
1712       if (expr == error_mark_node)
1713 	return NULL;
1714       from = TREE_TYPE (expr);
1715     }
1716 
1717   bool copy_list_init = false;
1718   if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1719     {
1720       maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
1721       /* DR 1288: Otherwise, if the initializer list has a single element
1722 	 of type E and ... [T's] referenced type is reference-related to E,
1723 	 the object or reference is initialized from that element...
1724 
1725 	 ??? With P0388R4, we should bind 't' directly to U{}:
1726 	   using U = A[2];
1727 	   A (&&t)[] = {U{}};
1728 	 because A[] and A[2] are reference-related.  But we don't do it
1729 	 because grok_reference_init has deduced the array size (to 1), and
1730 	 A[1] and A[2] aren't reference-related.  */
1731       if (CONSTRUCTOR_NELTS (expr) == 1
1732 	  && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
1733 	{
1734 	  tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
1735 	  if (error_operand_p (elt))
1736 	    return NULL;
1737 	  tree etype = TREE_TYPE (elt);
1738 	  if (reference_related_p (to, etype))
1739 	    {
1740 	      expr = elt;
1741 	      from = etype;
1742 	      goto skip;
1743 	    }
1744 	}
1745       /* Otherwise, if T is a reference type, a prvalue temporary of the type
1746 	 referenced by T is copy-list-initialized, and the reference is bound
1747 	 to that temporary. */
1748       copy_list_init = true;
1749     skip:;
1750     }
1751 
1752   if (TYPE_REF_P (from))
1753     {
1754       from = TREE_TYPE (from);
1755       if (!TYPE_REF_IS_RVALUE (rfrom)
1756 	  || TREE_CODE (from) == FUNCTION_TYPE)
1757 	gl_kind = clk_ordinary;
1758       else
1759 	gl_kind = clk_rvalueref;
1760     }
1761   else if (expr)
1762     gl_kind = lvalue_kind (expr);
1763   else if (CLASS_TYPE_P (from)
1764 	   || TREE_CODE (from) == ARRAY_TYPE)
1765     gl_kind = clk_class;
1766   else
1767     gl_kind = clk_none;
1768 
1769   /* Don't allow a class prvalue when LOOKUP_NO_TEMP_BIND.  */
1770   if ((flags & LOOKUP_NO_TEMP_BIND)
1771       && (gl_kind & clk_class))
1772     gl_kind = clk_none;
1773 
1774   /* Same mask as real_lvalue_p.  */
1775   is_lvalue = gl_kind && !(gl_kind & (clk_rvalueref|clk_class));
1776 
1777   tfrom = from;
1778   if ((gl_kind & clk_bitfield) != 0)
1779     tfrom = unlowered_expr_type (expr);
1780 
1781   /* Figure out whether or not the types are reference-related and
1782      reference compatible.  We have to do this after stripping
1783      references from FROM.  */
1784   related_p = reference_related_p (to, tfrom);
1785   /* If this is a C cast, first convert to an appropriately qualified
1786      type, so that we can later do a const_cast to the desired type.  */
1787   if (related_p && c_cast_p
1788       && !at_least_as_qualified_p (to, tfrom))
1789     to = cp_build_qualified_type (to, cp_type_quals (tfrom));
1790   compatible_p = reference_compatible_p (to, tfrom);
1791 
1792   /* Directly bind reference when target expression's type is compatible with
1793      the reference and expression is an lvalue. In DR391, the wording in
1794      [8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
1795      const and rvalue references to rvalues of compatible class type.
1796      We should also do direct bindings for non-class xvalues.  */
1797   if ((related_p || compatible_p) && gl_kind)
1798     {
1799       /* [dcl.init.ref]
1800 
1801 	 If the initializer expression
1802 
1803 	 -- is an lvalue (but not an lvalue for a bit-field), and "cv1 T1"
1804 	    is reference-compatible with "cv2 T2,"
1805 
1806 	 the reference is bound directly to the initializer expression
1807 	 lvalue.
1808 
1809 	 [...]
1810 	 If the initializer expression is an rvalue, with T2 a class type,
1811 	 and "cv1 T1" is reference-compatible with "cv2 T2", the reference
1812 	 is bound to the object represented by the rvalue or to a sub-object
1813 	 within that object.  */
1814 
1815       conv = build_identity_conv (tfrom, expr);
1816       conv = direct_reference_binding (rto, conv);
1817 
1818       if (TYPE_REF_P (rfrom))
1819 	/* Handle rvalue reference to function properly.  */
1820 	conv->rvaluedness_matches_p
1821 	  = (TYPE_REF_IS_RVALUE (rto) == TYPE_REF_IS_RVALUE (rfrom));
1822       else
1823 	conv->rvaluedness_matches_p
1824           = (TYPE_REF_IS_RVALUE (rto) == !is_lvalue);
1825 
1826       if ((gl_kind & clk_bitfield) != 0
1827 	  || ((gl_kind & clk_packed) != 0 && !TYPE_PACKED (to)))
1828 	/* For the purposes of overload resolution, we ignore the fact
1829 	   this expression is a bitfield or packed field. (In particular,
1830 	   [over.ics.ref] says specifically that a function with a
1831 	   non-const reference parameter is viable even if the
1832 	   argument is a bitfield.)
1833 
1834 	   However, when we actually call the function we must create
1835 	   a temporary to which to bind the reference.  If the
1836 	   reference is volatile, or isn't const, then we cannot make
1837 	   a temporary, so we just issue an error when the conversion
1838 	   actually occurs.  */
1839 	conv->need_temporary_p = true;
1840 
1841       /* Don't allow binding of lvalues (other than function lvalues) to
1842 	 rvalue references.  */
1843       if (is_lvalue && TYPE_REF_IS_RVALUE (rto)
1844 	  && TREE_CODE (to) != FUNCTION_TYPE)
1845 	conv->bad_p = true;
1846 
1847       /* Nor the reverse.  */
1848       if (!is_lvalue && !TYPE_REF_IS_RVALUE (rto)
1849 	  /* Unless it's really an lvalue.  */
1850 	  && !(cxx_dialect >= cxx20
1851 	       && (gl_kind & clk_implicit_rval))
1852 	  && (!CP_TYPE_CONST_NON_VOLATILE_P (to)
1853 	      || (flags & LOOKUP_NO_RVAL_BIND))
1854 	  && TREE_CODE (to) != FUNCTION_TYPE)
1855 	conv->bad_p = true;
1856 
1857       if (!compatible_p)
1858 	conv->bad_p = true;
1859 
1860       return conv;
1861     }
1862   /* [class.conv.fct] A conversion function is never used to convert a
1863      (possibly cv-qualified) object to the (possibly cv-qualified) same
1864      object type (or a reference to it), to a (possibly cv-qualified) base
1865      class of that type (or a reference to it).... */
1866   else if (CLASS_TYPE_P (from) && !related_p
1867 	   && !(flags & LOOKUP_NO_CONVERSION))
1868     {
1869       /* [dcl.init.ref]
1870 
1871 	 If the initializer expression
1872 
1873 	 -- has a class type (i.e., T2 is a class type) can be
1874 	    implicitly converted to an lvalue of type "cv3 T3," where
1875 	    "cv1 T1" is reference-compatible with "cv3 T3".  (this
1876 	    conversion is selected by enumerating the applicable
1877 	    conversion functions (_over.match.ref_) and choosing the
1878 	    best one through overload resolution.  (_over.match_).
1879 
1880 	the reference is bound to the lvalue result of the conversion
1881 	in the second case.  */
1882       z_candidate *cand = build_user_type_conversion_1 (rto, expr, flags,
1883 							complain);
1884       if (cand)
1885 	return cand->second_conv;
1886     }
1887 
1888   /* From this point on, we conceptually need temporaries, even if we
1889      elide them.  Only the cases above are "direct bindings".  */
1890   if (flags & LOOKUP_NO_TEMP_BIND)
1891     return NULL;
1892 
1893   /* [over.ics.rank]
1894 
1895      When a parameter of reference type is not bound directly to an
1896      argument expression, the conversion sequence is the one required
1897      to convert the argument expression to the underlying type of the
1898      reference according to _over.best.ics_.  Conceptually, this
1899      conversion sequence corresponds to copy-initializing a temporary
1900      of the underlying type with the argument expression.  Any
1901      difference in top-level cv-qualification is subsumed by the
1902      initialization itself and does not constitute a conversion.  */
1903 
1904   /* [dcl.init.ref]
1905 
1906      Otherwise, the reference shall be an lvalue reference to a
1907      non-volatile const type, or the reference shall be an rvalue
1908      reference.
1909 
1910      We try below to treat this as a bad conversion to improve diagnostics,
1911      but if TO is an incomplete class, we need to reject this conversion
1912      now to avoid unnecessary instantiation.  */
1913   if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto)
1914       && !COMPLETE_TYPE_P (to))
1915     return NULL;
1916 
1917   /* We're generating a temporary now, but don't bind any more in the
1918      conversion (specifically, don't slice the temporary returned by a
1919      conversion operator).  */
1920   flags |= LOOKUP_NO_TEMP_BIND;
1921 
1922   /* Core issue 899: When [copy-]initializing a temporary to be bound
1923      to the first parameter of a copy constructor (12.8) called with
1924      a single argument in the context of direct-initialization,
1925      explicit conversion functions are also considered.
1926 
1927      So don't set LOOKUP_ONLYCONVERTING in that case.  */
1928   if (!(flags & LOOKUP_COPY_PARM))
1929     flags |= LOOKUP_ONLYCONVERTING;
1930 
1931   if (!conv)
1932     conv = implicit_conversion (to, from, expr, c_cast_p,
1933 				flags, complain);
1934   if (!conv)
1935     return NULL;
1936 
1937   if (conv->user_conv_p)
1938     {
1939       if (copy_list_init)
1940 	/* Remember this was copy-list-initialization.  */
1941 	conv->need_temporary_p = true;
1942 
1943       /* If initializing the temporary used a conversion function,
1944 	 recalculate the second conversion sequence.  */
1945       for (conversion *t = conv; t; t = next_conversion (t))
1946 	if (t->kind == ck_user
1947 	    && DECL_CONV_FN_P (t->cand->fn))
1948 	  {
1949 	    tree ftype = TREE_TYPE (TREE_TYPE (t->cand->fn));
1950 	    /* A prvalue of non-class type is cv-unqualified.  */
1951 	    if (!TYPE_REF_P (ftype) && !CLASS_TYPE_P (ftype))
1952 	      ftype = cv_unqualified (ftype);
1953 	    int sflags = (flags|LOOKUP_NO_CONVERSION)&~LOOKUP_NO_TEMP_BIND;
1954 	    conversion *new_second
1955 	      = reference_binding (rto, ftype, NULL_TREE, c_cast_p,
1956 				   sflags, complain);
1957 	    if (!new_second)
1958 	      return NULL;
1959 	    return merge_conversion_sequences (t, new_second);
1960 	  }
1961     }
1962 
1963   conv = build_conv (ck_ref_bind, rto, conv);
1964   /* This reference binding, unlike those above, requires the
1965      creation of a temporary.  */
1966   conv->need_temporary_p = true;
1967   conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
1968 
1969   /* [dcl.init.ref]
1970 
1971      Otherwise, the reference shall be an lvalue reference to a
1972      non-volatile const type, or the reference shall be an rvalue
1973      reference.  */
1974   if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto))
1975     conv->bad_p = true;
1976 
1977   /* [dcl.init.ref]
1978 
1979      Otherwise, a temporary of type "cv1 T1" is created and
1980      initialized from the initializer expression using the rules for a
1981      non-reference copy initialization.  If T1 is reference-related to
1982      T2, cv1 must be the same cv-qualification as, or greater
1983      cv-qualification than, cv2; otherwise, the program is ill-formed.  */
1984   if (related_p && !at_least_as_qualified_p (to, from))
1985     conv->bad_p = true;
1986 
1987   return conv;
1988 }
1989 
1990 /* Most of the implementation of implicit_conversion, with the same
1991    parameters.  */
1992 
1993 static conversion *
implicit_conversion_1(tree to,tree from,tree expr,bool c_cast_p,int flags,tsubst_flags_t complain)1994 implicit_conversion_1 (tree to, tree from, tree expr, bool c_cast_p,
1995 		       int flags, tsubst_flags_t complain)
1996 {
1997   conversion *conv;
1998 
1999   if (from == error_mark_node || to == error_mark_node
2000       || expr == error_mark_node)
2001     return NULL;
2002 
2003   /* Other flags only apply to the primary function in overload
2004      resolution, or after we've chosen one.  */
2005   flags &= (LOOKUP_ONLYCONVERTING|LOOKUP_NO_CONVERSION|LOOKUP_COPY_PARM
2006 	    |LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND|LOOKUP_PREFER_RVALUE
2007 	    |LOOKUP_NO_NARROWING|LOOKUP_PROTECT|LOOKUP_NO_NON_INTEGRAL);
2008 
2009   /* FIXME: actually we don't want warnings either, but we can't just
2010      have 'complain &= ~(tf_warning|tf_error)' because it would cause
2011      the regression of, eg, g++.old-deja/g++.benjamin/16077.C.
2012      We really ought not to issue that warning until we've committed
2013      to that conversion.  */
2014   complain &= ~tf_error;
2015 
2016   /* Call reshape_init early to remove redundant braces.  */
2017   if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr)
2018       && CLASS_TYPE_P (to)
2019       && COMPLETE_TYPE_P (complete_type (to))
2020       && !CLASSTYPE_NON_AGGREGATE (to))
2021     {
2022       expr = reshape_init (to, expr, complain);
2023       if (expr == error_mark_node)
2024 	return NULL;
2025       from = TREE_TYPE (expr);
2026     }
2027 
2028   if (TYPE_REF_P (to))
2029     conv = reference_binding (to, from, expr, c_cast_p, flags, complain);
2030   else
2031     conv = standard_conversion (to, from, expr, c_cast_p, flags, complain);
2032 
2033   if (conv)
2034     return conv;
2035 
2036   if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
2037     {
2038       if (is_std_init_list (to) && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2039 	return build_list_conv (to, expr, flags, complain);
2040 
2041       /* As an extension, allow list-initialization of _Complex.  */
2042       if (TREE_CODE (to) == COMPLEX_TYPE
2043 	  && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2044 	{
2045 	  conv = build_complex_conv (to, expr, flags, complain);
2046 	  if (conv)
2047 	    return conv;
2048 	}
2049 
2050       /* Allow conversion from an initializer-list with one element to a
2051 	 scalar type.  */
2052       if (SCALAR_TYPE_P (to))
2053 	{
2054 	  int nelts = CONSTRUCTOR_NELTS (expr);
2055 	  tree elt;
2056 
2057 	  if (nelts == 0)
2058 	    elt = build_value_init (to, tf_none);
2059 	  else if (nelts == 1 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2060 	    elt = CONSTRUCTOR_ELT (expr, 0)->value;
2061 	  else
2062 	    elt = error_mark_node;
2063 
2064 	  conv = implicit_conversion (to, TREE_TYPE (elt), elt,
2065 				      c_cast_p, flags, complain);
2066 	  if (conv)
2067 	    {
2068 	      conv->check_narrowing = true;
2069 	      if (BRACE_ENCLOSED_INITIALIZER_P (elt))
2070 		/* Too many levels of braces, i.e. '{{1}}'.  */
2071 		conv->bad_p = true;
2072 	      return conv;
2073 	    }
2074 	}
2075       else if (TREE_CODE (to) == ARRAY_TYPE)
2076 	return build_array_conv (to, expr, flags, complain);
2077     }
2078 
2079   if (expr != NULL_TREE
2080       && (MAYBE_CLASS_TYPE_P (from)
2081 	  || MAYBE_CLASS_TYPE_P (to))
2082       && (flags & LOOKUP_NO_CONVERSION) == 0)
2083     {
2084       struct z_candidate *cand;
2085 
2086       if (CLASS_TYPE_P (to)
2087 	  && BRACE_ENCLOSED_INITIALIZER_P (expr)
2088 	  && !CLASSTYPE_NON_AGGREGATE (complete_type (to)))
2089 	return build_aggr_conv (to, expr, flags, complain);
2090 
2091       cand = build_user_type_conversion_1 (to, expr, flags, complain);
2092       if (cand)
2093 	{
2094 	  if (BRACE_ENCLOSED_INITIALIZER_P (expr)
2095 	      && CONSTRUCTOR_NELTS (expr) == 1
2096 	      && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
2097 	      && !is_list_ctor (cand->fn))
2098 	    {
2099 	      /* "If C is not an initializer-list constructor and the
2100 		 initializer list has a single element of type cv U, where U is
2101 		 X or a class derived from X, the implicit conversion sequence
2102 		 has Exact Match rank if U is X, or Conversion rank if U is
2103 		 derived from X."  */
2104 	      tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
2105 	      tree elttype = TREE_TYPE (elt);
2106 	      if (reference_related_p (to, elttype))
2107 		return implicit_conversion (to, elttype, elt,
2108 					    c_cast_p, flags, complain);
2109 	    }
2110 	  conv = cand->second_conv;
2111 	}
2112 
2113       /* We used to try to bind a reference to a temporary here, but that
2114 	 is now handled after the recursive call to this function at the end
2115 	 of reference_binding.  */
2116       return conv;
2117     }
2118 
2119   return NULL;
2120 }
2121 
2122 /* Returns the implicit conversion sequence (see [over.ics]) from type
2123    FROM to type TO.  The optional expression EXPR may affect the
2124    conversion.  FLAGS are the usual overloading flags.  If C_CAST_P is
2125    true, this conversion is coming from a C-style cast.  */
2126 
2127 static conversion *
implicit_conversion(tree to,tree from,tree expr,bool c_cast_p,int flags,tsubst_flags_t complain)2128 implicit_conversion (tree to, tree from, tree expr, bool c_cast_p,
2129 		     int flags, tsubst_flags_t complain)
2130 {
2131   conversion *conv = implicit_conversion_1 (to, from, expr, c_cast_p,
2132 					    flags, complain);
2133   if (!conv || conv->bad_p)
2134     return conv;
2135   if (conv_is_prvalue (conv)
2136       && CLASS_TYPE_P (conv->type)
2137       && CLASSTYPE_PURE_VIRTUALS (conv->type))
2138     conv->bad_p = true;
2139   return conv;
2140 }
2141 
2142 /* Like implicit_conversion, but return NULL if the conversion is bad.
2143 
2144    This is not static so that check_non_deducible_conversion can call it within
2145    add_template_candidate_real as part of overload resolution; it should not be
2146    called outside of overload resolution.  */
2147 
2148 conversion *
good_conversion(tree to,tree from,tree expr,int flags,tsubst_flags_t complain)2149 good_conversion (tree to, tree from, tree expr,
2150 		 int flags, tsubst_flags_t complain)
2151 {
2152   conversion *c = implicit_conversion (to, from, expr, /*cast*/false,
2153 				       flags, complain);
2154   if (c && c->bad_p)
2155     c = NULL;
2156   return c;
2157 }
2158 
2159 /* Add a new entry to the list of candidates.  Used by the add_*_candidate
2160    functions.  ARGS will not be changed until a single candidate is
2161    selected.  */
2162 
2163 static struct z_candidate *
add_candidate(struct z_candidate ** candidates,tree fn,tree first_arg,const vec<tree,va_gc> * args,size_t num_convs,conversion ** convs,tree access_path,tree conversion_path,int viable,struct rejection_reason * reason,int flags)2164 add_candidate (struct z_candidate **candidates,
2165 	       tree fn, tree first_arg, const vec<tree, va_gc> *args,
2166 	       size_t num_convs, conversion **convs,
2167 	       tree access_path, tree conversion_path,
2168 	       int viable, struct rejection_reason *reason,
2169 	       int flags)
2170 {
2171   struct z_candidate *cand = (struct z_candidate *)
2172     conversion_obstack_alloc (sizeof (struct z_candidate));
2173 
2174   cand->fn = fn;
2175   cand->first_arg = first_arg;
2176   cand->args = args;
2177   cand->convs = convs;
2178   cand->num_convs = num_convs;
2179   cand->access_path = access_path;
2180   cand->conversion_path = conversion_path;
2181   cand->viable = viable;
2182   cand->reason = reason;
2183   cand->next = *candidates;
2184   cand->flags = flags;
2185   *candidates = cand;
2186 
2187   if (convs && cand->reversed ())
2188     /* Swap the conversions for comparison in joust; we'll swap them back
2189        before build_over_call.  */
2190     std::swap (convs[0], convs[1]);
2191 
2192   return cand;
2193 }
2194 
2195 /* Return the number of remaining arguments in the parameter list
2196    beginning with ARG.  */
2197 
2198 int
remaining_arguments(tree arg)2199 remaining_arguments (tree arg)
2200 {
2201   int n;
2202 
2203   for (n = 0; arg != NULL_TREE && arg != void_list_node;
2204        arg = TREE_CHAIN (arg))
2205     n++;
2206 
2207   return n;
2208 }
2209 
2210 /* [over.match.copy]: When initializing a temporary object (12.2) to be bound
2211    to the first parameter of a constructor where the parameter is of type
2212    "reference to possibly cv-qualified T" and the constructor is called with a
2213    single argument in the context of direct-initialization of an object of type
2214    "cv2 T", explicit conversion functions are also considered.
2215 
2216    So set LOOKUP_COPY_PARM to let reference_binding know that
2217    it's being called in that context.  */
2218 
2219 int
conv_flags(int i,int nargs,tree fn,tree arg,int flags)2220 conv_flags (int i, int nargs, tree fn, tree arg, int flags)
2221 {
2222   int lflags = flags;
2223   tree t;
2224   if (i == 0 && nargs == 1 && DECL_CONSTRUCTOR_P (fn)
2225       && (t = FUNCTION_FIRST_USER_PARMTYPE (fn))
2226       && (same_type_ignoring_top_level_qualifiers_p
2227 	  (non_reference (TREE_VALUE (t)), DECL_CONTEXT (fn))))
2228     {
2229       if (!(flags & LOOKUP_ONLYCONVERTING))
2230 	lflags |= LOOKUP_COPY_PARM;
2231       if ((flags & LOOKUP_LIST_INIT_CTOR)
2232 	  && BRACE_ENCLOSED_INITIALIZER_P (arg))
2233 	lflags |= LOOKUP_NO_CONVERSION;
2234     }
2235   else
2236     lflags |= LOOKUP_ONLYCONVERTING;
2237 
2238   return lflags;
2239 }
2240 
2241 /* Build an appropriate 'this' conversion for the method FN and class
2242    type CTYPE from the value ARG (having type ARGTYPE) to the type PARMTYPE.
2243    This function modifies PARMTYPE, ARGTYPE and ARG.  */
2244 
2245 static conversion *
build_this_conversion(tree fn,tree ctype,tree & parmtype,tree & argtype,tree & arg,int flags,tsubst_flags_t complain)2246 build_this_conversion (tree fn, tree ctype,
2247 		       tree& parmtype, tree& argtype, tree& arg,
2248 		       int flags, tsubst_flags_t complain)
2249 {
2250   gcc_assert (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2251 	      && !DECL_CONSTRUCTOR_P (fn));
2252 
2253   /* The type of the implicit object parameter ('this') for
2254      overload resolution is not always the same as for the
2255      function itself; conversion functions are considered to
2256      be members of the class being converted, and functions
2257      introduced by a using-declaration are considered to be
2258      members of the class that uses them.
2259 
2260      Since build_over_call ignores the ICS for the `this'
2261      parameter, we can just change the parm type.  */
2262   parmtype = cp_build_qualified_type (ctype,
2263 				      cp_type_quals (TREE_TYPE (parmtype)));
2264   bool this_p = true;
2265   if (FUNCTION_REF_QUALIFIED (TREE_TYPE (fn)))
2266     {
2267       /* If the function has a ref-qualifier, the implicit
2268 	 object parameter has reference type.  */
2269       bool rv = FUNCTION_RVALUE_QUALIFIED (TREE_TYPE (fn));
2270       parmtype = cp_build_reference_type (parmtype, rv);
2271       /* The special handling of 'this' conversions in compare_ics
2272 	 does not apply if there is a ref-qualifier.  */
2273       this_p = false;
2274     }
2275   else
2276     {
2277       parmtype = build_pointer_type (parmtype);
2278       /* We don't use build_this here because we don't want to
2279 	 capture the object argument until we've chosen a
2280 	 non-static member function.  */
2281       arg = build_address (arg);
2282       argtype = lvalue_type (arg);
2283     }
2284   flags |= LOOKUP_ONLYCONVERTING;
2285   conversion *t = implicit_conversion (parmtype, argtype, arg,
2286 				       /*c_cast_p=*/false, flags, complain);
2287   t->this_p = this_p;
2288   return t;
2289 }
2290 
2291 /* Create an overload candidate for the function or method FN called
2292    with the argument list FIRST_ARG/ARGS and add it to CANDIDATES.
2293    FLAGS is passed on to implicit_conversion.
2294 
2295    This does not change ARGS.
2296 
2297    CTYPE, if non-NULL, is the type we want to pretend this function
2298    comes from for purposes of overload resolution.
2299 
2300    SHORTCUT_BAD_CONVS controls how we handle "bad" argument conversions.
2301    If true, we stop computing conversions upon seeing the first bad
2302    conversion.  This is used by add_candidates to avoid computing
2303    more conversions than necessary in the presence of a strictly viable
2304    candidate, while preserving the defacto behavior of overload resolution
2305    when it turns out there are only non-strictly viable candidates.  */
2306 
2307 static struct z_candidate *
add_function_candidate(struct z_candidate ** candidates,tree fn,tree ctype,tree first_arg,const vec<tree,va_gc> * args,tree access_path,tree conversion_path,int flags,conversion ** convs,bool shortcut_bad_convs,tsubst_flags_t complain)2308 add_function_candidate (struct z_candidate **candidates,
2309 			tree fn, tree ctype, tree first_arg,
2310 			const vec<tree, va_gc> *args, tree access_path,
2311 			tree conversion_path, int flags,
2312 			conversion **convs,
2313 			bool shortcut_bad_convs,
2314 			tsubst_flags_t complain)
2315 {
2316   tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
2317   int i, len;
2318   tree parmnode;
2319   tree orig_first_arg = first_arg;
2320   int skip;
2321   int viable = 1;
2322   struct rejection_reason *reason = NULL;
2323 
2324   /* The `this', `in_chrg' and VTT arguments to constructors are not
2325      considered in overload resolution.  */
2326   if (DECL_CONSTRUCTOR_P (fn))
2327     {
2328       if (ctor_omit_inherited_parms (fn))
2329 	/* Bring back parameters omitted from an inherited ctor.  */
2330 	parmlist = FUNCTION_FIRST_USER_PARMTYPE (DECL_ORIGIN (fn));
2331       else
2332 	parmlist = skip_artificial_parms_for (fn, parmlist);
2333       skip = num_artificial_parms_for (fn);
2334       if (skip > 0 && first_arg != NULL_TREE)
2335 	{
2336 	  --skip;
2337 	  first_arg = NULL_TREE;
2338 	}
2339     }
2340   else
2341     skip = 0;
2342 
2343   len = vec_safe_length (args) - skip + (first_arg != NULL_TREE ? 1 : 0);
2344   if (!convs)
2345     convs = alloc_conversions (len);
2346 
2347   /* 13.3.2 - Viable functions [over.match.viable]
2348      First, to be a viable function, a candidate function shall have enough
2349      parameters to agree in number with the arguments in the list.
2350 
2351      We need to check this first; otherwise, checking the ICSes might cause
2352      us to produce an ill-formed template instantiation.  */
2353 
2354   parmnode = parmlist;
2355   for (i = 0; i < len; ++i)
2356     {
2357       if (parmnode == NULL_TREE || parmnode == void_list_node)
2358 	break;
2359       parmnode = TREE_CHAIN (parmnode);
2360     }
2361 
2362   if ((i < len && parmnode)
2363       || !sufficient_parms_p (parmnode))
2364     {
2365       int remaining = remaining_arguments (parmnode);
2366       viable = 0;
2367       reason = arity_rejection (first_arg, i + remaining, len);
2368     }
2369 
2370   /* An inherited constructor (12.6.3 [class.inhctor.init]) that has a first
2371      parameter of type "reference to cv C" (including such a constructor
2372      instantiated from a template) is excluded from the set of candidate
2373      functions when used to construct an object of type D with an argument list
2374      containing a single argument if C is reference-related to D.  */
2375   if (viable && len == 1 && parmlist && DECL_CONSTRUCTOR_P (fn)
2376       && flag_new_inheriting_ctors
2377       && DECL_INHERITED_CTOR (fn))
2378     {
2379       tree ptype = non_reference (TREE_VALUE (parmlist));
2380       tree dtype = DECL_CONTEXT (fn);
2381       tree btype = DECL_INHERITED_CTOR_BASE (fn);
2382       if (reference_related_p (ptype, dtype)
2383 	  && reference_related_p (btype, ptype))
2384 	{
2385 	  viable = false;
2386 	  reason = inherited_ctor_rejection ();
2387 	}
2388     }
2389 
2390   /* Second, for a function to be viable, its constraints must be
2391      satisfied. */
2392   if (flag_concepts && viable && !constraints_satisfied_p (fn))
2393     {
2394       reason = constraint_failure ();
2395       viable = false;
2396     }
2397 
2398   /* When looking for a function from a subobject from an implicit
2399      copy/move constructor/operator=, don't consider anything that takes (a
2400      reference to) an unrelated type.  See c++/44909 and core 1092.  */
2401   if (viable && parmlist && (flags & LOOKUP_DEFAULTED))
2402     {
2403       if (DECL_CONSTRUCTOR_P (fn))
2404 	i = 1;
2405       else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
2406 	       && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR))
2407 	i = 2;
2408       else
2409 	i = 0;
2410       if (i && len == i)
2411 	{
2412 	  parmnode = chain_index (i-1, parmlist);
2413 	  if (!reference_related_p (non_reference (TREE_VALUE (parmnode)),
2414 				    ctype))
2415 	    viable = 0;
2416 	}
2417 
2418       /* This only applies at the top level.  */
2419       flags &= ~LOOKUP_DEFAULTED;
2420     }
2421 
2422   if (! viable)
2423     goto out;
2424 
2425   /* Third, for F to be a viable function, there shall exist for each
2426      argument an implicit conversion sequence that converts that argument
2427      to the corresponding parameter of F.  */
2428 
2429   parmnode = parmlist;
2430 
2431   for (i = 0; i < len; ++i)
2432     {
2433       tree argtype, to_type;
2434       tree arg;
2435 
2436       if (parmnode == void_list_node)
2437 	break;
2438 
2439       if (convs[i])
2440 	{
2441 	  /* Already set during deduction.  */
2442 	  parmnode = TREE_CHAIN (parmnode);
2443 	  continue;
2444 	}
2445 
2446       if (i == 0 && first_arg != NULL_TREE)
2447 	arg = first_arg;
2448       else
2449 	arg = CONST_CAST_TREE (
2450 		(*args)[i + skip - (first_arg != NULL_TREE ? 1 : 0)]);
2451       argtype = lvalue_type (arg);
2452 
2453       conversion *t;
2454       if (parmnode)
2455 	{
2456 	  tree parmtype = TREE_VALUE (parmnode);
2457 	  if (i == 0
2458 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2459 	      && !DECL_CONSTRUCTOR_P (fn))
2460 	    t = build_this_conversion (fn, ctype, parmtype, argtype, arg,
2461 				       flags, complain);
2462 	  else
2463 	    {
2464 	      int lflags = conv_flags (i, len-skip, fn, arg, flags);
2465 	      t = implicit_conversion (parmtype, argtype, arg,
2466 				       /*c_cast_p=*/false, lflags, complain);
2467 	    }
2468 	  to_type = parmtype;
2469 	  parmnode = TREE_CHAIN (parmnode);
2470 	}
2471       else
2472 	{
2473 	  t = build_identity_conv (argtype, arg);
2474 	  t->ellipsis_p = true;
2475 	  to_type = argtype;
2476 	}
2477 
2478       convs[i] = t;
2479       if (! t)
2480 	{
2481 	  viable = 0;
2482 	  reason = arg_conversion_rejection (first_arg, i, argtype, to_type,
2483 					     EXPR_LOCATION (arg));
2484 	  break;
2485 	}
2486 
2487       if (t->bad_p)
2488 	{
2489 	  viable = -1;
2490 	  reason = bad_arg_conversion_rejection (first_arg, i, arg, to_type,
2491 						 EXPR_LOCATION (arg));
2492 	  if (shortcut_bad_convs)
2493 	    break;
2494 	}
2495     }
2496 
2497  out:
2498   return add_candidate (candidates, fn, orig_first_arg, args, len, convs,
2499 			access_path, conversion_path, viable, reason, flags);
2500 }
2501 
2502 /* Create an overload candidate for the conversion function FN which will
2503    be invoked for expression OBJ, producing a pointer-to-function which
2504    will in turn be called with the argument list FIRST_ARG/ARGLIST,
2505    and add it to CANDIDATES.  This does not change ARGLIST.  FLAGS is
2506    passed on to implicit_conversion.
2507 
2508    Actually, we don't really care about FN; we care about the type it
2509    converts to.  There may be multiple conversion functions that will
2510    convert to that type, and we rely on build_user_type_conversion_1 to
2511    choose the best one; so when we create our candidate, we record the type
2512    instead of the function.  */
2513 
2514 static struct z_candidate *
add_conv_candidate(struct z_candidate ** candidates,tree fn,tree obj,const vec<tree,va_gc> * arglist,tree access_path,tree conversion_path,tsubst_flags_t complain)2515 add_conv_candidate (struct z_candidate **candidates, tree fn, tree obj,
2516 		    const vec<tree, va_gc> *arglist,
2517 		    tree access_path, tree conversion_path,
2518 		    tsubst_flags_t complain)
2519 {
2520   tree totype = TREE_TYPE (TREE_TYPE (fn));
2521   int i, len, viable, flags;
2522   tree parmlist, parmnode;
2523   conversion **convs;
2524   struct rejection_reason *reason;
2525 
2526   for (parmlist = totype; TREE_CODE (parmlist) != FUNCTION_TYPE; )
2527     parmlist = TREE_TYPE (parmlist);
2528   parmlist = TYPE_ARG_TYPES (parmlist);
2529 
2530   len = vec_safe_length (arglist) + 1;
2531   convs = alloc_conversions (len);
2532   parmnode = parmlist;
2533   viable = 1;
2534   flags = LOOKUP_IMPLICIT;
2535   reason = NULL;
2536 
2537   /* Don't bother looking up the same type twice.  */
2538   if (*candidates && (*candidates)->fn == totype)
2539     return NULL;
2540 
2541   for (i = 0; i < len; ++i)
2542     {
2543       tree arg, argtype, convert_type = NULL_TREE;
2544       conversion *t;
2545 
2546       if (i == 0)
2547 	arg = obj;
2548       else
2549 	arg = (*arglist)[i - 1];
2550       argtype = lvalue_type (arg);
2551 
2552       if (i == 0)
2553 	{
2554 	  t = build_identity_conv (argtype, NULL_TREE);
2555 	  t = build_conv (ck_user, totype, t);
2556 	  /* Leave the 'cand' field null; we'll figure out the conversion in
2557 	     convert_like if this candidate is chosen.  */
2558 	  convert_type = totype;
2559 	}
2560       else if (parmnode == void_list_node)
2561 	break;
2562       else if (parmnode)
2563 	{
2564 	  t = implicit_conversion (TREE_VALUE (parmnode), argtype, arg,
2565 				   /*c_cast_p=*/false, flags, complain);
2566 	  convert_type = TREE_VALUE (parmnode);
2567 	}
2568       else
2569 	{
2570 	  t = build_identity_conv (argtype, arg);
2571 	  t->ellipsis_p = true;
2572 	  convert_type = argtype;
2573 	}
2574 
2575       convs[i] = t;
2576       if (! t)
2577 	break;
2578 
2579       if (t->bad_p)
2580 	{
2581 	  viable = -1;
2582 	  reason = bad_arg_conversion_rejection (NULL_TREE, i, arg, convert_type,
2583 						 EXPR_LOCATION (arg));
2584 	}
2585 
2586       if (i == 0)
2587 	continue;
2588 
2589       if (parmnode)
2590 	parmnode = TREE_CHAIN (parmnode);
2591     }
2592 
2593   if (i < len
2594       || ! sufficient_parms_p (parmnode))
2595     {
2596       int remaining = remaining_arguments (parmnode);
2597       viable = 0;
2598       reason = arity_rejection (NULL_TREE, i + remaining, len);
2599     }
2600 
2601   return add_candidate (candidates, totype, obj, arglist, len, convs,
2602 			access_path, conversion_path, viable, reason, flags);
2603 }
2604 
2605 static void
build_builtin_candidate(struct z_candidate ** candidates,tree fnname,tree type1,tree type2,const vec<tree,va_gc> & args,tree * argtypes,int flags,tsubst_flags_t complain)2606 build_builtin_candidate (struct z_candidate **candidates, tree fnname,
2607 			 tree type1, tree type2, const vec<tree,va_gc> &args,
2608 			 tree *argtypes, int flags, tsubst_flags_t complain)
2609 {
2610   conversion *t;
2611   conversion **convs;
2612   size_t num_convs;
2613   int viable = 1;
2614   tree types[2];
2615   struct rejection_reason *reason = NULL;
2616 
2617   types[0] = type1;
2618   types[1] = type2;
2619 
2620   num_convs = args.length ();
2621   convs = alloc_conversions (num_convs);
2622 
2623   /* TRUTH_*_EXPR do "contextual conversion to bool", which means explicit
2624      conversion ops are allowed.  We handle that here by just checking for
2625      boolean_type_node because other operators don't ask for it.  COND_EXPR
2626      also does contextual conversion to bool for the first operand, but we
2627      handle that in build_conditional_expr, and type1 here is operand 2.  */
2628   if (type1 != boolean_type_node)
2629     flags |= LOOKUP_ONLYCONVERTING;
2630 
2631   for (unsigned i = 0; i < 2 && i < num_convs; ++i)
2632     {
2633       t = implicit_conversion (types[i], argtypes[i], args[i],
2634 			       /*c_cast_p=*/false, flags, complain);
2635       if (! t)
2636 	{
2637 	  viable = 0;
2638 	  /* We need something for printing the candidate.  */
2639 	  t = build_identity_conv (types[i], NULL_TREE);
2640 	  reason = arg_conversion_rejection (NULL_TREE, i, argtypes[i],
2641 					     types[i], EXPR_LOCATION (args[i]));
2642 	}
2643       else if (t->bad_p)
2644 	{
2645 	  viable = 0;
2646 	  reason = bad_arg_conversion_rejection (NULL_TREE, i, args[i],
2647 						 types[i],
2648 						 EXPR_LOCATION (args[i]));
2649 	}
2650       convs[i] = t;
2651     }
2652 
2653   /* For COND_EXPR we rearranged the arguments; undo that now.  */
2654   if (num_convs == 3)
2655     {
2656       convs[2] = convs[1];
2657       convs[1] = convs[0];
2658       t = implicit_conversion (boolean_type_node, argtypes[2], args[2],
2659 			       /*c_cast_p=*/false, flags,
2660 			       complain);
2661       if (t)
2662 	convs[0] = t;
2663       else
2664 	{
2665 	  viable = 0;
2666 	  reason = arg_conversion_rejection (NULL_TREE, 0, argtypes[2],
2667 					     boolean_type_node,
2668 					     EXPR_LOCATION (args[2]));
2669 	}
2670     }
2671 
2672   add_candidate (candidates, fnname, /*first_arg=*/NULL_TREE, /*args=*/NULL,
2673 		 num_convs, convs,
2674 		 /*access_path=*/NULL_TREE,
2675 		 /*conversion_path=*/NULL_TREE,
2676 		 viable, reason, flags);
2677 }
2678 
2679 static bool
is_complete(tree t)2680 is_complete (tree t)
2681 {
2682   return COMPLETE_TYPE_P (complete_type (t));
2683 }
2684 
2685 /* Returns nonzero if TYPE is a promoted arithmetic type.  */
2686 
2687 static bool
promoted_arithmetic_type_p(tree type)2688 promoted_arithmetic_type_p (tree type)
2689 {
2690   /* [over.built]
2691 
2692      In this section, the term promoted integral type is used to refer
2693      to those integral types which are preserved by integral promotion
2694      (including e.g.  int and long but excluding e.g.  char).
2695      Similarly, the term promoted arithmetic type refers to promoted
2696      integral types plus floating types.  */
2697   return ((CP_INTEGRAL_TYPE_P (type)
2698 	   && same_type_p (type_promotes_to (type), type))
2699 	  || TREE_CODE (type) == REAL_TYPE);
2700 }
2701 
2702 /* Create any builtin operator overload candidates for the operator in
2703    question given the converted operand types TYPE1 and TYPE2.  The other
2704    args are passed through from add_builtin_candidates to
2705    build_builtin_candidate.
2706 
2707    TYPE1 and TYPE2 may not be permissible, and we must filter them.
2708    If CODE is requires candidates operands of the same type of the kind
2709    of which TYPE1 and TYPE2 are, we add both candidates
2710    CODE (TYPE1, TYPE1) and CODE (TYPE2, TYPE2).  */
2711 
2712 static void
add_builtin_candidate(struct z_candidate ** candidates,enum tree_code code,enum tree_code code2,tree fnname,tree type1,tree type2,vec<tree,va_gc> & args,tree * argtypes,int flags,tsubst_flags_t complain)2713 add_builtin_candidate (struct z_candidate **candidates, enum tree_code code,
2714 		       enum tree_code code2, tree fnname, tree type1,
2715 		       tree type2, vec<tree,va_gc> &args, tree *argtypes,
2716 		       int flags, tsubst_flags_t complain)
2717 {
2718   switch (code)
2719     {
2720     case POSTINCREMENT_EXPR:
2721     case POSTDECREMENT_EXPR:
2722       args[1] = integer_zero_node;
2723       type2 = integer_type_node;
2724       break;
2725     default:
2726       break;
2727     }
2728 
2729   switch (code)
2730     {
2731 
2732 /* 4 For every pair (T, VQ), where T is an arithmetic type other than bool,
2733      and  VQ  is  either  volatile or empty, there exist candidate operator
2734      functions of the form
2735 	     VQ T&   operator++(VQ T&);
2736 	     T       operator++(VQ T&, int);
2737    5 For every pair (T, VQ), where T is an arithmetic type other than bool,
2738      and VQ is either volatile or empty, there exist candidate operator
2739      functions of the form
2740 	     VQ T&   operator--(VQ T&);
2741 	     T       operator--(VQ T&, int);
2742    6 For every pair (T, VQ), where T is a cv-qualified or cv-unqualified object
2743      type, and VQ is either volatile or empty, there exist candidate operator
2744      functions of the form
2745 	     T*VQ&   operator++(T*VQ&);
2746 	     T*VQ&   operator--(T*VQ&);
2747 	     T*      operator++(T*VQ&, int);
2748 	     T*      operator--(T*VQ&, int);  */
2749 
2750     case POSTDECREMENT_EXPR:
2751     case PREDECREMENT_EXPR:
2752       if (TREE_CODE (type1) == BOOLEAN_TYPE)
2753 	return;
2754       /* FALLTHRU */
2755     case POSTINCREMENT_EXPR:
2756     case PREINCREMENT_EXPR:
2757       /* P0002R1, Remove deprecated operator++(bool) added "other than bool"
2758 	 to p4.  */
2759       if (TREE_CODE (type1) == BOOLEAN_TYPE && cxx_dialect >= cxx17)
2760 	return;
2761       if (ARITHMETIC_TYPE_P (type1) || TYPE_PTROB_P (type1))
2762 	{
2763 	  type1 = build_reference_type (type1);
2764 	  break;
2765 	}
2766       return;
2767 
2768 /* 7 For every cv-qualified or cv-unqualified object type T, there
2769      exist candidate operator functions of the form
2770 
2771 	     T&      operator*(T*);
2772 
2773 
2774    8 For every function type T that does not have cv-qualifiers or
2775      a ref-qualifier, there exist candidate operator functions of the form
2776 	     T&      operator*(T*);  */
2777 
2778     case INDIRECT_REF:
2779       if (TYPE_PTR_P (type1)
2780 	  && (TYPE_PTROB_P (type1)
2781 	      || TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE))
2782 	break;
2783       return;
2784 
2785 /* 9 For every type T, there exist candidate operator functions of the form
2786 	     T*      operator+(T*);
2787 
2788    10 For every floating-point or promoted integral type T, there exist
2789       candidate operator functions of the form
2790 	     T       operator+(T);
2791 	     T       operator-(T);  */
2792 
2793     case UNARY_PLUS_EXPR: /* unary + */
2794       if (TYPE_PTR_P (type1))
2795 	break;
2796       /* FALLTHRU */
2797     case NEGATE_EXPR:
2798       if (ARITHMETIC_TYPE_P (type1))
2799 	break;
2800       return;
2801 
2802 /* 11 For every promoted integral type T,  there  exist  candidate  operator
2803       functions of the form
2804 	     T       operator~(T);  */
2805 
2806     case BIT_NOT_EXPR:
2807       if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1))
2808 	break;
2809       return;
2810 
2811 /* 12 For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, C1
2812      is the same type as C2 or is a derived class of C2, and T is an object
2813      type or a function type there exist candidate operator functions of the
2814      form
2815 	     CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
2816      where CV12 is the union of CV1 and CV2.  */
2817 
2818     case MEMBER_REF:
2819       if (TYPE_PTR_P (type1) && TYPE_PTRMEM_P (type2))
2820 	{
2821 	  tree c1 = TREE_TYPE (type1);
2822 	  tree c2 = TYPE_PTRMEM_CLASS_TYPE (type2);
2823 
2824 	  if (MAYBE_CLASS_TYPE_P (c1) && DERIVED_FROM_P (c2, c1)
2825 	      && (TYPE_PTRMEMFUNC_P (type2)
2826 		  || is_complete (TYPE_PTRMEM_POINTED_TO_TYPE (type2))))
2827 	    break;
2828 	}
2829       return;
2830 
2831 /* 13 For every pair of types L and R, where each of L and R is a floating-point
2832       or promoted integral type, there exist candidate operator functions of the
2833       form
2834 	     LR      operator*(L, R);
2835 	     LR      operator/(L, R);
2836 	     LR      operator+(L, R);
2837 	     LR      operator-(L, R);
2838 	     bool    operator<(L, R);
2839 	     bool    operator>(L, R);
2840 	     bool    operator<=(L, R);
2841 	     bool    operator>=(L, R);
2842 	     bool    operator==(L, R);
2843 	     bool    operator!=(L, R);
2844       where  LR  is  the  result of the usual arithmetic conversions between
2845       types L and R.
2846 
2847    14 For every integral type T there exists a candidate operator function of
2848       the form
2849 
2850        std::strong_ordering operator<=>(T, T);
2851 
2852    15 For every pair of floating-point types L and R, there exists a candidate
2853       operator function of the form
2854 
2855        std::partial_ordering operator<=>(L, R);
2856 
2857    16 For every cv-qualified or cv-unqualified object type T there exist
2858       candidate operator functions of the form
2859 	     T*      operator+(T*, std::ptrdiff_t);
2860 	     T&      operator[](T*, std::ptrdiff_t);
2861 	     T*      operator-(T*, std::ptrdiff_t);
2862 	     T*      operator+(std::ptrdiff_t, T*);
2863 	     T&      operator[](std::ptrdiff_t, T*);
2864 
2865    17 For every T, where T is a pointer to object type, there exist candidate
2866       operator functions of the form
2867 	     std::ptrdiff_t operator-(T, T);
2868 
2869    18 For every T, where T is an enumeration type or a pointer type, there
2870       exist candidate operator functions of the form
2871 	     bool    operator<(T, T);
2872 	     bool    operator>(T, T);
2873 	     bool    operator<=(T, T);
2874 	     bool    operator>=(T, T);
2875 	     bool    operator==(T, T);
2876 	     bool    operator!=(T, T);
2877 	     R       operator<=>(T, T);
2878 
2879       where R is the result type specified in [expr.spaceship].
2880 
2881    19 For every T, where T is a pointer-to-member type or std::nullptr_t,
2882       there exist candidate operator functions of the form
2883 	     bool    operator==(T, T);
2884 	     bool    operator!=(T, T);  */
2885 
2886     case MINUS_EXPR:
2887       if (TYPE_PTROB_P (type1) && TYPE_PTROB_P (type2))
2888 	break;
2889       if (TYPE_PTROB_P (type1)
2890 	  && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2891 	{
2892 	  type2 = ptrdiff_type_node;
2893 	  break;
2894 	}
2895       /* FALLTHRU */
2896     case MULT_EXPR:
2897     case TRUNC_DIV_EXPR:
2898       if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2899 	break;
2900       return;
2901 
2902       /* This isn't exactly what's specified above for operator<=>, but it's
2903 	 close enough.  In particular, we don't care about the return type
2904 	 specified above; it doesn't participate in overload resolution and it
2905 	 doesn't affect the semantics of the built-in operator.  */
2906     case SPACESHIP_EXPR:
2907     case EQ_EXPR:
2908     case NE_EXPR:
2909       if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
2910 	  || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2)))
2911 	break;
2912       if (NULLPTR_TYPE_P (type1) && NULLPTR_TYPE_P (type2))
2913 	break;
2914       if (TYPE_PTRMEM_P (type1) && null_ptr_cst_p (args[1]))
2915 	{
2916 	  type2 = type1;
2917 	  break;
2918 	}
2919       if (TYPE_PTRMEM_P (type2) && null_ptr_cst_p (args[0]))
2920 	{
2921 	  type1 = type2;
2922 	  break;
2923 	}
2924       /* Fall through.  */
2925     case LT_EXPR:
2926     case GT_EXPR:
2927     case LE_EXPR:
2928     case GE_EXPR:
2929     case MAX_EXPR:
2930     case MIN_EXPR:
2931       if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2932 	break;
2933       if (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
2934 	break;
2935       if (TREE_CODE (type1) == ENUMERAL_TYPE
2936 	  && TREE_CODE (type2) == ENUMERAL_TYPE)
2937 	break;
2938       if (TYPE_PTR_P (type1)
2939 	  && null_ptr_cst_p (args[1]))
2940 	{
2941 	  type2 = type1;
2942 	  break;
2943 	}
2944       if (null_ptr_cst_p (args[0])
2945 	  && TYPE_PTR_P (type2))
2946 	{
2947 	  type1 = type2;
2948 	  break;
2949 	}
2950       return;
2951 
2952     case PLUS_EXPR:
2953       if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2954 	break;
2955       /* FALLTHRU */
2956     case ARRAY_REF:
2957       if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && TYPE_PTROB_P (type2))
2958 	{
2959 	  type1 = ptrdiff_type_node;
2960 	  break;
2961 	}
2962       if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2963 	{
2964 	  type2 = ptrdiff_type_node;
2965 	  break;
2966 	}
2967       return;
2968 
2969 /* 18For  every pair of promoted integral types L and R, there exist candi-
2970      date operator functions of the form
2971 	     LR      operator%(L, R);
2972 	     LR      operator&(L, R);
2973 	     LR      operator^(L, R);
2974 	     LR      operator|(L, R);
2975 	     L       operator<<(L, R);
2976 	     L       operator>>(L, R);
2977      where LR is the result of the  usual  arithmetic  conversions  between
2978      types L and R.  */
2979 
2980     case TRUNC_MOD_EXPR:
2981     case BIT_AND_EXPR:
2982     case BIT_IOR_EXPR:
2983     case BIT_XOR_EXPR:
2984     case LSHIFT_EXPR:
2985     case RSHIFT_EXPR:
2986       if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2987 	break;
2988       return;
2989 
2990 /* 19For  every  triple  L, VQ, R), where L is an arithmetic or enumeration
2991      type, VQ is either volatile or empty, and R is a  promoted  arithmetic
2992      type, there exist candidate operator functions of the form
2993 	     VQ L&   operator=(VQ L&, R);
2994 	     VQ L&   operator*=(VQ L&, R);
2995 	     VQ L&   operator/=(VQ L&, R);
2996 	     VQ L&   operator+=(VQ L&, R);
2997 	     VQ L&   operator-=(VQ L&, R);
2998 
2999    20For  every  pair T, VQ), where T is any type and VQ is either volatile
3000      or empty, there exist candidate operator functions of the form
3001 	     T*VQ&   operator=(T*VQ&, T*);
3002 
3003    21For every pair T, VQ), where T is a pointer to member type and  VQ  is
3004      either  volatile or empty, there exist candidate operator functions of
3005      the form
3006 	     VQ T&   operator=(VQ T&, T);
3007 
3008    22For every triple  T,  VQ,  I),  where  T  is  a  cv-qualified  or  cv-
3009      unqualified  complete object type, VQ is either volatile or empty, and
3010      I is a promoted integral type, there exist  candidate  operator  func-
3011      tions of the form
3012 	     T*VQ&   operator+=(T*VQ&, I);
3013 	     T*VQ&   operator-=(T*VQ&, I);
3014 
3015    23For  every  triple  L,  VQ,  R), where L is an integral or enumeration
3016      type, VQ is either volatile or empty, and R  is  a  promoted  integral
3017      type, there exist candidate operator functions of the form
3018 
3019 	     VQ L&   operator%=(VQ L&, R);
3020 	     VQ L&   operator<<=(VQ L&, R);
3021 	     VQ L&   operator>>=(VQ L&, R);
3022 	     VQ L&   operator&=(VQ L&, R);
3023 	     VQ L&   operator^=(VQ L&, R);
3024 	     VQ L&   operator|=(VQ L&, R);  */
3025 
3026     case MODIFY_EXPR:
3027       switch (code2)
3028 	{
3029 	case PLUS_EXPR:
3030 	case MINUS_EXPR:
3031 	  if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3032 	    {
3033 	      type2 = ptrdiff_type_node;
3034 	      break;
3035 	    }
3036 	  /* FALLTHRU */
3037 	case MULT_EXPR:
3038 	case TRUNC_DIV_EXPR:
3039 	  if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3040 	    break;
3041 	  return;
3042 
3043 	case TRUNC_MOD_EXPR:
3044 	case BIT_AND_EXPR:
3045 	case BIT_IOR_EXPR:
3046 	case BIT_XOR_EXPR:
3047 	case LSHIFT_EXPR:
3048 	case RSHIFT_EXPR:
3049 	  if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3050 	    break;
3051 	  return;
3052 
3053 	case NOP_EXPR:
3054 	  if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3055 	    break;
3056 	  if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3057 	      || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3058 	      || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3059 	      || ((TYPE_PTRMEMFUNC_P (type1)
3060 		   || TYPE_PTR_P (type1))
3061 		  && null_ptr_cst_p (args[1])))
3062 	    {
3063 	      type2 = type1;
3064 	      break;
3065 	    }
3066 	  return;
3067 
3068 	default:
3069 	  gcc_unreachable ();
3070 	}
3071       type1 = build_reference_type (type1);
3072       break;
3073 
3074     case COND_EXPR:
3075       /* [over.built]
3076 
3077 	 For every pair of promoted arithmetic types L and R, there
3078 	 exist candidate operator functions of the form
3079 
3080 	 LR operator?(bool, L, R);
3081 
3082 	 where LR is the result of the usual arithmetic conversions
3083 	 between types L and R.
3084 
3085 	 For every type T, where T is a pointer or pointer-to-member
3086 	 type, there exist candidate operator functions of the form T
3087 	 operator?(bool, T, T);  */
3088 
3089       if (promoted_arithmetic_type_p (type1)
3090 	  && promoted_arithmetic_type_p (type2))
3091 	/* That's OK.  */
3092 	break;
3093 
3094       /* Otherwise, the types should be pointers.  */
3095       if (!TYPE_PTR_OR_PTRMEM_P (type1) || !TYPE_PTR_OR_PTRMEM_P (type2))
3096 	return;
3097 
3098       /* We don't check that the two types are the same; the logic
3099 	 below will actually create two candidates; one in which both
3100 	 parameter types are TYPE1, and one in which both parameter
3101 	 types are TYPE2.  */
3102       break;
3103 
3104     case REALPART_EXPR:
3105     case IMAGPART_EXPR:
3106       if (ARITHMETIC_TYPE_P (type1))
3107 	break;
3108       return;
3109 
3110     default:
3111       gcc_unreachable ();
3112     }
3113 
3114   /* Make sure we don't create builtin candidates with dependent types.  */
3115   bool u1 = uses_template_parms (type1);
3116   bool u2 = type2 ? uses_template_parms (type2) : false;
3117   if (u1 || u2)
3118     {
3119       /* Try to recover if one of the types is non-dependent.  But if
3120 	 there's only one type, there's nothing we can do.  */
3121       if (!type2)
3122 	return;
3123       /* And we lose if both are dependent.  */
3124       if (u1 && u2)
3125 	return;
3126       /* Or if they have different forms.  */
3127       if (TREE_CODE (type1) != TREE_CODE (type2))
3128 	return;
3129 
3130       if (u1 && !u2)
3131 	type1 = type2;
3132       else if (u2 && !u1)
3133 	type2 = type1;
3134     }
3135 
3136   /* If we're dealing with two pointer types or two enumeral types,
3137      we need candidates for both of them.  */
3138   if (type2 && !same_type_p (type1, type2)
3139       && TREE_CODE (type1) == TREE_CODE (type2)
3140       && (TYPE_REF_P (type1)
3141 	  || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3142 	  || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3143 	  || TYPE_PTRMEMFUNC_P (type1)
3144 	  || MAYBE_CLASS_TYPE_P (type1)
3145 	  || TREE_CODE (type1) == ENUMERAL_TYPE))
3146     {
3147       if (TYPE_PTR_OR_PTRMEM_P (type1))
3148 	{
3149 	  tree cptype = composite_pointer_type (input_location,
3150 						type1, type2,
3151 						error_mark_node,
3152 						error_mark_node,
3153 						CPO_CONVERSION,
3154 						tf_none);
3155 	  if (cptype != error_mark_node)
3156 	    {
3157 	      build_builtin_candidate
3158 		(candidates, fnname, cptype, cptype, args, argtypes,
3159 		 flags, complain);
3160 	      return;
3161 	    }
3162 	}
3163 
3164       build_builtin_candidate
3165 	(candidates, fnname, type1, type1, args, argtypes, flags, complain);
3166       build_builtin_candidate
3167 	(candidates, fnname, type2, type2, args, argtypes, flags, complain);
3168       return;
3169     }
3170 
3171   build_builtin_candidate
3172     (candidates, fnname, type1, type2, args, argtypes, flags, complain);
3173 }
3174 
3175 tree
type_decays_to(tree type)3176 type_decays_to (tree type)
3177 {
3178   if (TREE_CODE (type) == ARRAY_TYPE)
3179     return build_pointer_type (TREE_TYPE (type));
3180   if (TREE_CODE (type) == FUNCTION_TYPE)
3181     return build_pointer_type (type);
3182   return type;
3183 }
3184 
3185 /* There are three conditions of builtin candidates:
3186 
3187    1) bool-taking candidates.  These are the same regardless of the input.
3188    2) pointer-pair taking candidates.  These are generated for each type
3189       one of the input types converts to.
3190    3) arithmetic candidates.  According to the standard, we should generate
3191       all of these, but I'm trying not to...
3192 
3193    Here we generate a superset of the possible candidates for this particular
3194    case.  That is a subset of the full set the standard defines, plus some
3195    other cases which the standard disallows. add_builtin_candidate will
3196    filter out the invalid set.  */
3197 
3198 static void
add_builtin_candidates(struct z_candidate ** candidates,enum tree_code code,enum tree_code code2,tree fnname,vec<tree,va_gc> * argv,int flags,tsubst_flags_t complain)3199 add_builtin_candidates (struct z_candidate **candidates, enum tree_code code,
3200 			enum tree_code code2, tree fnname,
3201 			vec<tree, va_gc> *argv,
3202 			int flags, tsubst_flags_t complain)
3203 {
3204   int ref1;
3205   int enum_p = 0;
3206   tree type, argtypes[3], t;
3207   /* TYPES[i] is the set of possible builtin-operator parameter types
3208      we will consider for the Ith argument.  */
3209   vec<tree, va_gc> *types[2];
3210   unsigned ix;
3211   vec<tree, va_gc> &args = *argv;
3212   unsigned len = args.length ();
3213 
3214   for (unsigned i = 0; i < len; ++i)
3215     {
3216       if (args[i])
3217 	argtypes[i] = unlowered_expr_type (args[i]);
3218       else
3219 	argtypes[i] = NULL_TREE;
3220     }
3221 
3222   switch (code)
3223     {
3224 /* 4 For every pair T, VQ), where T is an arithmetic or  enumeration  type,
3225      and  VQ  is  either  volatile or empty, there exist candidate operator
3226      functions of the form
3227 		 VQ T&   operator++(VQ T&);  */
3228 
3229     case POSTINCREMENT_EXPR:
3230     case PREINCREMENT_EXPR:
3231     case POSTDECREMENT_EXPR:
3232     case PREDECREMENT_EXPR:
3233     case MODIFY_EXPR:
3234       ref1 = 1;
3235       break;
3236 
3237 /* 24There also exist candidate operator functions of the form
3238 	     bool    operator!(bool);
3239 	     bool    operator&&(bool, bool);
3240 	     bool    operator||(bool, bool);  */
3241 
3242     case TRUTH_NOT_EXPR:
3243       build_builtin_candidate
3244 	(candidates, fnname, boolean_type_node,
3245 	 NULL_TREE, args, argtypes, flags, complain);
3246       return;
3247 
3248     case TRUTH_ORIF_EXPR:
3249     case TRUTH_ANDIF_EXPR:
3250       build_builtin_candidate
3251 	(candidates, fnname, boolean_type_node,
3252 	 boolean_type_node, args, argtypes, flags, complain);
3253       return;
3254 
3255     case ADDR_EXPR:
3256     case COMPOUND_EXPR:
3257     case COMPONENT_REF:
3258     case CO_AWAIT_EXPR:
3259       return;
3260 
3261     case COND_EXPR:
3262     case EQ_EXPR:
3263     case NE_EXPR:
3264     case LT_EXPR:
3265     case LE_EXPR:
3266     case GT_EXPR:
3267     case GE_EXPR:
3268     case SPACESHIP_EXPR:
3269       enum_p = 1;
3270       /* Fall through.  */
3271 
3272     default:
3273       ref1 = 0;
3274     }
3275 
3276   types[0] = make_tree_vector ();
3277   types[1] = make_tree_vector ();
3278 
3279   if (len == 3)
3280     len = 2;
3281   for (unsigned i = 0; i < len; ++i)
3282     {
3283       if (MAYBE_CLASS_TYPE_P (argtypes[i]))
3284 	{
3285 	  tree convs;
3286 
3287 	  if (i == 0 && code == MODIFY_EXPR && code2 == NOP_EXPR)
3288 	    return;
3289 
3290 	  convs = lookup_conversions (argtypes[i]);
3291 
3292 	  if (code == COND_EXPR)
3293 	    {
3294 	      if (lvalue_p (args[i]))
3295 		vec_safe_push (types[i], build_reference_type (argtypes[i]));
3296 
3297 	      vec_safe_push (types[i], TYPE_MAIN_VARIANT (argtypes[i]));
3298 	    }
3299 
3300 	  else if (! convs)
3301 	    return;
3302 
3303 	  for (; convs; convs = TREE_CHAIN (convs))
3304 	    {
3305 	      type = TREE_TYPE (convs);
3306 
3307 	      if (i == 0 && ref1
3308 		  && (!TYPE_REF_P (type)
3309 		      || CP_TYPE_CONST_P (TREE_TYPE (type))))
3310 		continue;
3311 
3312 	      if (code == COND_EXPR && TYPE_REF_P (type))
3313 		vec_safe_push (types[i], type);
3314 
3315 	      type = non_reference (type);
3316 	      if (i != 0 || ! ref1)
3317 		{
3318 		  type = cv_unqualified (type_decays_to (type));
3319 		  if (enum_p && TREE_CODE (type) == ENUMERAL_TYPE)
3320 		    vec_safe_push (types[i], type);
3321 		  if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3322 		    type = type_promotes_to (type);
3323 		}
3324 
3325 	      if (! vec_member (type, types[i]))
3326 		vec_safe_push (types[i], type);
3327 	    }
3328 	}
3329       else
3330 	{
3331 	  if (code == COND_EXPR && lvalue_p (args[i]))
3332 	    vec_safe_push (types[i], build_reference_type (argtypes[i]));
3333 	  type = non_reference (argtypes[i]);
3334 	  if (i != 0 || ! ref1)
3335 	    {
3336 	      type = cv_unqualified (type_decays_to (type));
3337 	      if (enum_p && UNSCOPED_ENUM_P (type))
3338 		vec_safe_push (types[i], type);
3339 	      if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3340 		type = type_promotes_to (type);
3341 	    }
3342 	  vec_safe_push (types[i], type);
3343 	}
3344     }
3345 
3346   /* Run through the possible parameter types of both arguments,
3347      creating candidates with those parameter types.  */
3348   FOR_EACH_VEC_ELT_REVERSE (*(types[0]), ix, t)
3349     {
3350       unsigned jx;
3351       tree u;
3352 
3353       if (!types[1]->is_empty ())
3354 	FOR_EACH_VEC_ELT_REVERSE (*(types[1]), jx, u)
3355 	  add_builtin_candidate
3356 	    (candidates, code, code2, fnname, t,
3357 	     u, args, argtypes, flags, complain);
3358       else
3359 	add_builtin_candidate
3360 	  (candidates, code, code2, fnname, t,
3361 	   NULL_TREE, args, argtypes, flags, complain);
3362     }
3363 
3364   release_tree_vector (types[0]);
3365   release_tree_vector (types[1]);
3366 }
3367 
3368 
3369 /* If TMPL can be successfully instantiated as indicated by
3370    EXPLICIT_TARGS and ARGLIST, adds the instantiation to CANDIDATES.
3371 
3372    TMPL is the template.  EXPLICIT_TARGS are any explicit template
3373    arguments.  ARGLIST is the arguments provided at the call-site.
3374    This does not change ARGLIST.  The RETURN_TYPE is the desired type
3375    for conversion operators.  If OBJ is NULL_TREE, FLAGS and CTYPE are
3376    as for add_function_candidate.  If an OBJ is supplied, FLAGS and
3377    CTYPE are ignored, and OBJ is as for add_conv_candidate.
3378 
3379    SHORTCUT_BAD_CONVS is as in add_function_candidate.  */
3380 
3381 static struct z_candidate*
add_template_candidate_real(struct z_candidate ** candidates,tree tmpl,tree ctype,tree explicit_targs,tree first_arg,const vec<tree,va_gc> * arglist,tree return_type,tree access_path,tree conversion_path,int flags,tree obj,unification_kind_t strict,bool shortcut_bad_convs,tsubst_flags_t complain)3382 add_template_candidate_real (struct z_candidate **candidates, tree tmpl,
3383 			     tree ctype, tree explicit_targs, tree first_arg,
3384 			     const vec<tree, va_gc> *arglist, tree return_type,
3385 			     tree access_path, tree conversion_path,
3386 			     int flags, tree obj, unification_kind_t strict,
3387 			     bool shortcut_bad_convs, tsubst_flags_t complain)
3388 {
3389   int ntparms = DECL_NTPARMS (tmpl);
3390   tree targs = make_tree_vec (ntparms);
3391   unsigned int len = vec_safe_length (arglist);
3392   unsigned int nargs = (first_arg == NULL_TREE ? 0 : 1) + len;
3393   unsigned int skip_without_in_chrg = 0;
3394   tree first_arg_without_in_chrg = first_arg;
3395   tree *args_without_in_chrg;
3396   unsigned int nargs_without_in_chrg;
3397   unsigned int ia, ix;
3398   tree arg;
3399   struct z_candidate *cand;
3400   tree fn;
3401   struct rejection_reason *reason = NULL;
3402   int errs;
3403   conversion **convs = NULL;
3404 
3405   /* We don't do deduction on the in-charge parameter, the VTT
3406      parameter or 'this'.  */
3407   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl))
3408     {
3409       if (first_arg_without_in_chrg != NULL_TREE)
3410 	first_arg_without_in_chrg = NULL_TREE;
3411       else if (return_type && strict == DEDUCE_CALL)
3412 	/* We're deducing for a call to the result of a template conversion
3413 	   function, so the args don't contain 'this'; leave them alone.  */;
3414       else
3415 	++skip_without_in_chrg;
3416     }
3417 
3418   if ((DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (tmpl)
3419        || DECL_BASE_CONSTRUCTOR_P (tmpl))
3420       && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (tmpl)))
3421     {
3422       if (first_arg_without_in_chrg != NULL_TREE)
3423 	first_arg_without_in_chrg = NULL_TREE;
3424       else
3425 	++skip_without_in_chrg;
3426     }
3427 
3428   if (len < skip_without_in_chrg)
3429     return NULL;
3430 
3431   if (DECL_CONSTRUCTOR_P (tmpl) && nargs == 2
3432       && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (first_arg),
3433 						    TREE_TYPE ((*arglist)[0])))
3434     {
3435       /* 12.8/6 says, "A declaration of a constructor for a class X is
3436 	 ill-formed if its first parameter is of type (optionally cv-qualified)
3437 	 X and either there are no other parameters or else all other
3438 	 parameters have default arguments. A member function template is never
3439 	 instantiated to produce such a constructor signature."
3440 
3441 	 So if we're trying to copy an object of the containing class, don't
3442 	 consider a template constructor that has a first parameter type that
3443 	 is just a template parameter, as we would deduce a signature that we
3444 	 would then reject in the code below.  */
3445       if (tree firstparm = FUNCTION_FIRST_USER_PARMTYPE (tmpl))
3446 	{
3447 	  firstparm = TREE_VALUE (firstparm);
3448 	  if (PACK_EXPANSION_P (firstparm))
3449 	    firstparm = PACK_EXPANSION_PATTERN (firstparm);
3450 	  if (TREE_CODE (firstparm) == TEMPLATE_TYPE_PARM)
3451 	    {
3452 	      gcc_assert (!explicit_targs);
3453 	      reason = invalid_copy_with_fn_template_rejection ();
3454 	      goto fail;
3455 	    }
3456 	}
3457     }
3458 
3459   nargs_without_in_chrg = ((first_arg_without_in_chrg != NULL_TREE ? 1 : 0)
3460 			   + (len - skip_without_in_chrg));
3461   args_without_in_chrg = XALLOCAVEC (tree, nargs_without_in_chrg);
3462   ia = 0;
3463   if (first_arg_without_in_chrg != NULL_TREE)
3464     {
3465       args_without_in_chrg[ia] = first_arg_without_in_chrg;
3466       ++ia;
3467     }
3468   for (ix = skip_without_in_chrg;
3469        vec_safe_iterate (arglist, ix, &arg);
3470        ++ix)
3471     {
3472       args_without_in_chrg[ia] = arg;
3473       ++ia;
3474     }
3475   gcc_assert (ia == nargs_without_in_chrg);
3476 
3477   if (!obj && explicit_targs)
3478     {
3479       /* Check that there's no obvious arity mismatch before proceeding with
3480 	 deduction.  This avoids substituting explicit template arguments
3481 	 into the template (which could result in an error outside the
3482 	 immediate context) when the resulting candidate would be unviable
3483 	 anyway.  */
3484       int min_arity = 0, max_arity = 0;
3485       tree parms = TYPE_ARG_TYPES (TREE_TYPE (tmpl));
3486       parms = skip_artificial_parms_for (tmpl, parms);
3487       for (; parms != void_list_node; parms = TREE_CHAIN (parms))
3488 	{
3489 	  if (!parms || PACK_EXPANSION_P (TREE_VALUE (parms)))
3490 	    {
3491 	      max_arity = -1;
3492 	      break;
3493 	    }
3494 	  if (TREE_PURPOSE (parms))
3495 	    /* A parameter with a default argument.  */
3496 	    ++max_arity;
3497 	  else
3498 	    ++min_arity, ++max_arity;
3499 	}
3500       if (ia < (unsigned)min_arity)
3501 	{
3502 	  /* Too few arguments.  */
3503 	  reason = arity_rejection (NULL_TREE, min_arity, ia,
3504 				    /*least_p=*/(max_arity == -1));
3505 	  goto fail;
3506 	}
3507       else if (max_arity != -1 && ia > (unsigned)max_arity)
3508 	{
3509 	  /* Too many arguments.  */
3510 	  reason = arity_rejection (NULL_TREE, max_arity, ia);
3511 	  goto fail;
3512 	}
3513     }
3514 
3515   errs = errorcount+sorrycount;
3516   if (!obj)
3517     {
3518       convs = alloc_conversions (nargs);
3519 
3520       if (shortcut_bad_convs
3521 	  && DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl)
3522 	  && !DECL_CONSTRUCTOR_P (tmpl))
3523 	{
3524 	  /* Check the 'this' conversion before proceeding with deduction.
3525 	     This is effectively an extension of the DR 1391 resolution
3526 	     that we perform in check_non_deducible_conversions, though it's
3527 	     convenient to do this extra check here instead of there.  */
3528 	  tree parmtype = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (tmpl)));
3529 	  tree argtype = lvalue_type (first_arg);
3530 	  tree arg = first_arg;
3531 	  conversion *t = build_this_conversion (tmpl, ctype,
3532 						 parmtype, argtype, arg,
3533 						 flags, complain);
3534 	  convs[0] = t;
3535 	  if (t->bad_p)
3536 	    {
3537 	      reason = bad_arg_conversion_rejection (first_arg, 0,
3538 						     arg, parmtype,
3539 						     EXPR_LOCATION (arg));
3540 	      goto fail;
3541 	    }
3542 	}
3543     }
3544   fn = fn_type_unification (tmpl, explicit_targs, targs,
3545 			    args_without_in_chrg,
3546 			    nargs_without_in_chrg,
3547 			    return_type, strict, flags, convs,
3548 			    false, complain & tf_decltype);
3549 
3550   if (fn == error_mark_node)
3551     {
3552       /* Don't repeat unification later if it already resulted in errors.  */
3553       if (errorcount+sorrycount == errs)
3554 	reason = template_unification_rejection (tmpl, explicit_targs,
3555 						 targs, args_without_in_chrg,
3556 						 nargs_without_in_chrg,
3557 						 return_type, strict, flags);
3558       else
3559 	reason = template_unification_error_rejection ();
3560       goto fail;
3561     }
3562 
3563   /* Now the explicit specifier might have been deduced; check if this
3564      declaration is explicit.  If it is and we're ignoring non-converting
3565      constructors, don't add this function to the set of candidates.  */
3566   if ((flags & LOOKUP_ONLYCONVERTING) && DECL_NONCONVERTING_P (fn))
3567     return NULL;
3568 
3569   if (DECL_CONSTRUCTOR_P (fn) && nargs == 2)
3570     {
3571       tree arg_types = FUNCTION_FIRST_USER_PARMTYPE (fn);
3572       if (arg_types && same_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (arg_types)),
3573 				    ctype))
3574 	{
3575 	  /* We're trying to produce a constructor with a prohibited signature,
3576 	     as discussed above; handle here any cases we didn't catch then,
3577 	     such as X(X<T>).  */
3578 	  reason = invalid_copy_with_fn_template_rejection ();
3579 	  goto fail;
3580 	}
3581     }
3582 
3583   if (obj != NULL_TREE)
3584     /* Aha, this is a conversion function.  */
3585     cand = add_conv_candidate (candidates, fn, obj, arglist,
3586 			       access_path, conversion_path, complain);
3587   else
3588     cand = add_function_candidate (candidates, fn, ctype,
3589 				   first_arg, arglist, access_path,
3590 				   conversion_path, flags, convs,
3591 				   shortcut_bad_convs, complain);
3592   if (DECL_TI_TEMPLATE (fn) != tmpl)
3593     /* This situation can occur if a member template of a template
3594        class is specialized.  Then, instantiate_template might return
3595        an instantiation of the specialization, in which case the
3596        DECL_TI_TEMPLATE field will point at the original
3597        specialization.  For example:
3598 
3599 	 template <class T> struct S { template <class U> void f(U);
3600 				       template <> void f(int) {}; };
3601 	 S<double> sd;
3602 	 sd.f(3);
3603 
3604        Here, TMPL will be template <class U> S<double>::f(U).
3605        And, instantiate template will give us the specialization
3606        template <> S<double>::f(int).  But, the DECL_TI_TEMPLATE field
3607        for this will point at template <class T> template <> S<T>::f(int),
3608        so that we can find the definition.  For the purposes of
3609        overload resolution, however, we want the original TMPL.  */
3610     cand->template_decl = build_template_info (tmpl, targs);
3611   else
3612     cand->template_decl = DECL_TEMPLATE_INFO (fn);
3613   cand->explicit_targs = explicit_targs;
3614 
3615   return cand;
3616  fail:
3617   int viable = (reason->code == rr_bad_arg_conversion ? -1 : 0);
3618   return add_candidate (candidates, tmpl, first_arg, arglist, nargs, convs,
3619 			access_path, conversion_path, viable, reason, flags);
3620 }
3621 
3622 
3623 static struct z_candidate *
add_template_candidate(struct z_candidate ** candidates,tree tmpl,tree ctype,tree explicit_targs,tree first_arg,const vec<tree,va_gc> * arglist,tree return_type,tree access_path,tree conversion_path,int flags,unification_kind_t strict,bool shortcut_bad_convs,tsubst_flags_t complain)3624 add_template_candidate (struct z_candidate **candidates, tree tmpl, tree ctype,
3625 			tree explicit_targs, tree first_arg,
3626 			const vec<tree, va_gc> *arglist, tree return_type,
3627 			tree access_path, tree conversion_path, int flags,
3628 			unification_kind_t strict, bool shortcut_bad_convs,
3629 			tsubst_flags_t complain)
3630 {
3631   return
3632     add_template_candidate_real (candidates, tmpl, ctype,
3633 				 explicit_targs, first_arg, arglist,
3634 				 return_type, access_path, conversion_path,
3635 				 flags, NULL_TREE, strict, shortcut_bad_convs,
3636 				 complain);
3637 }
3638 
3639 /* Create an overload candidate for the conversion function template TMPL,
3640    returning RETURN_TYPE, which will be invoked for expression OBJ to produce a
3641    pointer-to-function which will in turn be called with the argument list
3642    ARGLIST, and add it to CANDIDATES.  This does not change ARGLIST.  FLAGS is
3643    passed on to implicit_conversion.  */
3644 
3645 static struct z_candidate *
add_template_conv_candidate(struct z_candidate ** candidates,tree tmpl,tree obj,const vec<tree,va_gc> * arglist,tree return_type,tree access_path,tree conversion_path,tsubst_flags_t complain)3646 add_template_conv_candidate (struct z_candidate **candidates, tree tmpl,
3647 			     tree obj,
3648 			     const vec<tree, va_gc> *arglist,
3649 			     tree return_type, tree access_path,
3650 			     tree conversion_path, tsubst_flags_t complain)
3651 {
3652   /* Making this work broke PR 71117 and 85118, so until the committee resolves
3653      core issue 2189, let's disable this candidate if there are any call
3654      operators.  */
3655   if (*candidates)
3656     return NULL;
3657 
3658   return
3659     add_template_candidate_real (candidates, tmpl, NULL_TREE, NULL_TREE,
3660 				 NULL_TREE, arglist, return_type, access_path,
3661 				 conversion_path, 0, obj, DEDUCE_CALL,
3662 				 /*shortcut_bad_convs=*/false, complain);
3663 }
3664 
3665 /* The CANDS are the set of candidates that were considered for
3666    overload resolution.  Return the set of viable candidates, or CANDS
3667    if none are viable.  If any of the candidates were viable, set
3668    *ANY_VIABLE_P to true.  STRICT_P is true if a candidate should be
3669    considered viable only if it is strictly viable.  */
3670 
3671 static struct z_candidate*
splice_viable(struct z_candidate * cands,bool strict_p,bool * any_viable_p)3672 splice_viable (struct z_candidate *cands,
3673 	       bool strict_p,
3674 	       bool *any_viable_p)
3675 {
3676   struct z_candidate *viable;
3677   struct z_candidate **last_viable;
3678   struct z_candidate **cand;
3679   bool found_strictly_viable = false;
3680 
3681   /* Be strict inside templates, since build_over_call won't actually
3682      do the conversions to get pedwarns.  */
3683   if (processing_template_decl)
3684     strict_p = true;
3685 
3686   viable = NULL;
3687   last_viable = &viable;
3688   *any_viable_p = false;
3689 
3690   cand = &cands;
3691   while (*cand)
3692     {
3693       struct z_candidate *c = *cand;
3694       if (!strict_p
3695 	  && (c->viable == 1 || TREE_CODE (c->fn) == TEMPLATE_DECL))
3696 	{
3697 	  /* Be strict in the presence of a viable candidate.  Also if
3698 	     there are template candidates, so that we get deduction errors
3699 	     for them instead of silently preferring a bad conversion.  */
3700 	  strict_p = true;
3701 	  if (viable && !found_strictly_viable)
3702 	    {
3703 	      /* Put any spliced near matches back onto the main list so
3704 		 that we see them if there is no strict match.  */
3705 	      *any_viable_p = false;
3706 	      *last_viable = cands;
3707 	      cands = viable;
3708 	      viable = NULL;
3709 	      last_viable = &viable;
3710 	    }
3711 	}
3712 
3713       if (strict_p ? c->viable == 1 : c->viable)
3714 	{
3715 	  *last_viable = c;
3716 	  *cand = c->next;
3717 	  c->next = NULL;
3718 	  last_viable = &c->next;
3719 	  *any_viable_p = true;
3720 	  if (c->viable == 1)
3721 	    found_strictly_viable = true;
3722 	}
3723       else
3724 	cand = &c->next;
3725     }
3726 
3727   return viable ? viable : cands;
3728 }
3729 
3730 static bool
any_strictly_viable(struct z_candidate * cands)3731 any_strictly_viable (struct z_candidate *cands)
3732 {
3733   for (; cands; cands = cands->next)
3734     if (cands->viable == 1)
3735       return true;
3736   return false;
3737 }
3738 
3739 /* OBJ is being used in an expression like "OBJ.f (...)".  In other
3740    words, it is about to become the "this" pointer for a member
3741    function call.  Take the address of the object.  */
3742 
3743 static tree
build_this(tree obj)3744 build_this (tree obj)
3745 {
3746   /* In a template, we are only concerned about the type of the
3747      expression, so we can take a shortcut.  */
3748   if (processing_template_decl)
3749     return build_address (obj);
3750 
3751   return cp_build_addr_expr (obj, tf_warning_or_error);
3752 }
3753 
3754 /* Returns true iff functions are equivalent. Equivalent functions are
3755    not '==' only if one is a function-local extern function or if
3756    both are extern "C".  */
3757 
3758 static inline int
equal_functions(tree fn1,tree fn2)3759 equal_functions (tree fn1, tree fn2)
3760 {
3761   if (TREE_CODE (fn1) != TREE_CODE (fn2))
3762     return 0;
3763   if (TREE_CODE (fn1) == TEMPLATE_DECL)
3764     return fn1 == fn2;
3765   if (DECL_LOCAL_DECL_P (fn1) || DECL_LOCAL_DECL_P (fn2)
3766       || DECL_EXTERN_C_FUNCTION_P (fn1))
3767     return decls_match (fn1, fn2);
3768   return fn1 == fn2;
3769 }
3770 
3771 /* Print information about a candidate FN being rejected due to INFO.  */
3772 
3773 static void
print_conversion_rejection(location_t loc,struct conversion_info * info,tree fn)3774 print_conversion_rejection (location_t loc, struct conversion_info *info,
3775 			    tree fn)
3776 {
3777   tree from = info->from;
3778   if (!TYPE_P (from))
3779     from = lvalue_type (from);
3780   if (info->n_arg == -1)
3781     {
3782       /* Conversion of implicit `this' argument failed.  */
3783       if (!TYPE_P (info->from))
3784 	/* A bad conversion for 'this' must be discarding cv-quals.  */
3785 	inform (loc, "  passing %qT as %<this%> "
3786 		"argument discards qualifiers",
3787 		from);
3788       else
3789 	inform (loc, "  no known conversion for implicit "
3790 		"%<this%> parameter from %qH to %qI",
3791 		from, info->to_type);
3792     }
3793   else if (!TYPE_P (info->from))
3794     {
3795       if (info->n_arg >= 0)
3796 	inform (loc, "  conversion of argument %d would be ill-formed:",
3797 		info->n_arg + 1);
3798       perform_implicit_conversion (info->to_type, info->from,
3799 				   tf_warning_or_error);
3800     }
3801   else if (info->n_arg == -2)
3802     /* Conversion of conversion function return value failed.  */
3803     inform (loc, "  no known conversion from %qH to %qI",
3804 	    from, info->to_type);
3805   else
3806     {
3807       if (TREE_CODE (fn) == FUNCTION_DECL)
3808 	loc = get_fndecl_argument_location (fn, info->n_arg);
3809       inform (loc, "  no known conversion for argument %d from %qH to %qI",
3810 	      info->n_arg + 1, from, info->to_type);
3811     }
3812 }
3813 
3814 /* Print information about a candidate with WANT parameters and we found
3815    HAVE.  */
3816 
3817 static void
print_arity_information(location_t loc,unsigned int have,unsigned int want,bool least_p)3818 print_arity_information (location_t loc, unsigned int have, unsigned int want,
3819 			 bool least_p)
3820 {
3821   if (least_p)
3822     inform_n (loc, want,
3823 	      "  candidate expects at least %d argument, %d provided",
3824 	      "  candidate expects at least %d arguments, %d provided",
3825 	      want, have);
3826   else
3827     inform_n (loc, want,
3828 	      "  candidate expects %d argument, %d provided",
3829 	      "  candidate expects %d arguments, %d provided",
3830 	      want, have);
3831 }
3832 
3833 /* Print information about one overload candidate CANDIDATE.  MSGSTR
3834    is the text to print before the candidate itself.
3835 
3836    NOTE: Unlike most diagnostic functions in GCC, MSGSTR is expected
3837    to have been run through gettext by the caller.  This wart makes
3838    life simpler in print_z_candidates and for the translators.  */
3839 
3840 static void
print_z_candidate(location_t loc,const char * msgstr,struct z_candidate * candidate)3841 print_z_candidate (location_t loc, const char *msgstr,
3842 		   struct z_candidate *candidate)
3843 {
3844   const char *msg = (msgstr == NULL
3845 		     ? ""
3846 		     : ACONCAT ((_(msgstr), " ", NULL)));
3847   tree fn = candidate->fn;
3848   if (flag_new_inheriting_ctors)
3849     fn = strip_inheriting_ctors (fn);
3850   location_t cloc = location_of (fn);
3851 
3852   if (identifier_p (fn))
3853     {
3854       cloc = loc;
3855       if (candidate->num_convs == 3)
3856 	inform (cloc, "%s%<%D(%T, %T, %T)%> (built-in)", msg, fn,
3857 		candidate->convs[0]->type,
3858 		candidate->convs[1]->type,
3859 		candidate->convs[2]->type);
3860       else if (candidate->num_convs == 2)
3861 	inform (cloc, "%s%<%D(%T, %T)%> (built-in)", msg, fn,
3862 		candidate->convs[0]->type,
3863 		candidate->convs[1]->type);
3864       else
3865 	inform (cloc, "%s%<%D(%T)%> (built-in)", msg, fn,
3866 		candidate->convs[0]->type);
3867     }
3868   else if (TYPE_P (fn))
3869     inform (cloc, "%s%qT (conversion)", msg, fn);
3870   else if (candidate->viable == -1)
3871     inform (cloc, "%s%#qD (near match)", msg, fn);
3872   else if (DECL_DELETED_FN (fn))
3873     inform (cloc, "%s%#qD (deleted)", msg, fn);
3874   else if (candidate->reversed ())
3875     inform (cloc, "%s%#qD (reversed)", msg, fn);
3876   else if (candidate->rewritten ())
3877     inform (cloc, "%s%#qD (rewritten)", msg, fn);
3878   else
3879     inform (cloc, "%s%#qD", msg, fn);
3880   if (fn != candidate->fn)
3881     {
3882       cloc = location_of (candidate->fn);
3883       inform (cloc, "  inherited here");
3884     }
3885   /* Give the user some information about why this candidate failed.  */
3886   if (candidate->reason != NULL)
3887     {
3888       struct rejection_reason *r = candidate->reason;
3889 
3890       switch (r->code)
3891 	{
3892 	case rr_arity:
3893 	  print_arity_information (cloc, r->u.arity.actual,
3894 				   r->u.arity.expected,
3895 				   r->u.arity.least_p);
3896 	  break;
3897 	case rr_arg_conversion:
3898 	  print_conversion_rejection (cloc, &r->u.conversion, fn);
3899 	  break;
3900 	case rr_bad_arg_conversion:
3901 	  print_conversion_rejection (cloc, &r->u.bad_conversion, fn);
3902 	  break;
3903 	case rr_explicit_conversion:
3904 	  inform (cloc, "  return type %qT of explicit conversion function "
3905 		  "cannot be converted to %qT with a qualification "
3906 		  "conversion", r->u.conversion.from,
3907 		  r->u.conversion.to_type);
3908 	  break;
3909 	case rr_template_conversion:
3910 	  inform (cloc, "  conversion from return type %qT of template "
3911 		  "conversion function specialization to %qT is not an "
3912 		  "exact match", r->u.conversion.from,
3913 		  r->u.conversion.to_type);
3914 	  break;
3915 	case rr_template_unification:
3916 	  /* We use template_unification_error_rejection if unification caused
3917 	     actual non-SFINAE errors, in which case we don't need to repeat
3918 	     them here.  */
3919 	  if (r->u.template_unification.tmpl == NULL_TREE)
3920 	    {
3921 	      inform (cloc, "  substitution of deduced template arguments "
3922 		      "resulted in errors seen above");
3923 	      break;
3924 	    }
3925 	  /* Re-run template unification with diagnostics.  */
3926 	  inform (cloc, "  template argument deduction/substitution failed:");
3927 	  fn_type_unification (r->u.template_unification.tmpl,
3928 			       r->u.template_unification.explicit_targs,
3929 			       (make_tree_vec
3930 				(r->u.template_unification.num_targs)),
3931 			       r->u.template_unification.args,
3932 			       r->u.template_unification.nargs,
3933 			       r->u.template_unification.return_type,
3934 			       r->u.template_unification.strict,
3935 			       r->u.template_unification.flags,
3936 			       NULL, true, false);
3937 	  break;
3938 	case rr_invalid_copy:
3939 	  inform (cloc,
3940 		  "  a constructor taking a single argument of its own "
3941 		  "class type is invalid");
3942 	  break;
3943 	case rr_constraint_failure:
3944 	  diagnose_constraints (cloc, fn, NULL_TREE);
3945 	  break;
3946 	case rr_inherited_ctor:
3947 	  inform (cloc, "  an inherited constructor is not a candidate for "
3948 		  "initialization from an expression of the same or derived "
3949 		  "type");
3950 	  break;
3951 	case rr_none:
3952 	default:
3953 	  /* This candidate didn't have any issues or we failed to
3954 	     handle a particular code.  Either way...  */
3955 	  gcc_unreachable ();
3956 	}
3957     }
3958 }
3959 
3960 static void
print_z_candidates(location_t loc,struct z_candidate * candidates)3961 print_z_candidates (location_t loc, struct z_candidate *candidates)
3962 {
3963   struct z_candidate *cand1;
3964   struct z_candidate **cand2;
3965 
3966   if (!candidates)
3967     return;
3968 
3969   /* Remove non-viable deleted candidates.  */
3970   cand1 = candidates;
3971   for (cand2 = &cand1; *cand2; )
3972     {
3973       if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
3974 	  && !(*cand2)->viable
3975 	  && DECL_DELETED_FN ((*cand2)->fn))
3976 	*cand2 = (*cand2)->next;
3977       else
3978 	cand2 = &(*cand2)->next;
3979     }
3980   /* ...if there are any non-deleted ones.  */
3981   if (cand1)
3982     candidates = cand1;
3983 
3984   /* There may be duplicates in the set of candidates.  We put off
3985      checking this condition as long as possible, since we have no way
3986      to eliminate duplicates from a set of functions in less than n^2
3987      time.  Now we are about to emit an error message, so it is more
3988      permissible to go slowly.  */
3989   for (cand1 = candidates; cand1; cand1 = cand1->next)
3990     {
3991       tree fn = cand1->fn;
3992       /* Skip builtin candidates and conversion functions.  */
3993       if (!DECL_P (fn))
3994 	continue;
3995       cand2 = &cand1->next;
3996       while (*cand2)
3997 	{
3998 	  if (DECL_P ((*cand2)->fn)
3999 	      && equal_functions (fn, (*cand2)->fn))
4000 	    *cand2 = (*cand2)->next;
4001 	  else
4002 	    cand2 = &(*cand2)->next;
4003 	}
4004     }
4005 
4006   for (; candidates; candidates = candidates->next)
4007     print_z_candidate (loc, N_("candidate:"), candidates);
4008 }
4009 
4010 /* USER_SEQ is a user-defined conversion sequence, beginning with a
4011    USER_CONV.  STD_SEQ is the standard conversion sequence applied to
4012    the result of the conversion function to convert it to the final
4013    desired type.  Merge the two sequences into a single sequence,
4014    and return the merged sequence.  */
4015 
4016 static conversion *
merge_conversion_sequences(conversion * user_seq,conversion * std_seq)4017 merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
4018 {
4019   conversion **t;
4020   bool bad = user_seq->bad_p;
4021 
4022   gcc_assert (user_seq->kind == ck_user);
4023 
4024   /* Find the end of the second conversion sequence.  */
4025   for (t = &std_seq; (*t)->kind != ck_identity; t = &((*t)->u.next))
4026     {
4027       /* The entire sequence is a user-conversion sequence.  */
4028       (*t)->user_conv_p = true;
4029       if (bad)
4030 	(*t)->bad_p = true;
4031     }
4032 
4033   if ((*t)->rvaluedness_matches_p)
4034     /* We're binding a reference directly to the result of the conversion.
4035        build_user_type_conversion_1 stripped the REFERENCE_TYPE from the return
4036        type, but we want it back.  */
4037     user_seq->type = TREE_TYPE (TREE_TYPE (user_seq->cand->fn));
4038 
4039   /* Replace the identity conversion with the user conversion
4040      sequence.  */
4041   *t = user_seq;
4042 
4043   return std_seq;
4044 }
4045 
4046 /* Handle overload resolution for initializing an object of class type from
4047    an initializer list.  First we look for a suitable constructor that
4048    takes a std::initializer_list; if we don't find one, we then look for a
4049    non-list constructor.
4050 
4051    Parameters are as for add_candidates, except that the arguments are in
4052    the form of a CONSTRUCTOR (the initializer list) rather than a vector, and
4053    the RETURN_TYPE parameter is replaced by TOTYPE, the desired type.  */
4054 
4055 static void
add_list_candidates(tree fns,tree first_arg,const vec<tree,va_gc> * args,tree totype,tree explicit_targs,bool template_only,tree conversion_path,tree access_path,int flags,struct z_candidate ** candidates,tsubst_flags_t complain)4056 add_list_candidates (tree fns, tree first_arg,
4057 		     const vec<tree, va_gc> *args, tree totype,
4058 		     tree explicit_targs, bool template_only,
4059 		     tree conversion_path, tree access_path,
4060 		     int flags,
4061 		     struct z_candidate **candidates,
4062 		     tsubst_flags_t complain)
4063 {
4064   gcc_assert (*candidates == NULL);
4065 
4066   /* We're looking for a ctor for list-initialization.  */
4067   flags |= LOOKUP_LIST_INIT_CTOR;
4068   /* And we don't allow narrowing conversions.  We also use this flag to
4069      avoid the copy constructor call for copy-list-initialization.  */
4070   flags |= LOOKUP_NO_NARROWING;
4071 
4072   unsigned nart = num_artificial_parms_for (OVL_FIRST (fns)) - 1;
4073   tree init_list = (*args)[nart];
4074 
4075   /* Always use the default constructor if the list is empty (DR 990).  */
4076   if (CONSTRUCTOR_NELTS (init_list) == 0
4077       && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
4078     ;
4079   /* If the class has a list ctor, try passing the list as a single
4080      argument first, but only consider list ctors.  */
4081   else if (TYPE_HAS_LIST_CTOR (totype))
4082     {
4083       flags |= LOOKUP_LIST_ONLY;
4084       add_candidates (fns, first_arg, args, NULL_TREE,
4085 		      explicit_targs, template_only, conversion_path,
4086 		      access_path, flags, candidates, complain);
4087       if (any_strictly_viable (*candidates))
4088 	return;
4089     }
4090   else if (CONSTRUCTOR_IS_DESIGNATED_INIT (init_list)
4091 	   && !CP_AGGREGATE_TYPE_P (totype))
4092     {
4093       if (complain & tf_error)
4094 	error ("designated initializers cannot be used with a "
4095 	       "non-aggregate type %qT", totype);
4096       return;
4097     }
4098 
4099   /* Expand the CONSTRUCTOR into a new argument vec.  */
4100   vec<tree, va_gc> *new_args;
4101   vec_alloc (new_args, nart + CONSTRUCTOR_NELTS (init_list));
4102   for (unsigned i = 0; i < nart; ++i)
4103     new_args->quick_push ((*args)[i]);
4104   for (unsigned i = 0; i < CONSTRUCTOR_NELTS (init_list); ++i)
4105     new_args->quick_push (CONSTRUCTOR_ELT (init_list, i)->value);
4106 
4107   /* We aren't looking for list-ctors anymore.  */
4108   flags &= ~LOOKUP_LIST_ONLY;
4109   /* We allow more user-defined conversions within an init-list.  */
4110   flags &= ~LOOKUP_NO_CONVERSION;
4111 
4112   add_candidates (fns, first_arg, new_args, NULL_TREE,
4113 		  explicit_targs, template_only, conversion_path,
4114 		  access_path, flags, candidates, complain);
4115 }
4116 
4117 /* Returns the best overload candidate to perform the requested
4118    conversion.  This function is used for three the overloading situations
4119    described in [over.match.copy], [over.match.conv], and [over.match.ref].
4120    If TOTYPE is a REFERENCE_TYPE, we're trying to find a direct binding as
4121    per [dcl.init.ref], so we ignore temporary bindings.  */
4122 
4123 static struct z_candidate *
build_user_type_conversion_1(tree totype,tree expr,int flags,tsubst_flags_t complain)4124 build_user_type_conversion_1 (tree totype, tree expr, int flags,
4125 			      tsubst_flags_t complain)
4126 {
4127   struct z_candidate *candidates, *cand;
4128   tree fromtype;
4129   tree ctors = NULL_TREE;
4130   tree conv_fns = NULL_TREE;
4131   conversion *conv = NULL;
4132   tree first_arg = NULL_TREE;
4133   vec<tree, va_gc> *args = NULL;
4134   bool any_viable_p;
4135   int convflags;
4136 
4137   if (!expr)
4138     return NULL;
4139 
4140   fromtype = TREE_TYPE (expr);
4141 
4142   /* We represent conversion within a hierarchy using RVALUE_CONV and
4143      BASE_CONV, as specified by [over.best.ics]; these become plain
4144      constructor calls, as specified in [dcl.init].  */
4145   gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
4146 	      || !DERIVED_FROM_P (totype, fromtype));
4147 
4148   if (CLASS_TYPE_P (totype))
4149     /* Use lookup_fnfields_slot instead of lookup_fnfields to avoid
4150        creating a garbage BASELINK; constructors can't be inherited.  */
4151     ctors = get_class_binding (totype, complete_ctor_identifier);
4152 
4153   tree to_nonref = non_reference (totype);
4154   if (MAYBE_CLASS_TYPE_P (fromtype))
4155     {
4156       if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
4157 	  (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
4158 	   && DERIVED_FROM_P (to_nonref, fromtype)))
4159 	{
4160 	  /* [class.conv.fct] A conversion function is never used to
4161 	     convert a (possibly cv-qualified) object to the (possibly
4162 	     cv-qualified) same object type (or a reference to it), to a
4163 	     (possibly cv-qualified) base class of that type (or a
4164 	     reference to it)...  */
4165 	}
4166       else
4167 	conv_fns = lookup_conversions (fromtype);
4168     }
4169 
4170   candidates = 0;
4171   flags |= LOOKUP_NO_CONVERSION;
4172   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4173     flags |= LOOKUP_NO_NARROWING;
4174   /* Prevent add_candidates from treating a non-strictly viable candidate
4175      as unviable.  */
4176   complain |= tf_conv;
4177 
4178   /* It's OK to bind a temporary for converting constructor arguments, but
4179      not in converting the return value of a conversion operator.  */
4180   convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION
4181 	       | (flags & LOOKUP_NO_NARROWING));
4182   flags &= ~LOOKUP_NO_TEMP_BIND;
4183 
4184   if (ctors)
4185     {
4186       int ctorflags = flags;
4187 
4188       first_arg = build_dummy_object (totype);
4189 
4190       /* We should never try to call the abstract or base constructor
4191 	 from here.  */
4192       gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_FIRST (ctors))
4193 		  && !DECL_HAS_VTT_PARM_P (OVL_FIRST (ctors)));
4194 
4195       args = make_tree_vector_single (expr);
4196       if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4197 	{
4198 	  /* List-initialization.  */
4199 	  add_list_candidates (ctors, first_arg, args, totype, NULL_TREE,
4200 			       false, TYPE_BINFO (totype), TYPE_BINFO (totype),
4201 			       ctorflags, &candidates, complain);
4202 	}
4203       else
4204 	{
4205 	  add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
4206 			  TYPE_BINFO (totype), TYPE_BINFO (totype),
4207 			  ctorflags, &candidates, complain);
4208 	}
4209 
4210       for (cand = candidates; cand; cand = cand->next)
4211 	{
4212 	  cand->second_conv = build_identity_conv (totype, NULL_TREE);
4213 
4214 	  /* If totype isn't a reference, and LOOKUP_ONLYCONVERTING is
4215 	     set, then this is copy-initialization.  In that case, "The
4216 	     result of the call is then used to direct-initialize the
4217 	     object that is the destination of the copy-initialization."
4218 	     [dcl.init]
4219 
4220 	     We represent this in the conversion sequence with an
4221 	     rvalue conversion, which means a constructor call.  */
4222 	  if (!TYPE_REF_P (totype)
4223 	      && cxx_dialect < cxx17
4224 	      && (flags & LOOKUP_ONLYCONVERTING)
4225 	      && !(convflags & LOOKUP_NO_TEMP_BIND))
4226 	    cand->second_conv
4227 	      = build_conv (ck_rvalue, totype, cand->second_conv);
4228 	}
4229     }
4230 
4231   if (conv_fns)
4232     {
4233       if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4234 	first_arg = CONSTRUCTOR_ELT (expr, 0)->value;
4235       else
4236 	first_arg = expr;
4237     }
4238 
4239   for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
4240     {
4241       tree conversion_path = TREE_PURPOSE (conv_fns);
4242       struct z_candidate *old_candidates;
4243 
4244       /* If LOOKUP_NO_CONVERSION, don't consider a conversion function that
4245 	 would need an addional user-defined conversion, i.e. if the return
4246 	 type differs in class-ness from the desired type.  So we avoid
4247 	 considering operator bool when calling a copy constructor.
4248 
4249 	 This optimization avoids the failure in PR97600, and is allowed by
4250 	 [temp.inst]/9: "If the function selected by overload resolution can be
4251 	 determined without instantiating a class template definition, it is
4252 	 unspecified whether that instantiation actually takes place."	*/
4253       tree convtype = non_reference (TREE_TYPE (conv_fns));
4254       if ((flags & LOOKUP_NO_CONVERSION)
4255 	  && !WILDCARD_TYPE_P (convtype)
4256 	  && (CLASS_TYPE_P (to_nonref)
4257 	      != CLASS_TYPE_P (convtype)))
4258 	continue;
4259 
4260       /* If we are called to convert to a reference type, we are trying to
4261 	 find a direct binding, so don't even consider temporaries.  If
4262 	 we don't find a direct binding, the caller will try again to
4263 	 look for a temporary binding.  */
4264       if (TYPE_REF_P (totype))
4265 	convflags |= LOOKUP_NO_TEMP_BIND;
4266 
4267       old_candidates = candidates;
4268       add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
4269 		      NULL_TREE, false,
4270 		      conversion_path, TYPE_BINFO (fromtype),
4271 		      flags, &candidates, complain);
4272 
4273       for (cand = candidates; cand != old_candidates; cand = cand->next)
4274 	{
4275 	  if (cand->viable == 0)
4276 	    /* Already rejected, don't change to -1.  */
4277 	    continue;
4278 
4279 	  tree rettype = TREE_TYPE (TREE_TYPE (cand->fn));
4280 	  conversion *ics
4281 	    = implicit_conversion (totype,
4282 				   rettype,
4283 				   0,
4284 				   /*c_cast_p=*/false, convflags,
4285 				   complain);
4286 
4287 	  /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
4288 	     copy-initialization.  In that case, "The result of the
4289 	     call is then used to direct-initialize the object that is
4290 	     the destination of the copy-initialization."  [dcl.init]
4291 
4292 	     We represent this in the conversion sequence with an
4293 	     rvalue conversion, which means a constructor call.  But
4294 	     don't add a second rvalue conversion if there's already
4295 	     one there.  Which there really shouldn't be, but it's
4296 	     harmless since we'd add it here anyway. */
4297 	  if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
4298 	      && !(convflags & LOOKUP_NO_TEMP_BIND))
4299 	    ics = build_conv (ck_rvalue, totype, ics);
4300 
4301 	  cand->second_conv = ics;
4302 
4303 	  if (!ics)
4304 	    {
4305 	      cand->viable = 0;
4306 	      cand->reason = arg_conversion_rejection (NULL_TREE, -2,
4307 						       rettype, totype,
4308 						       EXPR_LOCATION (expr));
4309 	    }
4310 	  else if (TYPE_REF_P (totype) && !ics->rvaluedness_matches_p
4311 		   /* Limit this to non-templates for now (PR90546).  */
4312 		   && !cand->template_decl
4313 		   && TREE_CODE (TREE_TYPE (totype)) != FUNCTION_TYPE)
4314 	    {
4315 	      /* If we are called to convert to a reference type, we are trying
4316 		 to find a direct binding per [over.match.ref], so rvaluedness
4317 		 must match for non-functions.  */
4318 	      cand->viable = 0;
4319 	    }
4320 	  else if (DECL_NONCONVERTING_P (cand->fn)
4321 		   && ics->rank > cr_exact)
4322 	    {
4323 	      /* 13.3.1.5: For direct-initialization, those explicit
4324 		 conversion functions that are not hidden within S and
4325 		 yield type T or a type that can be converted to type T
4326 		 with a qualification conversion (4.4) are also candidate
4327 		 functions.  */
4328 	      /* 13.3.1.6 doesn't have a parallel restriction, but it should;
4329 		 I've raised this issue with the committee. --jason 9/2011 */
4330 	      cand->viable = -1;
4331 	      cand->reason = explicit_conversion_rejection (rettype, totype);
4332 	    }
4333 	  else if (cand->viable == 1 && ics->bad_p)
4334 	    {
4335 	      cand->viable = -1;
4336 	      cand->reason
4337 		= bad_arg_conversion_rejection (NULL_TREE, -2,
4338 						rettype, totype,
4339 						EXPR_LOCATION (expr));
4340 	    }
4341 	  else if (primary_template_specialization_p (cand->fn)
4342 		   && ics->rank > cr_exact)
4343 	    {
4344 	      /* 13.3.3.1.2: If the user-defined conversion is specified by
4345 		 a specialization of a conversion function template, the
4346 		 second standard conversion sequence shall have exact match
4347 		 rank.  */
4348 	      cand->viable = -1;
4349 	      cand->reason = template_conversion_rejection (rettype, totype);
4350 	    }
4351 	}
4352     }
4353 
4354   candidates = splice_viable (candidates, false, &any_viable_p);
4355   if (!any_viable_p)
4356     {
4357       if (args)
4358 	release_tree_vector (args);
4359       return NULL;
4360     }
4361 
4362   cand = tourney (candidates, complain);
4363   if (cand == NULL)
4364     {
4365       if (complain & tf_error)
4366 	{
4367 	  auto_diagnostic_group d;
4368 	  error_at (cp_expr_loc_or_input_loc (expr),
4369 		    "conversion from %qH to %qI is ambiguous",
4370 		    fromtype, totype);
4371 	  print_z_candidates (location_of (expr), candidates);
4372 	}
4373 
4374       cand = candidates;	/* any one will do */
4375       cand->second_conv = build_ambiguous_conv (totype, expr);
4376       cand->second_conv->user_conv_p = true;
4377       if (!any_strictly_viable (candidates))
4378 	cand->second_conv->bad_p = true;
4379       if (flags & LOOKUP_ONLYCONVERTING)
4380 	cand->second_conv->need_temporary_p = true;
4381       /* If there are viable candidates, don't set ICS_BAD_FLAG; an
4382 	 ambiguous conversion is no worse than another user-defined
4383 	 conversion.  */
4384 
4385       return cand;
4386     }
4387 
4388   tree convtype;
4389   if (!DECL_CONSTRUCTOR_P (cand->fn))
4390     convtype = non_reference (TREE_TYPE (TREE_TYPE (cand->fn)));
4391   else if (cand->second_conv->kind == ck_rvalue)
4392     /* DR 5: [in the first step of copy-initialization]...if the function
4393        is a constructor, the call initializes a temporary of the
4394        cv-unqualified version of the destination type. */
4395     convtype = cv_unqualified (totype);
4396   else
4397     convtype = totype;
4398   /* Build the user conversion sequence.  */
4399   conv = build_conv
4400     (ck_user,
4401      convtype,
4402      build_identity_conv (TREE_TYPE (expr), expr));
4403   conv->cand = cand;
4404   if (cand->viable == -1)
4405     conv->bad_p = true;
4406 
4407   /* We're performing the maybe-rvalue overload resolution and
4408      a conversion function is in play.  Reject converting the return
4409      value of the conversion function to a base class.  */
4410   if ((flags & LOOKUP_PREFER_RVALUE) && !DECL_CONSTRUCTOR_P (cand->fn))
4411     for (conversion *t = cand->second_conv; t; t = next_conversion (t))
4412       if (t->kind == ck_base)
4413 	return NULL;
4414 
4415   /* Remember that this was a list-initialization.  */
4416   if (flags & LOOKUP_NO_NARROWING)
4417     conv->check_narrowing = true;
4418 
4419   /* Combine it with the second conversion sequence.  */
4420   cand->second_conv = merge_conversion_sequences (conv,
4421 						  cand->second_conv);
4422 
4423   return cand;
4424 }
4425 
4426 /* Wrapper for above. */
4427 
4428 tree
build_user_type_conversion(tree totype,tree expr,int flags,tsubst_flags_t complain)4429 build_user_type_conversion (tree totype, tree expr, int flags,
4430 			    tsubst_flags_t complain)
4431 {
4432   struct z_candidate *cand;
4433   tree ret;
4434 
4435   auto_cond_timevar tv (TV_OVERLOAD);
4436   cand = build_user_type_conversion_1 (totype, expr, flags, complain);
4437 
4438   if (cand)
4439     {
4440       if (cand->second_conv->kind == ck_ambig)
4441 	ret = error_mark_node;
4442       else
4443         {
4444           expr = convert_like (cand->second_conv, expr, complain);
4445           ret = convert_from_reference (expr);
4446         }
4447     }
4448   else
4449     ret = NULL_TREE;
4450 
4451   return ret;
4452 }
4453 
4454 /* Give a helpful diagnostic when implicit_conversion fails.  */
4455 
4456 static void
implicit_conversion_error(location_t loc,tree type,tree expr)4457 implicit_conversion_error (location_t loc, tree type, tree expr)
4458 {
4459   tsubst_flags_t complain = tf_warning_or_error;
4460 
4461   /* If expr has unknown type, then it is an overloaded function.
4462      Call instantiate_type to get good error messages.  */
4463   if (TREE_TYPE (expr) == unknown_type_node)
4464     instantiate_type (type, expr, complain);
4465   else if (invalid_nonstatic_memfn_p (loc, expr, complain))
4466     /* We gave an error.  */;
4467   else if (BRACE_ENCLOSED_INITIALIZER_P (expr)
4468 	   && CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
4469 	   && !CP_AGGREGATE_TYPE_P (type))
4470     error_at (loc, "designated initializers cannot be used with a "
4471 	      "non-aggregate type %qT", type);
4472   else
4473     {
4474       range_label_for_type_mismatch label (TREE_TYPE (expr), type);
4475       gcc_rich_location rich_loc (loc, &label);
4476       error_at (&rich_loc, "could not convert %qE from %qH to %qI",
4477 		expr, TREE_TYPE (expr), type);
4478     }
4479 }
4480 
4481 /* Worker for build_converted_constant_expr.  */
4482 
4483 static tree
build_converted_constant_expr_internal(tree type,tree expr,int flags,tsubst_flags_t complain)4484 build_converted_constant_expr_internal (tree type, tree expr,
4485 					int flags, tsubst_flags_t complain)
4486 {
4487   conversion *conv;
4488   void *p;
4489   tree t;
4490   location_t loc = cp_expr_loc_or_input_loc (expr);
4491 
4492   if (error_operand_p (expr))
4493     return error_mark_node;
4494 
4495   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
4496   p = conversion_obstack_alloc (0);
4497 
4498   conv = implicit_conversion (type, TREE_TYPE (expr), expr,
4499 			      /*c_cast_p=*/false, flags, complain);
4500 
4501   /* A converted constant expression of type T is an expression, implicitly
4502      converted to type T, where the converted expression is a constant
4503      expression and the implicit conversion sequence contains only
4504 
4505        * user-defined conversions,
4506        * lvalue-to-rvalue conversions (7.1),
4507        * array-to-pointer conversions (7.2),
4508        * function-to-pointer conversions (7.3),
4509        * qualification conversions (7.5),
4510        * integral promotions (7.6),
4511        * integral conversions (7.8) other than narrowing conversions (11.6.4),
4512        * null pointer conversions (7.11) from std::nullptr_t,
4513        * null member pointer conversions (7.12) from std::nullptr_t, and
4514        * function pointer conversions (7.13),
4515 
4516      and where the reference binding (if any) binds directly.  */
4517 
4518   for (conversion *c = conv;
4519        c && c->kind != ck_identity;
4520        c = next_conversion (c))
4521     {
4522       switch (c->kind)
4523 	{
4524 	  /* A conversion function is OK.  If it isn't constexpr, we'll
4525 	     complain later that the argument isn't constant.  */
4526 	case ck_user:
4527 	  /* List-initialization is OK.  */
4528 	case ck_aggr:
4529 	  /* The lvalue-to-rvalue conversion is OK.  */
4530 	case ck_rvalue:
4531 	  /* Array-to-pointer and function-to-pointer.  */
4532 	case ck_lvalue:
4533 	  /* Function pointer conversions.  */
4534 	case ck_fnptr:
4535 	  /* Qualification conversions.  */
4536 	case ck_qual:
4537 	  break;
4538 
4539 	case ck_ref_bind:
4540 	  if (c->need_temporary_p)
4541 	    {
4542 	      if (complain & tf_error)
4543 		error_at (loc, "initializing %qH with %qI in converted "
4544 			  "constant expression does not bind directly",
4545 			  type, next_conversion (c)->type);
4546 	      conv = NULL;
4547 	    }
4548 	  break;
4549 
4550 	case ck_base:
4551 	case ck_pmem:
4552 	case ck_ptr:
4553 	case ck_std:
4554 	  t = next_conversion (c)->type;
4555 	  if (INTEGRAL_OR_ENUMERATION_TYPE_P (t)
4556 	      && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4557 	    /* Integral promotion or conversion.  */
4558 	    break;
4559 	  if (NULLPTR_TYPE_P (t))
4560 	    /* Conversion from nullptr to pointer or pointer-to-member.  */
4561 	    break;
4562 
4563 	  if (complain & tf_error)
4564 	    error_at (loc, "conversion from %qH to %qI in a "
4565 		      "converted constant expression", t, type);
4566 	  /* fall through.  */
4567 
4568 	default:
4569 	  conv = NULL;
4570 	  break;
4571 	}
4572     }
4573 
4574   /* Avoid confusing convert_nontype_argument by introducing
4575      a redundant conversion to the same reference type.  */
4576   if (conv && conv->kind == ck_ref_bind
4577       && REFERENCE_REF_P (expr))
4578     {
4579       tree ref = TREE_OPERAND (expr, 0);
4580       if (same_type_p (type, TREE_TYPE (ref)))
4581 	return ref;
4582     }
4583 
4584   if (conv)
4585     {
4586       /* Don't copy a class in a template.  */
4587       if (CLASS_TYPE_P (type) && conv->kind == ck_rvalue
4588 	  && processing_template_decl)
4589 	conv = next_conversion (conv);
4590 
4591       /* Issuing conversion warnings for value-dependent expressions is
4592 	 likely too noisy.  */
4593       warning_sentinel w (warn_conversion);
4594       conv->check_narrowing = true;
4595       conv->check_narrowing_const_only = true;
4596       expr = convert_like (conv, expr, complain);
4597     }
4598   else
4599     {
4600       if (complain & tf_error)
4601 	implicit_conversion_error (loc, type, expr);
4602       expr = error_mark_node;
4603     }
4604 
4605   /* Free all the conversions we allocated.  */
4606   obstack_free (&conversion_obstack, p);
4607 
4608   return expr;
4609 }
4610 
4611 /* Subroutine of convert_nontype_argument.
4612 
4613    EXPR is an expression used in a context that requires a converted
4614    constant-expression, such as a template non-type parameter.  Do any
4615    necessary conversions (that are permitted for converted
4616    constant-expressions) to convert it to the desired type.
4617 
4618    This function doesn't consider explicit conversion functions.  If
4619    you mean to use "a contextually converted constant expression of type
4620    bool", use build_converted_constant_bool_expr.
4621 
4622    If conversion is successful, returns the converted expression;
4623    otherwise, returns error_mark_node.  */
4624 
4625 tree
build_converted_constant_expr(tree type,tree expr,tsubst_flags_t complain)4626 build_converted_constant_expr (tree type, tree expr, tsubst_flags_t complain)
4627 {
4628   return build_converted_constant_expr_internal (type, expr, LOOKUP_IMPLICIT,
4629 						 complain);
4630 }
4631 
4632 /* Used to create "a contextually converted constant expression of type
4633    bool".  This differs from build_converted_constant_expr in that it
4634    also considers explicit conversion functions.  */
4635 
4636 tree
build_converted_constant_bool_expr(tree expr,tsubst_flags_t complain)4637 build_converted_constant_bool_expr (tree expr, tsubst_flags_t complain)
4638 {
4639   return build_converted_constant_expr_internal (boolean_type_node, expr,
4640 						 LOOKUP_NORMAL, complain);
4641 }
4642 
4643 /* Do any initial processing on the arguments to a function call.  */
4644 
4645 vec<tree, va_gc> *
resolve_args(vec<tree,va_gc> * args,tsubst_flags_t complain)4646 resolve_args (vec<tree, va_gc> *args, tsubst_flags_t complain)
4647 {
4648   unsigned int ix;
4649   tree arg;
4650 
4651   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
4652     {
4653       if (error_operand_p (arg))
4654 	return NULL;
4655       else if (VOID_TYPE_P (TREE_TYPE (arg)))
4656 	{
4657 	  if (complain & tf_error)
4658 	    error_at (cp_expr_loc_or_input_loc (arg),
4659 		      "invalid use of void expression");
4660 	  return NULL;
4661 	}
4662       else if (invalid_nonstatic_memfn_p (EXPR_LOCATION (arg), arg, complain))
4663 	return NULL;
4664     }
4665   return args;
4666 }
4667 
4668 /* Perform overload resolution on FN, which is called with the ARGS.
4669 
4670    Return the candidate function selected by overload resolution, or
4671    NULL if the event that overload resolution failed.  In the case
4672    that overload resolution fails, *CANDIDATES will be the set of
4673    candidates considered, and ANY_VIABLE_P will be set to true or
4674    false to indicate whether or not any of the candidates were
4675    viable.
4676 
4677    The ARGS should already have gone through RESOLVE_ARGS before this
4678    function is called.  */
4679 
4680 static struct z_candidate *
perform_overload_resolution(tree fn,const vec<tree,va_gc> * args,struct z_candidate ** candidates,bool * any_viable_p,tsubst_flags_t complain)4681 perform_overload_resolution (tree fn,
4682 			     const vec<tree, va_gc> *args,
4683 			     struct z_candidate **candidates,
4684 			     bool *any_viable_p, tsubst_flags_t complain)
4685 {
4686   struct z_candidate *cand;
4687   tree explicit_targs;
4688   int template_only;
4689 
4690   auto_cond_timevar tv (TV_OVERLOAD);
4691 
4692   explicit_targs = NULL_TREE;
4693   template_only = 0;
4694 
4695   *candidates = NULL;
4696   *any_viable_p = true;
4697 
4698   /* Check FN.  */
4699   gcc_assert (OVL_P (fn) || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
4700 
4701   if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4702     {
4703       explicit_targs = TREE_OPERAND (fn, 1);
4704       fn = TREE_OPERAND (fn, 0);
4705       template_only = 1;
4706     }
4707 
4708   /* Add the various candidate functions.  */
4709   add_candidates (fn, NULL_TREE, args, NULL_TREE,
4710 		  explicit_targs, template_only,
4711 		  /*conversion_path=*/NULL_TREE,
4712 		  /*access_path=*/NULL_TREE,
4713 		  LOOKUP_NORMAL,
4714 		  candidates, complain);
4715 
4716   *candidates = splice_viable (*candidates, false, any_viable_p);
4717   if (*any_viable_p)
4718     cand = tourney (*candidates, complain);
4719   else
4720     cand = NULL;
4721 
4722   return cand;
4723 }
4724 
4725 /* Print an error message about being unable to build a call to FN with
4726    ARGS.  ANY_VIABLE_P indicates whether any candidate functions could
4727    be located; CANDIDATES is a possibly empty list of such
4728    functions.  */
4729 
4730 static void
print_error_for_call_failure(tree fn,const vec<tree,va_gc> * args,struct z_candidate * candidates)4731 print_error_for_call_failure (tree fn, const vec<tree, va_gc> *args,
4732 			      struct z_candidate *candidates)
4733 {
4734   tree targs = NULL_TREE;
4735   if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4736     {
4737       targs = TREE_OPERAND (fn, 1);
4738       fn = TREE_OPERAND (fn, 0);
4739     }
4740   tree name = OVL_NAME (fn);
4741   location_t loc = location_of (name);
4742   if (targs)
4743     name = lookup_template_function (name, targs);
4744 
4745   auto_diagnostic_group d;
4746   if (!any_strictly_viable (candidates))
4747     error_at (loc, "no matching function for call to %<%D(%A)%>",
4748 	      name, build_tree_list_vec (args));
4749   else
4750     error_at (loc, "call of overloaded %<%D(%A)%> is ambiguous",
4751 	      name, build_tree_list_vec (args));
4752   if (candidates)
4753     print_z_candidates (loc, candidates);
4754 }
4755 
4756 /* Perform overload resolution on the set of deduction guides DGUIDES
4757    using ARGS.  Returns the selected deduction guide, or error_mark_node
4758    if overload resolution fails.  */
4759 
4760 tree
perform_dguide_overload_resolution(tree dguides,const vec<tree,va_gc> * args,tsubst_flags_t complain)4761 perform_dguide_overload_resolution (tree dguides, const vec<tree, va_gc> *args,
4762 				    tsubst_flags_t complain)
4763 {
4764   z_candidate *candidates;
4765   bool any_viable_p;
4766   tree result;
4767 
4768   gcc_assert (deduction_guide_p (OVL_FIRST (dguides)));
4769 
4770   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
4771   void *p = conversion_obstack_alloc (0);
4772 
4773   z_candidate *cand = perform_overload_resolution (dguides, args, &candidates,
4774 						   &any_viable_p, complain);
4775   if (!cand)
4776     {
4777       if (complain & tf_error)
4778 	print_error_for_call_failure (dguides, args, candidates);
4779       result = error_mark_node;
4780     }
4781   else
4782     result = cand->fn;
4783 
4784   /* Free all the conversions we allocated.  */
4785   obstack_free (&conversion_obstack, p);
4786 
4787   return result;
4788 }
4789 
4790 /* Return an expression for a call to FN (a namespace-scope function,
4791    or a static member function) with the ARGS.  This may change
4792    ARGS.  */
4793 
4794 tree
build_new_function_call(tree fn,vec<tree,va_gc> ** args,tsubst_flags_t complain)4795 build_new_function_call (tree fn, vec<tree, va_gc> **args,
4796 			 tsubst_flags_t complain)
4797 {
4798   struct z_candidate *candidates, *cand;
4799   bool any_viable_p;
4800   void *p;
4801   tree result;
4802 
4803   if (args != NULL && *args != NULL)
4804     {
4805       *args = resolve_args (*args, complain);
4806       if (*args == NULL)
4807 	return error_mark_node;
4808     }
4809 
4810   if (flag_tm)
4811     tm_malloc_replacement (fn);
4812 
4813   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
4814   p = conversion_obstack_alloc (0);
4815 
4816   cand = perform_overload_resolution (fn, *args, &candidates, &any_viable_p,
4817 				      complain);
4818 
4819   if (!cand)
4820     {
4821       if (complain & tf_error)
4822 	{
4823 	  // If there is a single (non-viable) function candidate,
4824 	  // let the error be diagnosed by cp_build_function_call_vec.
4825 	  if (!any_viable_p && candidates && ! candidates->next
4826 	      && (TREE_CODE (candidates->fn) == FUNCTION_DECL))
4827 	    return cp_build_function_call_vec (candidates->fn, args, complain);
4828 
4829 	  // Otherwise, emit notes for non-viable candidates.
4830 	  print_error_for_call_failure (fn, *args, candidates);
4831 	}
4832       result = error_mark_node;
4833     }
4834   else
4835     {
4836       result = build_over_call (cand, LOOKUP_NORMAL, complain);
4837     }
4838 
4839   if (flag_coroutines
4840       && result
4841       && TREE_CODE (result) == CALL_EXPR
4842       && DECL_BUILT_IN_CLASS (TREE_OPERAND (CALL_EXPR_FN (result), 0))
4843 	  == BUILT_IN_NORMAL)
4844    result = coro_validate_builtin_call (result);
4845 
4846   /* Free all the conversions we allocated.  */
4847   obstack_free (&conversion_obstack, p);
4848 
4849   return result;
4850 }
4851 
4852 /* Build a call to a global operator new.  FNNAME is the name of the
4853    operator (either "operator new" or "operator new[]") and ARGS are
4854    the arguments provided.  This may change ARGS.  *SIZE points to the
4855    total number of bytes required by the allocation, and is updated if
4856    that is changed here.  *COOKIE_SIZE is non-NULL if a cookie should
4857    be used.  If this function determines that no cookie should be
4858    used, after all, *COOKIE_SIZE is set to NULL_TREE.  If SIZE_CHECK
4859    is not NULL_TREE, it is evaluated before calculating the final
4860    array size, and if it fails, the array size is replaced with
4861    (size_t)-1 (usually triggering a std::bad_alloc exception).  If FN
4862    is non-NULL, it will be set, upon return, to the allocation
4863    function called.  */
4864 
4865 tree
build_operator_new_call(tree fnname,vec<tree,va_gc> ** args,tree * size,tree * cookie_size,tree align_arg,tree size_check,tree * fn,tsubst_flags_t complain)4866 build_operator_new_call (tree fnname, vec<tree, va_gc> **args,
4867 			 tree *size, tree *cookie_size,
4868 			 tree align_arg, tree size_check,
4869 			 tree *fn, tsubst_flags_t complain)
4870 {
4871   tree original_size = *size;
4872   tree fns;
4873   struct z_candidate *candidates;
4874   struct z_candidate *cand = NULL;
4875   bool any_viable_p;
4876 
4877   if (fn)
4878     *fn = NULL_TREE;
4879   /* Set to (size_t)-1 if the size check fails.  */
4880   if (size_check != NULL_TREE)
4881     {
4882       tree errval = TYPE_MAX_VALUE (sizetype);
4883       if (cxx_dialect >= cxx11 && flag_exceptions)
4884 	errval = throw_bad_array_new_length ();
4885       *size = fold_build3 (COND_EXPR, sizetype, size_check,
4886 			   original_size, errval);
4887     }
4888   vec_safe_insert (*args, 0, *size);
4889   *args = resolve_args (*args, complain);
4890   if (*args == NULL)
4891     return error_mark_node;
4892 
4893   /* Based on:
4894 
4895        [expr.new]
4896 
4897        If this lookup fails to find the name, or if the allocated type
4898        is not a class type, the allocation function's name is looked
4899        up in the global scope.
4900 
4901      we disregard block-scope declarations of "operator new".  */
4902   fns = lookup_name (fnname, LOOK_where::NAMESPACE);
4903   fns = lookup_arg_dependent (fnname, fns, *args);
4904 
4905   if (align_arg)
4906     {
4907       vec<tree, va_gc>* align_args
4908 	= vec_copy_and_insert (*args, align_arg, 1);
4909       cand = perform_overload_resolution (fns, align_args, &candidates,
4910 					  &any_viable_p, tf_none);
4911       if (cand)
4912 	*args = align_args;
4913       /* If no aligned allocation function matches, try again without the
4914 	 alignment.  */
4915     }
4916 
4917   /* Figure out what function is being called.  */
4918   if (!cand)
4919     cand = perform_overload_resolution (fns, *args, &candidates, &any_viable_p,
4920 					complain);
4921 
4922   /* If no suitable function could be found, issue an error message
4923      and give up.  */
4924   if (!cand)
4925     {
4926       if (complain & tf_error)
4927 	print_error_for_call_failure (fns, *args, candidates);
4928       return error_mark_node;
4929     }
4930 
4931    /* If a cookie is required, add some extra space.  Whether
4932       or not a cookie is required cannot be determined until
4933       after we know which function was called.  */
4934    if (*cookie_size)
4935      {
4936        bool use_cookie = true;
4937        tree arg_types;
4938 
4939        arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
4940        /* Skip the size_t parameter.  */
4941        arg_types = TREE_CHAIN (arg_types);
4942        /* Check the remaining parameters (if any).  */
4943        if (arg_types
4944 	   && TREE_CHAIN (arg_types) == void_list_node
4945 	   && same_type_p (TREE_VALUE (arg_types),
4946 			   ptr_type_node))
4947 	 use_cookie = false;
4948        /* If we need a cookie, adjust the number of bytes allocated.  */
4949        if (use_cookie)
4950 	 {
4951 	   /* Update the total size.  */
4952 	   *size = size_binop (PLUS_EXPR, original_size, *cookie_size);
4953 	   if (size_check)
4954 	     {
4955 	       /* Set to (size_t)-1 if the size check fails.  */
4956 	       gcc_assert (size_check != NULL_TREE);
4957 	       *size = fold_build3 (COND_EXPR, sizetype, size_check,
4958 				    *size, TYPE_MAX_VALUE (sizetype));
4959 	    }
4960 	   /* Update the argument list to reflect the adjusted size.  */
4961 	   (**args)[0] = *size;
4962 	 }
4963        else
4964 	 *cookie_size = NULL_TREE;
4965      }
4966 
4967    /* Tell our caller which function we decided to call.  */
4968    if (fn)
4969      *fn = cand->fn;
4970 
4971    /* Build the CALL_EXPR.  */
4972    tree ret = build_over_call (cand, LOOKUP_NORMAL, complain);
4973 
4974    /* Set this flag for all callers of this function.  In addition to
4975       new-expressions, this is called for allocating coroutine state; treat
4976       that as an implicit new-expression.  */
4977    tree call = extract_call_expr (ret);
4978    if (TREE_CODE (call) == CALL_EXPR)
4979      CALL_FROM_NEW_OR_DELETE_P (call) = 1;
4980 
4981    return ret;
4982 }
4983 
4984 /* Build a new call to operator().  This may change ARGS.  */
4985 
4986 tree
build_op_call(tree obj,vec<tree,va_gc> ** args,tsubst_flags_t complain)4987 build_op_call (tree obj, vec<tree, va_gc> **args, tsubst_flags_t complain)
4988 {
4989   struct z_candidate *candidates = 0, *cand;
4990   tree fns, convs, first_mem_arg = NULL_TREE;
4991   bool any_viable_p;
4992   tree result = NULL_TREE;
4993   void *p;
4994 
4995   auto_cond_timevar tv (TV_OVERLOAD);
4996 
4997   obj = mark_lvalue_use (obj);
4998 
4999   if (error_operand_p (obj))
5000     return error_mark_node;
5001 
5002   tree type = TREE_TYPE (obj);
5003 
5004   obj = prep_operand (obj);
5005 
5006   if (TYPE_PTRMEMFUNC_P (type))
5007     {
5008       if (complain & tf_error)
5009         /* It's no good looking for an overloaded operator() on a
5010            pointer-to-member-function.  */
5011 	error ("pointer-to-member function %qE cannot be called without "
5012 	       "an object; consider using %<.*%> or %<->*%>", obj);
5013       return error_mark_node;
5014     }
5015 
5016   if (TYPE_BINFO (type))
5017     {
5018       fns = lookup_fnfields (TYPE_BINFO (type), call_op_identifier, 1, complain);
5019       if (fns == error_mark_node)
5020 	return error_mark_node;
5021     }
5022   else
5023     fns = NULL_TREE;
5024 
5025   if (args != NULL && *args != NULL)
5026     {
5027       *args = resolve_args (*args, complain);
5028       if (*args == NULL)
5029 	return error_mark_node;
5030     }
5031 
5032   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
5033   p = conversion_obstack_alloc (0);
5034 
5035   if (fns)
5036     {
5037       first_mem_arg = obj;
5038 
5039       add_candidates (BASELINK_FUNCTIONS (fns),
5040 		      first_mem_arg, *args, NULL_TREE,
5041 		      NULL_TREE, false,
5042 		      BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
5043 		      LOOKUP_NORMAL, &candidates, complain);
5044     }
5045 
5046   convs = lookup_conversions (type);
5047 
5048   for (; convs; convs = TREE_CHAIN (convs))
5049     {
5050       tree totype = TREE_TYPE (convs);
5051 
5052       if (TYPE_PTRFN_P (totype)
5053 	  || TYPE_REFFN_P (totype)
5054 	  || (TYPE_REF_P (totype)
5055 	      && TYPE_PTRFN_P (TREE_TYPE (totype))))
5056 	for (tree fn : ovl_range (TREE_VALUE (convs)))
5057 	  {
5058 	    if (DECL_NONCONVERTING_P (fn))
5059 	      continue;
5060 
5061 	    if (TREE_CODE (fn) == TEMPLATE_DECL)
5062 	      add_template_conv_candidate
5063 		(&candidates, fn, obj, *args, totype,
5064 		 /*access_path=*/NULL_TREE,
5065 		 /*conversion_path=*/NULL_TREE, complain);
5066 	    else
5067 	      add_conv_candidate (&candidates, fn, obj,
5068 				  *args, /*conversion_path=*/NULL_TREE,
5069 				  /*access_path=*/NULL_TREE, complain);
5070 	  }
5071     }
5072 
5073   /* Be strict here because if we choose a bad conversion candidate, the
5074      errors we get won't mention the call context.  */
5075   candidates = splice_viable (candidates, true, &any_viable_p);
5076   if (!any_viable_p)
5077     {
5078       if (complain & tf_error)
5079         {
5080           auto_diagnostic_group d;
5081           error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
5082 		 build_tree_list_vec (*args));
5083           print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5084         }
5085       result = error_mark_node;
5086     }
5087   else
5088     {
5089       cand = tourney (candidates, complain);
5090       if (cand == 0)
5091 	{
5092           if (complain & tf_error)
5093             {
5094               auto_diagnostic_group d;
5095               error ("call of %<(%T) (%A)%> is ambiguous",
5096                      TREE_TYPE (obj), build_tree_list_vec (*args));
5097               print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5098             }
5099 	  result = error_mark_node;
5100 	}
5101       else if (TREE_CODE (cand->fn) == FUNCTION_DECL
5102 	       && DECL_OVERLOADED_OPERATOR_P (cand->fn)
5103 	       && DECL_OVERLOADED_OPERATOR_IS (cand->fn, CALL_EXPR))
5104 	result = build_over_call (cand, LOOKUP_NORMAL, complain);
5105       else
5106 	{
5107 	  if (TREE_CODE (cand->fn) == FUNCTION_DECL)
5108 	    obj = convert_like_with_context (cand->convs[0], obj, cand->fn,
5109 					     -1, complain);
5110 	  else
5111 	    {
5112 	      gcc_checking_assert (TYPE_P (cand->fn));
5113 	      obj = convert_like (cand->convs[0], obj, complain);
5114 	    }
5115 	  obj = convert_from_reference (obj);
5116 	  result = cp_build_function_call_vec (obj, args, complain);
5117 	}
5118     }
5119 
5120   /* Free all the conversions we allocated.  */
5121   obstack_free (&conversion_obstack, p);
5122 
5123   return result;
5124 }
5125 
5126 /* Called by op_error to prepare format strings suitable for the error
5127    function.  It concatenates a prefix (controlled by MATCH), ERRMSG,
5128    and a suffix (controlled by NTYPES).  */
5129 
5130 static const char *
op_error_string(const char * errmsg,int ntypes,bool match)5131 op_error_string (const char *errmsg, int ntypes, bool match)
5132 {
5133   const char *msg;
5134 
5135   const char *msgp = concat (match ? G_("ambiguous overload for ")
5136 			           : G_("no match for "), errmsg, NULL);
5137 
5138   if (ntypes == 3)
5139     msg = concat (msgp, G_(" (operand types are %qT, %qT, and %qT)"), NULL);
5140   else if (ntypes == 2)
5141     msg = concat (msgp, G_(" (operand types are %qT and %qT)"), NULL);
5142   else
5143     msg = concat (msgp, G_(" (operand type is %qT)"), NULL);
5144 
5145   return msg;
5146 }
5147 
5148 static void
op_error(const op_location_t & loc,enum tree_code code,enum tree_code code2,tree arg1,tree arg2,tree arg3,bool match)5149 op_error (const op_location_t &loc,
5150 	  enum tree_code code, enum tree_code code2,
5151 	  tree arg1, tree arg2, tree arg3, bool match)
5152 {
5153   bool assop = code == MODIFY_EXPR;
5154   const char *opname = OVL_OP_INFO (assop, assop ? code2 : code)->name;
5155 
5156   switch (code)
5157     {
5158     case COND_EXPR:
5159       if (flag_diagnostics_show_caret)
5160 	error_at (loc, op_error_string (G_("ternary %<operator?:%>"),
5161 					3, match),
5162 		  TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5163       else
5164 	error_at (loc, op_error_string (G_("ternary %<operator?:%> "
5165 					   "in %<%E ? %E : %E%>"), 3, match),
5166 		  arg1, arg2, arg3,
5167 		  TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5168       break;
5169 
5170     case POSTINCREMENT_EXPR:
5171     case POSTDECREMENT_EXPR:
5172       if (flag_diagnostics_show_caret)
5173 	error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5174 		  opname, TREE_TYPE (arg1));
5175       else
5176 	error_at (loc, op_error_string (G_("%<operator%s%> in %<%E%s%>"),
5177 					1, match),
5178 		  opname, arg1, opname, TREE_TYPE (arg1));
5179       break;
5180 
5181     case ARRAY_REF:
5182       if (flag_diagnostics_show_caret)
5183 	error_at (loc, op_error_string (G_("%<operator[]%>"), 2, match),
5184 		  TREE_TYPE (arg1), TREE_TYPE (arg2));
5185       else
5186 	error_at (loc, op_error_string (G_("%<operator[]%> in %<%E[%E]%>"),
5187 					2, match),
5188 		  arg1, arg2, TREE_TYPE (arg1), TREE_TYPE (arg2));
5189       break;
5190 
5191     case REALPART_EXPR:
5192     case IMAGPART_EXPR:
5193       if (flag_diagnostics_show_caret)
5194 	error_at (loc, op_error_string (G_("%qs"), 1, match),
5195 		  opname, TREE_TYPE (arg1));
5196       else
5197 	error_at (loc, op_error_string (G_("%qs in %<%s %E%>"), 1, match),
5198 		  opname, opname, arg1, TREE_TYPE (arg1));
5199       break;
5200 
5201     case CO_AWAIT_EXPR:
5202       if (flag_diagnostics_show_caret)
5203 	error_at (loc, op_error_string (G_("%<operator %s%>"), 1, match),
5204 		  opname, TREE_TYPE (arg1));
5205       else
5206 	error_at (loc, op_error_string (G_("%<operator %s%> in %<%s%E%>"),
5207 					  1, match),
5208 		   opname, opname, arg1, TREE_TYPE (arg1));
5209       break;
5210 
5211     default:
5212       if (arg2)
5213 	if (flag_diagnostics_show_caret)
5214 	  {
5215 	    binary_op_rich_location richloc (loc, arg1, arg2, true);
5216 	    error_at (&richloc,
5217 		      op_error_string (G_("%<operator%s%>"), 2, match),
5218 		      opname, TREE_TYPE (arg1), TREE_TYPE (arg2));
5219 	  }
5220 	else
5221 	  error_at (loc, op_error_string (G_("%<operator%s%> in %<%E %s %E%>"),
5222 					  2, match),
5223 		    opname, arg1, opname, arg2,
5224 		    TREE_TYPE (arg1), TREE_TYPE (arg2));
5225       else
5226 	if (flag_diagnostics_show_caret)
5227 	  error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5228 		    opname, TREE_TYPE (arg1));
5229 	else
5230 	  error_at (loc, op_error_string (G_("%<operator%s%> in %<%s%E%>"),
5231 					  1, match),
5232 		    opname, opname, arg1, TREE_TYPE (arg1));
5233       break;
5234     }
5235 }
5236 
5237 /* Return the implicit conversion sequence that could be used to
5238    convert E1 to E2 in [expr.cond].  */
5239 
5240 static conversion *
conditional_conversion(tree e1,tree e2,tsubst_flags_t complain)5241 conditional_conversion (tree e1, tree e2, tsubst_flags_t complain)
5242 {
5243   tree t1 = non_reference (TREE_TYPE (e1));
5244   tree t2 = non_reference (TREE_TYPE (e2));
5245   conversion *conv;
5246   bool good_base;
5247 
5248   /* [expr.cond]
5249 
5250      If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5251      implicitly converted (clause _conv_) to the type "lvalue reference to
5252      T2", subject to the constraint that in the conversion the
5253      reference must bind directly (_dcl.init.ref_) to an lvalue.
5254 
5255      If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5256      implicitly converted to the type "rvalue reference to T2", subject to
5257      the constraint that the reference must bind directly.  */
5258   if (glvalue_p (e2))
5259     {
5260       tree rtype = cp_build_reference_type (t2, !lvalue_p (e2));
5261       conv = implicit_conversion (rtype,
5262 				  t1,
5263 				  e1,
5264 				  /*c_cast_p=*/false,
5265 				  LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND
5266 				  |LOOKUP_ONLYCONVERTING,
5267 				  complain);
5268       if (conv && !conv->bad_p)
5269 	return conv;
5270     }
5271 
5272   /* If E2 is a prvalue or if neither of the conversions above can be done
5273      and at least one of the operands has (possibly cv-qualified) class
5274      type: */
5275   if (!CLASS_TYPE_P (t1) && !CLASS_TYPE_P (t2))
5276     return NULL;
5277 
5278   /* [expr.cond]
5279 
5280      If E1 and E2 have class type, and the underlying class types are
5281      the same or one is a base class of the other: E1 can be converted
5282      to match E2 if the class of T2 is the same type as, or a base
5283      class of, the class of T1, and the cv-qualification of T2 is the
5284      same cv-qualification as, or a greater cv-qualification than, the
5285      cv-qualification of T1.  If the conversion is applied, E1 is
5286      changed to an rvalue of type T2 that still refers to the original
5287      source class object (or the appropriate subobject thereof).  */
5288   if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
5289       && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
5290     {
5291       if (good_base && at_least_as_qualified_p (t2, t1))
5292 	{
5293 	  conv = build_identity_conv (t1, e1);
5294 	  if (!same_type_p (TYPE_MAIN_VARIANT (t1),
5295 			    TYPE_MAIN_VARIANT (t2)))
5296 	    conv = build_conv (ck_base, t2, conv);
5297 	  else
5298 	    conv = build_conv (ck_rvalue, t2, conv);
5299 	  return conv;
5300 	}
5301       else
5302 	return NULL;
5303     }
5304   else
5305     /* [expr.cond]
5306 
5307        Otherwise: E1 can be converted to match E2 if E1 can be implicitly
5308        converted to the type that expression E2 would have if E2 were
5309        converted to an rvalue (or the type it has, if E2 is an rvalue).  */
5310     return implicit_conversion (t2, t1, e1, /*c_cast_p=*/false,
5311 				LOOKUP_IMPLICIT, complain);
5312 }
5313 
5314 /* Implement [expr.cond].  ARG1, ARG2, and ARG3 are the three
5315    arguments to the conditional expression.  */
5316 
5317 tree
build_conditional_expr(const op_location_t & loc,tree arg1,tree arg2,tree arg3,tsubst_flags_t complain)5318 build_conditional_expr (const op_location_t &loc,
5319 			tree arg1, tree arg2, tree arg3,
5320 			tsubst_flags_t complain)
5321 {
5322   tree arg2_type;
5323   tree arg3_type;
5324   tree result = NULL_TREE;
5325   tree result_type = NULL_TREE;
5326   bool is_glvalue = true;
5327   struct z_candidate *candidates = 0;
5328   struct z_candidate *cand;
5329   void *p;
5330   tree orig_arg2, orig_arg3;
5331 
5332   auto_cond_timevar tv (TV_OVERLOAD);
5333 
5334   /* As a G++ extension, the second argument to the conditional can be
5335      omitted.  (So that `a ? : c' is roughly equivalent to `a ? a :
5336      c'.)  If the second operand is omitted, make sure it is
5337      calculated only once.  */
5338   if (!arg2)
5339     {
5340       if (complain & tf_error)
5341 	pedwarn (loc, OPT_Wpedantic,
5342 		 "ISO C++ forbids omitting the middle term of "
5343 		 "a %<?:%> expression");
5344 
5345       if ((complain & tf_warning) && !truth_value_p (TREE_CODE (arg1)))
5346 	warn_for_omitted_condop (loc, arg1);
5347 
5348       /* Make sure that lvalues remain lvalues.  See g++.oliva/ext1.C.  */
5349       if (glvalue_p (arg1))
5350 	{
5351 	  arg1 = cp_stabilize_reference (arg1);
5352 	  arg2 = arg1 = prevent_lifetime_extension (arg1);
5353 	}
5354       else
5355 	arg2 = arg1 = cp_save_expr (arg1);
5356     }
5357 
5358   /* If something has already gone wrong, just pass that fact up the
5359      tree.  */
5360   if (error_operand_p (arg1)
5361       || error_operand_p (arg2)
5362       || error_operand_p (arg3))
5363     return error_mark_node;
5364 
5365   orig_arg2 = arg2;
5366   orig_arg3 = arg3;
5367 
5368   if (gnu_vector_type_p (TREE_TYPE (arg1))
5369       && VECTOR_INTEGER_TYPE_P (TREE_TYPE (arg1)))
5370     {
5371       tree arg1_type = TREE_TYPE (arg1);
5372 
5373       /* If arg1 is another cond_expr choosing between -1 and 0,
5374 	 then we can use its comparison.  It may help to avoid
5375 	 additional comparison, produce more accurate diagnostics
5376 	 and enables folding.  */
5377       if (TREE_CODE (arg1) == VEC_COND_EXPR
5378 	  && integer_minus_onep (TREE_OPERAND (arg1, 1))
5379 	  && integer_zerop (TREE_OPERAND (arg1, 2)))
5380 	arg1 = TREE_OPERAND (arg1, 0);
5381 
5382       arg1 = force_rvalue (arg1, complain);
5383       arg2 = force_rvalue (arg2, complain);
5384       arg3 = force_rvalue (arg3, complain);
5385 
5386       /* force_rvalue can return error_mark on valid arguments.  */
5387       if (error_operand_p (arg1)
5388 	  || error_operand_p (arg2)
5389 	  || error_operand_p (arg3))
5390 	return error_mark_node;
5391 
5392       arg2_type = TREE_TYPE (arg2);
5393       arg3_type = TREE_TYPE (arg3);
5394 
5395       if (!VECTOR_TYPE_P (arg2_type)
5396 	  && !VECTOR_TYPE_P (arg3_type))
5397 	{
5398 	  /* Rely on the error messages of the scalar version.  */
5399 	  tree scal = build_conditional_expr (loc, integer_one_node,
5400 					      orig_arg2, orig_arg3, complain);
5401 	  if (scal == error_mark_node)
5402 	    return error_mark_node;
5403 	  tree stype = TREE_TYPE (scal);
5404 	  tree ctype = TREE_TYPE (arg1_type);
5405 	  if (TYPE_SIZE (stype) != TYPE_SIZE (ctype)
5406 	      || (!INTEGRAL_TYPE_P (stype) && !SCALAR_FLOAT_TYPE_P (stype)))
5407 	    {
5408 	      if (complain & tf_error)
5409 		error_at (loc, "inferred scalar type %qT is not an integer or "
5410 			  "floating-point type of the same size as %qT", stype,
5411 			  COMPARISON_CLASS_P (arg1)
5412 			  ? TREE_TYPE (TREE_TYPE (TREE_OPERAND (arg1, 0)))
5413 			  : ctype);
5414 	      return error_mark_node;
5415 	    }
5416 
5417 	  tree vtype = build_opaque_vector_type (stype,
5418 			 TYPE_VECTOR_SUBPARTS (arg1_type));
5419 	  /* We could pass complain & tf_warning to unsafe_conversion_p,
5420 	     but the warnings (like Wsign-conversion) have already been
5421 	     given by the scalar build_conditional_expr_1. We still check
5422 	     unsafe_conversion_p to forbid truncating long long -> float.  */
5423 	  if (unsafe_conversion_p (stype, arg2, NULL_TREE, false))
5424 	    {
5425 	      if (complain & tf_error)
5426 		error_at (loc, "conversion of scalar %qH to vector %qI "
5427 			       "involves truncation", arg2_type, vtype);
5428 	      return error_mark_node;
5429 	    }
5430 	  if (unsafe_conversion_p (stype, arg3, NULL_TREE, false))
5431 	    {
5432 	      if (complain & tf_error)
5433 		error_at (loc, "conversion of scalar %qH to vector %qI "
5434 			       "involves truncation", arg3_type, vtype);
5435 	      return error_mark_node;
5436 	    }
5437 
5438 	  arg2 = cp_convert (stype, arg2, complain);
5439 	  arg2 = save_expr (arg2);
5440 	  arg2 = build_vector_from_val (vtype, arg2);
5441 	  arg2_type = vtype;
5442 	  arg3 = cp_convert (stype, arg3, complain);
5443 	  arg3 = save_expr (arg3);
5444 	  arg3 = build_vector_from_val (vtype, arg3);
5445 	  arg3_type = vtype;
5446 	}
5447 
5448       if ((gnu_vector_type_p (arg2_type) && !VECTOR_TYPE_P (arg3_type))
5449 	  || (gnu_vector_type_p (arg3_type) && !VECTOR_TYPE_P (arg2_type)))
5450 	{
5451 	  enum stv_conv convert_flag =
5452 	    scalar_to_vector (loc, VEC_COND_EXPR, arg2, arg3,
5453 			      complain & tf_error);
5454 
5455 	  switch (convert_flag)
5456 	    {
5457 	      case stv_error:
5458 		return error_mark_node;
5459 	      case stv_firstarg:
5460 		{
5461 		  arg2 = save_expr (arg2);
5462 		  arg2 = convert (TREE_TYPE (arg3_type), arg2);
5463 		  arg2 = build_vector_from_val (arg3_type, arg2);
5464 		  arg2_type = TREE_TYPE (arg2);
5465 		  break;
5466 		}
5467 	      case stv_secondarg:
5468 		{
5469 		  arg3 = save_expr (arg3);
5470 		  arg3 = convert (TREE_TYPE (arg2_type), arg3);
5471 		  arg3 = build_vector_from_val (arg2_type, arg3);
5472 		  arg3_type = TREE_TYPE (arg3);
5473 		  break;
5474 		}
5475 	      default:
5476 		break;
5477 	    }
5478 	}
5479 
5480       if (!gnu_vector_type_p (arg2_type)
5481 	  || !gnu_vector_type_p (arg3_type)
5482 	  || !same_type_p (arg2_type, arg3_type)
5483 	  || maybe_ne (TYPE_VECTOR_SUBPARTS (arg1_type),
5484 		       TYPE_VECTOR_SUBPARTS (arg2_type))
5485 	  || TYPE_SIZE (arg1_type) != TYPE_SIZE (arg2_type))
5486 	{
5487 	  if (complain & tf_error)
5488 	    error_at (loc,
5489 		      "incompatible vector types in conditional expression: "
5490 		      "%qT, %qT and %qT", TREE_TYPE (arg1),
5491 		      TREE_TYPE (orig_arg2), TREE_TYPE (orig_arg3));
5492 	  return error_mark_node;
5493 	}
5494 
5495       if (!COMPARISON_CLASS_P (arg1))
5496 	{
5497 	  tree cmp_type = truth_type_for (arg1_type);
5498 	  arg1 = build2 (NE_EXPR, cmp_type, arg1, build_zero_cst (arg1_type));
5499 	}
5500       return build3_loc (loc, VEC_COND_EXPR, arg2_type, arg1, arg2, arg3);
5501     }
5502 
5503   /* [expr.cond]
5504 
5505      The first expression is implicitly converted to bool (clause
5506      _conv_).  */
5507   arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
5508 					    LOOKUP_NORMAL);
5509   if (error_operand_p (arg1))
5510     return error_mark_node;
5511 
5512   /* [expr.cond]
5513 
5514      If either the second or the third operand has type (possibly
5515      cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
5516      array-to-pointer (_conv.array_), and function-to-pointer
5517      (_conv.func_) standard conversions are performed on the second
5518      and third operands.  */
5519   arg2_type = unlowered_expr_type (arg2);
5520   arg3_type = unlowered_expr_type (arg3);
5521   if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
5522     {
5523       /* 'void' won't help in resolving an overloaded expression on the
5524 	 other side, so require it to resolve by itself.  */
5525       if (arg2_type == unknown_type_node)
5526 	{
5527 	  arg2 = resolve_nondeduced_context_or_error (arg2, complain);
5528 	  arg2_type = TREE_TYPE (arg2);
5529 	}
5530       if (arg3_type == unknown_type_node)
5531 	{
5532 	  arg3 = resolve_nondeduced_context_or_error (arg3, complain);
5533 	  arg3_type = TREE_TYPE (arg3);
5534 	}
5535 
5536       /* [expr.cond]
5537 
5538 	 One of the following shall hold:
5539 
5540 	 --The second or the third operand (but not both) is a
5541 	   throw-expression (_except.throw_); the result is of the type
5542 	   and value category of the other.
5543 
5544 	 --Both the second and the third operands have type void; the
5545 	   result is of type void and is a prvalue.  */
5546       if (TREE_CODE (arg2) == THROW_EXPR
5547 	  && TREE_CODE (arg3) != THROW_EXPR)
5548 	{
5549 	  result_type = arg3_type;
5550 	  is_glvalue = glvalue_p (arg3);
5551 	}
5552       else if (TREE_CODE (arg2) != THROW_EXPR
5553 	       && TREE_CODE (arg3) == THROW_EXPR)
5554 	{
5555 	  result_type = arg2_type;
5556 	  is_glvalue = glvalue_p (arg2);
5557 	}
5558       else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
5559 	{
5560 	  result_type = void_type_node;
5561 	  is_glvalue = false;
5562 	}
5563       else
5564 	{
5565           if (complain & tf_error)
5566             {
5567               if (VOID_TYPE_P (arg2_type))
5568                 error_at (cp_expr_loc_or_loc (arg3, loc),
5569 			  "second operand to the conditional operator "
5570 			  "is of type %<void%>, but the third operand is "
5571 			  "neither a throw-expression nor of type %<void%>");
5572               else
5573                 error_at (cp_expr_loc_or_loc (arg2, loc),
5574 			  "third operand to the conditional operator "
5575 			  "is of type %<void%>, but the second operand is "
5576 			  "neither a throw-expression nor of type %<void%>");
5577             }
5578 	  return error_mark_node;
5579 	}
5580 
5581       goto valid_operands;
5582     }
5583   /* [expr.cond]
5584 
5585      Otherwise, if the second and third operand have different types,
5586      and either has (possibly cv-qualified) class type, or if both are
5587      glvalues of the same value category and the same type except for
5588      cv-qualification, an attempt is made to convert each of those operands
5589      to the type of the other.  */
5590   else if (!same_type_p (arg2_type, arg3_type)
5591 	    && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)
5592 		|| (same_type_ignoring_top_level_qualifiers_p (arg2_type,
5593 							       arg3_type)
5594 		    && glvalue_p (arg2) && glvalue_p (arg3)
5595 		    && lvalue_p (arg2) == lvalue_p (arg3))))
5596     {
5597       conversion *conv2;
5598       conversion *conv3;
5599       bool converted = false;
5600 
5601       /* Get the high-water mark for the CONVERSION_OBSTACK.  */
5602       p = conversion_obstack_alloc (0);
5603 
5604       conv2 = conditional_conversion (arg2, arg3, complain);
5605       conv3 = conditional_conversion (arg3, arg2, complain);
5606 
5607       /* [expr.cond]
5608 
5609 	 If both can be converted, or one can be converted but the
5610 	 conversion is ambiguous, the program is ill-formed.  If
5611 	 neither can be converted, the operands are left unchanged and
5612 	 further checking is performed as described below.  If exactly
5613 	 one conversion is possible, that conversion is applied to the
5614 	 chosen operand and the converted operand is used in place of
5615 	 the original operand for the remainder of this section.  */
5616       if ((conv2 && !conv2->bad_p
5617 	   && conv3 && !conv3->bad_p)
5618 	  || (conv2 && conv2->kind == ck_ambig)
5619 	  || (conv3 && conv3->kind == ck_ambig))
5620 	{
5621 	  if (complain & tf_error)
5622 	    {
5623 	      error_at (loc, "operands to %<?:%> have different types "
5624 			"%qT and %qT",
5625 			arg2_type, arg3_type);
5626 	      if (conv2 && !conv2->bad_p && conv3 && !conv3->bad_p)
5627 		inform (loc, "  and each type can be converted to the other");
5628 	      else if (conv2 && conv2->kind == ck_ambig)
5629 		convert_like (conv2, arg2, complain);
5630 	      else
5631 		convert_like (conv3, arg3, complain);
5632 	    }
5633 	  result = error_mark_node;
5634 	}
5635       else if (conv2 && !conv2->bad_p)
5636 	{
5637 	  arg2 = convert_like (conv2, arg2, complain);
5638 	  arg2 = convert_from_reference (arg2);
5639 	  arg2_type = TREE_TYPE (arg2);
5640 	  /* Even if CONV2 is a valid conversion, the result of the
5641 	     conversion may be invalid.  For example, if ARG3 has type
5642 	     "volatile X", and X does not have a copy constructor
5643 	     accepting a "volatile X&", then even if ARG2 can be
5644 	     converted to X, the conversion will fail.  */
5645 	  if (error_operand_p (arg2))
5646 	    result = error_mark_node;
5647 	  converted = true;
5648 	}
5649       else if (conv3 && !conv3->bad_p)
5650 	{
5651 	  arg3 = convert_like (conv3, arg3, complain);
5652 	  arg3 = convert_from_reference (arg3);
5653 	  arg3_type = TREE_TYPE (arg3);
5654 	  if (error_operand_p (arg3))
5655 	    result = error_mark_node;
5656 	  converted = true;
5657 	}
5658 
5659       /* Free all the conversions we allocated.  */
5660       obstack_free (&conversion_obstack, p);
5661 
5662       if (result)
5663 	return result;
5664 
5665       /* If, after the conversion, both operands have class type,
5666 	 treat the cv-qualification of both operands as if it were the
5667 	 union of the cv-qualification of the operands.
5668 
5669 	 The standard is not clear about what to do in this
5670 	 circumstance.  For example, if the first operand has type
5671 	 "const X" and the second operand has a user-defined
5672 	 conversion to "volatile X", what is the type of the second
5673 	 operand after this step?  Making it be "const X" (matching
5674 	 the first operand) seems wrong, as that discards the
5675 	 qualification without actually performing a copy.  Leaving it
5676 	 as "volatile X" seems wrong as that will result in the
5677 	 conditional expression failing altogether, even though,
5678 	 according to this step, the one operand could be converted to
5679 	 the type of the other.  */
5680       if (converted
5681 	  && CLASS_TYPE_P (arg2_type)
5682 	  && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
5683 	arg2_type = arg3_type =
5684 	  cp_build_qualified_type (arg2_type,
5685 				   cp_type_quals (arg2_type)
5686 				   | cp_type_quals (arg3_type));
5687     }
5688 
5689   /* [expr.cond]
5690 
5691      If the second and third operands are glvalues of the same value
5692      category and have the same type, the result is of that type and
5693      value category.  */
5694   if (((lvalue_p (arg2) && lvalue_p (arg3))
5695        || (xvalue_p (arg2) && xvalue_p (arg3)))
5696       && same_type_p (arg2_type, arg3_type))
5697     {
5698       result_type = arg2_type;
5699       goto valid_operands;
5700     }
5701 
5702   /* [expr.cond]
5703 
5704      Otherwise, the result is an rvalue.  If the second and third
5705      operand do not have the same type, and either has (possibly
5706      cv-qualified) class type, overload resolution is used to
5707      determine the conversions (if any) to be applied to the operands
5708      (_over.match.oper_, _over.built_).  */
5709   is_glvalue = false;
5710   if (!same_type_p (arg2_type, arg3_type)
5711       && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
5712     {
5713       releasing_vec args;
5714       conversion *conv;
5715       bool any_viable_p;
5716 
5717       /* Rearrange the arguments so that add_builtin_candidate only has
5718 	 to know about two args.  In build_builtin_candidate, the
5719 	 arguments are unscrambled.  */
5720       args->quick_push (arg2);
5721       args->quick_push (arg3);
5722       args->quick_push (arg1);
5723       add_builtin_candidates (&candidates,
5724 			      COND_EXPR,
5725 			      NOP_EXPR,
5726 			      ovl_op_identifier (false, COND_EXPR),
5727 			      args,
5728 			      LOOKUP_NORMAL, complain);
5729 
5730       /* [expr.cond]
5731 
5732 	 If the overload resolution fails, the program is
5733 	 ill-formed.  */
5734       candidates = splice_viable (candidates, false, &any_viable_p);
5735       if (!any_viable_p)
5736 	{
5737           if (complain & tf_error)
5738 	    error_at (loc, "operands to %<?:%> have different types %qT and %qT",
5739 		      arg2_type, arg3_type);
5740 	  return error_mark_node;
5741 	}
5742       cand = tourney (candidates, complain);
5743       if (!cand)
5744 	{
5745           if (complain & tf_error)
5746             {
5747               auto_diagnostic_group d;
5748               op_error (loc, COND_EXPR, NOP_EXPR, arg1, arg2, arg3, FALSE);
5749               print_z_candidates (loc, candidates);
5750             }
5751 	  return error_mark_node;
5752 	}
5753 
5754       /* [expr.cond]
5755 
5756 	 Otherwise, the conversions thus determined are applied, and
5757 	 the converted operands are used in place of the original
5758 	 operands for the remainder of this section.  */
5759       conv = cand->convs[0];
5760       arg1 = convert_like (conv, arg1, complain);
5761       conv = cand->convs[1];
5762       arg2 = convert_like (conv, arg2, complain);
5763       arg2_type = TREE_TYPE (arg2);
5764       conv = cand->convs[2];
5765       arg3 = convert_like (conv, arg3, complain);
5766       arg3_type = TREE_TYPE (arg3);
5767     }
5768 
5769   /* [expr.cond]
5770 
5771      Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
5772      and function-to-pointer (_conv.func_) standard conversions are
5773      performed on the second and third operands.
5774 
5775      We need to force the lvalue-to-rvalue conversion here for class types,
5776      so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
5777      that isn't wrapped with a TARGET_EXPR plays havoc with exception
5778      regions.  */
5779 
5780   arg2 = force_rvalue (arg2, complain);
5781   if (!CLASS_TYPE_P (arg2_type))
5782     arg2_type = TREE_TYPE (arg2);
5783 
5784   arg3 = force_rvalue (arg3, complain);
5785   if (!CLASS_TYPE_P (arg3_type))
5786     arg3_type = TREE_TYPE (arg3);
5787 
5788   if (arg2 == error_mark_node || arg3 == error_mark_node)
5789     return error_mark_node;
5790 
5791   /* [expr.cond]
5792 
5793      After those conversions, one of the following shall hold:
5794 
5795      --The second and third operands have the same type; the result  is  of
5796        that type.  */
5797   if (same_type_p (arg2_type, arg3_type))
5798     result_type = arg2_type;
5799   /* [expr.cond]
5800 
5801      --The second and third operands have arithmetic or enumeration
5802        type; the usual arithmetic conversions are performed to bring
5803        them to a common type, and the result is of that type.  */
5804   else if ((ARITHMETIC_TYPE_P (arg2_type)
5805 	    || UNSCOPED_ENUM_P (arg2_type))
5806 	   && (ARITHMETIC_TYPE_P (arg3_type)
5807 	       || UNSCOPED_ENUM_P (arg3_type)))
5808     {
5809       /* In this case, there is always a common type.  */
5810       result_type = type_after_usual_arithmetic_conversions (arg2_type,
5811 							     arg3_type);
5812       if (complain & tf_warning)
5813 	do_warn_double_promotion (result_type, arg2_type, arg3_type,
5814 				  "implicit conversion from %qH to %qI to "
5815 				  "match other result of conditional",
5816 				  loc);
5817 
5818       if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
5819 	  && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
5820         {
5821 	  tree stripped_orig_arg2 = tree_strip_any_location_wrapper (orig_arg2);
5822 	  tree stripped_orig_arg3 = tree_strip_any_location_wrapper (orig_arg3);
5823 	  if (TREE_CODE (stripped_orig_arg2) == CONST_DECL
5824 	      && TREE_CODE (stripped_orig_arg3) == CONST_DECL
5825 	      && (DECL_CONTEXT (stripped_orig_arg2)
5826 		  == DECL_CONTEXT (stripped_orig_arg3)))
5827 	    /* Two enumerators from the same enumeration can have different
5828 	       types when the enumeration is still being defined.  */;
5829           else if (complain & tf_warning)
5830 	    warning_at (loc, OPT_Wenum_compare, "enumerated mismatch "
5831 			"in conditional expression: %qT vs %qT",
5832 			arg2_type, arg3_type);
5833         }
5834       else if ((complain & tf_warning)
5835 	       && warn_deprecated_enum_float_conv
5836 	       && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
5837 		    && TREE_CODE (arg3_type) == REAL_TYPE)
5838 		   || (TREE_CODE (arg2_type) == REAL_TYPE
5839 		       && TREE_CODE (arg3_type) == ENUMERAL_TYPE)))
5840 	{
5841 	  if (TREE_CODE (arg2_type) == ENUMERAL_TYPE)
5842 	    warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
5843 			"conditional expression between enumeration type "
5844 			"%qT and floating-point type %qT is deprecated",
5845 			arg2_type, arg3_type);
5846 	  else
5847 	    warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
5848 			"conditional expression between floating-point "
5849 			"type %qT and enumeration type %qT is deprecated",
5850 			arg2_type, arg3_type);
5851 	}
5852       else if ((extra_warnings || warn_enum_conversion)
5853 	       && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
5854 		    && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
5855 		   || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
5856 		       && !same_type_p (arg2_type,
5857 					type_promotes_to (arg3_type)))))
5858 	{
5859 	  if (complain & tf_warning)
5860 	    {
5861 	      enum opt_code opt = (warn_enum_conversion
5862 				   ? OPT_Wenum_conversion
5863 				   : OPT_Wextra);
5864 	      warning_at (loc, opt, "enumerated and "
5865 			  "non-enumerated type in conditional expression");
5866 	    }
5867 	}
5868 
5869       arg2 = perform_implicit_conversion (result_type, arg2, complain);
5870       arg3 = perform_implicit_conversion (result_type, arg3, complain);
5871     }
5872   /* [expr.cond]
5873 
5874      --The second and third operands have pointer type, or one has
5875        pointer type and the other is a null pointer constant; pointer
5876        conversions (_conv.ptr_) and qualification conversions
5877        (_conv.qual_) are performed to bring them to their composite
5878        pointer type (_expr.rel_).  The result is of the composite
5879        pointer type.
5880 
5881      --The second and third operands have pointer to member type, or
5882        one has pointer to member type and the other is a null pointer
5883        constant; pointer to member conversions (_conv.mem_) and
5884        qualification conversions (_conv.qual_) are performed to bring
5885        them to a common type, whose cv-qualification shall match the
5886        cv-qualification of either the second or the third operand.
5887        The result is of the common type.  */
5888   else if ((null_ptr_cst_p (arg2)
5889 	    && TYPE_PTR_OR_PTRMEM_P (arg3_type))
5890 	   || (null_ptr_cst_p (arg3)
5891 	       && TYPE_PTR_OR_PTRMEM_P (arg2_type))
5892 	   || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
5893 	   || (TYPE_PTRDATAMEM_P (arg2_type) && TYPE_PTRDATAMEM_P (arg3_type))
5894 	   || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
5895     {
5896       result_type = composite_pointer_type (loc,
5897 					    arg2_type, arg3_type, arg2,
5898 					    arg3, CPO_CONDITIONAL_EXPR,
5899 					    complain);
5900       if (result_type == error_mark_node)
5901 	return error_mark_node;
5902       arg2 = perform_implicit_conversion (result_type, arg2, complain);
5903       arg3 = perform_implicit_conversion (result_type, arg3, complain);
5904     }
5905 
5906   if (!result_type)
5907     {
5908       if (complain & tf_error)
5909 	error_at (loc, "operands to %<?:%> have different types %qT and %qT",
5910 		  arg2_type, arg3_type);
5911       return error_mark_node;
5912     }
5913 
5914   if (arg2 == error_mark_node || arg3 == error_mark_node)
5915     return error_mark_node;
5916 
5917  valid_operands:
5918   if (processing_template_decl && is_glvalue)
5919     {
5920       /* Let lvalue_kind know this was a glvalue.  */
5921       tree arg = (result_type == arg2_type ? arg2 : arg3);
5922       result_type = cp_build_reference_type (result_type, xvalue_p (arg));
5923     }
5924 
5925   result = build3_loc (loc, COND_EXPR, result_type, arg1, arg2, arg3);
5926 
5927   /* If the ARG2 and ARG3 are the same and don't have side-effects,
5928      warn here, because the COND_EXPR will be turned into ARG2.  */
5929   if (warn_duplicated_branches
5930       && (complain & tf_warning)
5931       && (arg2 == arg3 || operand_equal_p (arg2, arg3,
5932 					   OEP_ADDRESS_OF_SAME_FIELD)))
5933     warning_at (EXPR_LOCATION (result), OPT_Wduplicated_branches,
5934 		"this condition has identical branches");
5935 
5936   /* We can't use result_type below, as fold might have returned a
5937      throw_expr.  */
5938 
5939   if (!is_glvalue)
5940     {
5941       /* Expand both sides into the same slot, hopefully the target of
5942 	 the ?: expression.  We used to check for TARGET_EXPRs here,
5943 	 but now we sometimes wrap them in NOP_EXPRs so the test would
5944 	 fail.  */
5945       if (CLASS_TYPE_P (TREE_TYPE (result)))
5946 	result = get_target_expr_sfinae (result, complain);
5947       /* If this expression is an rvalue, but might be mistaken for an
5948 	 lvalue, we must add a NON_LVALUE_EXPR.  */
5949       result = rvalue (result);
5950     }
5951   else
5952     result = force_paren_expr (result);
5953 
5954   return result;
5955 }
5956 
5957 /* OPERAND is an operand to an expression.  Perform necessary steps
5958    required before using it.  If OPERAND is NULL_TREE, NULL_TREE is
5959    returned.  */
5960 
5961 static tree
prep_operand(tree operand)5962 prep_operand (tree operand)
5963 {
5964   if (operand)
5965     {
5966       if (CLASS_TYPE_P (TREE_TYPE (operand))
5967 	  && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
5968 	/* Make sure the template type is instantiated now.  */
5969 	instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
5970     }
5971 
5972   return operand;
5973 }
5974 
5975 /* True iff CONV represents a conversion sequence which no other can be better
5976    than under [over.ics.rank]: in other words, a "conversion" to the exact same
5977    type (including binding to a reference to the same type).  This is stronger
5978    than the standard's "identity" category, which also includes reference
5979    bindings that add cv-qualifiers or change rvalueness.  */
5980 
5981 static bool
perfect_conversion_p(conversion * conv)5982 perfect_conversion_p (conversion *conv)
5983 {
5984   if (CONVERSION_RANK (conv) != cr_identity)
5985     return false;
5986   if (conv->kind == ck_ref_bind)
5987     {
5988       if (!conv->rvaluedness_matches_p)
5989 	return false;
5990       if (!same_type_p (TREE_TYPE (conv->type),
5991 			next_conversion (conv)->type))
5992 	return false;
5993     }
5994   if (conv->check_narrowing)
5995     /* Brace elision is imperfect.  */
5996     return false;
5997   return true;
5998 }
5999 
6000 /* True if CAND represents a perfect match, i.e. all perfect conversions, so no
6001    other candidate can be a better match.  Since the template/non-template
6002    tiebreaker comes immediately after the conversion comparison in
6003    [over.match.best], a perfect non-template candidate is better than all
6004    templates.  */
6005 
6006 static bool
perfect_candidate_p(z_candidate * cand)6007 perfect_candidate_p (z_candidate *cand)
6008 {
6009   if (cand->viable < 1)
6010     return false;
6011   /* CWG1402 makes an implicitly deleted move op worse than other
6012      candidates.  */
6013   if (DECL_DELETED_FN (cand->fn) && DECL_DEFAULTED_FN (cand->fn)
6014       && move_fn_p (cand->fn))
6015     return false;
6016   int len = cand->num_convs;
6017   for (int i = 0; i < len; ++i)
6018     if (!perfect_conversion_p (cand->convs[i]))
6019       return false;
6020   if (conversion *conv = cand->second_conv)
6021     if (!perfect_conversion_p (conv))
6022       return false;
6023   return true;
6024 }
6025 
6026 /* Add each of the viable functions in FNS (a FUNCTION_DECL or
6027    OVERLOAD) to the CANDIDATES, returning an updated list of
6028    CANDIDATES.  The ARGS are the arguments provided to the call;
6029    if FIRST_ARG is non-null it is the implicit object argument,
6030    otherwise the first element of ARGS is used if needed.  The
6031    EXPLICIT_TARGS are explicit template arguments provided.
6032    TEMPLATE_ONLY is true if only template functions should be
6033    considered.  CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
6034    add_function_candidate.  */
6035 
6036 static void
add_candidates(tree fns,tree first_arg,const vec<tree,va_gc> * args,tree return_type,tree explicit_targs,bool template_only,tree conversion_path,tree access_path,int flags,struct z_candidate ** candidates,tsubst_flags_t complain)6037 add_candidates (tree fns, tree first_arg, const vec<tree, va_gc> *args,
6038 		tree return_type,
6039 		tree explicit_targs, bool template_only,
6040 		tree conversion_path, tree access_path,
6041 		int flags,
6042 		struct z_candidate **candidates,
6043 		tsubst_flags_t complain)
6044 {
6045   tree ctype;
6046   const vec<tree, va_gc> *non_static_args;
6047   bool check_list_ctor = false;
6048   bool check_converting = false;
6049   unification_kind_t strict;
6050 
6051   if (!fns)
6052     return;
6053 
6054   /* Precalculate special handling of constructors and conversion ops.  */
6055   tree fn = OVL_FIRST (fns);
6056   if (DECL_CONV_FN_P (fn))
6057     {
6058       check_list_ctor = false;
6059       check_converting = (flags & LOOKUP_ONLYCONVERTING) != 0;
6060       if (flags & LOOKUP_NO_CONVERSION)
6061 	/* We're doing return_type(x).  */
6062 	strict = DEDUCE_CONV;
6063       else
6064 	/* We're doing x.operator return_type().  */
6065 	strict = DEDUCE_EXACT;
6066       /* [over.match.funcs] For conversion functions, the function
6067 	 is considered to be a member of the class of the implicit
6068 	 object argument for the purpose of defining the type of
6069 	 the implicit object parameter.  */
6070       ctype = TYPE_MAIN_VARIANT (TREE_TYPE (first_arg));
6071     }
6072   else
6073     {
6074       if (DECL_CONSTRUCTOR_P (fn))
6075 	{
6076 	  check_list_ctor = (flags & LOOKUP_LIST_ONLY) != 0;
6077 	  /* For list-initialization we consider explicit constructors
6078 	     and complain if one is chosen.  */
6079 	  check_converting
6080 	    = ((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
6081 	       == LOOKUP_ONLYCONVERTING);
6082 	}
6083       strict = DEDUCE_CALL;
6084       ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
6085     }
6086 
6087   if (first_arg)
6088     non_static_args = args;
6089   else
6090     /* Delay creating the implicit this parameter until it is needed.  */
6091     non_static_args = NULL;
6092 
6093   bool seen_strictly_viable = any_strictly_viable (*candidates);
6094   /* If there's a non-template perfect match, we don't need to consider
6095      templates.  So check non-templates first.  This optimization is only
6096      really needed for the defaulted copy constructor of tuple and the like
6097      (96926), but it seems like we might as well enable it more generally.  */
6098   bool seen_perfect = false;
6099   enum { templates, non_templates, either } which = either;
6100   if (template_only)
6101     which = templates;
6102   else /*if (flags & LOOKUP_DEFAULTED)*/
6103     which = non_templates;
6104 
6105   /* During overload resolution, we first consider each function under the
6106      assumption that we'll eventually find a strictly viable candidate.
6107      This allows us to circumvent our defacto behavior when checking
6108      argument conversions and shortcut consideration of the candidate
6109      upon encountering the first bad conversion.  If this assumption
6110      turns out to be false, and all candidates end up being non-strictly
6111      viable, then we reconsider such candidates under the defacto behavior.
6112      This trick is important for pruning member function overloads according
6113      to their const/ref-qualifiers (since all 'this' conversions are at
6114      worst bad) without breaking -fpermissive.  */
6115   tree bad_fns = NULL_TREE;
6116   bool shortcut_bad_convs = true;
6117 
6118  again:
6119   for (tree fn : lkp_range (fns))
6120     {
6121       if (check_converting && DECL_NONCONVERTING_P (fn))
6122 	continue;
6123       if (check_list_ctor && !is_list_ctor (fn))
6124 	continue;
6125       if (which == templates && TREE_CODE (fn) != TEMPLATE_DECL)
6126 	continue;
6127       if (which == non_templates && TREE_CODE (fn) == TEMPLATE_DECL)
6128 	continue;
6129 
6130       tree fn_first_arg = NULL_TREE;
6131       const vec<tree, va_gc> *fn_args = args;
6132 
6133       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
6134 	{
6135 	  /* Figure out where the object arg comes from.  If this
6136 	     function is a non-static member and we didn't get an
6137 	     implicit object argument, move it out of args.  */
6138 	  if (first_arg == NULL_TREE)
6139 	    {
6140 	      unsigned int ix;
6141 	      tree arg;
6142 	      vec<tree, va_gc> *tempvec;
6143 	      vec_alloc (tempvec, args->length () - 1);
6144 	      for (ix = 1; args->iterate (ix, &arg); ++ix)
6145 		tempvec->quick_push (arg);
6146 	      non_static_args = tempvec;
6147 	      first_arg = (*args)[0];
6148 	    }
6149 
6150 	  fn_first_arg = first_arg;
6151 	  fn_args = non_static_args;
6152 	}
6153 
6154       /* Don't bother reversing an operator with two identical parameters.  */
6155       else if (vec_safe_length (args) == 2 && (flags & LOOKUP_REVERSED))
6156 	{
6157 	  tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
6158 	  if (same_type_p (TREE_VALUE (parmlist),
6159 			   TREE_VALUE (TREE_CHAIN (parmlist))))
6160 	    continue;
6161 	}
6162 
6163       if (TREE_CODE (fn) == TEMPLATE_DECL)
6164 	{
6165 	  if (!add_template_candidate (candidates,
6166 				       fn,
6167 				       ctype,
6168 				       explicit_targs,
6169 				       fn_first_arg,
6170 				       fn_args,
6171 				       return_type,
6172 				       access_path,
6173 				       conversion_path,
6174 				       flags,
6175 				       strict,
6176 				       shortcut_bad_convs,
6177 				       complain))
6178 	    continue;
6179 	}
6180       else
6181 	{
6182 	  add_function_candidate (candidates,
6183 				  fn,
6184 				  ctype,
6185 				  fn_first_arg,
6186 				  fn_args,
6187 				  access_path,
6188 				  conversion_path,
6189 				  flags,
6190 				  NULL,
6191 				  shortcut_bad_convs,
6192 				  complain);
6193 	  if (perfect_candidate_p (*candidates))
6194 	    seen_perfect = true;
6195 	}
6196 
6197       z_candidate *cand = *candidates;
6198       if (cand->viable == 1)
6199 	seen_strictly_viable = true;
6200 
6201       if (cand->viable == -1
6202 	  && shortcut_bad_convs
6203 	  && !cand->convs[cand->reversed () ? 0 : cand->num_convs - 1])
6204 	{
6205 	  /* This candidate has been tentatively marked non-strictly viable,
6206 	     and we didn't compute all argument conversions for it (having
6207 	     stopped at the first bad conversion).  Add the function to BAD_FNS
6208 	     to fully reconsider later if we don't find any strictly viable
6209 	     candidates.  */
6210 	  if (complain & (tf_error | tf_conv))
6211 	    {
6212 	      bad_fns = lookup_add (fn, bad_fns);
6213 	      *candidates = (*candidates)->next;
6214 	    }
6215 	  else
6216 	    /* But if we're in a SFINAE context, just mark this candidate as
6217 	       unviable outright and avoid potentially reconsidering it.
6218 	       This is safe to do because in a SFINAE context, performing a bad
6219 	       conversion is always an error (even with -fpermissive), so a
6220 	       non-strictly viable candidate is effectively unviable anyway.  */
6221 	    cand->viable = 0;
6222 	}
6223     }
6224   if (which == non_templates && !seen_perfect)
6225     {
6226       which = templates;
6227       goto again;
6228     }
6229   else if (which == templates
6230 	   && !seen_strictly_viable
6231 	   && shortcut_bad_convs
6232 	   && bad_fns)
6233     {
6234       /* None of the candidates are strictly viable, so consider again those
6235 	 functions in BAD_FNS, this time without shortcutting bad conversions
6236 	 so that all their argument conversions are computed.  */
6237       which = either;
6238       fns = bad_fns;
6239       shortcut_bad_convs = false;
6240       goto again;
6241     }
6242 }
6243 
6244 /* Returns 1 if P0145R2 says that the LHS of operator CODE is evaluated first,
6245    -1 if the RHS is evaluated first, or 0 if the order is unspecified.  */
6246 
6247 static int
op_is_ordered(tree_code code)6248 op_is_ordered (tree_code code)
6249 {
6250   switch (code)
6251     {
6252       // 5. b @= a
6253     case MODIFY_EXPR:
6254       return (flag_strong_eval_order > 1 ? -1 : 0);
6255 
6256       // 6. a[b]
6257     case ARRAY_REF:
6258       return (flag_strong_eval_order > 1 ? 1 : 0);
6259 
6260       // 1. a.b
6261       // Not overloadable (yet).
6262       // 2. a->b
6263       // Only one argument.
6264       // 3. a->*b
6265     case MEMBER_REF:
6266       // 7. a << b
6267     case LSHIFT_EXPR:
6268       // 8. a >> b
6269     case RSHIFT_EXPR:
6270       // a && b
6271       // Predates P0145R3.
6272     case TRUTH_ANDIF_EXPR:
6273       // a || b
6274       // Predates P0145R3.
6275     case TRUTH_ORIF_EXPR:
6276       // a , b
6277       // Predates P0145R3.
6278     case COMPOUND_EXPR:
6279       return (flag_strong_eval_order ? 1 : 0);
6280 
6281     default:
6282       return 0;
6283     }
6284 }
6285 
6286 /* Subroutine of build_new_op: Add to CANDIDATES all candidates for the
6287    operator indicated by CODE/CODE2.  This function calls itself recursively to
6288    handle C++20 rewritten comparison operator candidates.  */
6289 
6290 static tree
add_operator_candidates(z_candidate ** candidates,tree_code code,tree_code code2,vec<tree,va_gc> * arglist,int flags,tsubst_flags_t complain)6291 add_operator_candidates (z_candidate **candidates,
6292 			 tree_code code, tree_code code2,
6293 			 vec<tree, va_gc> *arglist,
6294 			 int flags, tsubst_flags_t complain)
6295 {
6296   z_candidate *start_candidates = *candidates;
6297   bool ismodop = code2 != ERROR_MARK;
6298   tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
6299 
6300   /* LOOKUP_REWRITTEN is set when we're looking for the == or <=> operator to
6301      rewrite from, and also when we're looking for the e.g. < operator to use
6302      on the result of <=>.  In the latter case, we don't want the flag set in
6303      the candidate, we just want to suppress looking for rewrites.  */
6304   bool rewritten = (flags & LOOKUP_REWRITTEN);
6305   if (rewritten && code != EQ_EXPR && code != SPACESHIP_EXPR)
6306     flags &= ~LOOKUP_REWRITTEN;
6307 
6308   bool memonly = false;
6309   switch (code)
6310     {
6311       /* =, ->, [], () must be non-static member functions.  */
6312     case MODIFY_EXPR:
6313       if (code2 != NOP_EXPR)
6314 	break;
6315       /* FALLTHRU */
6316     case COMPONENT_REF:
6317     case ARRAY_REF:
6318       memonly = true;
6319       break;
6320 
6321     default:
6322       break;
6323     }
6324 
6325   /* Add namespace-scope operators to the list of functions to
6326      consider.  */
6327   if (!memonly)
6328     {
6329       tree fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
6330       fns = lookup_arg_dependent (fnname, fns, arglist);
6331       add_candidates (fns, NULL_TREE, arglist, NULL_TREE,
6332 		      NULL_TREE, false, NULL_TREE, NULL_TREE,
6333 		      flags, candidates, complain);
6334     }
6335 
6336   /* Add class-member operators to the candidate set.  */
6337   tree arg1_type = TREE_TYPE ((*arglist)[0]);
6338   unsigned nargs = arglist->length () > 1 ? 2 : 1;
6339   tree arg2_type = nargs > 1 ? TREE_TYPE ((*arglist)[1]) : NULL_TREE;
6340   if (CLASS_TYPE_P (arg1_type))
6341     {
6342       tree fns = lookup_fnfields (arg1_type, fnname, 1, complain);
6343       if (fns == error_mark_node)
6344 	return error_mark_node;
6345       if (fns)
6346 	add_candidates (BASELINK_FUNCTIONS (fns),
6347 			NULL_TREE, arglist, NULL_TREE,
6348 			NULL_TREE, false,
6349 			BASELINK_BINFO (fns),
6350 			BASELINK_ACCESS_BINFO (fns),
6351 			flags, candidates, complain);
6352     }
6353   /* Per [over.match.oper]3.2, if no operand has a class type, then
6354      only non-member functions that have type T1 or reference to
6355      cv-qualified-opt T1 for the first argument, if the first argument
6356      has an enumeration type, or T2 or reference to cv-qualified-opt
6357      T2 for the second argument, if the second argument has an
6358      enumeration type.  Filter out those that don't match.  */
6359   else if (! arg2_type || ! CLASS_TYPE_P (arg2_type))
6360     {
6361       struct z_candidate **candp, **next;
6362 
6363       for (candp = candidates; *candp != start_candidates; candp = next)
6364 	{
6365 	  unsigned i;
6366 	  z_candidate *cand = *candp;
6367 	  next = &cand->next;
6368 
6369 	  tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
6370 
6371 	  for (i = 0; i < nargs; ++i)
6372 	    {
6373 	      tree parmtype = TREE_VALUE (parmlist);
6374 	      tree argtype = unlowered_expr_type ((*arglist)[i]);
6375 
6376 	      if (TYPE_REF_P (parmtype))
6377 		parmtype = TREE_TYPE (parmtype);
6378 	      if (TREE_CODE (argtype) == ENUMERAL_TYPE
6379 		  && (same_type_ignoring_top_level_qualifiers_p
6380 		      (argtype, parmtype)))
6381 		break;
6382 
6383 	      parmlist = TREE_CHAIN (parmlist);
6384 	    }
6385 
6386 	  /* No argument has an appropriate type, so remove this
6387 	     candidate function from the list.  */
6388 	  if (i == nargs)
6389 	    {
6390 	      *candp = cand->next;
6391 	      next = candp;
6392 	    }
6393 	}
6394     }
6395 
6396   if (!rewritten)
6397     {
6398       /* The standard says to rewrite built-in candidates, too,
6399 	 but there's no point.  */
6400       add_builtin_candidates (candidates, code, code2, fnname, arglist,
6401 			      flags, complain);
6402 
6403       /* Maybe add C++20 rewritten comparison candidates.  */
6404       tree_code rewrite_code = ERROR_MARK;
6405       if (cxx_dialect >= cxx20
6406 	  && nargs == 2
6407 	  && (OVERLOAD_TYPE_P (arg1_type) || OVERLOAD_TYPE_P (arg2_type)))
6408 	switch (code)
6409 	  {
6410 	  case LT_EXPR:
6411 	  case LE_EXPR:
6412 	  case GT_EXPR:
6413 	  case GE_EXPR:
6414 	  case SPACESHIP_EXPR:
6415 	    rewrite_code = SPACESHIP_EXPR;
6416 	    break;
6417 
6418 	  case NE_EXPR:
6419 	  case EQ_EXPR:
6420 	    rewrite_code = EQ_EXPR;
6421 	    break;
6422 
6423 	  default:;
6424 	  }
6425 
6426       if (rewrite_code)
6427 	{
6428 	  flags |= LOOKUP_REWRITTEN;
6429 	  if (rewrite_code != code)
6430 	    /* Add rewritten candidates in same order.  */
6431 	    add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
6432 				     arglist, flags, complain);
6433 
6434 	  z_candidate *save_cand = *candidates;
6435 
6436 	  /* Add rewritten candidates in reverse order.  */
6437 	  flags |= LOOKUP_REVERSED;
6438 	  vec<tree,va_gc> *revlist = make_tree_vector ();
6439 	  revlist->quick_push ((*arglist)[1]);
6440 	  revlist->quick_push ((*arglist)[0]);
6441 	  add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
6442 				   revlist, flags, complain);
6443 
6444 	  /* Release the vec if we didn't add a candidate that uses it.  */
6445 	  for (z_candidate *c = *candidates; c != save_cand; c = c->next)
6446 	    if (c->args == revlist)
6447 	      {
6448 		revlist = NULL;
6449 		break;
6450 	      }
6451 	  release_tree_vector (revlist);
6452 	}
6453     }
6454 
6455   return NULL_TREE;
6456 }
6457 
6458 tree
build_new_op(const op_location_t & loc,enum tree_code code,int flags,tree arg1,tree arg2,tree arg3,tree * overload,tsubst_flags_t complain)6459 build_new_op (const op_location_t &loc, enum tree_code code, int flags,
6460 	      tree arg1, tree arg2, tree arg3, tree *overload,
6461 	      tsubst_flags_t complain)
6462 {
6463   struct z_candidate *candidates = 0, *cand;
6464   vec<tree, va_gc> *arglist;
6465   tree result = NULL_TREE;
6466   bool result_valid_p = false;
6467   enum tree_code code2 = ERROR_MARK;
6468   enum tree_code code_orig_arg1 = ERROR_MARK;
6469   enum tree_code code_orig_arg2 = ERROR_MARK;
6470   conversion *conv;
6471   void *p;
6472   bool strict_p;
6473   bool any_viable_p;
6474 
6475   auto_cond_timevar tv (TV_OVERLOAD);
6476 
6477   if (error_operand_p (arg1)
6478       || error_operand_p (arg2)
6479       || error_operand_p (arg3))
6480     return error_mark_node;
6481 
6482   bool ismodop = code == MODIFY_EXPR;
6483   if (ismodop)
6484     {
6485       code2 = TREE_CODE (arg3);
6486       arg3 = NULL_TREE;
6487     }
6488 
6489   tree arg1_type = unlowered_expr_type (arg1);
6490   tree arg2_type = arg2 ? unlowered_expr_type (arg2) : NULL_TREE;
6491 
6492   arg1 = prep_operand (arg1);
6493 
6494   switch (code)
6495     {
6496     case NEW_EXPR:
6497     case VEC_NEW_EXPR:
6498     case VEC_DELETE_EXPR:
6499     case DELETE_EXPR:
6500       /* Use build_operator_new_call and build_op_delete_call instead.  */
6501       gcc_unreachable ();
6502 
6503     case CALL_EXPR:
6504       /* Use build_op_call instead.  */
6505       gcc_unreachable ();
6506 
6507     case TRUTH_ORIF_EXPR:
6508     case TRUTH_ANDIF_EXPR:
6509     case TRUTH_AND_EXPR:
6510     case TRUTH_OR_EXPR:
6511       /* These are saved for the sake of warn_logical_operator.  */
6512       code_orig_arg1 = TREE_CODE (arg1);
6513       code_orig_arg2 = TREE_CODE (arg2);
6514       break;
6515     case GT_EXPR:
6516     case LT_EXPR:
6517     case GE_EXPR:
6518     case LE_EXPR:
6519     case EQ_EXPR:
6520     case NE_EXPR:
6521       /* These are saved for the sake of maybe_warn_bool_compare.  */
6522       code_orig_arg1 = TREE_CODE (arg1_type);
6523       code_orig_arg2 = TREE_CODE (arg2_type);
6524       break;
6525 
6526     default:
6527       break;
6528     }
6529 
6530   arg2 = prep_operand (arg2);
6531   arg3 = prep_operand (arg3);
6532 
6533   if (code == COND_EXPR)
6534     /* Use build_conditional_expr instead.  */
6535     gcc_unreachable ();
6536   else if (! OVERLOAD_TYPE_P (arg1_type)
6537 	   && (! arg2 || ! OVERLOAD_TYPE_P (arg2_type)))
6538     goto builtin;
6539 
6540   if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
6541     {
6542       arg2 = integer_zero_node;
6543       arg2_type = integer_type_node;
6544     }
6545 
6546   vec_alloc (arglist, 3);
6547   arglist->quick_push (arg1);
6548   if (arg2 != NULL_TREE)
6549     arglist->quick_push (arg2);
6550   if (arg3 != NULL_TREE)
6551     arglist->quick_push (arg3);
6552 
6553   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
6554   p = conversion_obstack_alloc (0);
6555 
6556   result = add_operator_candidates (&candidates, code, code2, arglist,
6557 				    flags, complain);
6558   if (result == error_mark_node)
6559     goto user_defined_result_ready;
6560 
6561   switch (code)
6562     {
6563     case COMPOUND_EXPR:
6564     case ADDR_EXPR:
6565       /* For these, the built-in candidates set is empty
6566 	 [over.match.oper]/3.  We don't want non-strict matches
6567 	 because exact matches are always possible with built-in
6568 	 operators.  The built-in candidate set for COMPONENT_REF
6569 	 would be empty too, but since there are no such built-in
6570 	 operators, we accept non-strict matches for them.  */
6571       strict_p = true;
6572       break;
6573 
6574     default:
6575       strict_p = false;
6576       break;
6577     }
6578 
6579   candidates = splice_viable (candidates, strict_p, &any_viable_p);
6580   if (!any_viable_p)
6581     {
6582       switch (code)
6583 	{
6584 	case POSTINCREMENT_EXPR:
6585 	case POSTDECREMENT_EXPR:
6586 	  /* Don't try anything fancy if we're not allowed to produce
6587 	     errors.  */
6588 	  if (!(complain & tf_error))
6589 	    return error_mark_node;
6590 
6591 	  /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
6592 	     distinguish between prefix and postfix ++ and
6593 	     operator++() was used for both, so we allow this with
6594 	     -fpermissive.  */
6595 	  else
6596 	    {
6597 	      tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
6598 	      const char *msg = (flag_permissive)
6599 		? G_("no %<%D(int)%> declared for postfix %qs,"
6600 		     " trying prefix operator instead")
6601 		: G_("no %<%D(int)%> declared for postfix %qs");
6602 	      permerror (loc, msg, fnname, OVL_OP_INFO (false, code)->name);
6603 	    }
6604 
6605 	  if (!flag_permissive)
6606 	    return error_mark_node;
6607 
6608 	  if (code == POSTINCREMENT_EXPR)
6609 	    code = PREINCREMENT_EXPR;
6610 	  else
6611 	    code = PREDECREMENT_EXPR;
6612 	  result = build_new_op (loc, code, flags, arg1, NULL_TREE,
6613 				 NULL_TREE, overload, complain);
6614 	  break;
6615 
6616 	  /* The caller will deal with these.  */
6617 	case ADDR_EXPR:
6618 	case COMPOUND_EXPR:
6619 	case COMPONENT_REF:
6620 	case CO_AWAIT_EXPR:
6621 	  result = NULL_TREE;
6622 	  result_valid_p = true;
6623 	  break;
6624 
6625 	default:
6626 	  if (complain & tf_error)
6627 	    {
6628 		/* If one of the arguments of the operator represents
6629 		   an invalid use of member function pointer, try to report
6630 		   a meaningful error ...  */
6631 	      if (invalid_nonstatic_memfn_p (loc, arg1, tf_error)
6632 		    || invalid_nonstatic_memfn_p (loc, arg2, tf_error)
6633 		    || invalid_nonstatic_memfn_p (loc, arg3, tf_error))
6634 		  /* We displayed the error message.  */;
6635 		else
6636 		  {
6637 		    /* ... Otherwise, report the more generic
6638 		       "no matching operator found" error */
6639 		    auto_diagnostic_group d;
6640 		    op_error (loc, code, code2, arg1, arg2, arg3, FALSE);
6641 		    print_z_candidates (loc, candidates);
6642 		  }
6643 	    }
6644 	  result = error_mark_node;
6645 	  break;
6646 	}
6647     }
6648   else
6649     {
6650       cand = tourney (candidates, complain);
6651       if (cand == 0)
6652 	{
6653 	  if (complain & tf_error)
6654 	    {
6655 	      auto_diagnostic_group d;
6656 	      op_error (loc, code, code2, arg1, arg2, arg3, TRUE);
6657 	      print_z_candidates (loc, candidates);
6658 	    }
6659 	  result = error_mark_node;
6660 	  if (overload)
6661 	    *overload = error_mark_node;
6662 	}
6663       else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
6664 	{
6665 	  if (overload)
6666 	    *overload = cand->fn;
6667 
6668 	  if (resolve_args (arglist, complain) == NULL)
6669 	    result = error_mark_node;
6670 	  else
6671 	    {
6672 	      tsubst_flags_t ocomplain = complain;
6673 	      if (cand->rewritten ())
6674 		/* We'll wrap this call in another one.  */
6675 		ocomplain &= ~tf_decltype;
6676 	      if (cand->reversed ())
6677 		{
6678 		  /* We swapped these in add_candidate, swap them back now.  */
6679 		  std::swap (cand->convs[0], cand->convs[1]);
6680 		  if (cand->fn == current_function_decl)
6681 		    warning_at (loc, 0, "in C++20 this comparison calls the "
6682 				"current function recursively with reversed "
6683 				"arguments");
6684 		}
6685 	      result = build_over_call (cand, LOOKUP_NORMAL, ocomplain);
6686 	    }
6687 
6688 	  if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
6689 	    /* There won't be a CALL_EXPR.  */;
6690 	  else if (result && result != error_mark_node)
6691 	    {
6692 	      tree call = extract_call_expr (result);
6693 	      CALL_EXPR_OPERATOR_SYNTAX (call) = true;
6694 
6695 	      /* Specify evaluation order as per P0145R2.  */
6696 	      CALL_EXPR_ORDERED_ARGS (call) = false;
6697 	      switch (op_is_ordered (code))
6698 		{
6699 		case -1:
6700 		  CALL_EXPR_REVERSE_ARGS (call) = true;
6701 		  break;
6702 
6703 		case 1:
6704 		  CALL_EXPR_ORDERED_ARGS (call) = true;
6705 		  break;
6706 
6707 		default:
6708 		  break;
6709 		}
6710 	    }
6711 
6712 	  /* If this was a C++20 rewritten comparison, adjust the result.  */
6713 	  if (cand->rewritten ())
6714 	    {
6715 	      /* FIXME build_min_non_dep_op_overload can't handle rewrites.  */
6716 	      if (overload)
6717 		*overload = NULL_TREE;
6718 	      switch (code)
6719 		{
6720 		case EQ_EXPR:
6721 		  gcc_checking_assert (cand->reversed ());
6722 		  gcc_fallthrough ();
6723 		case NE_EXPR:
6724 		  /* If a rewritten operator== candidate is selected by
6725 		     overload resolution for an operator @, its return type
6726 		     shall be cv bool.... */
6727 		  if (TREE_CODE (TREE_TYPE (result)) != BOOLEAN_TYPE)
6728 		    {
6729 		      if (complain & tf_error)
6730 			{
6731 			  auto_diagnostic_group d;
6732 			  error_at (loc, "return type of %qD is not %qs",
6733 				    cand->fn, "bool");
6734 			  inform (loc, "used as rewritten candidate for "
6735 				  "comparison of %qT and %qT",
6736 				  arg1_type, arg2_type);
6737 			}
6738 		      result = error_mark_node;
6739 		    }
6740 		  else if (code == NE_EXPR)
6741 		    /* !(y == x) or !(x == y)  */
6742 		    result = build1_loc (loc, TRUTH_NOT_EXPR,
6743 					 boolean_type_node, result);
6744 		  break;
6745 
6746 		  /* If a rewritten operator<=> candidate is selected by
6747 		     overload resolution for an operator @, x @ y is
6748 		     interpreted as 0 @ (y <=> x) if the selected candidate is
6749 		     a synthesized candidate with reversed order of parameters,
6750 		     or (x <=> y) @ 0 otherwise, using the selected rewritten
6751 		     operator<=> candidate.  */
6752 		case SPACESHIP_EXPR:
6753 		  if (!cand->reversed ())
6754 		    /* We're in the build_new_op call below for an outer
6755 		       reversed call; we don't need to do anything more.  */
6756 		    break;
6757 		  gcc_fallthrough ();
6758 		case LT_EXPR:
6759 		case LE_EXPR:
6760 		case GT_EXPR:
6761 		case GE_EXPR:
6762 		  {
6763 		    tree lhs = result;
6764 		    tree rhs = integer_zero_node;
6765 		    if (cand->reversed ())
6766 		      std::swap (lhs, rhs);
6767 		    warning_sentinel ws (warn_zero_as_null_pointer_constant);
6768 		    result = build_new_op (loc, code,
6769 					   LOOKUP_NORMAL|LOOKUP_REWRITTEN,
6770 					   lhs, rhs, NULL_TREE,
6771 					   NULL, complain);
6772 		  }
6773 		  break;
6774 
6775 		default:
6776 		  gcc_unreachable ();
6777 		}
6778 	    }
6779 	}
6780       else
6781 	{
6782 	  /* Give any warnings we noticed during overload resolution.  */
6783 	  if (cand->warnings && (complain & tf_warning))
6784 	    {
6785 	      struct candidate_warning *w;
6786 	      for (w = cand->warnings; w; w = w->next)
6787 		joust (cand, w->loser, 1, complain);
6788 	    }
6789 
6790 	  /* Check for comparison of different enum types.  */
6791 	  switch (code)
6792 	    {
6793 	    case GT_EXPR:
6794 	    case LT_EXPR:
6795 	    case GE_EXPR:
6796 	    case LE_EXPR:
6797 	    case EQ_EXPR:
6798 	    case NE_EXPR:
6799 	      if (TREE_CODE (arg1_type) == ENUMERAL_TYPE
6800 		  && TREE_CODE (arg2_type) == ENUMERAL_TYPE
6801 		  && (TYPE_MAIN_VARIANT (arg1_type)
6802 		      != TYPE_MAIN_VARIANT (arg2_type))
6803 		  && (complain & tf_warning))
6804 		warning_at (loc, OPT_Wenum_compare,
6805 			    "comparison between %q#T and %q#T",
6806 			    arg1_type, arg2_type);
6807 	      break;
6808 	    default:
6809 	      break;
6810 	    }
6811 
6812 	  /* "If a built-in candidate is selected by overload resolution, the
6813 	     operands of class type are converted to the types of the
6814 	     corresponding parameters of the selected operation function,
6815 	     except that the second standard conversion sequence of a
6816 	     user-defined conversion sequence (12.3.3.1.2) is not applied."  */
6817 	  conv = cand->convs[0];
6818 	  if (conv->user_conv_p)
6819 	    {
6820 	      conv = strip_standard_conversion (conv);
6821 	      arg1 = convert_like (conv, arg1, complain);
6822 	    }
6823 
6824 	  if (arg2)
6825 	    {
6826 	      conv = cand->convs[1];
6827 	      if (conv->user_conv_p)
6828 		{
6829 		  conv = strip_standard_conversion (conv);
6830 		  arg2 = convert_like (conv, arg2, complain);
6831 		}
6832 	    }
6833 
6834 	  if (arg3)
6835 	    {
6836 	      conv = cand->convs[2];
6837 	      if (conv->user_conv_p)
6838 		{
6839 		  conv = strip_standard_conversion (conv);
6840 		  arg3 = convert_like (conv, arg3, complain);
6841 		}
6842 	    }
6843 	}
6844     }
6845 
6846  user_defined_result_ready:
6847 
6848   /* Free all the conversions we allocated.  */
6849   obstack_free (&conversion_obstack, p);
6850 
6851   if (result || result_valid_p)
6852     return result;
6853 
6854  builtin:
6855   switch (code)
6856     {
6857     case MODIFY_EXPR:
6858       return cp_build_modify_expr (loc, arg1, code2, arg2, complain);
6859 
6860     case INDIRECT_REF:
6861       return cp_build_indirect_ref (loc, arg1, RO_UNARY_STAR, complain);
6862 
6863     case TRUTH_ANDIF_EXPR:
6864     case TRUTH_ORIF_EXPR:
6865     case TRUTH_AND_EXPR:
6866     case TRUTH_OR_EXPR:
6867       if (complain & tf_warning)
6868 	warn_logical_operator (loc, code, boolean_type_node,
6869 			       code_orig_arg1, arg1,
6870 			       code_orig_arg2, arg2);
6871       /* Fall through.  */
6872     case GT_EXPR:
6873     case LT_EXPR:
6874     case GE_EXPR:
6875     case LE_EXPR:
6876     case EQ_EXPR:
6877     case NE_EXPR:
6878       if ((complain & tf_warning)
6879 	  && ((code_orig_arg1 == BOOLEAN_TYPE)
6880 	      ^ (code_orig_arg2 == BOOLEAN_TYPE)))
6881 	maybe_warn_bool_compare (loc, code, arg1, arg2);
6882       if (complain & tf_warning && warn_tautological_compare)
6883 	warn_tautological_cmp (loc, code, arg1, arg2);
6884       /* Fall through.  */
6885     case SPACESHIP_EXPR:
6886     case PLUS_EXPR:
6887     case MINUS_EXPR:
6888     case MULT_EXPR:
6889     case TRUNC_DIV_EXPR:
6890     case MAX_EXPR:
6891     case MIN_EXPR:
6892     case LSHIFT_EXPR:
6893     case RSHIFT_EXPR:
6894     case TRUNC_MOD_EXPR:
6895     case BIT_AND_EXPR:
6896     case BIT_IOR_EXPR:
6897     case BIT_XOR_EXPR:
6898       return cp_build_binary_op (loc, code, arg1, arg2, complain);
6899 
6900     case UNARY_PLUS_EXPR:
6901     case NEGATE_EXPR:
6902     case BIT_NOT_EXPR:
6903     case TRUTH_NOT_EXPR:
6904     case PREINCREMENT_EXPR:
6905     case POSTINCREMENT_EXPR:
6906     case PREDECREMENT_EXPR:
6907     case POSTDECREMENT_EXPR:
6908     case REALPART_EXPR:
6909     case IMAGPART_EXPR:
6910     case ABS_EXPR:
6911     case CO_AWAIT_EXPR:
6912       return cp_build_unary_op (code, arg1, false, complain);
6913 
6914     case ARRAY_REF:
6915       return cp_build_array_ref (input_location, arg1, arg2, complain);
6916 
6917     case MEMBER_REF:
6918       return build_m_component_ref (cp_build_indirect_ref (loc, arg1,
6919 							   RO_ARROW_STAR,
6920                                                            complain),
6921                                     arg2, complain);
6922 
6923       /* The caller will deal with these.  */
6924     case ADDR_EXPR:
6925     case COMPONENT_REF:
6926     case COMPOUND_EXPR:
6927       return NULL_TREE;
6928 
6929     default:
6930       gcc_unreachable ();
6931     }
6932   return NULL_TREE;
6933 }
6934 
6935 /* Build a new call to operator[].  This may change ARGS.  */
6936 
6937 tree
build_op_subscript(const op_location_t & loc,tree obj,vec<tree,va_gc> ** args,tree * overload,tsubst_flags_t complain)6938 build_op_subscript (const op_location_t &loc, tree obj,
6939 		    vec<tree, va_gc> **args, tree *overload,
6940 		    tsubst_flags_t complain)
6941 {
6942   struct z_candidate *candidates = 0, *cand;
6943   tree fns, first_mem_arg = NULL_TREE;
6944   bool any_viable_p;
6945   tree result = NULL_TREE;
6946   void *p;
6947 
6948   auto_cond_timevar tv (TV_OVERLOAD);
6949 
6950   obj = mark_lvalue_use (obj);
6951 
6952   if (error_operand_p (obj))
6953     return error_mark_node;
6954 
6955   tree type = TREE_TYPE (obj);
6956 
6957   obj = prep_operand (obj);
6958 
6959   if (TYPE_BINFO (type))
6960     {
6961       fns = lookup_fnfields (TYPE_BINFO (type), ovl_op_identifier (ARRAY_REF),
6962 			     1, complain);
6963       if (fns == error_mark_node)
6964 	return error_mark_node;
6965     }
6966   else
6967     fns = NULL_TREE;
6968 
6969   if (args != NULL && *args != NULL)
6970     {
6971       *args = resolve_args (*args, complain);
6972       if (*args == NULL)
6973 	return error_mark_node;
6974     }
6975 
6976   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
6977   p = conversion_obstack_alloc (0);
6978 
6979   if (fns)
6980     {
6981       first_mem_arg = obj;
6982 
6983       add_candidates (BASELINK_FUNCTIONS (fns),
6984 		      first_mem_arg, *args, NULL_TREE,
6985 		      NULL_TREE, false,
6986 		      BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
6987 		      LOOKUP_NORMAL, &candidates, complain);
6988     }
6989 
6990   /* Be strict here because if we choose a bad conversion candidate, the
6991      errors we get won't mention the call context.  */
6992   candidates = splice_viable (candidates, true, &any_viable_p);
6993   if (!any_viable_p)
6994     {
6995       if (complain & tf_error)
6996 	{
6997 	  auto_diagnostic_group d;
6998 	  error ("no match for call to %<%T::operator[] (%A)%>",
6999 		 TREE_TYPE (obj), build_tree_list_vec (*args));
7000 	  print_z_candidates (loc, candidates);
7001 	}
7002       result = error_mark_node;
7003     }
7004   else
7005     {
7006       cand = tourney (candidates, complain);
7007       if (cand == 0)
7008 	{
7009 	  if (complain & tf_error)
7010 	    {
7011 	      auto_diagnostic_group d;
7012 	      error ("call of %<%T::operator[] (%A)%> is ambiguous",
7013 		     TREE_TYPE (obj), build_tree_list_vec (*args));
7014 	      print_z_candidates (loc, candidates);
7015 	    }
7016 	  result = error_mark_node;
7017 	}
7018       else if (TREE_CODE (cand->fn) == FUNCTION_DECL
7019 	       && DECL_OVERLOADED_OPERATOR_P (cand->fn)
7020 	       && DECL_OVERLOADED_OPERATOR_IS (cand->fn, ARRAY_REF))
7021 	{
7022 	  if (overload)
7023 	    *overload = cand->fn;
7024 	  result = build_over_call (cand, LOOKUP_NORMAL, complain);
7025 	  if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7026 	    /* There won't be a CALL_EXPR.  */;
7027 	  else if (result && result != error_mark_node)
7028 	    {
7029 	      tree call = extract_call_expr (result);
7030 	      CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7031 
7032 	      /* Specify evaluation order as per P0145R2.  */
7033 	      CALL_EXPR_ORDERED_ARGS (call) = op_is_ordered (ARRAY_REF) == 1;
7034 	    }
7035 	}
7036       else
7037 	gcc_unreachable ();
7038     }
7039 
7040   /* Free all the conversions we allocated.  */
7041   obstack_free (&conversion_obstack, p);
7042 
7043   return result;
7044 }
7045 
7046 /* CALL was returned by some call-building function; extract the actual
7047    CALL_EXPR from any bits that have been tacked on, e.g. by
7048    convert_from_reference.  */
7049 
7050 tree
extract_call_expr(tree call)7051 extract_call_expr (tree call)
7052 {
7053   while (TREE_CODE (call) == COMPOUND_EXPR)
7054     call = TREE_OPERAND (call, 1);
7055   if (REFERENCE_REF_P (call))
7056     call = TREE_OPERAND (call, 0);
7057   if (TREE_CODE (call) == TARGET_EXPR)
7058     call = TARGET_EXPR_INITIAL (call);
7059   if (cxx_dialect >= cxx20)
7060     switch (TREE_CODE (call))
7061       {
7062 	/* C++20 rewritten comparison operators.  */
7063       case TRUTH_NOT_EXPR:
7064 	call = TREE_OPERAND (call, 0);
7065 	break;
7066       case LT_EXPR:
7067       case LE_EXPR:
7068       case GT_EXPR:
7069       case GE_EXPR:
7070       case SPACESHIP_EXPR:
7071 	{
7072 	  tree op0 = TREE_OPERAND (call, 0);
7073 	  if (integer_zerop (op0))
7074 	    call = TREE_OPERAND (call, 1);
7075 	  else
7076 	    call = op0;
7077 	}
7078 	break;
7079       default:;
7080       }
7081 
7082   gcc_assert (TREE_CODE (call) == CALL_EXPR
7083 	      || TREE_CODE (call) == AGGR_INIT_EXPR
7084 	      || call == error_mark_node);
7085   return call;
7086 }
7087 
7088 /* Returns true if FN has two parameters, of which the second has type
7089    size_t.  */
7090 
7091 static bool
second_parm_is_size_t(tree fn)7092 second_parm_is_size_t (tree fn)
7093 {
7094   tree t = FUNCTION_ARG_CHAIN (fn);
7095   if (!t || !same_type_p (TREE_VALUE (t), size_type_node))
7096     return false;
7097   t = TREE_CHAIN (t);
7098   if (t == void_list_node)
7099     return true;
7100   return false;
7101 }
7102 
7103 /* True if T, an allocation function, has std::align_val_t as its second
7104    argument.  */
7105 
7106 bool
aligned_allocation_fn_p(tree t)7107 aligned_allocation_fn_p (tree t)
7108 {
7109   if (!aligned_new_threshold)
7110     return false;
7111 
7112   tree a = FUNCTION_ARG_CHAIN (t);
7113   return (a && same_type_p (TREE_VALUE (a), align_type_node));
7114 }
7115 
7116 /* True if T is std::destroying_delete_t.  */
7117 
7118 static bool
std_destroying_delete_t_p(tree t)7119 std_destroying_delete_t_p (tree t)
7120 {
7121   return (TYPE_CONTEXT (t) == std_node
7122 	  && id_equal (TYPE_IDENTIFIER (t), "destroying_delete_t"));
7123 }
7124 
7125 /* A deallocation function with at least two parameters whose second parameter
7126    type is of type std::destroying_delete_t is a destroying operator delete. A
7127    destroying operator delete shall be a class member function named operator
7128    delete. [ Note: Array deletion cannot use a destroying operator
7129    delete. --end note ] */
7130 
7131 tree
destroying_delete_p(tree t)7132 destroying_delete_p (tree t)
7133 {
7134   tree a = TYPE_ARG_TYPES (TREE_TYPE (t));
7135   if (!a || !TREE_CHAIN (a))
7136     return NULL_TREE;
7137   tree type = TREE_VALUE (TREE_CHAIN (a));
7138   return std_destroying_delete_t_p (type) ? type : NULL_TREE;
7139 }
7140 
7141 struct dealloc_info
7142 {
7143   bool sized;
7144   bool aligned;
7145   tree destroying;
7146 };
7147 
7148 /* Returns true iff T, an element of an OVERLOAD chain, is a usual deallocation
7149    function (3.7.4.2 [basic.stc.dynamic.deallocation]).  If so, and DI is
7150    non-null, also set *DI. */
7151 
7152 static bool
usual_deallocation_fn_p(tree t,dealloc_info * di)7153 usual_deallocation_fn_p (tree t, dealloc_info *di)
7154 {
7155   if (di) *di = dealloc_info();
7156 
7157   /* A template instance is never a usual deallocation function,
7158      regardless of its signature.  */
7159   if (TREE_CODE (t) == TEMPLATE_DECL
7160       || primary_template_specialization_p (t))
7161     return false;
7162 
7163   /* A usual deallocation function is a deallocation function whose parameters
7164      after the first are
7165      - optionally, a parameter of type std::destroying_delete_t, then
7166      - optionally, a parameter of type std::size_t, then
7167      - optionally, a parameter of type std::align_val_t.  */
7168   bool global = DECL_NAMESPACE_SCOPE_P (t);
7169   tree chain = FUNCTION_ARG_CHAIN (t);
7170   if (chain && destroying_delete_p (t))
7171     {
7172       if (di) di->destroying = TREE_VALUE (chain);
7173       chain = TREE_CHAIN (chain);
7174     }
7175   if (chain
7176       && (!global || flag_sized_deallocation)
7177       && same_type_p (TREE_VALUE (chain), size_type_node))
7178     {
7179       if (di) di->sized = true;
7180       chain = TREE_CHAIN (chain);
7181     }
7182   if (chain && aligned_new_threshold
7183       && same_type_p (TREE_VALUE (chain), align_type_node))
7184     {
7185       if (di) di->aligned = true;
7186       chain = TREE_CHAIN (chain);
7187     }
7188   return (chain == void_list_node);
7189 }
7190 
7191 /* Just return whether FN is a usual deallocation function.  */
7192 
7193 bool
usual_deallocation_fn_p(tree fn)7194 usual_deallocation_fn_p (tree fn)
7195 {
7196   return usual_deallocation_fn_p (fn, NULL);
7197 }
7198 
7199 /* Build a call to operator delete.  This has to be handled very specially,
7200    because the restrictions on what signatures match are different from all
7201    other call instances.  For a normal delete, only a delete taking (void *)
7202    or (void *, size_t) is accepted.  For a placement delete, only an exact
7203    match with the placement new is accepted.
7204 
7205    CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
7206    ADDR is the pointer to be deleted.
7207    SIZE is the size of the memory block to be deleted.
7208    GLOBAL_P is true if the delete-expression should not consider
7209    class-specific delete operators.
7210    PLACEMENT is the corresponding placement new call, or NULL_TREE.
7211 
7212    If this call to "operator delete" is being generated as part to
7213    deallocate memory allocated via a new-expression (as per [expr.new]
7214    which requires that if the initialization throws an exception then
7215    we call a deallocation function), then ALLOC_FN is the allocation
7216    function.  */
7217 
7218 tree
build_op_delete_call(enum tree_code code,tree addr,tree size,bool global_p,tree placement,tree alloc_fn,tsubst_flags_t complain)7219 build_op_delete_call (enum tree_code code, tree addr, tree size,
7220 		      bool global_p, tree placement,
7221 		      tree alloc_fn, tsubst_flags_t complain)
7222 {
7223   tree fn = NULL_TREE;
7224   tree fns, fnname, type, t;
7225   dealloc_info di_fn = { };
7226 
7227   if (addr == error_mark_node)
7228     return error_mark_node;
7229 
7230   type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
7231 
7232   fnname = ovl_op_identifier (false, code);
7233 
7234   if (CLASS_TYPE_P (type)
7235       && COMPLETE_TYPE_P (complete_type (type))
7236       && !global_p)
7237     /* In [class.free]
7238 
7239        If the result of the lookup is ambiguous or inaccessible, or if
7240        the lookup selects a placement deallocation function, the
7241        program is ill-formed.
7242 
7243        Therefore, we ask lookup_fnfields to complain about ambiguity.  */
7244     {
7245       fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1, complain);
7246       if (fns == error_mark_node)
7247 	return error_mark_node;
7248     }
7249   else
7250     fns = NULL_TREE;
7251 
7252   if (fns == NULL_TREE)
7253     fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
7254 
7255   /* Strip const and volatile from addr.  */
7256   tree oaddr = addr;
7257   addr = cp_convert (ptr_type_node, addr, complain);
7258 
7259   if (placement)
7260     {
7261       /* "A declaration of a placement deallocation function matches the
7262 	 declaration of a placement allocation function if it has the same
7263 	 number of parameters and, after parameter transformations (8.3.5),
7264 	 all parameter types except the first are identical."
7265 
7266 	 So we build up the function type we want and ask instantiate_type
7267 	 to get it for us.  */
7268       t = FUNCTION_ARG_CHAIN (alloc_fn);
7269       t = tree_cons (NULL_TREE, ptr_type_node, t);
7270       t = build_function_type (void_type_node, t);
7271 
7272       fn = instantiate_type (t, fns, tf_none);
7273       if (fn == error_mark_node)
7274 	return NULL_TREE;
7275 
7276       fn = MAYBE_BASELINK_FUNCTIONS (fn);
7277 
7278       /* "If the lookup finds the two-parameter form of a usual deallocation
7279 	 function (3.7.4.2) and that function, considered as a placement
7280 	 deallocation function, would have been selected as a match for the
7281 	 allocation function, the program is ill-formed."  */
7282       if (second_parm_is_size_t (fn))
7283 	{
7284 	  const char *const msg1
7285 	    = G_("exception cleanup for this placement new selects "
7286 		 "non-placement %<operator delete%>");
7287 	  const char *const msg2
7288 	    = G_("%qD is a usual (non-placement) deallocation "
7289 		 "function in C++14 (or with %<-fsized-deallocation%>)");
7290 
7291 	  /* But if the class has an operator delete (void *), then that is
7292 	     the usual deallocation function, so we shouldn't complain
7293 	     about using the operator delete (void *, size_t).  */
7294 	  if (DECL_CLASS_SCOPE_P (fn))
7295 	    for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7296 	      {
7297 		if (usual_deallocation_fn_p (elt)
7298 		    && FUNCTION_ARG_CHAIN (elt) == void_list_node)
7299 		  goto ok;
7300 	      }
7301 	  /* Before C++14 a two-parameter global deallocation function is
7302 	     always a placement deallocation function, but warn if
7303 	     -Wc++14-compat.  */
7304 	  else if (!flag_sized_deallocation)
7305 	    {
7306 	      if (complain & tf_warning)
7307 		{
7308 		  auto_diagnostic_group d;
7309 		  if (warning (OPT_Wc__14_compat, msg1))
7310 		    inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7311 		}
7312 	      goto ok;
7313 	    }
7314 
7315 	  if (complain & tf_warning_or_error)
7316 	    {
7317 	      auto_diagnostic_group d;
7318 	      if (permerror (input_location, msg1))
7319 		{
7320 		  /* Only mention C++14 for namespace-scope delete.  */
7321 		  if (DECL_NAMESPACE_SCOPE_P (fn))
7322 		    inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7323 		  else
7324 		    inform (DECL_SOURCE_LOCATION (fn),
7325 			    "%qD is a usual (non-placement) deallocation "
7326 			    "function", fn);
7327 		}
7328 	    }
7329 	  else
7330 	    return error_mark_node;
7331 	ok:;
7332 	}
7333     }
7334   else
7335     /* "Any non-placement deallocation function matches a non-placement
7336        allocation function. If the lookup finds a single matching
7337        deallocation function, that function will be called; otherwise, no
7338        deallocation function will be called."  */
7339     for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7340       {
7341 	dealloc_info di_elt;
7342 	if (usual_deallocation_fn_p (elt, &di_elt))
7343 	  {
7344 	    if (!fn)
7345 	      {
7346 		fn = elt;
7347 		di_fn = di_elt;
7348 		continue;
7349 	      }
7350 
7351 	    /* -- If any of the deallocation functions is a destroying
7352 	       operator delete, all deallocation functions that are not
7353 	       destroying operator deletes are eliminated from further
7354 	       consideration.  */
7355 	    if (di_elt.destroying != di_fn.destroying)
7356 	      {
7357 		if (di_elt.destroying)
7358 		  {
7359 		    fn = elt;
7360 		    di_fn = di_elt;
7361 		  }
7362 		continue;
7363 	      }
7364 
7365 	    /* -- If the type has new-extended alignment, a function with a
7366 	       parameter of type std::align_val_t is preferred; otherwise a
7367 	       function without such a parameter is preferred. If exactly one
7368 	       preferred function is found, that function is selected and the
7369 	       selection process terminates. If more than one preferred
7370 	       function is found, all non-preferred functions are eliminated
7371 	       from further consideration.  */
7372 	    if (aligned_new_threshold)
7373 	      {
7374 		bool want_align = type_has_new_extended_alignment (type);
7375 		if (di_elt.aligned != di_fn.aligned)
7376 		  {
7377 		    if (want_align == di_elt.aligned)
7378 		      {
7379 			fn = elt;
7380 			di_fn = di_elt;
7381 		      }
7382 		    continue;
7383 		  }
7384 	      }
7385 
7386 	    /* -- If the deallocation functions have class scope, the one
7387 	       without a parameter of type std::size_t is selected.  */
7388 	    bool want_size;
7389 	    if (DECL_CLASS_SCOPE_P (fn))
7390 	      want_size = false;
7391 
7392 	    /* -- If the type is complete and if, for the second alternative
7393 	       (delete array) only, the operand is a pointer to a class type
7394 	       with a non-trivial destructor or a (possibly multi-dimensional)
7395 	       array thereof, the function with a parameter of type std::size_t
7396 	       is selected.
7397 
7398 	       -- Otherwise, it is unspecified whether a deallocation function
7399 	       with a parameter of type std::size_t is selected.  */
7400 	    else
7401 	      {
7402 		want_size = COMPLETE_TYPE_P (type);
7403 		if (code == VEC_DELETE_EXPR
7404 		    && !TYPE_VEC_NEW_USES_COOKIE (type))
7405 		  /* We need a cookie to determine the array size.  */
7406 		  want_size = false;
7407 	      }
7408 	    gcc_assert (di_fn.sized != di_elt.sized);
7409 	    if (want_size == di_elt.sized)
7410 	      {
7411 		fn = elt;
7412 		di_fn = di_elt;
7413 	      }
7414 	  }
7415       }
7416 
7417   /* If we have a matching function, call it.  */
7418   if (fn)
7419     {
7420       gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
7421 
7422       /* If the FN is a member function, make sure that it is
7423 	 accessible.  */
7424       if (BASELINK_P (fns))
7425 	perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn,
7426 				       complain);
7427 
7428       /* Core issue 901: It's ok to new a type with deleted delete.  */
7429       if (DECL_DELETED_FN (fn) && alloc_fn)
7430 	return NULL_TREE;
7431 
7432       tree ret;
7433       if (placement)
7434 	{
7435 	  /* The placement args might not be suitable for overload
7436 	     resolution at this point, so build the call directly.  */
7437 	  int nargs = call_expr_nargs (placement);
7438 	  tree *argarray = XALLOCAVEC (tree, nargs);
7439 	  int i;
7440 	  argarray[0] = addr;
7441 	  for (i = 1; i < nargs; i++)
7442 	    argarray[i] = CALL_EXPR_ARG (placement, i);
7443 	  if (!mark_used (fn, complain) && !(complain & tf_error))
7444 	    return error_mark_node;
7445 	  ret = build_cxx_call (fn, nargs, argarray, complain);
7446 	}
7447       else
7448 	{
7449 	  tree destroying = di_fn.destroying;
7450 	  if (destroying)
7451 	    {
7452 	      /* Strip const and volatile from addr but retain the type of the
7453 		 object.  */
7454 	      tree rtype = TREE_TYPE (TREE_TYPE (oaddr));
7455 	      rtype = cv_unqualified (rtype);
7456 	      rtype = TYPE_POINTER_TO (rtype);
7457 	      addr = cp_convert (rtype, oaddr, complain);
7458 	      destroying = build_functional_cast (input_location,
7459 						  destroying, NULL_TREE,
7460 						  complain);
7461 	    }
7462 
7463 	  releasing_vec args;
7464 	  args->quick_push (addr);
7465 	  if (destroying)
7466 	    args->quick_push (destroying);
7467 	  if (di_fn.sized)
7468 	    args->quick_push (size);
7469 	  if (di_fn.aligned)
7470 	    {
7471 	      tree al = build_int_cst (align_type_node, TYPE_ALIGN_UNIT (type));
7472 	      args->quick_push (al);
7473 	    }
7474 	  ret = cp_build_function_call_vec (fn, &args, complain);
7475 	}
7476 
7477       /* Set this flag for all callers of this function.  In addition to
7478 	 delete-expressions, this is called for deallocating coroutine state;
7479 	 treat that as an implicit delete-expression.  This is also called for
7480 	 the delete if the constructor throws in a new-expression, and for a
7481 	 deleting destructor (which implements a delete-expression).  */
7482       /* But leave this flag off for destroying delete to avoid wrong
7483 	 assumptions in the optimizers.  */
7484       tree call = extract_call_expr (ret);
7485       if (TREE_CODE (call) == CALL_EXPR && !destroying_delete_p (fn))
7486 	CALL_FROM_NEW_OR_DELETE_P (call) = 1;
7487 
7488       return ret;
7489     }
7490 
7491   /* [expr.new]
7492 
7493      If no unambiguous matching deallocation function can be found,
7494      propagating the exception does not cause the object's memory to
7495      be freed.  */
7496   if (alloc_fn)
7497     {
7498       if ((complain & tf_warning)
7499 	  && !placement)
7500 	warning (0, "no corresponding deallocation function for %qD",
7501 		 alloc_fn);
7502       return NULL_TREE;
7503     }
7504 
7505   if (complain & tf_error)
7506     error ("no suitable %<operator %s%> for %qT",
7507 	   OVL_OP_INFO (false, code)->name, type);
7508   return error_mark_node;
7509 }
7510 
7511 /* Issue diagnostics about a disallowed access of DECL, using DIAG_DECL
7512    in the diagnostics.
7513 
7514    If ISSUE_ERROR is true, then issue an error about the access, followed
7515    by a note showing the declaration.  Otherwise, just show the note.
7516 
7517    DIAG_DECL and DIAG_LOCATION will almost always be the same.
7518    DIAG_LOCATION is just another DECL.  NO_ACCESS_REASON is an optional
7519    parameter used to specify why DECL wasn't accessible (e.g. ak_private
7520    would be because DECL was private).  If not using NO_ACCESS_REASON,
7521    then it must be ak_none, and the access failure reason will be
7522    figured out by looking at the protection of DECL.  */
7523 
7524 void
complain_about_access(tree decl,tree diag_decl,tree diag_location,bool issue_error,access_kind no_access_reason)7525 complain_about_access (tree decl, tree diag_decl, tree diag_location,
7526 		       bool issue_error, access_kind no_access_reason)
7527 {
7528   /* If we have not already figured out why DECL is inaccessible...  */
7529   if (no_access_reason == ak_none)
7530     {
7531       /* Examine the access of DECL to find out why.  */
7532       if (TREE_PRIVATE (decl))
7533 	no_access_reason = ak_private;
7534       else if (TREE_PROTECTED (decl))
7535 	no_access_reason = ak_protected;
7536     }
7537 
7538   /* Now generate an error message depending on calculated access.  */
7539   if (no_access_reason == ak_private)
7540     {
7541       if (issue_error)
7542 	error ("%q#D is private within this context", diag_decl);
7543       inform (DECL_SOURCE_LOCATION (diag_location), "declared private here");
7544     }
7545   else if (no_access_reason == ak_protected)
7546     {
7547       if (issue_error)
7548 	error ("%q#D is protected within this context", diag_decl);
7549       inform (DECL_SOURCE_LOCATION (diag_location), "declared protected here");
7550     }
7551   /* Couldn't figure out why DECL is inaccesible, so just say it's
7552      inaccessible.  */
7553   else
7554     {
7555       if (issue_error)
7556 	error ("%q#D is inaccessible within this context", diag_decl);
7557       inform (DECL_SOURCE_LOCATION (diag_decl), "declared here");
7558     }
7559 }
7560 
7561 /* Initialize a temporary of type TYPE with EXPR.  The FLAGS are a
7562    bitwise or of LOOKUP_* values.  If any errors are warnings are
7563    generated, set *DIAGNOSTIC_FN to "error" or "warning",
7564    respectively.  If no diagnostics are generated, set *DIAGNOSTIC_FN
7565    to NULL.  */
7566 
7567 static tree
build_temp(tree expr,tree type,int flags,diagnostic_t * diagnostic_kind,tsubst_flags_t complain)7568 build_temp (tree expr, tree type, int flags,
7569 	    diagnostic_t *diagnostic_kind, tsubst_flags_t complain)
7570 {
7571   int savew, savee;
7572 
7573   *diagnostic_kind = DK_UNSPECIFIED;
7574 
7575   /* If the source is a packed field, calling the copy constructor will require
7576      binding the field to the reference parameter to the copy constructor, and
7577      we'll end up with an infinite loop.  If we can use a bitwise copy, then
7578      do that now.  */
7579   if ((lvalue_kind (expr) & clk_packed)
7580       && CLASS_TYPE_P (TREE_TYPE (expr))
7581       && !type_has_nontrivial_copy_init (TREE_TYPE (expr)))
7582     return get_target_expr_sfinae (expr, complain);
7583 
7584   /* In decltype, we might have decided not to wrap this call in a TARGET_EXPR.
7585      But it turns out to be a subexpression, so perform temporary
7586      materialization now.  */
7587   if (TREE_CODE (expr) == CALL_EXPR
7588       && CLASS_TYPE_P (type)
7589       && same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7590     expr = build_cplus_new (type, expr, complain);
7591 
7592   savew = warningcount + werrorcount, savee = errorcount;
7593   releasing_vec args (make_tree_vector_single (expr));
7594   expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
7595 				    &args, type, flags, complain);
7596   if (warningcount + werrorcount > savew)
7597     *diagnostic_kind = DK_WARNING;
7598   else if (errorcount > savee)
7599     *diagnostic_kind = DK_ERROR;
7600   return expr;
7601 }
7602 
7603 /* Get any location for EXPR, falling back to input_location.
7604 
7605    If the result is in a system header and is the virtual location for
7606    a token coming from the expansion of a macro, unwind it to the
7607    location of the expansion point of the macro (e.g. to avoid the
7608    diagnostic being suppressed for expansions of NULL where "NULL" is
7609    in a system header).  */
7610 
7611 static location_t
get_location_for_expr_unwinding_for_system_header(tree expr)7612 get_location_for_expr_unwinding_for_system_header (tree expr)
7613 {
7614   location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
7615   loc = expansion_point_location_if_in_system_header (loc);
7616   return loc;
7617 }
7618 
7619 /* Perform warnings about peculiar, but valid, conversions from/to NULL.
7620    Also handle a subset of zero as null warnings.
7621    EXPR is implicitly converted to type TOTYPE.
7622    FN and ARGNUM are used for diagnostics.  */
7623 
7624 static void
conversion_null_warnings(tree totype,tree expr,tree fn,int argnum)7625 conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
7626 {
7627   /* Issue warnings about peculiar, but valid, uses of NULL.  */
7628   if (TREE_CODE (totype) != BOOLEAN_TYPE
7629       && ARITHMETIC_TYPE_P (totype)
7630       && null_node_p (expr))
7631     {
7632       location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
7633       if (fn)
7634 	{
7635 	  auto_diagnostic_group d;
7636 	  if (warning_at (loc, OPT_Wconversion_null,
7637 			  "passing NULL to non-pointer argument %P of %qD",
7638 			  argnum, fn))
7639 	    inform (get_fndecl_argument_location (fn, argnum),
7640 		    "  declared here");
7641 	}
7642       else
7643 	warning_at (loc, OPT_Wconversion_null,
7644 		    "converting to non-pointer type %qT from NULL", totype);
7645     }
7646 
7647   /* Issue warnings if "false" is converted to a NULL pointer */
7648   else if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
7649 	   && TYPE_PTR_P (totype))
7650     {
7651       location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
7652       if (fn)
7653 	{
7654 	  auto_diagnostic_group d;
7655 	  if (warning_at (loc, OPT_Wconversion_null,
7656 			  "converting %<false%> to pointer type for argument "
7657 			  "%P of %qD", argnum, fn))
7658 	    inform (get_fndecl_argument_location (fn, argnum),
7659 		    "  declared here");
7660 	}
7661       else
7662 	warning_at (loc, OPT_Wconversion_null,
7663 		    "converting %<false%> to pointer type %qT", totype);
7664     }
7665   /* Handle zero as null pointer warnings for cases other
7666      than EQ_EXPR and NE_EXPR */
7667   else if ((TYPE_PTR_OR_PTRMEM_P (totype) || NULLPTR_TYPE_P (totype))
7668 	   && null_ptr_cst_p (expr))
7669     {
7670       location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
7671       maybe_warn_zero_as_null_pointer_constant (expr, loc);
7672     }
7673 }
7674 
7675 /* We gave a diagnostic during a conversion.  If this was in the second
7676    standard conversion sequence of a user-defined conversion sequence, say
7677    which user-defined conversion.  */
7678 
7679 static void
maybe_print_user_conv_context(conversion * convs)7680 maybe_print_user_conv_context (conversion *convs)
7681 {
7682   if (convs->user_conv_p)
7683     for (conversion *t = convs; t; t = next_conversion (t))
7684       if (t->kind == ck_user)
7685 	{
7686 	  print_z_candidate (0, N_("  after user-defined conversion:"),
7687 			     t->cand);
7688 	  break;
7689 	}
7690 }
7691 
7692 /* Locate the parameter with the given index within FNDECL.
7693    ARGNUM is zero based, -1 indicates the `this' argument of a method.
7694    Return the location of the FNDECL itself if there are problems.  */
7695 
7696 location_t
get_fndecl_argument_location(tree fndecl,int argnum)7697 get_fndecl_argument_location (tree fndecl, int argnum)
7698 {
7699   /* The locations of implicitly-declared functions are likely to be
7700      more meaningful than those of their parameters.  */
7701   if (DECL_ARTIFICIAL (fndecl))
7702     return DECL_SOURCE_LOCATION (fndecl);
7703 
7704   int i;
7705   tree param;
7706 
7707   /* Locate param by index within DECL_ARGUMENTS (fndecl).  */
7708   for (i = 0, param = FUNCTION_FIRST_USER_PARM (fndecl);
7709        i < argnum && param;
7710        i++, param = TREE_CHAIN (param))
7711     ;
7712 
7713   /* If something went wrong (e.g. if we have a builtin and thus no arguments),
7714      return the location of FNDECL.  */
7715   if (param == NULL)
7716     return DECL_SOURCE_LOCATION (fndecl);
7717 
7718   return DECL_SOURCE_LOCATION (param);
7719 }
7720 
7721 /* If FNDECL is non-NULL, issue a note highlighting ARGNUM
7722    within its declaration (or the fndecl itself if something went
7723    wrong).  */
7724 
7725 void
maybe_inform_about_fndecl_for_bogus_argument_init(tree fn,int argnum)7726 maybe_inform_about_fndecl_for_bogus_argument_init (tree fn, int argnum)
7727 {
7728   if (fn)
7729     inform (get_fndecl_argument_location (fn, argnum),
7730 	    "  initializing argument %P of %qD", argnum, fn);
7731 }
7732 
7733 /* Maybe warn about C++20 Conversions to arrays of unknown bound.  C is
7734    the conversion, EXPR is the expression we're converting.  */
7735 
7736 static void
maybe_warn_array_conv(location_t loc,conversion * c,tree expr)7737 maybe_warn_array_conv (location_t loc, conversion *c, tree expr)
7738 {
7739   if (cxx_dialect >= cxx20)
7740     return;
7741 
7742   tree type = TREE_TYPE (expr);
7743   type = strip_pointer_operator (type);
7744 
7745   if (TREE_CODE (type) != ARRAY_TYPE
7746       || TYPE_DOMAIN (type) == NULL_TREE)
7747     return;
7748 
7749   if (pedantic && conv_binds_to_array_of_unknown_bound (c))
7750     pedwarn (loc, OPT_Wc__20_extensions,
7751 	     "conversions to arrays of unknown bound "
7752 	     "are only available with %<-std=c++20%> or %<-std=gnu++20%>");
7753 }
7754 
7755 /* We call this recursively in convert_like_internal.  */
7756 static tree convert_like (conversion *, tree, tree, int, bool, bool,
7757 			  tsubst_flags_t);
7758 
7759 /* Perform the conversions in CONVS on the expression EXPR.  FN and
7760    ARGNUM are used for diagnostics.  ARGNUM is zero based, -1
7761    indicates the `this' argument of a method.  INNER is nonzero when
7762    being called to continue a conversion chain. It is negative when a
7763    reference binding will be applied, positive otherwise.  If
7764    ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
7765    conversions will be emitted if appropriate.  If C_CAST_P is true,
7766    this conversion is coming from a C-style cast; in that case,
7767    conversions to inaccessible bases are permitted.  */
7768 
7769 static tree
convert_like_internal(conversion * convs,tree expr,tree fn,int argnum,bool issue_conversion_warnings,bool c_cast_p,tsubst_flags_t complain)7770 convert_like_internal (conversion *convs, tree expr, tree fn, int argnum,
7771 		       bool issue_conversion_warnings, bool c_cast_p,
7772 		       tsubst_flags_t complain)
7773 {
7774   tree totype = convs->type;
7775   diagnostic_t diag_kind;
7776   int flags;
7777   location_t loc = cp_expr_loc_or_input_loc (expr);
7778 
7779   if (convs->bad_p && !(complain & tf_error))
7780     return error_mark_node;
7781 
7782   if (convs->bad_p
7783       && convs->kind != ck_user
7784       && convs->kind != ck_list
7785       && convs->kind != ck_ambig
7786       && (convs->kind != ck_ref_bind
7787 	  || (convs->user_conv_p && next_conversion (convs)->bad_p))
7788       && (convs->kind != ck_rvalue
7789 	  || SCALAR_TYPE_P (totype))
7790       && convs->kind != ck_base)
7791     {
7792       bool complained = false;
7793       conversion *t = convs;
7794 
7795       /* Give a helpful error if this is bad because of excess braces.  */
7796       if (BRACE_ENCLOSED_INITIALIZER_P (expr)
7797 	  && SCALAR_TYPE_P (totype)
7798 	  && CONSTRUCTOR_NELTS (expr) > 0
7799 	  && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
7800 	{
7801 	  complained = permerror (loc, "too many braces around initializer "
7802 				  "for %qT", totype);
7803 	  while (BRACE_ENCLOSED_INITIALIZER_P (expr)
7804 		 && CONSTRUCTOR_NELTS (expr) == 1)
7805 	    expr = CONSTRUCTOR_ELT (expr, 0)->value;
7806 	}
7807 
7808       /* Give a helpful error if this is bad because a conversion to bool
7809 	 from std::nullptr_t requires direct-initialization.  */
7810       if (NULLPTR_TYPE_P (TREE_TYPE (expr))
7811 	  && TREE_CODE (totype) == BOOLEAN_TYPE)
7812 	complained = permerror (loc, "converting to %qH from %qI requires "
7813 				"direct-initialization",
7814 				totype, TREE_TYPE (expr));
7815 
7816       for (; t ; t = next_conversion (t))
7817 	{
7818 	  if (t->kind == ck_user && t->cand->reason)
7819 	    {
7820 	      auto_diagnostic_group d;
7821 	      complained = permerror (loc, "invalid user-defined conversion "
7822 				      "from %qH to %qI", TREE_TYPE (expr),
7823 				      totype);
7824 	      if (complained)
7825 		print_z_candidate (loc, N_("candidate is:"), t->cand);
7826 	      expr = convert_like (t, expr, fn, argnum,
7827 				   /*issue_conversion_warnings=*/false,
7828 				   /*c_cast_p=*/false, complain);
7829 	      if (convs->kind == ck_ref_bind)
7830 		expr = convert_to_reference (totype, expr, CONV_IMPLICIT,
7831 					     LOOKUP_NORMAL, NULL_TREE,
7832 					     complain);
7833 	      else
7834 		expr = cp_convert (totype, expr, complain);
7835 	      if (complained)
7836 		maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
7837 	      return expr;
7838 	    }
7839 	  else if (t->kind == ck_user || !t->bad_p)
7840 	    {
7841 	      expr = convert_like (t, expr, fn, argnum,
7842 				   /*issue_conversion_warnings=*/false,
7843 				   /*c_cast_p=*/false, complain);
7844 	      break;
7845 	    }
7846 	  else if (t->kind == ck_ambig)
7847 	    return convert_like (t, expr, fn, argnum,
7848 				 /*issue_conversion_warnings=*/false,
7849 				 /*c_cast_p=*/false, complain);
7850 	  else if (t->kind == ck_identity)
7851 	    break;
7852 	}
7853       if (!complained && expr != error_mark_node)
7854 	{
7855 	  range_label_for_type_mismatch label (TREE_TYPE (expr), totype);
7856 	  gcc_rich_location richloc (loc, &label);
7857 	  complained = permerror (&richloc,
7858 				  "invalid conversion from %qH to %qI",
7859 				  TREE_TYPE (expr), totype);
7860 	}
7861       if (complained)
7862 	maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
7863 
7864       return cp_convert (totype, expr, complain);
7865     }
7866 
7867   if (issue_conversion_warnings && (complain & tf_warning))
7868     conversion_null_warnings (totype, expr, fn, argnum);
7869 
7870   switch (convs->kind)
7871     {
7872     case ck_user:
7873       {
7874 	struct z_candidate *cand = convs->cand;
7875 
7876 	if (cand == NULL)
7877 	  /* We chose the surrogate function from add_conv_candidate, now we
7878 	     actually need to build the conversion.  */
7879 	  cand = build_user_type_conversion_1 (totype, expr,
7880 					       LOOKUP_NO_CONVERSION, complain);
7881 
7882 	tree convfn = cand->fn;
7883 
7884 	/* When converting from an init list we consider explicit
7885 	   constructors, but actually trying to call one is an error.  */
7886 	if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn)
7887 	    && BRACE_ENCLOSED_INITIALIZER_P (expr)
7888 	    /* Unless this is for direct-list-initialization.  */
7889 	    && (!CONSTRUCTOR_IS_DIRECT_INIT (expr) || convs->need_temporary_p)
7890 	    /* And in C++98 a default constructor can't be explicit.  */
7891 	    && cxx_dialect >= cxx11)
7892 	  {
7893 	    if (!(complain & tf_error))
7894 	      return error_mark_node;
7895 	    location_t loc = location_of (expr);
7896 	    if (CONSTRUCTOR_NELTS (expr) == 0
7897 		&& FUNCTION_FIRST_USER_PARMTYPE (convfn) != void_list_node)
7898 	      {
7899 		auto_diagnostic_group d;
7900 		if (pedwarn (loc, 0, "converting to %qT from initializer list "
7901 			     "would use explicit constructor %qD",
7902 			     totype, convfn))
7903 		  inform (loc, "in C++11 and above a default constructor "
7904 			  "can be explicit");
7905 	      }
7906 	    else
7907 	      error ("converting to %qT from initializer list would use "
7908 		     "explicit constructor %qD", totype, convfn);
7909 	  }
7910 
7911 	/* If we're initializing from {}, it's value-initialization.  */
7912 	if (BRACE_ENCLOSED_INITIALIZER_P (expr)
7913 	    && CONSTRUCTOR_NELTS (expr) == 0
7914 	    && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype)
7915 	    && !processing_template_decl)
7916 	  {
7917 	    bool direct = CONSTRUCTOR_IS_DIRECT_INIT (expr);
7918 	    if (abstract_virtuals_error_sfinae (NULL_TREE, totype, complain))
7919 	      return error_mark_node;
7920 	    expr = build_value_init (totype, complain);
7921 	    expr = get_target_expr_sfinae (expr, complain);
7922 	    if (expr != error_mark_node)
7923 	      {
7924 		TARGET_EXPR_LIST_INIT_P (expr) = true;
7925 		TARGET_EXPR_DIRECT_INIT_P (expr) = direct;
7926 	      }
7927 	    return expr;
7928 	  }
7929 
7930 	/* We don't know here whether EXPR is being used as an lvalue or
7931 	   rvalue, but we know it's read.  */
7932 	mark_exp_read (expr);
7933 
7934 	/* Pass LOOKUP_NO_CONVERSION so rvalue/base handling knows not to allow
7935 	   any more UDCs.  */
7936 	expr = build_over_call (cand, LOOKUP_NORMAL|LOOKUP_NO_CONVERSION,
7937 				complain);
7938 
7939 	/* If this is a constructor or a function returning an aggr type,
7940 	   we need to build up a TARGET_EXPR.  */
7941 	if (DECL_CONSTRUCTOR_P (convfn))
7942 	  {
7943 	    expr = build_cplus_new (totype, expr, complain);
7944 
7945 	    /* Remember that this was list-initialization.  */
7946 	    if (convs->check_narrowing && expr != error_mark_node)
7947 	      TARGET_EXPR_LIST_INIT_P (expr) = true;
7948 	  }
7949 
7950 	return expr;
7951       }
7952     case ck_identity:
7953       if (BRACE_ENCLOSED_INITIALIZER_P (expr))
7954 	{
7955 	  int nelts = CONSTRUCTOR_NELTS (expr);
7956 	  if (nelts == 0)
7957 	    expr = build_value_init (totype, complain);
7958 	  else if (nelts == 1)
7959 	    expr = CONSTRUCTOR_ELT (expr, 0)->value;
7960 	  else
7961 	    gcc_unreachable ();
7962 	}
7963       expr = mark_use (expr, /*rvalue_p=*/!convs->rvaluedness_matches_p,
7964 		       /*read_p=*/true, UNKNOWN_LOCATION,
7965 		       /*reject_builtin=*/true);
7966 
7967       if (type_unknown_p (expr))
7968 	expr = instantiate_type (totype, expr, complain);
7969       if (expr == null_node
7970 	  && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
7971 	/* If __null has been converted to an integer type, we do not want to
7972 	   continue to warn about uses of EXPR as an integer, rather than as a
7973 	   pointer.  */
7974 	expr = build_int_cst (totype, 0);
7975       return expr;
7976     case ck_ambig:
7977       /* We leave bad_p off ck_ambig because overload resolution considers
7978 	 it valid, it just fails when we try to perform it.  So we need to
7979          check complain here, too.  */
7980       if (complain & tf_error)
7981 	{
7982 	  /* Call build_user_type_conversion again for the error.  */
7983 	  int flags = (convs->need_temporary_p
7984 		       ? LOOKUP_IMPLICIT : LOOKUP_NORMAL);
7985 	  build_user_type_conversion (totype, convs->u.expr, flags, complain);
7986 	  gcc_assert (seen_error ());
7987 	  maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
7988 	}
7989       return error_mark_node;
7990 
7991     case ck_list:
7992       {
7993 	/* Conversion to std::initializer_list<T>.  */
7994 	tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
7995 	unsigned len = CONSTRUCTOR_NELTS (expr);
7996 	tree array;
7997 
7998 	if (len)
7999 	  {
8000 	    tree val; unsigned ix;
8001 
8002 	    tree new_ctor = build_constructor (init_list_type_node, NULL);
8003 
8004 	    /* Convert all the elements.  */
8005 	    FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
8006 	      {
8007 		tree sub = convert_like (convs->u.list[ix], val, fn,
8008 					 argnum, false, false, complain);
8009 		if (sub == error_mark_node)
8010 		  return sub;
8011 		if (!BRACE_ENCLOSED_INITIALIZER_P (val)
8012 		    && !check_narrowing (TREE_TYPE (sub), val, complain))
8013 		  return error_mark_node;
8014 		CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor),
8015 					NULL_TREE, sub);
8016 		if (!TREE_CONSTANT (sub))
8017 		  TREE_CONSTANT (new_ctor) = false;
8018 	      }
8019 	    /* Build up the array.  */
8020 	    elttype = cp_build_qualified_type
8021 	      (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
8022 	    array = build_array_of_n_type (elttype, len);
8023 	    array = finish_compound_literal (array, new_ctor, complain);
8024 	    /* Take the address explicitly rather than via decay_conversion
8025 	       to avoid the error about taking the address of a temporary.  */
8026 	    array = cp_build_addr_expr (array, complain);
8027 	  }
8028 	else
8029 	  array = nullptr_node;
8030 
8031 	array = cp_convert (build_pointer_type (elttype), array, complain);
8032 	if (array == error_mark_node)
8033 	  return error_mark_node;
8034 
8035 	/* Build up the initializer_list object.  Note: fail gracefully
8036 	   if the object cannot be completed because, for example, no
8037 	   definition is provided (c++/80956).  */
8038 	totype = complete_type_or_maybe_complain (totype, NULL_TREE, complain);
8039 	if (!totype)
8040 	  return error_mark_node;
8041 	tree field = next_initializable_field (TYPE_FIELDS (totype));
8042 	vec<constructor_elt, va_gc> *vec = NULL;
8043 	CONSTRUCTOR_APPEND_ELT (vec, field, array);
8044 	field = next_initializable_field (DECL_CHAIN (field));
8045 	CONSTRUCTOR_APPEND_ELT (vec, field, size_int (len));
8046 	tree new_ctor = build_constructor (totype, vec);
8047 	return get_target_expr_sfinae (new_ctor, complain);
8048       }
8049 
8050     case ck_aggr:
8051       if (TREE_CODE (totype) == COMPLEX_TYPE)
8052 	{
8053 	  tree real = CONSTRUCTOR_ELT (expr, 0)->value;
8054 	  tree imag = CONSTRUCTOR_ELT (expr, 1)->value;
8055 	  real = perform_implicit_conversion (TREE_TYPE (totype),
8056 					      real, complain);
8057 	  imag = perform_implicit_conversion (TREE_TYPE (totype),
8058 					      imag, complain);
8059 	  expr = build2 (COMPLEX_EXPR, totype, real, imag);
8060 	  return expr;
8061 	}
8062       expr = reshape_init (totype, expr, complain);
8063       expr = get_target_expr_sfinae (digest_init (totype, expr, complain),
8064 				     complain);
8065       if (expr != error_mark_node)
8066 	TARGET_EXPR_LIST_INIT_P (expr) = true;
8067       return expr;
8068 
8069     default:
8070       break;
8071     };
8072 
8073   expr = convert_like (next_conversion (convs), expr, fn, argnum,
8074 		       convs->kind == ck_ref_bind
8075 		       ? issue_conversion_warnings : false,
8076 		       c_cast_p, complain & ~tf_no_cleanup);
8077   if (expr == error_mark_node)
8078     return error_mark_node;
8079 
8080   switch (convs->kind)
8081     {
8082     case ck_rvalue:
8083       expr = decay_conversion (expr, complain);
8084       if (expr == error_mark_node)
8085 	{
8086 	  if (complain & tf_error)
8087 	    {
8088 	      auto_diagnostic_group d;
8089 	      maybe_print_user_conv_context (convs);
8090 	      maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8091 	    }
8092 	  return error_mark_node;
8093 	}
8094 
8095       if (! MAYBE_CLASS_TYPE_P (totype))
8096 	return expr;
8097 
8098       /* Don't introduce copies when passing arguments along to the inherited
8099 	 constructor.  */
8100       if (current_function_decl
8101 	  && flag_new_inheriting_ctors
8102 	  && DECL_INHERITED_CTOR (current_function_decl))
8103 	return expr;
8104 
8105       if (TREE_CODE (expr) == TARGET_EXPR
8106 	  && TARGET_EXPR_LIST_INIT_P (expr))
8107 	/* Copy-list-initialization doesn't actually involve a copy.  */
8108 	return expr;
8109 
8110       /* Fall through.  */
8111     case ck_base:
8112       if (convs->kind == ck_base && !convs->need_temporary_p)
8113 	{
8114 	  /* We are going to bind a reference directly to a base-class
8115 	     subobject of EXPR.  */
8116 	  /* Build an expression for `*((base*) &expr)'.  */
8117 	  expr = convert_to_base (expr, totype,
8118 				  !c_cast_p, /*nonnull=*/true, complain);
8119 	  return expr;
8120 	}
8121 
8122       /* Copy-initialization where the cv-unqualified version of the source
8123 	 type is the same class as, or a derived class of, the class of the
8124 	 destination [is treated as direct-initialization].  [dcl.init] */
8125       flags = LOOKUP_NORMAL;
8126       /* This conversion is being done in the context of a user-defined
8127 	 conversion (i.e. the second step of copy-initialization), so
8128 	 don't allow any more.  */
8129       if (convs->user_conv_p)
8130 	flags |= LOOKUP_NO_CONVERSION;
8131       /* We might be performing a conversion of the argument
8132 	 to the user-defined conversion, i.e., not a conversion of the
8133 	 result of the user-defined conversion.  In which case we skip
8134 	 explicit constructors.  */
8135       if (convs->copy_init_p)
8136 	flags |= LOOKUP_ONLYCONVERTING;
8137       if (convs->rvaluedness_matches_p)
8138 	/* standard_conversion got LOOKUP_PREFER_RVALUE.  */
8139 	flags |= LOOKUP_PREFER_RVALUE;
8140       expr = build_temp (expr, totype, flags, &diag_kind, complain);
8141       if (diag_kind && complain)
8142 	{
8143 	  auto_diagnostic_group d;
8144 	  maybe_print_user_conv_context (convs);
8145 	  maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8146 	}
8147 
8148       return build_cplus_new (totype, expr, complain);
8149 
8150     case ck_ref_bind:
8151       {
8152 	tree ref_type = totype;
8153 
8154 	/* direct_reference_binding might have inserted a ck_qual under
8155 	   this ck_ref_bind for the benefit of conversion sequence ranking.
8156 	   Ignore the conversion; we'll create our own below.  */
8157 	if (next_conversion (convs)->kind == ck_qual
8158 	    && !convs->need_temporary_p)
8159 	  {
8160 	    gcc_assert (same_type_p (TREE_TYPE (expr),
8161 				     next_conversion (convs)->type));
8162 	    /* Strip the cast created by the ck_qual; cp_build_addr_expr
8163 	       below expects an lvalue.  */
8164 	    STRIP_NOPS (expr);
8165 	  }
8166 
8167 	if (convs->bad_p && !next_conversion (convs)->bad_p)
8168 	  {
8169 	    tree extype = TREE_TYPE (expr);
8170 	    auto_diagnostic_group d;
8171 	    if (TYPE_REF_IS_RVALUE (ref_type)
8172 		&& lvalue_p (expr))
8173 	      error_at (loc, "cannot bind rvalue reference of type %qH to "
8174                         "lvalue of type %qI", totype, extype);
8175 	    else if (!TYPE_REF_IS_RVALUE (ref_type) && !lvalue_p (expr)
8176 		     && !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (ref_type)))
8177 	      {
8178 		conversion *next = next_conversion (convs);
8179 		if (next->kind == ck_std)
8180 		  {
8181 		    next = next_conversion (next);
8182 		    error_at (loc, "cannot bind non-const lvalue reference of "
8183 			      "type %qH to a value of type %qI",
8184 			      totype, next->type);
8185 		  }
8186 		else if (!CP_TYPE_CONST_P (TREE_TYPE (ref_type)))
8187 		  error_at (loc, "cannot bind non-const lvalue reference of "
8188 			    "type %qH to an rvalue of type %qI", totype, extype);
8189 		else // extype is volatile
8190 		  error_at (loc, "cannot bind lvalue reference of type "
8191 			    "%qH to an rvalue of type %qI", totype,
8192 			    extype);
8193 	      }
8194 	    else if (!reference_compatible_p (TREE_TYPE (totype), extype))
8195 	      {
8196 		/* If we're converting from T[] to T[N], don't talk
8197 		   about discarding qualifiers.  (Converting from T[N] to
8198 		   T[] is allowed by P0388R4.)  */
8199 		if (TREE_CODE (extype) == ARRAY_TYPE
8200 		    && TYPE_DOMAIN (extype) == NULL_TREE
8201 		    && TREE_CODE (TREE_TYPE (totype)) == ARRAY_TYPE
8202 		    && TYPE_DOMAIN (TREE_TYPE (totype)) != NULL_TREE)
8203 		  error_at (loc, "cannot bind reference of type %qH to %qI "
8204 			    "due to different array bounds", totype, extype);
8205 		else
8206 		  error_at (loc, "binding reference of type %qH to %qI "
8207 			    "discards qualifiers", totype, extype);
8208 	      }
8209 	    else
8210 	      gcc_unreachable ();
8211 	    maybe_print_user_conv_context (convs);
8212 	    maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8213 
8214 	    return error_mark_node;
8215 	  }
8216 	else if (complain & tf_warning)
8217 	  maybe_warn_array_conv (loc, convs, expr);
8218 
8219 	/* If necessary, create a temporary.
8220 
8221            VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
8222            that need temporaries, even when their types are reference
8223            compatible with the type of reference being bound, so the
8224            upcoming call to cp_build_addr_expr doesn't fail.  */
8225 	if (convs->need_temporary_p
8226 	    || TREE_CODE (expr) == CONSTRUCTOR
8227 	    || TREE_CODE (expr) == VA_ARG_EXPR)
8228 	  {
8229 	    /* Otherwise, a temporary of type "cv1 T1" is created and
8230 	       initialized from the initializer expression using the rules
8231 	       for a non-reference copy-initialization (8.5).  */
8232 
8233 	    tree type = TREE_TYPE (ref_type);
8234 	    cp_lvalue_kind lvalue = lvalue_kind (expr);
8235 
8236 	    gcc_assert (similar_type_p (type, next_conversion (convs)->type));
8237 	    if (!CP_TYPE_CONST_NON_VOLATILE_P (type)
8238 		&& !TYPE_REF_IS_RVALUE (ref_type))
8239 	      {
8240 		/* If the reference is volatile or non-const, we
8241 		   cannot create a temporary.  */
8242 		if (complain & tf_error)
8243 		  {
8244 		    if (lvalue & clk_bitfield)
8245 		      error_at (loc, "cannot bind bit-field %qE to %qT",
8246 				expr, ref_type);
8247 		    else if (lvalue & clk_packed)
8248 		      error_at (loc, "cannot bind packed field %qE to %qT",
8249 				expr, ref_type);
8250 		    else
8251 		      error_at (loc, "cannot bind rvalue %qE to %qT",
8252 				expr, ref_type);
8253 		  }
8254 		return error_mark_node;
8255 	      }
8256 	    /* If the source is a packed field, and we must use a copy
8257 	       constructor, then building the target expr will require
8258 	       binding the field to the reference parameter to the
8259 	       copy constructor, and we'll end up with an infinite
8260 	       loop.  If we can use a bitwise copy, then we'll be
8261 	       OK.  */
8262 	    if ((lvalue & clk_packed)
8263 		&& CLASS_TYPE_P (type)
8264 		&& type_has_nontrivial_copy_init (type))
8265 	      {
8266 		error_at (loc, "cannot bind packed field %qE to %qT",
8267 			  expr, ref_type);
8268 		return error_mark_node;
8269 	      }
8270 	    if (lvalue & clk_bitfield)
8271 	      {
8272 		expr = convert_bitfield_to_declared_type (expr);
8273 		expr = fold_convert (type, expr);
8274 	      }
8275 
8276 	    /* Creating &TARGET_EXPR<> in a template would break when
8277 	       tsubsting the expression, so use an IMPLICIT_CONV_EXPR
8278 	       instead.  This can happen even when there's no class
8279 	       involved, e.g., when converting an integer to a reference
8280 	       type.  */
8281 	    if (processing_template_decl)
8282 	      return build1 (IMPLICIT_CONV_EXPR, totype, expr);
8283 	    expr = build_target_expr_with_type (expr, type, complain);
8284 	  }
8285 
8286 	/* Take the address of the thing to which we will bind the
8287 	   reference.  */
8288 	expr = cp_build_addr_expr (expr, complain);
8289 	if (expr == error_mark_node)
8290 	  return error_mark_node;
8291 
8292 	/* Convert it to a pointer to the type referred to by the
8293 	   reference.  This will adjust the pointer if a derived to
8294 	   base conversion is being performed.  */
8295 	expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
8296 			   expr, complain);
8297 	/* Convert the pointer to the desired reference type.  */
8298 	return build_nop (ref_type, expr);
8299       }
8300 
8301     case ck_lvalue:
8302       return decay_conversion (expr, complain);
8303 
8304     case ck_fnptr:
8305       /* ??? Should the address of a transaction-safe pointer point to the TM
8306         clone, and this conversion look up the primary function?  */
8307       return build_nop (totype, expr);
8308 
8309     case ck_qual:
8310       /* Warn about deprecated conversion if appropriate.  */
8311       if (complain & tf_warning)
8312 	{
8313 	  string_conv_p (totype, expr, 1);
8314 	  maybe_warn_array_conv (loc, convs, expr);
8315 	}
8316       break;
8317 
8318     case ck_ptr:
8319       if (convs->base_p)
8320 	expr = convert_to_base (expr, totype, !c_cast_p,
8321 				/*nonnull=*/false, complain);
8322       return build_nop (totype, expr);
8323 
8324     case ck_pmem:
8325       return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
8326 			     c_cast_p, complain);
8327 
8328     default:
8329       break;
8330     }
8331 
8332   if (convs->check_narrowing
8333       && !check_narrowing (totype, expr, complain,
8334 			   convs->check_narrowing_const_only))
8335     return error_mark_node;
8336 
8337   warning_sentinel w (warn_zero_as_null_pointer_constant);
8338   if (issue_conversion_warnings)
8339     expr = cp_convert_and_check (totype, expr, complain);
8340   else
8341     expr = cp_convert (totype, expr, complain);
8342 
8343   return expr;
8344 }
8345 
8346 /* Return true if converting FROM to TO is unsafe in a template.  */
8347 
8348 static bool
conv_unsafe_in_template_p(tree to,tree from)8349 conv_unsafe_in_template_p (tree to, tree from)
8350 {
8351   /* Converting classes involves TARGET_EXPR.  */
8352   if (CLASS_TYPE_P (to) || CLASS_TYPE_P (from))
8353     return true;
8354 
8355   /* Converting real to integer produces FIX_TRUNC_EXPR which tsubst
8356      doesn't handle.  */
8357   if (SCALAR_FLOAT_TYPE_P (from) && INTEGRAL_OR_ENUMERATION_TYPE_P (to))
8358     return true;
8359 
8360   /* Converting integer to real isn't a trivial conversion, either.  */
8361   if (INTEGRAL_OR_ENUMERATION_TYPE_P (from) && SCALAR_FLOAT_TYPE_P (to))
8362     return true;
8363 
8364   return false;
8365 }
8366 
8367 /* Wrapper for convert_like_internal that handles creating
8368    IMPLICIT_CONV_EXPR.  */
8369 
8370 static tree
convert_like(conversion * convs,tree expr,tree fn,int argnum,bool issue_conversion_warnings,bool c_cast_p,tsubst_flags_t complain)8371 convert_like (conversion *convs, tree expr, tree fn, int argnum,
8372 	      bool issue_conversion_warnings, bool c_cast_p,
8373 	      tsubst_flags_t complain)
8374 {
8375   /* Creating &TARGET_EXPR<> in a template breaks when substituting,
8376      and creating a CALL_EXPR in a template breaks in finish_call_expr
8377      so use an IMPLICIT_CONV_EXPR for this conversion.  We would have
8378      created such codes e.g. when calling a user-defined conversion
8379      function.  */
8380   tree conv_expr = NULL_TREE;
8381   if (processing_template_decl
8382       && convs->kind != ck_identity
8383       && conv_unsafe_in_template_p (convs->type, TREE_TYPE (expr)))
8384     {
8385       conv_expr = build1 (IMPLICIT_CONV_EXPR, convs->type, expr);
8386       if (convs->kind != ck_ref_bind)
8387 	conv_expr = convert_from_reference (conv_expr);
8388       if (!convs->bad_p)
8389 	return conv_expr;
8390       /* Do the normal processing to give the bad_p errors.  But we still
8391 	 need to return the IMPLICIT_CONV_EXPR, unless we're returning
8392 	 error_mark_node.  */
8393     }
8394   expr = convert_like_internal (convs, expr, fn, argnum,
8395 				issue_conversion_warnings, c_cast_p, complain);
8396   if (expr == error_mark_node)
8397     return error_mark_node;
8398   return conv_expr ? conv_expr : expr;
8399 }
8400 
8401 /* Convenience wrapper for convert_like.  */
8402 
8403 static inline tree
convert_like(conversion * convs,tree expr,tsubst_flags_t complain)8404 convert_like (conversion *convs, tree expr, tsubst_flags_t complain)
8405 {
8406   return convert_like (convs, expr, NULL_TREE, 0,
8407 		       /*issue_conversion_warnings=*/true,
8408 		       /*c_cast_p=*/false, complain);
8409 }
8410 
8411 /* Convenience wrapper for convert_like.  */
8412 
8413 static inline tree
convert_like_with_context(conversion * convs,tree expr,tree fn,int argnum,tsubst_flags_t complain)8414 convert_like_with_context (conversion *convs, tree expr, tree fn, int argnum,
8415 			   tsubst_flags_t complain)
8416 {
8417   return convert_like (convs, expr, fn, argnum,
8418 		       /*issue_conversion_warnings=*/true,
8419 		       /*c_cast_p=*/false, complain);
8420 }
8421 
8422 /* ARG is being passed to a varargs function.  Perform any conversions
8423    required.  Return the converted value.  */
8424 
8425 tree
convert_arg_to_ellipsis(tree arg,tsubst_flags_t complain)8426 convert_arg_to_ellipsis (tree arg, tsubst_flags_t complain)
8427 {
8428   tree arg_type = TREE_TYPE (arg);
8429   location_t loc = cp_expr_loc_or_input_loc (arg);
8430 
8431   /* [expr.call]
8432 
8433      If the argument has integral or enumeration type that is subject
8434      to the integral promotions (_conv.prom_), or a floating-point
8435      type that is subject to the floating-point promotion
8436      (_conv.fpprom_), the value of the argument is converted to the
8437      promoted type before the call.  */
8438   if (TREE_CODE (arg_type) == REAL_TYPE
8439       && (TYPE_PRECISION (arg_type)
8440 	  < TYPE_PRECISION (double_type_node))
8441       && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (arg_type)))
8442     {
8443       if ((complain & tf_warning)
8444 	  && warn_double_promotion && !c_inhibit_evaluation_warnings)
8445 	warning_at (loc, OPT_Wdouble_promotion,
8446 		    "implicit conversion from %qH to %qI when passing "
8447 		    "argument to function",
8448 		    arg_type, double_type_node);
8449       arg = mark_rvalue_use (arg);
8450       arg = convert_to_real_nofold (double_type_node, arg);
8451     }
8452   else if (NULLPTR_TYPE_P (arg_type))
8453     {
8454       arg = mark_rvalue_use (arg);
8455       if (TREE_SIDE_EFFECTS (arg))
8456 	{
8457 	  warning_sentinel w(warn_unused_result);
8458 	  arg = cp_build_compound_expr (arg, null_pointer_node, complain);
8459 	}
8460       else
8461 	arg = null_pointer_node;
8462     }
8463   else if (INTEGRAL_OR_ENUMERATION_TYPE_P (arg_type))
8464     {
8465       if (SCOPED_ENUM_P (arg_type))
8466 	{
8467 	  tree prom = cp_convert (ENUM_UNDERLYING_TYPE (arg_type), arg,
8468 				  complain);
8469 	  prom = cp_perform_integral_promotions (prom, complain);
8470 	  if (abi_version_crosses (6)
8471 	      && TYPE_MODE (TREE_TYPE (prom)) != TYPE_MODE (arg_type)
8472 	      && (complain & tf_warning))
8473 	    warning_at (loc, OPT_Wabi, "scoped enum %qT passed through %<...%>"
8474 			" as %qT before %<-fabi-version=6%>, %qT after",
8475 			arg_type,
8476 			TREE_TYPE (prom), ENUM_UNDERLYING_TYPE (arg_type));
8477 	  if (!abi_version_at_least (6))
8478 	    arg = prom;
8479 	}
8480       else
8481 	arg = cp_perform_integral_promotions (arg, complain);
8482     }
8483   else
8484     /* [expr.call]
8485 
8486        The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
8487        standard conversions are performed.  */
8488     arg = decay_conversion (arg, complain);
8489 
8490   arg = require_complete_type_sfinae (arg, complain);
8491   arg_type = TREE_TYPE (arg);
8492 
8493   if (arg != error_mark_node
8494       /* In a template (or ill-formed code), we can have an incomplete type
8495 	 even after require_complete_type_sfinae, in which case we don't know
8496 	 whether it has trivial copy or not.  */
8497       && COMPLETE_TYPE_P (arg_type)
8498       && !cp_unevaluated_operand)
8499     {
8500       /* [expr.call] 5.2.2/7:
8501 	 Passing a potentially-evaluated argument of class type (Clause 9)
8502 	 with a non-trivial copy constructor or a non-trivial destructor
8503 	 with no corresponding parameter is conditionally-supported, with
8504 	 implementation-defined semantics.
8505 
8506 	 We support it as pass-by-invisible-reference, just like a normal
8507 	 value parameter.
8508 
8509 	 If the call appears in the context of a sizeof expression,
8510 	 it is not potentially-evaluated.  */
8511       if (type_has_nontrivial_copy_init (arg_type)
8512 	  || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (arg_type))
8513 	{
8514 	  arg = force_rvalue (arg, complain);
8515 	  if (complain & tf_warning)
8516 	    warning (OPT_Wconditionally_supported,
8517 		     "passing objects of non-trivially-copyable "
8518 		     "type %q#T through %<...%> is conditionally supported",
8519 		     arg_type);
8520 	  return build1 (ADDR_EXPR, build_reference_type (arg_type), arg);
8521 	}
8522       /* Build up a real lvalue-to-rvalue conversion in case the
8523 	 copy constructor is trivial but not callable.  */
8524       else if (CLASS_TYPE_P (arg_type))
8525 	force_rvalue (arg, complain);
8526 
8527     }
8528 
8529   return arg;
8530 }
8531 
8532 /* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused.  */
8533 
8534 tree
build_x_va_arg(location_t loc,tree expr,tree type)8535 build_x_va_arg (location_t loc, tree expr, tree type)
8536 {
8537   if (processing_template_decl)
8538     {
8539       tree r = build_min (VA_ARG_EXPR, type, expr);
8540       SET_EXPR_LOCATION (r, loc);
8541       return r;
8542     }
8543 
8544   type = complete_type_or_else (type, NULL_TREE);
8545 
8546   if (expr == error_mark_node || !type)
8547     return error_mark_node;
8548 
8549   expr = mark_lvalue_use (expr);
8550 
8551   if (TYPE_REF_P (type))
8552     {
8553       error ("cannot receive reference type %qT through %<...%>", type);
8554       return error_mark_node;
8555     }
8556 
8557   if (type_has_nontrivial_copy_init (type)
8558       || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
8559     {
8560       /* conditionally-supported behavior [expr.call] 5.2.2/7.  Let's treat
8561 	 it as pass by invisible reference.  */
8562       warning_at (loc, OPT_Wconditionally_supported,
8563 		 "receiving objects of non-trivially-copyable type %q#T "
8564 		 "through %<...%> is conditionally-supported", type);
8565 
8566       tree ref = cp_build_reference_type (type, false);
8567       expr = build_va_arg (loc, expr, ref);
8568       return convert_from_reference (expr);
8569     }
8570 
8571   tree ret = build_va_arg (loc, expr, type);
8572   if (CLASS_TYPE_P (type))
8573     /* Wrap the VA_ARG_EXPR in a TARGET_EXPR now so other code doesn't need to
8574        know how to handle it.  */
8575     ret = get_target_expr (ret);
8576   return ret;
8577 }
8578 
8579 /* TYPE has been given to va_arg.  Apply the default conversions which
8580    would have happened when passed via ellipsis.  Return the promoted
8581    type, or the passed type if there is no change.  */
8582 
8583 tree
cxx_type_promotes_to(tree type)8584 cxx_type_promotes_to (tree type)
8585 {
8586   tree promote;
8587 
8588   /* Perform the array-to-pointer and function-to-pointer
8589      conversions.  */
8590   type = type_decays_to (type);
8591 
8592   promote = type_promotes_to (type);
8593   if (same_type_p (type, promote))
8594     promote = type;
8595 
8596   return promote;
8597 }
8598 
8599 /* ARG is a default argument expression being passed to a parameter of
8600    the indicated TYPE, which is a parameter to FN.  PARMNUM is the
8601    zero-based argument number.  Do any required conversions.  Return
8602    the converted value.  */
8603 
8604 static GTY(()) vec<tree, va_gc> *default_arg_context;
8605 void
push_defarg_context(tree fn)8606 push_defarg_context (tree fn)
8607 { vec_safe_push (default_arg_context, fn); }
8608 
8609 void
pop_defarg_context(void)8610 pop_defarg_context (void)
8611 { default_arg_context->pop (); }
8612 
8613 tree
convert_default_arg(tree type,tree arg,tree fn,int parmnum,tsubst_flags_t complain)8614 convert_default_arg (tree type, tree arg, tree fn, int parmnum,
8615 		     tsubst_flags_t complain)
8616 {
8617   int i;
8618   tree t;
8619 
8620   /* See through clones.  */
8621   fn = DECL_ORIGIN (fn);
8622   /* And inheriting ctors.  */
8623   if (flag_new_inheriting_ctors)
8624     fn = strip_inheriting_ctors (fn);
8625 
8626   /* Detect recursion.  */
8627   FOR_EACH_VEC_SAFE_ELT (default_arg_context, i, t)
8628     if (t == fn)
8629       {
8630 	if (complain & tf_error)
8631 	  error ("recursive evaluation of default argument for %q#D", fn);
8632 	return error_mark_node;
8633       }
8634 
8635   /* If the ARG is an unparsed default argument expression, the
8636      conversion cannot be performed.  */
8637   if (TREE_CODE (arg) == DEFERRED_PARSE)
8638     {
8639       if (complain & tf_error)
8640 	error ("call to %qD uses the default argument for parameter %P, which "
8641 	       "is not yet defined", fn, parmnum);
8642       return error_mark_node;
8643     }
8644 
8645   push_defarg_context (fn);
8646 
8647   if (fn && DECL_TEMPLATE_INFO (fn))
8648     arg = tsubst_default_argument (fn, parmnum, type, arg, complain);
8649 
8650   /* Due to:
8651 
8652        [dcl.fct.default]
8653 
8654        The names in the expression are bound, and the semantic
8655        constraints are checked, at the point where the default
8656        expressions appears.
8657 
8658      we must not perform access checks here.  */
8659   push_deferring_access_checks (dk_no_check);
8660   /* We must make a copy of ARG, in case subsequent processing
8661      alters any part of it.  */
8662   arg = break_out_target_exprs (arg, /*clear location*/true);
8663 
8664   arg = convert_for_initialization (0, type, arg, LOOKUP_IMPLICIT,
8665 				    ICR_DEFAULT_ARGUMENT, fn, parmnum,
8666 				    complain);
8667   arg = convert_for_arg_passing (type, arg, complain);
8668   pop_deferring_access_checks();
8669 
8670   pop_defarg_context ();
8671 
8672   return arg;
8673 }
8674 
8675 /* Returns the type which will really be used for passing an argument of
8676    type TYPE.  */
8677 
8678 tree
type_passed_as(tree type)8679 type_passed_as (tree type)
8680 {
8681   /* Pass classes with copy ctors by invisible reference.  */
8682   if (TREE_ADDRESSABLE (type))
8683     type = build_reference_type (type);
8684   else if (targetm.calls.promote_prototypes (NULL_TREE)
8685 	   && INTEGRAL_TYPE_P (type)
8686 	   && COMPLETE_TYPE_P (type)
8687 	   && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
8688     type = integer_type_node;
8689 
8690   return type;
8691 }
8692 
8693 /* Actually perform the appropriate conversion.  */
8694 
8695 tree
convert_for_arg_passing(tree type,tree val,tsubst_flags_t complain)8696 convert_for_arg_passing (tree type, tree val, tsubst_flags_t complain)
8697 {
8698   tree bitfield_type;
8699 
8700   /* If VAL is a bitfield, then -- since it has already been converted
8701      to TYPE -- it cannot have a precision greater than TYPE.
8702 
8703      If it has a smaller precision, we must widen it here.  For
8704      example, passing "int f:3;" to a function expecting an "int" will
8705      not result in any conversion before this point.
8706 
8707      If the precision is the same we must not risk widening.  For
8708      example, the COMPONENT_REF for a 32-bit "long long" bitfield will
8709      often have type "int", even though the C++ type for the field is
8710      "long long".  If the value is being passed to a function
8711      expecting an "int", then no conversions will be required.  But,
8712      if we call convert_bitfield_to_declared_type, the bitfield will
8713      be converted to "long long".  */
8714   bitfield_type = is_bitfield_expr_with_lowered_type (val);
8715   if (bitfield_type
8716       && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
8717     val = convert_to_integer_nofold (TYPE_MAIN_VARIANT (bitfield_type), val);
8718 
8719   if (val == error_mark_node)
8720     ;
8721   /* Pass classes with copy ctors by invisible reference.  */
8722   else if (TREE_ADDRESSABLE (type))
8723     val = build1 (ADDR_EXPR, build_reference_type (type), val);
8724   else if (targetm.calls.promote_prototypes (NULL_TREE)
8725 	   && INTEGRAL_TYPE_P (type)
8726 	   && COMPLETE_TYPE_P (type)
8727 	   && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
8728     val = cp_perform_integral_promotions (val, complain);
8729   if (complain & tf_warning)
8730     {
8731       if (warn_suggest_attribute_format)
8732 	{
8733 	  tree rhstype = TREE_TYPE (val);
8734 	  const enum tree_code coder = TREE_CODE (rhstype);
8735 	  const enum tree_code codel = TREE_CODE (type);
8736 	  if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
8737 	      && coder == codel
8738 	      && check_missing_format_attribute (type, rhstype))
8739 	    warning (OPT_Wsuggest_attribute_format,
8740 		     "argument of function call might be a candidate "
8741 		     "for a format attribute");
8742 	}
8743       maybe_warn_parm_abi (type, cp_expr_loc_or_input_loc (val));
8744     }
8745 
8746   if (complain & tf_warning)
8747     warn_for_address_or_pointer_of_packed_member (type, val);
8748 
8749   return val;
8750 }
8751 
8752 /* Returns non-zero iff FN is a function with magic varargs, i.e. ones for
8753    which just decay_conversion or no conversions at all should be done.
8754    This is true for some builtins which don't act like normal functions.
8755    Return 2 if no conversions at all should be done, 1 if just
8756    decay_conversion.  Return 3 for special treatment of the 3rd argument
8757    for __builtin_*_overflow_p.  */
8758 
8759 int
magic_varargs_p(tree fn)8760 magic_varargs_p (tree fn)
8761 {
8762   if (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
8763     switch (DECL_FUNCTION_CODE (fn))
8764       {
8765       case BUILT_IN_CLASSIFY_TYPE:
8766       case BUILT_IN_CONSTANT_P:
8767       case BUILT_IN_NEXT_ARG:
8768       case BUILT_IN_VA_START:
8769 	return 1;
8770 
8771       case BUILT_IN_ADD_OVERFLOW_P:
8772       case BUILT_IN_SUB_OVERFLOW_P:
8773       case BUILT_IN_MUL_OVERFLOW_P:
8774 	return 3;
8775 
8776       default:;
8777 	return lookup_attribute ("type generic",
8778 				 TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
8779       }
8780 
8781   return 0;
8782 }
8783 
8784 /* Returns the decl of the dispatcher function if FN is a function version.  */
8785 
8786 tree
get_function_version_dispatcher(tree fn)8787 get_function_version_dispatcher (tree fn)
8788 {
8789   tree dispatcher_decl = NULL;
8790 
8791   if (DECL_LOCAL_DECL_P (fn))
8792     fn = DECL_LOCAL_DECL_ALIAS (fn);
8793 
8794   gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
8795 	      && DECL_FUNCTION_VERSIONED (fn));
8796 
8797   gcc_assert (targetm.get_function_versions_dispatcher);
8798   dispatcher_decl = targetm.get_function_versions_dispatcher (fn);
8799 
8800   if (dispatcher_decl == NULL)
8801     {
8802       error_at (input_location, "use of multiversioned function "
8803 				"without a default");
8804       return NULL;
8805     }
8806 
8807   retrofit_lang_decl (dispatcher_decl);
8808   gcc_assert (dispatcher_decl != NULL);
8809   return dispatcher_decl;
8810 }
8811 
8812 /* fn is a function version dispatcher that is marked used. Mark all the
8813    semantically identical function versions it will dispatch as used.  */
8814 
8815 void
mark_versions_used(tree fn)8816 mark_versions_used (tree fn)
8817 {
8818   struct cgraph_node *node;
8819   struct cgraph_function_version_info *node_v;
8820   struct cgraph_function_version_info *it_v;
8821 
8822   gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
8823 
8824   node = cgraph_node::get (fn);
8825   if (node == NULL)
8826     return;
8827 
8828   gcc_assert (node->dispatcher_function);
8829 
8830   node_v = node->function_version ();
8831   if (node_v == NULL)
8832     return;
8833 
8834   /* All semantically identical versions are chained.  Traverse and mark each
8835      one of them as used.  */
8836   it_v = node_v->next;
8837   while (it_v != NULL)
8838     {
8839       mark_used (it_v->this_node->decl);
8840       it_v = it_v->next;
8841     }
8842 }
8843 
8844 /* Build a call to "the copy constructor" for the type of A, even if it
8845    wouldn't be selected by normal overload resolution.  Used for
8846    diagnostics.  */
8847 
8848 static tree
call_copy_ctor(tree a,tsubst_flags_t complain)8849 call_copy_ctor (tree a, tsubst_flags_t complain)
8850 {
8851   tree ctype = TYPE_MAIN_VARIANT (TREE_TYPE (a));
8852   tree binfo = TYPE_BINFO (ctype);
8853   tree copy = get_copy_ctor (ctype, complain);
8854   copy = build_baselink (binfo, binfo, copy, NULL_TREE);
8855   tree ob = build_dummy_object (ctype);
8856   releasing_vec args (make_tree_vector_single (a));
8857   tree r = build_new_method_call (ob, copy, &args, NULL_TREE,
8858 				  LOOKUP_NORMAL, NULL, complain);
8859   return r;
8860 }
8861 
8862 /* Return the base constructor corresponding to COMPLETE_CTOR or NULL_TREE.  */
8863 
8864 static tree
base_ctor_for(tree complete_ctor)8865 base_ctor_for (tree complete_ctor)
8866 {
8867   tree clone;
8868   FOR_EACH_CLONE (clone, DECL_CLONED_FUNCTION (complete_ctor))
8869     if (DECL_BASE_CONSTRUCTOR_P (clone))
8870       return clone;
8871   return NULL_TREE;
8872 }
8873 
8874 /* Try to make EXP suitable to be used as the initializer for a base subobject,
8875    and return whether we were successful.  EXP must have already been cleared
8876    by unsafe_copy_elision_p{,_opt}.  */
8877 
8878 static bool
make_base_init_ok(tree exp)8879 make_base_init_ok (tree exp)
8880 {
8881   if (TREE_CODE (exp) == TARGET_EXPR)
8882     exp = TARGET_EXPR_INITIAL (exp);
8883   while (TREE_CODE (exp) == COMPOUND_EXPR)
8884     exp = TREE_OPERAND (exp, 1);
8885   if (TREE_CODE (exp) == COND_EXPR)
8886     {
8887       bool ret = make_base_init_ok (TREE_OPERAND (exp, 2));
8888       if (tree op1 = TREE_OPERAND (exp, 1))
8889 	{
8890 	  bool r1 = make_base_init_ok (op1);
8891 	  /* If unsafe_copy_elision_p was false, the arms should match.  */
8892 	  gcc_assert (r1 == ret);
8893 	}
8894       return ret;
8895     }
8896   if (TREE_CODE (exp) != AGGR_INIT_EXPR)
8897     /* A trivial copy is OK.  */
8898     return true;
8899   if (!AGGR_INIT_VIA_CTOR_P (exp))
8900     /* unsafe_copy_elision_p_opt must have said this is OK.  */
8901     return true;
8902   tree fn = cp_get_callee_fndecl_nofold (exp);
8903   if (DECL_BASE_CONSTRUCTOR_P (fn))
8904     return true;
8905   gcc_assert (DECL_COMPLETE_CONSTRUCTOR_P (fn));
8906   fn = base_ctor_for (fn);
8907   if (!fn || DECL_HAS_VTT_PARM_P (fn))
8908     /* The base constructor has more parameters, so we can't just change the
8909        call target.  It would be possible to splice in the appropriate
8910        arguments, but probably not worth the complexity.  */
8911     return false;
8912   AGGR_INIT_EXPR_FN (exp) = build_address (fn);
8913   return true;
8914 }
8915 
8916 /* Return 2 if T refers to a base, 1 if a potentially-overlapping field,
8917    neither of which can be used for return by invisible reference.  We avoid
8918    doing C++17 mandatory copy elision for either of these cases.
8919 
8920    This returns non-zero even if the type of T has no tail padding that other
8921    data could be allocated into, because that depends on the particular ABI.
8922    unsafe_copy_elision_p_opt does consider whether there is padding.  */
8923 
8924 int
unsafe_return_slot_p(tree t)8925 unsafe_return_slot_p (tree t)
8926 {
8927   /* Check empty bases separately, they don't have fields.  */
8928   if (is_empty_base_ref (t))
8929     return 2;
8930 
8931   STRIP_NOPS (t);
8932   if (TREE_CODE (t) == ADDR_EXPR)
8933     t = TREE_OPERAND (t, 0);
8934   if (TREE_CODE (t) == COMPONENT_REF)
8935     t = TREE_OPERAND (t, 1);
8936   if (TREE_CODE (t) != FIELD_DECL)
8937     return false;
8938   if (!CLASS_TYPE_P (TREE_TYPE (t)))
8939     /* The middle-end will do the right thing for scalar types.  */
8940     return false;
8941   if (DECL_FIELD_IS_BASE (t))
8942     return 2;
8943   if (lookup_attribute ("no_unique_address", DECL_ATTRIBUTES (t)))
8944     return 1;
8945   return 0;
8946 }
8947 
8948 /* True IFF EXP is a prvalue that represents return by invisible reference.  */
8949 
8950 static bool
init_by_return_slot_p(tree exp)8951 init_by_return_slot_p (tree exp)
8952 {
8953   /* Copy elision only happens with a TARGET_EXPR.  */
8954   if (TREE_CODE (exp) != TARGET_EXPR)
8955     return false;
8956   tree init = TARGET_EXPR_INITIAL (exp);
8957   /* build_compound_expr pushes COMPOUND_EXPR inside TARGET_EXPR.  */
8958   while (TREE_CODE (init) == COMPOUND_EXPR)
8959     init = TREE_OPERAND (init, 1);
8960   if (TREE_CODE (init) == COND_EXPR)
8961     {
8962       /* We'll end up copying from each of the arms of the COND_EXPR directly
8963 	 into the target, so look at them.  */
8964       if (tree op = TREE_OPERAND (init, 1))
8965 	if (init_by_return_slot_p (op))
8966 	  return true;
8967       return init_by_return_slot_p (TREE_OPERAND (init, 2));
8968     }
8969   return (TREE_CODE (init) == AGGR_INIT_EXPR
8970 	  && !AGGR_INIT_VIA_CTOR_P (init));
8971 }
8972 
8973 /* We can't elide a copy from a function returning by value to a
8974    potentially-overlapping subobject, as the callee might clobber tail padding.
8975    Return true iff this could be that case.
8976 
8977    Places that use this function (or _opt) to decide to elide a copy should
8978    probably use make_safe_copy_elision instead.  */
8979 
8980 static bool
unsafe_copy_elision_p(tree target,tree exp)8981 unsafe_copy_elision_p (tree target, tree exp)
8982 {
8983   return unsafe_return_slot_p (target) && init_by_return_slot_p (exp);
8984 }
8985 
8986 /* As above, but for optimization allow more cases that are actually safe.  */
8987 
8988 static bool
unsafe_copy_elision_p_opt(tree target,tree exp)8989 unsafe_copy_elision_p_opt (tree target, tree exp)
8990 {
8991   tree type = TYPE_MAIN_VARIANT (TREE_TYPE (exp));
8992   /* It's safe to elide the copy for a class with no tail padding.  */
8993   if (!is_empty_class (type)
8994       && tree_int_cst_equal (TYPE_SIZE (type), CLASSTYPE_SIZE (type)))
8995     return false;
8996   return unsafe_copy_elision_p (target, exp);
8997 }
8998 
8999 /* Try to make EXP suitable to be used as the initializer for TARGET,
9000    and return whether we were successful.  */
9001 
9002 bool
make_safe_copy_elision(tree target,tree exp)9003 make_safe_copy_elision (tree target, tree exp)
9004 {
9005   int uns = unsafe_return_slot_p (target);
9006   if (!uns)
9007     return true;
9008   if (init_by_return_slot_p (exp))
9009     return false;
9010   if (uns == 1)
9011     return true;
9012   return make_base_init_ok (exp);
9013 }
9014 
9015 /* True IFF the result of the conversion C is a prvalue.  */
9016 
9017 static bool
conv_is_prvalue(conversion * c)9018 conv_is_prvalue (conversion *c)
9019 {
9020   if (c->kind == ck_rvalue)
9021     return true;
9022   if (c->kind == ck_base && c->need_temporary_p)
9023     return true;
9024   if (c->kind == ck_user && !TYPE_REF_P (c->type))
9025     return true;
9026   if (c->kind == ck_identity && c->u.expr
9027       && TREE_CODE (c->u.expr) == TARGET_EXPR)
9028     return true;
9029 
9030   return false;
9031 }
9032 
9033 /* True iff C is a conversion that binds a reference to a prvalue.  */
9034 
9035 static bool
conv_binds_ref_to_prvalue(conversion * c)9036 conv_binds_ref_to_prvalue (conversion *c)
9037 {
9038   if (c->kind != ck_ref_bind)
9039     return false;
9040   if (c->need_temporary_p)
9041     return true;
9042 
9043   return conv_is_prvalue (next_conversion (c));
9044 }
9045 
9046 /* True iff converting EXPR to a reference type TYPE does not involve
9047    creating a temporary.  */
9048 
9049 bool
ref_conv_binds_directly_p(tree type,tree expr)9050 ref_conv_binds_directly_p (tree type, tree expr)
9051 {
9052   gcc_assert (TYPE_REF_P (type));
9053 
9054   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
9055   void *p = conversion_obstack_alloc (0);
9056 
9057   conversion *conv = implicit_conversion (type, TREE_TYPE (expr), expr,
9058 					  /*c_cast_p=*/false,
9059 					  LOOKUP_IMPLICIT, tf_none);
9060   bool ret = conv && !conv->bad_p && !conv_binds_ref_to_prvalue (conv);
9061 
9062   /* Free all the conversions we allocated.  */
9063   obstack_free (&conversion_obstack, p);
9064 
9065   return ret;
9066 }
9067 
9068 /* Call the trivial destructor for INSTANCE, which can be either an lvalue of
9069    class type or a pointer to class type.  If NO_PTR_DEREF is true and
9070    INSTANCE has pointer type, clobber the pointer rather than what it points
9071    to.  */
9072 
9073 tree
build_trivial_dtor_call(tree instance,bool no_ptr_deref)9074 build_trivial_dtor_call (tree instance, bool no_ptr_deref)
9075 {
9076   gcc_assert (!is_dummy_object (instance));
9077 
9078   if (!flag_lifetime_dse)
9079     {
9080     no_clobber:
9081       return fold_convert (void_type_node, instance);
9082     }
9083 
9084   if (INDIRECT_TYPE_P (TREE_TYPE (instance))
9085       && (!no_ptr_deref || TYPE_REF_P (TREE_TYPE (instance))))
9086     {
9087       if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (instance))))
9088 	goto no_clobber;
9089       instance = cp_build_fold_indirect_ref (instance);
9090     }
9091 
9092   /* A trivial destructor should still clobber the object.  */
9093   tree clobber = build_clobber (TREE_TYPE (instance));
9094   return build2 (MODIFY_EXPR, void_type_node,
9095 		 instance, clobber);
9096 }
9097 
9098 /* Return true if in an immediate function context, or an unevaluated operand,
9099    or a subexpression of an immediate invocation.  */
9100 
9101 bool
in_immediate_context()9102 in_immediate_context ()
9103 {
9104   return (cp_unevaluated_operand != 0
9105 	  || (current_function_decl != NULL_TREE
9106 	      && DECL_IMMEDIATE_FUNCTION_P (current_function_decl))
9107 	  || (current_binding_level->kind == sk_function_parms
9108 	      && current_binding_level->immediate_fn_ctx_p)
9109 	  || in_consteval_if_p);
9110 }
9111 
9112 /* Return true if a call to FN with number of arguments NARGS
9113    is an immediate invocation.  */
9114 
9115 static bool
immediate_invocation_p(tree fn,int nargs)9116 immediate_invocation_p (tree fn, int nargs)
9117 {
9118   return (TREE_CODE (fn) == FUNCTION_DECL
9119 	  && DECL_IMMEDIATE_FUNCTION_P (fn)
9120 	  && !in_immediate_context ()
9121 	  /* As an exception, we defer std::source_location::current ()
9122 	     invocations until genericization because LWG3396 mandates
9123 	     special behavior for it.  */
9124 	  && (nargs > 1 || !source_location_current_p (fn)));
9125 }
9126 
9127 /* temp_override for in_consteval_if_p, which can't use make_temp_override
9128    because it is a bitfield.  */
9129 
9130 struct in_consteval_if_p_temp_override {
9131   bool save_in_consteval_if_p;
in_consteval_if_p_temp_overridein_consteval_if_p_temp_override9132   in_consteval_if_p_temp_override ()
9133     : save_in_consteval_if_p (in_consteval_if_p) {}
resetin_consteval_if_p_temp_override9134   void reset () { in_consteval_if_p = save_in_consteval_if_p; }
~in_consteval_if_p_temp_overridein_consteval_if_p_temp_override9135   ~in_consteval_if_p_temp_override ()
9136   { reset (); }
9137 };
9138 
9139 /* Subroutine of the various build_*_call functions.  Overload resolution
9140    has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
9141    ARGS is a TREE_LIST of the unconverted arguments to the call.  FLAGS is a
9142    bitmask of various LOOKUP_* flags which apply to the call itself.  */
9143 
9144 static tree
build_over_call(struct z_candidate * cand,int flags,tsubst_flags_t complain)9145 build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
9146 {
9147   tree fn = cand->fn;
9148   const vec<tree, va_gc> *args = cand->args;
9149   tree first_arg = cand->first_arg;
9150   conversion **convs = cand->convs;
9151   conversion *conv;
9152   tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
9153   int parmlen;
9154   tree val;
9155   int i = 0;
9156   int j = 0;
9157   unsigned int arg_index = 0;
9158   int is_method = 0;
9159   int nargs;
9160   tree *argarray;
9161   bool already_used = false;
9162 
9163   /* In a template, there is no need to perform all of the work that
9164      is normally done.  We are only interested in the type of the call
9165      expression, i.e., the return type of the function.  Any semantic
9166      errors will be deferred until the template is instantiated.  */
9167   if (processing_template_decl)
9168     {
9169       tree expr, addr;
9170       tree return_type;
9171       const tree *argarray;
9172       unsigned int nargs;
9173 
9174       if (undeduced_auto_decl (fn))
9175 	mark_used (fn, complain);
9176       else
9177 	/* Otherwise set TREE_USED for the benefit of -Wunused-function.
9178 	   See PR80598.  */
9179 	TREE_USED (fn) = 1;
9180 
9181       return_type = TREE_TYPE (TREE_TYPE (fn));
9182       nargs = vec_safe_length (args);
9183       if (first_arg == NULL_TREE)
9184 	argarray = args->address ();
9185       else
9186 	{
9187 	  tree *alcarray;
9188 	  unsigned int ix;
9189 	  tree arg;
9190 
9191 	  ++nargs;
9192 	  alcarray = XALLOCAVEC (tree, nargs);
9193 	  alcarray[0] = build_this (first_arg);
9194 	  FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
9195 	    alcarray[ix + 1] = arg;
9196 	  argarray = alcarray;
9197 	}
9198 
9199       addr = build_addr_func (fn, complain);
9200       if (addr == error_mark_node)
9201 	return error_mark_node;
9202       expr = build_call_array_loc (input_location, return_type,
9203 				   addr, nargs, argarray);
9204       if (TREE_THIS_VOLATILE (fn) && cfun)
9205 	current_function_returns_abnormally = 1;
9206       if (immediate_invocation_p (fn, nargs))
9207 	{
9208 	  tree obj_arg = NULL_TREE, exprimm = expr;
9209 	  if (DECL_CONSTRUCTOR_P (fn))
9210 	    obj_arg = first_arg;
9211 	  if (obj_arg
9212 	      && is_dummy_object (obj_arg)
9213 	      && !type_dependent_expression_p (obj_arg))
9214 	    {
9215 	      exprimm = build_cplus_new (DECL_CONTEXT (fn), expr, complain);
9216 	      obj_arg = NULL_TREE;
9217 	    }
9218 	  /* Look through *(const T *)&obj.  */
9219 	  else if (obj_arg && TREE_CODE (obj_arg) == INDIRECT_REF)
9220 	    {
9221 	      tree addr = TREE_OPERAND (obj_arg, 0);
9222 	      STRIP_NOPS (addr);
9223 	      if (TREE_CODE (addr) == ADDR_EXPR)
9224 		{
9225 		  tree typeo = TREE_TYPE (obj_arg);
9226 		  tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
9227 		  if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
9228 		    obj_arg = TREE_OPERAND (addr, 0);
9229 		}
9230 	    }
9231 	  fold_non_dependent_expr (exprimm, complain,
9232 				   /*manifestly_const_eval=*/true,
9233 				   obj_arg);
9234 	}
9235       return convert_from_reference (expr);
9236     }
9237 
9238   /* Give any warnings we noticed during overload resolution.  */
9239   if (cand->warnings && (complain & tf_warning))
9240     {
9241       struct candidate_warning *w;
9242       for (w = cand->warnings; w; w = w->next)
9243 	joust (cand, w->loser, 1, complain);
9244     }
9245 
9246   /* Core issue 2327: P0135 doesn't say how to handle the case where the
9247      argument to the copy constructor ends up being a prvalue after
9248      conversion.  Let's do the normal processing, but pretend we aren't
9249      actually using the copy constructor.  */
9250   bool force_elide = false;
9251   if (cxx_dialect >= cxx17
9252       && cand->num_convs == 1
9253       && DECL_COMPLETE_CONSTRUCTOR_P (fn)
9254       && (DECL_COPY_CONSTRUCTOR_P (fn)
9255 	  || DECL_MOVE_CONSTRUCTOR_P (fn))
9256       && !unsafe_return_slot_p (first_arg)
9257       && conv_binds_ref_to_prvalue (convs[0]))
9258     {
9259       force_elide = true;
9260       goto not_really_used;
9261     }
9262 
9263   /* OK, we're actually calling this inherited constructor; set its deletedness
9264      appropriately.  We can get away with doing this here because calling is
9265      the only way to refer to a constructor.  */
9266   if (DECL_INHERITED_CTOR (fn)
9267       && !deduce_inheriting_ctor (fn))
9268     {
9269       if (complain & tf_error)
9270 	mark_used (fn);
9271       return error_mark_node;
9272     }
9273 
9274   /* Make =delete work with SFINAE.  */
9275   if (DECL_DELETED_FN (fn))
9276     {
9277       if (complain & tf_error)
9278 	mark_used (fn);
9279       return error_mark_node;
9280     }
9281 
9282   if (DECL_FUNCTION_MEMBER_P (fn))
9283     {
9284       tree access_fn;
9285       /* If FN is a template function, two cases must be considered.
9286 	 For example:
9287 
9288 	   struct A {
9289 	     protected:
9290 	       template <class T> void f();
9291 	   };
9292 	   template <class T> struct B {
9293 	     protected:
9294 	       void g();
9295 	   };
9296 	   struct C : A, B<int> {
9297 	     using A::f;	// #1
9298 	     using B<int>::g;	// #2
9299 	   };
9300 
9301 	 In case #1 where `A::f' is a member template, DECL_ACCESS is
9302 	 recorded in the primary template but not in its specialization.
9303 	 We check access of FN using its primary template.
9304 
9305 	 In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
9306 	 because it is a member of class template B, DECL_ACCESS is
9307 	 recorded in the specialization `B<int>::g'.  We cannot use its
9308 	 primary template because `B<T>::g' and `B<int>::g' may have
9309 	 different access.  */
9310       if (DECL_TEMPLATE_INFO (fn)
9311 	  && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
9312 	access_fn = DECL_TI_TEMPLATE (fn);
9313       else
9314 	access_fn = fn;
9315       if (!perform_or_defer_access_check (cand->access_path, access_fn,
9316 					  fn, complain))
9317 	return error_mark_node;
9318     }
9319 
9320   /* If we're checking for implicit delete, don't bother with argument
9321      conversions.  */
9322   if (flags & LOOKUP_SPECULATIVE)
9323     {
9324       if (cand->viable == 1)
9325 	return fn;
9326       else if (!(complain & tf_error))
9327 	/* Reject bad conversions now.  */
9328 	return error_mark_node;
9329       /* else continue to get conversion error.  */
9330     }
9331 
9332  not_really_used:
9333 
9334   /* N3276 magic doesn't apply to nested calls.  */
9335   tsubst_flags_t decltype_flag = (complain & tf_decltype);
9336   complain &= ~tf_decltype;
9337   /* No-Cleanup doesn't apply to nested calls either.  */
9338   tsubst_flags_t no_cleanup_complain = complain;
9339   complain &= ~tf_no_cleanup;
9340 
9341   /* Find maximum size of vector to hold converted arguments.  */
9342   parmlen = list_length (parm);
9343   nargs = vec_safe_length (args) + (first_arg != NULL_TREE ? 1 : 0);
9344   if (parmlen > nargs)
9345     nargs = parmlen;
9346   argarray = XALLOCAVEC (tree, nargs);
9347 
9348   in_consteval_if_p_temp_override icip;
9349   /* If the call is immediate function invocation, make sure
9350      taking address of immediate functions is allowed in its arguments.  */
9351   if (immediate_invocation_p (STRIP_TEMPLATE (fn), nargs))
9352     in_consteval_if_p = true;
9353 
9354   /* The implicit parameters to a constructor are not considered by overload
9355      resolution, and must be of the proper type.  */
9356   if (DECL_CONSTRUCTOR_P (fn))
9357     {
9358       tree object_arg;
9359       if (first_arg != NULL_TREE)
9360 	{
9361 	  object_arg = first_arg;
9362 	  first_arg = NULL_TREE;
9363 	}
9364       else
9365 	{
9366 	  object_arg = (*args)[arg_index];
9367 	  ++arg_index;
9368 	}
9369       argarray[j++] = build_this (object_arg);
9370       parm = TREE_CHAIN (parm);
9371       /* We should never try to call the abstract constructor.  */
9372       gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
9373 
9374       if (DECL_HAS_VTT_PARM_P (fn))
9375 	{
9376 	  argarray[j++] = (*args)[arg_index];
9377 	  ++arg_index;
9378 	  parm = TREE_CHAIN (parm);
9379 	}
9380 
9381       if (cxx_dialect < cxx20
9382 	  && (cand->flags & LOOKUP_PREFER_RVALUE))
9383 	{
9384 	  /* The implicit move specified in 15.8.3/3 fails "...if the type of
9385 	     the first parameter of the selected constructor is not an rvalue
9386 	     reference to the object's type (possibly cv-qualified)...." */
9387 	  gcc_assert (!(complain & tf_error));
9388 	  tree ptype = convs[0]->type;
9389 	  /* Allow calling a by-value converting constructor even though it
9390 	     isn't permitted by the above, because we've allowed it since GCC 5
9391 	     (PR58051) and it's allowed in C++20.  But don't call a copy
9392 	     constructor.  */
9393 	  if ((TYPE_REF_P (ptype) && !TYPE_REF_IS_RVALUE (ptype))
9394 	      || CONVERSION_RANK (convs[0]) > cr_exact)
9395 	    return error_mark_node;
9396 	}
9397     }
9398   /* Bypass access control for 'this' parameter.  */
9399   else if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
9400     {
9401       tree arg = build_this (first_arg != NULL_TREE
9402 			     ? first_arg
9403 			     : (*args)[arg_index]);
9404       tree argtype = TREE_TYPE (arg);
9405 
9406       if (arg == error_mark_node)
9407 	return error_mark_node;
9408 
9409       if (convs[i]->bad_p)
9410 	{
9411 	  if (complain & tf_error)
9412 	    {
9413 	      auto_diagnostic_group d;
9414 	      if (permerror (input_location, "passing %qT as %<this%> "
9415 			     "argument discards qualifiers",
9416 			     TREE_TYPE (argtype)))
9417 		inform (DECL_SOURCE_LOCATION (fn), "  in call to %qD", fn);
9418 	    }
9419 	  else
9420 	    return error_mark_node;
9421 	}
9422 
9423       /* The class where FN is defined.  */
9424       tree ctx = DECL_CONTEXT (fn);
9425 
9426       /* See if the function member or the whole class type is declared
9427 	 final and the call can be devirtualized.  */
9428       if (DECL_FINAL_P (fn) || CLASSTYPE_FINAL (ctx))
9429 	flags |= LOOKUP_NONVIRTUAL;
9430 
9431       /* [class.mfct.non-static]: If a non-static member function of a class
9432 	 X is called for an object that is not of type X, or of a type
9433 	 derived from X, the behavior is undefined.
9434 
9435 	 So we can assume that anything passed as 'this' is non-null, and
9436 	 optimize accordingly.  */
9437       /* Check that the base class is accessible.  */
9438       if (!accessible_base_p (TREE_TYPE (argtype),
9439 			      BINFO_TYPE (cand->conversion_path), true))
9440 	{
9441 	  if (complain & tf_error)
9442 	    error ("%qT is not an accessible base of %qT",
9443 		   BINFO_TYPE (cand->conversion_path),
9444 		   TREE_TYPE (argtype));
9445 	  else
9446 	    return error_mark_node;
9447 	}
9448       /* If fn was found by a using declaration, the conversion path
9449 	 will be to the derived class, not the base declaring fn. We
9450 	 must convert to the base.  */
9451       tree base_binfo = cand->conversion_path;
9452       if (BINFO_TYPE (base_binfo) != ctx)
9453 	{
9454 	  base_binfo = lookup_base (base_binfo, ctx, ba_unique, NULL, complain);
9455 	  if (base_binfo == error_mark_node)
9456 	    return error_mark_node;
9457 	}
9458 
9459       /* If we know the dynamic type of the object, look up the final overrider
9460 	 in the BINFO.  */
9461       if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0
9462 	  && resolves_to_fixed_type_p (arg))
9463 	{
9464 	  tree ov = lookup_vfn_in_binfo (DECL_VINDEX (fn), base_binfo);
9465 
9466 	  /* And unwind base_binfo to match.  If we don't find the type we're
9467 	     looking for in BINFO_INHERITANCE_CHAIN, we're looking at diamond
9468 	     inheritance; for now do a normal virtual call in that case.  */
9469 	  tree octx = DECL_CONTEXT (ov);
9470 	  tree obinfo = base_binfo;
9471 	  while (obinfo && !SAME_BINFO_TYPE_P (BINFO_TYPE (obinfo), octx))
9472 	    obinfo = BINFO_INHERITANCE_CHAIN (obinfo);
9473 	  if (obinfo)
9474 	    {
9475 	      fn = ov;
9476 	      base_binfo = obinfo;
9477 	      flags |= LOOKUP_NONVIRTUAL;
9478 	    }
9479 	}
9480 
9481       tree converted_arg = build_base_path (PLUS_EXPR, arg,
9482 					    base_binfo, 1, complain);
9483 
9484       argarray[j++] = converted_arg;
9485       parm = TREE_CHAIN (parm);
9486       if (first_arg != NULL_TREE)
9487 	first_arg = NULL_TREE;
9488       else
9489 	++arg_index;
9490       ++i;
9491       is_method = 1;
9492     }
9493 
9494   gcc_assert (first_arg == NULL_TREE);
9495   for (; arg_index < vec_safe_length (args) && parm;
9496        parm = TREE_CHAIN (parm), ++arg_index, ++i)
9497     {
9498       tree type = TREE_VALUE (parm);
9499       tree arg = (*args)[arg_index];
9500       bool conversion_warning = true;
9501 
9502       conv = convs[i];
9503 
9504       /* If the argument is NULL and used to (implicitly) instantiate a
9505          template function (and bind one of the template arguments to
9506          the type of 'long int'), we don't want to warn about passing NULL
9507          to non-pointer argument.
9508          For example, if we have this template function:
9509 
9510            template<typename T> void func(T x) {}
9511 
9512          we want to warn (when -Wconversion is enabled) in this case:
9513 
9514            void foo() {
9515              func<int>(NULL);
9516            }
9517 
9518          but not in this case:
9519 
9520            void foo() {
9521              func(NULL);
9522            }
9523       */
9524       if (null_node_p (arg)
9525           && DECL_TEMPLATE_INFO (fn)
9526           && cand->template_decl
9527 	  && !cand->explicit_targs)
9528         conversion_warning = false;
9529 
9530       /* Set user_conv_p on the argument conversions, so rvalue/base handling
9531 	 knows not to allow any more UDCs.  This needs to happen after we
9532 	 process cand->warnings.  */
9533       if (flags & LOOKUP_NO_CONVERSION)
9534 	conv->user_conv_p = true;
9535 
9536       tsubst_flags_t arg_complain = complain;
9537       if (!conversion_warning)
9538 	arg_complain &= ~tf_warning;
9539 
9540       val = convert_like_with_context (conv, arg, fn, i - is_method,
9541 				       arg_complain);
9542       val = convert_for_arg_passing (type, val, arg_complain);
9543 
9544       if (val == error_mark_node)
9545         return error_mark_node;
9546       else
9547         argarray[j++] = val;
9548     }
9549 
9550   /* Default arguments */
9551   for (; parm && parm != void_list_node; parm = TREE_CHAIN (parm), i++)
9552     {
9553       if (TREE_VALUE (parm) == error_mark_node)
9554 	return error_mark_node;
9555       val = convert_default_arg (TREE_VALUE (parm),
9556 				 TREE_PURPOSE (parm),
9557 				 fn, i - is_method,
9558 				 complain);
9559       if (val == error_mark_node)
9560         return error_mark_node;
9561       argarray[j++] = val;
9562     }
9563 
9564   /* Ellipsis */
9565   int magic = magic_varargs_p (fn);
9566   for (; arg_index < vec_safe_length (args); ++arg_index)
9567     {
9568       tree a = (*args)[arg_index];
9569       if ((magic == 3 && arg_index == 2) || magic == 2)
9570 	{
9571 	  /* Do no conversions for certain magic varargs.  */
9572 	  a = mark_type_use (a);
9573 	  if (TREE_CODE (a) == FUNCTION_DECL && reject_gcc_builtin (a))
9574 	    return error_mark_node;
9575 	}
9576       else if (magic != 0)
9577 	/* For other magic varargs only do decay_conversion.  */
9578 	a = decay_conversion (a, complain);
9579       else if (DECL_CONSTRUCTOR_P (fn)
9580 	       && same_type_ignoring_top_level_qualifiers_p (DECL_CONTEXT (fn),
9581 							     TREE_TYPE (a)))
9582 	{
9583 	  /* Avoid infinite recursion trying to call A(...).  */
9584 	  if (complain & tf_error)
9585 	    /* Try to call the actual copy constructor for a good error.  */
9586 	    call_copy_ctor (a, complain);
9587 	  return error_mark_node;
9588 	}
9589       else
9590 	a = convert_arg_to_ellipsis (a, complain);
9591       if (a == error_mark_node)
9592 	return error_mark_node;
9593       argarray[j++] = a;
9594     }
9595 
9596   gcc_assert (j <= nargs);
9597   nargs = j;
9598   icip.reset ();
9599 
9600   /* Avoid performing argument transformation if warnings are disabled.
9601      When tf_warning is set and at least one of the warnings is active
9602      the check_function_arguments function might warn about something.  */
9603 
9604   bool warned_p = false;
9605   if ((complain & tf_warning)
9606       && (warn_nonnull
9607 	  || warn_format
9608 	  || warn_suggest_attribute_format
9609 	  || warn_restrict))
9610     {
9611       tree *fargs = (!nargs ? argarray
9612 			    : (tree *) alloca (nargs * sizeof (tree)));
9613       for (j = 0; j < nargs; j++)
9614 	{
9615 	  /* For -Wformat undo the implicit passing by hidden reference
9616 	     done by convert_arg_to_ellipsis.  */
9617 	  if (TREE_CODE (argarray[j]) == ADDR_EXPR
9618 	      && TYPE_REF_P (TREE_TYPE (argarray[j])))
9619 	    fargs[j] = TREE_OPERAND (argarray[j], 0);
9620 	  else
9621 	    fargs[j] = argarray[j];
9622 	}
9623 
9624       warned_p = check_function_arguments (input_location, fn, TREE_TYPE (fn),
9625 					   nargs, fargs, NULL);
9626     }
9627 
9628   if (DECL_INHERITED_CTOR (fn))
9629     {
9630       /* Check for passing ellipsis arguments to an inherited constructor.  We
9631 	 could handle this by open-coding the inherited constructor rather than
9632 	 defining it, but let's not bother now.  */
9633       if (!cp_unevaluated_operand
9634 	  && cand->num_convs
9635 	  && cand->convs[cand->num_convs-1]->ellipsis_p)
9636 	{
9637 	  if (complain & tf_error)
9638 	    {
9639 	      sorry ("passing arguments to ellipsis of inherited constructor "
9640 		     "%qD", cand->fn);
9641 	      inform (DECL_SOURCE_LOCATION (cand->fn), "declared here");
9642 	    }
9643 	  return error_mark_node;
9644 	}
9645 
9646       /* A base constructor inheriting from a virtual base doesn't get the
9647 	 inherited arguments, just this and __vtt.  */
9648       if (ctor_omit_inherited_parms (fn))
9649 	nargs = 2;
9650     }
9651 
9652   /* Avoid actually calling copy constructors and copy assignment operators,
9653      if possible.  */
9654 
9655   if (! flag_elide_constructors && !force_elide)
9656     /* Do things the hard way.  */;
9657   else if (cand->num_convs == 1
9658            && (DECL_COPY_CONSTRUCTOR_P (fn)
9659                || DECL_MOVE_CONSTRUCTOR_P (fn))
9660 	   /* It's unsafe to elide the constructor when handling
9661 	      a noexcept-expression, it may evaluate to the wrong
9662 	      value (c++/53025).  */
9663 	   && (force_elide || cp_noexcept_operand == 0))
9664     {
9665       tree targ;
9666       tree arg = argarray[num_artificial_parms_for (fn)];
9667       tree fa = argarray[0];
9668       bool trivial = trivial_fn_p (fn);
9669 
9670       /* Pull out the real argument, disregarding const-correctness.  */
9671       targ = arg;
9672       /* Strip the reference binding for the constructor parameter.  */
9673       if (CONVERT_EXPR_P (targ)
9674 	  && TYPE_REF_P (TREE_TYPE (targ)))
9675 	targ = TREE_OPERAND (targ, 0);
9676       /* But don't strip any other reference bindings; binding a temporary to a
9677 	 reference prevents copy elision.  */
9678       while ((CONVERT_EXPR_P (targ)
9679 	      && !TYPE_REF_P (TREE_TYPE (targ)))
9680 	     || TREE_CODE (targ) == NON_LVALUE_EXPR)
9681 	targ = TREE_OPERAND (targ, 0);
9682       if (TREE_CODE (targ) == ADDR_EXPR)
9683 	{
9684 	  targ = TREE_OPERAND (targ, 0);
9685 	  if (!same_type_ignoring_top_level_qualifiers_p
9686 	      (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
9687 	    targ = NULL_TREE;
9688 	}
9689       else
9690 	targ = NULL_TREE;
9691 
9692       if (targ)
9693 	arg = targ;
9694       else
9695 	arg = cp_build_fold_indirect_ref (arg);
9696 
9697       /* In C++17 we shouldn't be copying a TARGET_EXPR except into a
9698 	 potentially-overlapping subobject.  */
9699       if (CHECKING_P && cxx_dialect >= cxx17)
9700 	gcc_assert (TREE_CODE (arg) != TARGET_EXPR
9701 		    || force_elide
9702 		    /* It's from binding the ref parm to a packed field. */
9703 		    || convs[0]->need_temporary_p
9704 		    || seen_error ()
9705 		    /* See unsafe_copy_elision_p.  */
9706 		    || unsafe_return_slot_p (fa));
9707 
9708       bool unsafe = unsafe_copy_elision_p_opt (fa, arg);
9709       bool eliding_temp = (TREE_CODE (arg) == TARGET_EXPR && !unsafe);
9710 
9711       /* [class.copy]: the copy constructor is implicitly defined even if the
9712 	 implementation elided its use.  But don't warn about deprecation when
9713 	 eliding a temporary, as then no copy is actually performed.  */
9714       warning_sentinel s (warn_deprecated_copy, eliding_temp);
9715       if (force_elide)
9716 	/* The language says this isn't called.  */;
9717       else if (!trivial)
9718 	{
9719 	  if (!mark_used (fn, complain) && !(complain & tf_error))
9720 	    return error_mark_node;
9721 	  already_used = true;
9722 	}
9723       else
9724 	cp_handle_deprecated_or_unavailable (fn, complain);
9725 
9726       if (eliding_temp && DECL_BASE_CONSTRUCTOR_P (fn)
9727 	  && !make_base_init_ok (arg))
9728 	unsafe = true;
9729 
9730       /* If we're creating a temp and we already have one, don't create a
9731 	 new one.  If we're not creating a temp but we get one, use
9732 	 INIT_EXPR to collapse the temp into our target.  Otherwise, if the
9733 	 ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
9734 	 temp or an INIT_EXPR otherwise.  */
9735       if (is_dummy_object (fa))
9736 	{
9737 	  if (TREE_CODE (arg) == TARGET_EXPR)
9738 	    return arg;
9739 	  else if (trivial)
9740 	    return force_target_expr (DECL_CONTEXT (fn), arg, complain);
9741 	}
9742       else if ((trivial || TREE_CODE (arg) == TARGET_EXPR)
9743 	       && !unsafe)
9744 	{
9745 	  tree to = cp_build_fold_indirect_ref (fa);
9746 	  val = build2 (INIT_EXPR, DECL_CONTEXT (fn), to, arg);
9747 	  return val;
9748 	}
9749     }
9750   else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
9751 	   && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR)
9752 	   && trivial_fn_p (fn))
9753     {
9754       tree to = cp_build_fold_indirect_ref (argarray[0]);
9755       tree type = TREE_TYPE (to);
9756       tree as_base = CLASSTYPE_AS_BASE (type);
9757       tree arg = argarray[1];
9758       location_t loc = cp_expr_loc_or_input_loc (arg);
9759 
9760       if (is_really_empty_class (type, /*ignore_vptr*/true))
9761 	{
9762 	  /* Avoid copying empty classes.  */
9763 	  val = build2 (COMPOUND_EXPR, type, arg, to);
9764 	  suppress_warning (val, OPT_Wunused);
9765 	}
9766       else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
9767 	{
9768 	  if (is_std_init_list (type)
9769 	      && conv_binds_ref_to_prvalue (convs[1]))
9770 	    warning_at (loc, OPT_Winit_list_lifetime,
9771 			"assignment from temporary %<initializer_list%> does "
9772 			"not extend the lifetime of the underlying array");
9773 	  arg = cp_build_fold_indirect_ref (arg);
9774 	  val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
9775 	}
9776       else
9777 	{
9778 	  /* We must only copy the non-tail padding parts.  */
9779 	  tree arg0, arg2, t;
9780 	  tree array_type, alias_set;
9781 
9782 	  arg2 = TYPE_SIZE_UNIT (as_base);
9783 	  to = cp_stabilize_reference (to);
9784 	  arg0 = cp_build_addr_expr (to, complain);
9785 
9786 	  array_type = build_array_type (unsigned_char_type_node,
9787 					 build_index_type
9788 					   (size_binop (MINUS_EXPR,
9789 							arg2, size_int (1))));
9790 	  alias_set = build_int_cst (build_pointer_type (type), 0);
9791 	  t = build2 (MODIFY_EXPR, void_type_node,
9792 		      build2 (MEM_REF, array_type, arg0, alias_set),
9793 		      build2 (MEM_REF, array_type, arg, alias_set));
9794 	  val = build2 (COMPOUND_EXPR, TREE_TYPE (to), t, to);
9795           suppress_warning (val, OPT_Wunused);
9796 	}
9797 
9798       cp_handle_deprecated_or_unavailable (fn, complain);
9799 
9800       return val;
9801     }
9802   else if (trivial_fn_p (fn))
9803     {
9804       if (DECL_DESTRUCTOR_P (fn))
9805 	return build_trivial_dtor_call (argarray[0]);
9806       else if (default_ctor_p (fn))
9807 	{
9808 	  if (is_dummy_object (argarray[0]))
9809 	    return force_target_expr (DECL_CONTEXT (fn), void_node,
9810 				      no_cleanup_complain);
9811 	  else
9812 	    return cp_build_fold_indirect_ref (argarray[0]);
9813 	}
9814     }
9815 
9816   gcc_assert (!force_elide);
9817 
9818   if (!already_used
9819       && !mark_used (fn, complain))
9820     return error_mark_node;
9821 
9822   /* Warn if the built-in writes to an object of a non-trivial type.  */
9823   if (warn_class_memaccess
9824       && vec_safe_length (args) >= 2
9825       && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
9826     maybe_warn_class_memaccess (input_location, fn, args);
9827 
9828   if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
9829     {
9830       tree t;
9831       tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
9832 				DECL_CONTEXT (fn),
9833 				ba_any, NULL, complain);
9834       gcc_assert (binfo && binfo != error_mark_node);
9835 
9836       argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1,
9837 				     complain);
9838       if (TREE_SIDE_EFFECTS (argarray[0]))
9839 	argarray[0] = save_expr (argarray[0]);
9840       t = build_pointer_type (TREE_TYPE (fn));
9841       fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
9842       TREE_TYPE (fn) = t;
9843     }
9844   else
9845     {
9846       /* If FN is marked deprecated, then we've already issued a deprecated-use
9847 	 warning from mark_used above, so avoid redundantly issuing another one
9848 	 from build_addr_func.  */
9849       warning_sentinel w (warn_deprecated_decl);
9850 
9851       fn = build_addr_func (fn, complain);
9852       if (fn == error_mark_node)
9853 	return error_mark_node;
9854     }
9855 
9856   tree call = build_cxx_call (fn, nargs, argarray, complain|decltype_flag);
9857   if (call == error_mark_node)
9858     return call;
9859   if (cand->flags & LOOKUP_LIST_INIT_CTOR)
9860     {
9861       tree c = extract_call_expr (call);
9862       /* build_new_op will clear this when appropriate.  */
9863       CALL_EXPR_ORDERED_ARGS (c) = true;
9864     }
9865   if (warned_p)
9866     {
9867       tree c = extract_call_expr (call);
9868       if (TREE_CODE (c) == CALL_EXPR)
9869 	suppress_warning (c /* Suppress all warnings.  */);
9870     }
9871   if (TREE_CODE (fn) == ADDR_EXPR)
9872     {
9873       tree fndecl = STRIP_TEMPLATE (TREE_OPERAND (fn, 0));
9874       if (immediate_invocation_p (fndecl, nargs))
9875 	{
9876 	  tree obj_arg = NULL_TREE;
9877 	  /* Undo convert_from_reference called by build_cxx_call.  */
9878 	  if (REFERENCE_REF_P (call))
9879 	    call = TREE_OPERAND (call, 0);
9880 	  if (DECL_CONSTRUCTOR_P (fndecl))
9881 	    obj_arg = cand->first_arg ? cand->first_arg : (*args)[0];
9882 	  if (obj_arg && is_dummy_object (obj_arg))
9883 	    {
9884 	      call = build_cplus_new (DECL_CONTEXT (fndecl), call, complain);
9885 	      obj_arg = NULL_TREE;
9886 	    }
9887 	  /* Look through *(const T *)&obj.  */
9888 	  else if (obj_arg && TREE_CODE (obj_arg) == INDIRECT_REF)
9889 	    {
9890 	      tree addr = TREE_OPERAND (obj_arg, 0);
9891 	      STRIP_NOPS (addr);
9892 	      if (TREE_CODE (addr) == ADDR_EXPR)
9893 		{
9894 		  tree typeo = TREE_TYPE (obj_arg);
9895 		  tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
9896 		  if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
9897 		    obj_arg = TREE_OPERAND (addr, 0);
9898 		}
9899 	    }
9900 	  call = cxx_constant_value (call, obj_arg);
9901 	  if (obj_arg && !error_operand_p (call))
9902 	    call = build2 (INIT_EXPR, void_type_node, obj_arg, call);
9903 	  call = convert_from_reference (call);
9904 	}
9905     }
9906   return call;
9907 }
9908 
9909 namespace
9910 {
9911 
9912 /* Return the DECL of the first non-static subobject of class TYPE
9913    that satisfies the predicate PRED or null if none can be found.  */
9914 
9915 template <class Predicate>
9916 tree
first_non_static_field(tree type,Predicate pred)9917 first_non_static_field (tree type, Predicate pred)
9918 {
9919   if (!type || !CLASS_TYPE_P (type))
9920     return NULL_TREE;
9921 
9922   for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
9923     {
9924       if (TREE_CODE (field) != FIELD_DECL)
9925 	continue;
9926       if (TREE_STATIC (field))
9927 	continue;
9928       if (pred (field))
9929 	return field;
9930     }
9931 
9932   int i = 0;
9933 
9934   for (tree base_binfo, binfo = TYPE_BINFO (type);
9935        BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
9936     {
9937       tree base = TREE_TYPE (base_binfo);
9938       if (pred (base))
9939 	return base;
9940       if (tree field = first_non_static_field (base, pred))
9941 	return field;
9942     }
9943 
9944   return NULL_TREE;
9945 }
9946 
9947 struct NonPublicField
9948 {
operatorNonPublicField9949   bool operator() (const_tree t) const
9950   {
9951     return DECL_P (t) && (TREE_PRIVATE (t) || TREE_PROTECTED (t));
9952   }
9953 };
9954 
9955 /* Return the DECL of the first non-public subobject of class TYPE
9956    or null if none can be found.  */
9957 
9958 static inline tree
first_non_public_field(tree type)9959 first_non_public_field (tree type)
9960 {
9961   return first_non_static_field (type, NonPublicField ());
9962 }
9963 
9964 struct NonTrivialField
9965 {
operatorNonTrivialField9966   bool operator() (const_tree t) const
9967   {
9968     return !trivial_type_p (DECL_P (t) ? TREE_TYPE (t) : t);
9969   }
9970 };
9971 
9972 /* Return the DECL of the first non-trivial subobject of class TYPE
9973    or null if none can be found.  */
9974 
9975 static inline tree
first_non_trivial_field(tree type)9976 first_non_trivial_field (tree type)
9977 {
9978   return first_non_static_field (type, NonTrivialField ());
9979 }
9980 
9981 }   /* unnamed namespace */
9982 
9983 /* Return true if all copy and move assignment operator overloads for
9984    class TYPE are trivial and at least one of them is not deleted and,
9985    when ACCESS is set, accessible.  Return false otherwise.  Set
9986    HASASSIGN to true when the TYPE has a (not necessarily trivial)
9987    copy or move assignment.  */
9988 
9989 static bool
has_trivial_copy_assign_p(tree type,bool access,bool * hasassign)9990 has_trivial_copy_assign_p (tree type, bool access, bool *hasassign)
9991 {
9992   tree fns = get_class_binding (type, assign_op_identifier);
9993   bool all_trivial = true;
9994 
9995   /* Iterate over overloads of the assignment operator, checking
9996      accessible copy assignments for triviality.  */
9997 
9998   for (tree f : ovl_range (fns))
9999     {
10000       /* Skip operators that aren't copy assignments.  */
10001       if (!copy_fn_p (f))
10002 	continue;
10003 
10004       bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10005 			 || accessible_p (TYPE_BINFO (type), f, true));
10006 
10007       /* Skip template assignment operators and deleted functions.  */
10008       if (TREE_CODE (f) != FUNCTION_DECL || DECL_DELETED_FN (f))
10009 	continue;
10010 
10011       if (accessible)
10012 	*hasassign = true;
10013 
10014       if (!accessible || !trivial_fn_p (f))
10015 	all_trivial = false;
10016 
10017       /* Break early when both properties have been determined.  */
10018       if (*hasassign && !all_trivial)
10019 	break;
10020     }
10021 
10022   /* Return true if they're all trivial and one of the expressions
10023      TYPE() = TYPE() or TYPE() = (TYPE&)() is valid.  */
10024   tree ref = cp_build_reference_type (type, false);
10025   return (all_trivial
10026 	  && (is_trivially_xible (MODIFY_EXPR, type, type)
10027 	      || is_trivially_xible (MODIFY_EXPR, type, ref)));
10028 }
10029 
10030 /* Return true if all copy and move ctor overloads for class TYPE are
10031    trivial and at least one of them is not deleted and, when ACCESS is
10032    set, accessible.  Return false otherwise.  Set each element of HASCTOR[]
10033    to true when the TYPE has a (not necessarily trivial) default and copy
10034    (or move) ctor, respectively.  */
10035 
10036 static bool
has_trivial_copy_p(tree type,bool access,bool hasctor[2])10037 has_trivial_copy_p (tree type, bool access, bool hasctor[2])
10038 {
10039   tree fns = get_class_binding (type, complete_ctor_identifier);
10040   bool all_trivial = true;
10041 
10042   for (tree f : ovl_range (fns))
10043     {
10044       /* Skip template constructors.  */
10045       if (TREE_CODE (f) != FUNCTION_DECL)
10046 	continue;
10047 
10048       bool cpy_or_move_ctor_p = copy_fn_p (f);
10049 
10050       /* Skip ctors other than default, copy, and move.  */
10051       if (!cpy_or_move_ctor_p && !default_ctor_p (f))
10052 	continue;
10053 
10054       if (DECL_DELETED_FN (f))
10055 	continue;
10056 
10057       bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10058 			 || accessible_p (TYPE_BINFO (type), f, true));
10059 
10060       if (accessible)
10061 	hasctor[cpy_or_move_ctor_p] = true;
10062 
10063       if (cpy_or_move_ctor_p && (!accessible || !trivial_fn_p (f)))
10064 	all_trivial = false;
10065 
10066       /* Break early when both properties have been determined.  */
10067       if (hasctor[0] && hasctor[1] && !all_trivial)
10068 	break;
10069     }
10070 
10071   return all_trivial;
10072 }
10073 
10074 /* Issue a warning on a call to the built-in function FNDECL if it is
10075    a raw memory write whose destination is not an object of (something
10076    like) trivial or standard layout type with a non-deleted assignment
10077    and copy ctor.  Detects const correctness violations, corrupting
10078    references, virtual table pointers, and bypassing non-trivial
10079    assignments.  */
10080 
10081 static void
maybe_warn_class_memaccess(location_t loc,tree fndecl,const vec<tree,va_gc> * args)10082 maybe_warn_class_memaccess (location_t loc, tree fndecl,
10083 			    const vec<tree, va_gc> *args)
10084 {
10085   /* Except for bcopy where it's second, the destination pointer is
10086      the first argument for all functions handled here.  Compute
10087      the index of the destination and source arguments.  */
10088   unsigned dstidx = DECL_FUNCTION_CODE (fndecl) == BUILT_IN_BCOPY;
10089   unsigned srcidx = !dstidx;
10090 
10091   tree dest = (*args)[dstidx];
10092   if (!TREE_TYPE (dest)
10093       || (TREE_CODE (TREE_TYPE (dest)) != ARRAY_TYPE
10094 	  && !INDIRECT_TYPE_P (TREE_TYPE (dest))))
10095     return;
10096 
10097   tree srctype = NULL_TREE;
10098 
10099   /* Determine the type of the pointed-to object and whether it's
10100      a complete class type.  */
10101   tree desttype = TREE_TYPE (TREE_TYPE (dest));
10102 
10103   if (!desttype || !COMPLETE_TYPE_P (desttype) || !CLASS_TYPE_P (desttype))
10104     return;
10105 
10106   /* Check to see if the raw memory call is made by a non-static member
10107      function with THIS as the destination argument for the destination
10108      type.  If so, and if the class has no non-trivial bases or members,
10109      be more permissive.  */
10110   if (current_function_decl
10111       && DECL_NONSTATIC_MEMBER_FUNCTION_P (current_function_decl)
10112       && is_this_parameter (tree_strip_nop_conversions (dest)))
10113     {
10114       tree ctx = DECL_CONTEXT (current_function_decl);
10115       bool special = same_type_ignoring_top_level_qualifiers_p (ctx, desttype);
10116       tree binfo = TYPE_BINFO (ctx);
10117 
10118       if (special
10119 	  && !BINFO_VTABLE (binfo)
10120 	  && !first_non_trivial_field (desttype))
10121 	return;
10122     }
10123 
10124   /* True if the class is trivial.  */
10125   bool trivial = trivial_type_p (desttype);
10126 
10127   /* Set to true if DESTYPE has an accessible copy assignment.  */
10128   bool hasassign = false;
10129   /* True if all of the class' overloaded copy assignment operators
10130      are all trivial (and not deleted) and at least one of them is
10131      accessible.  */
10132   bool trivassign = has_trivial_copy_assign_p (desttype, true, &hasassign);
10133 
10134   /* Set to true if DESTTYPE has an accessible default and copy ctor,
10135      respectively.  */
10136   bool hasctors[2] = { false, false };
10137 
10138   /* True if all of the class' overloaded copy constructors are all
10139      trivial (and not deleted) and at least one of them is accessible.  */
10140   bool trivcopy = has_trivial_copy_p (desttype, true, hasctors);
10141 
10142   /* Set FLD to the first private/protected member of the class.  */
10143   tree fld = trivial ? first_non_public_field (desttype) : NULL_TREE;
10144 
10145   /* The warning format string.  */
10146   const char *warnfmt = NULL;
10147   /* A suggested alternative to offer instead of the raw memory call.
10148      Empty string when none can be come up with.  */
10149   const char *suggest = "";
10150   bool warned = false;
10151 
10152   switch (DECL_FUNCTION_CODE (fndecl))
10153     {
10154     case BUILT_IN_MEMSET:
10155       if (!integer_zerop (maybe_constant_value ((*args)[1])))
10156 	{
10157 	  /* Diagnose setting non-copy-assignable or non-trivial types,
10158 	     or types with a private member, to (potentially) non-zero
10159 	     bytes.  Since the value of the bytes being written is unknown,
10160 	     suggest using assignment instead (if one exists).  Also warn
10161 	     for writes into objects for which zero-initialization doesn't
10162 	     mean all bits clear (pointer-to-member data, where null is all
10163 	     bits set).  Since the value being written is (most likely)
10164 	     non-zero, simply suggest assignment (but not copy assignment).  */
10165 	  suggest = "; use assignment instead";
10166 	  if (!trivassign)
10167 	    warnfmt = G_("%qD writing to an object of type %#qT with "
10168 			 "no trivial copy-assignment");
10169 	  else if (!trivial)
10170 	    warnfmt = G_("%qD writing to an object of non-trivial type %#qT%s");
10171 	  else if (fld)
10172 	    {
10173 	      const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10174 	      warned = warning_at (loc, OPT_Wclass_memaccess,
10175 				   "%qD writing to an object of type %#qT with "
10176 				   "%qs member %qD",
10177 				   fndecl, desttype, access, fld);
10178 	    }
10179 	  else if (!zero_init_p (desttype))
10180 	    warnfmt = G_("%qD writing to an object of type %#qT containing "
10181 			 "a pointer to data member%s");
10182 
10183 	  break;
10184 	}
10185       /* Fall through.  */
10186 
10187     case BUILT_IN_BZERO:
10188       /* Similarly to the above, diagnose clearing non-trivial or non-
10189 	 standard layout objects, or objects of types with no assignmenmt.
10190 	 Since the value being written is known to be zero, suggest either
10191 	 copy assignment, copy ctor, or default ctor as an alternative,
10192 	 depending on what's available.  */
10193 
10194       if (hasassign && hasctors[0])
10195 	suggest = G_("; use assignment or value-initialization instead");
10196       else if (hasassign)
10197 	suggest = G_("; use assignment instead");
10198       else if (hasctors[0])
10199 	suggest = G_("; use value-initialization instead");
10200 
10201       if (!trivassign)
10202 	warnfmt = G_("%qD clearing an object of type %#qT with "
10203 		     "no trivial copy-assignment%s");
10204       else if (!trivial)
10205 	warnfmt =  G_("%qD clearing an object of non-trivial type %#qT%s");
10206       else if (!zero_init_p (desttype))
10207 	warnfmt = G_("%qD clearing an object of type %#qT containing "
10208 		     "a pointer-to-member%s");
10209       break;
10210 
10211     case BUILT_IN_BCOPY:
10212     case BUILT_IN_MEMCPY:
10213     case BUILT_IN_MEMMOVE:
10214     case BUILT_IN_MEMPCPY:
10215       /* Determine the type of the source object.  */
10216       srctype = TREE_TYPE ((*args)[srcidx]);
10217       if (!srctype || !INDIRECT_TYPE_P (srctype))
10218 	srctype = void_type_node;
10219       else
10220 	srctype = TREE_TYPE (srctype);
10221 
10222       /* Since it's impossible to determine wheter the byte copy is
10223 	 being used in place of assignment to an existing object or
10224 	 as a substitute for initialization, assume it's the former.
10225 	 Determine the best alternative to use instead depending on
10226 	 what's not deleted.  */
10227       if (hasassign && hasctors[1])
10228 	suggest = G_("; use copy-assignment or copy-initialization instead");
10229       else if (hasassign)
10230 	suggest = G_("; use copy-assignment instead");
10231       else if (hasctors[1])
10232 	suggest = G_("; use copy-initialization instead");
10233 
10234       if (!trivassign)
10235 	warnfmt = G_("%qD writing to an object of type %#qT with no trivial "
10236 		     "copy-assignment%s");
10237       else if (!trivially_copyable_p (desttype))
10238 	warnfmt = G_("%qD writing to an object of non-trivially copyable "
10239 		     "type %#qT%s");
10240       else if (!trivcopy)
10241 	warnfmt = G_("%qD writing to an object with a deleted copy constructor");
10242 
10243       else if (!trivial
10244 	       && !VOID_TYPE_P (srctype)
10245 	       && !is_byte_access_type (srctype)
10246 	       && !same_type_ignoring_top_level_qualifiers_p (desttype,
10247 							      srctype))
10248 	{
10249 	  /* Warn when copying into a non-trivial object from an object
10250 	     of a different type other than void or char.  */
10251 	  warned = warning_at (loc, OPT_Wclass_memaccess,
10252 			       "%qD copying an object of non-trivial type "
10253 			       "%#qT from an array of %#qT",
10254 			       fndecl, desttype, srctype);
10255 	}
10256       else if (fld
10257 	       && !VOID_TYPE_P (srctype)
10258 	       && !is_byte_access_type (srctype)
10259 	       && !same_type_ignoring_top_level_qualifiers_p (desttype,
10260 							      srctype))
10261 	{
10262 	  const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10263 	  warned = warning_at (loc, OPT_Wclass_memaccess,
10264 			       "%qD copying an object of type %#qT with "
10265 			       "%qs member %qD from an array of %#qT; use "
10266 			       "assignment or copy-initialization instead",
10267 			       fndecl, desttype, access, fld, srctype);
10268 	}
10269       else if (!trivial && vec_safe_length (args) > 2)
10270 	{
10271 	  tree sz = maybe_constant_value ((*args)[2]);
10272 	  if (!tree_fits_uhwi_p (sz))
10273 	    break;
10274 
10275 	  /* Finally, warn on partial copies.  */
10276 	  unsigned HOST_WIDE_INT typesize
10277 	    = tree_to_uhwi (TYPE_SIZE_UNIT (desttype));
10278 	  if (unsigned HOST_WIDE_INT partial = tree_to_uhwi (sz) % typesize)
10279 	    warned = warning_at (loc, OPT_Wclass_memaccess,
10280 				 (typesize - partial > 1
10281 				  ? G_("%qD writing to an object of "
10282 				       "a non-trivial type %#qT leaves %wu "
10283 				       "bytes unchanged")
10284 				  : G_("%qD writing to an object of "
10285 				       "a non-trivial type %#qT leaves %wu "
10286 				       "byte unchanged")),
10287 				 fndecl, desttype, typesize - partial);
10288 	}
10289       break;
10290 
10291     case BUILT_IN_REALLOC:
10292 
10293       if (!trivially_copyable_p (desttype))
10294 	warnfmt = G_("%qD moving an object of non-trivially copyable type "
10295 		     "%#qT; use %<new%> and %<delete%> instead");
10296       else if (!trivcopy)
10297 	warnfmt = G_("%qD moving an object of type %#qT with deleted copy "
10298 		     "constructor; use %<new%> and %<delete%> instead");
10299       else if (!get_dtor (desttype, tf_none))
10300 	warnfmt = G_("%qD moving an object of type %#qT with deleted "
10301 		     "destructor");
10302       else if (!trivial)
10303 	{
10304 	  tree sz = maybe_constant_value ((*args)[1]);
10305 	  if (TREE_CODE (sz) == INTEGER_CST
10306 	      && tree_int_cst_lt (sz, TYPE_SIZE_UNIT (desttype)))
10307 	    /* Finally, warn on reallocation into insufficient space.  */
10308 	    warned = warning_at (loc, OPT_Wclass_memaccess,
10309 				 "%qD moving an object of non-trivial type "
10310 				 "%#qT and size %E into a region of size %E",
10311 				 fndecl, desttype, TYPE_SIZE_UNIT (desttype),
10312 				 sz);
10313 	}
10314       break;
10315 
10316     default:
10317       return;
10318     }
10319 
10320   if (warnfmt)
10321     {
10322       if (suggest)
10323 	warned = warning_at (loc, OPT_Wclass_memaccess,
10324 			     warnfmt, fndecl, desttype, suggest);
10325       else
10326 	warned = warning_at (loc, OPT_Wclass_memaccess,
10327 			     warnfmt, fndecl, desttype);
10328     }
10329 
10330   if (warned)
10331     inform (location_of (desttype), "%#qT declared here", desttype);
10332 }
10333 
10334 /* Build and return a call to FN, using NARGS arguments in ARGARRAY.
10335    If FN is the result of resolving an overloaded target built-in,
10336    ORIG_FNDECL is the original function decl, otherwise it is null.
10337    This function performs no overload resolution, conversion, or other
10338    high-level operations.  */
10339 
10340 tree
build_cxx_call(tree fn,int nargs,tree * argarray,tsubst_flags_t complain,tree orig_fndecl)10341 build_cxx_call (tree fn, int nargs, tree *argarray,
10342 		tsubst_flags_t complain, tree orig_fndecl)
10343 {
10344   tree fndecl;
10345 
10346   /* Remember roughly where this call is.  */
10347   location_t loc = cp_expr_loc_or_input_loc (fn);
10348   fn = build_call_a (fn, nargs, argarray);
10349   SET_EXPR_LOCATION (fn, loc);
10350 
10351   fndecl = get_callee_fndecl (fn);
10352   if (!orig_fndecl)
10353     orig_fndecl = fndecl;
10354 
10355   /* Check that arguments to builtin functions match the expectations.  */
10356   if (fndecl
10357       && !processing_template_decl
10358       && fndecl_built_in_p (fndecl))
10359     {
10360       int i;
10361 
10362       /* We need to take care that values to BUILT_IN_NORMAL
10363          are reduced.  */
10364       for (i = 0; i < nargs; i++)
10365 	argarray[i] = maybe_constant_value (argarray[i]);
10366 
10367       if (!check_builtin_function_arguments (EXPR_LOCATION (fn), vNULL, fndecl,
10368 					     orig_fndecl, nargs, argarray))
10369 	return error_mark_node;
10370     }
10371 
10372   if (VOID_TYPE_P (TREE_TYPE (fn)))
10373     return fn;
10374 
10375   /* 5.2.2/11: If a function call is a prvalue of object type: if the
10376      function call is either the operand of a decltype-specifier or the
10377      right operand of a comma operator that is the operand of a
10378      decltype-specifier, a temporary object is not introduced for the
10379      prvalue. The type of the prvalue may be incomplete.  */
10380   if (!(complain & tf_decltype))
10381     {
10382       fn = require_complete_type_sfinae (fn, complain);
10383       if (fn == error_mark_node)
10384 	return error_mark_node;
10385 
10386       if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
10387 	{
10388 	  fn = build_cplus_new (TREE_TYPE (fn), fn, complain);
10389 	  maybe_warn_parm_abi (TREE_TYPE (fn), loc);
10390 	}
10391     }
10392   return convert_from_reference (fn);
10393 }
10394 
10395 /* Returns the value to use for the in-charge parameter when making a
10396    call to a function with the indicated NAME.
10397 
10398    FIXME:Can't we find a neater way to do this mapping?  */
10399 
10400 tree
in_charge_arg_for_name(tree name)10401 in_charge_arg_for_name (tree name)
10402 {
10403   if (IDENTIFIER_CTOR_P (name))
10404     {
10405       if (name == complete_ctor_identifier)
10406 	return integer_one_node;
10407       gcc_checking_assert (name == base_ctor_identifier);
10408     }
10409   else
10410     {
10411       if (name == complete_dtor_identifier)
10412 	return integer_two_node;
10413       else if (name == deleting_dtor_identifier)
10414 	return integer_three_node;
10415       gcc_checking_assert (name == base_dtor_identifier);
10416     }
10417 
10418   return integer_zero_node;
10419 }
10420 
10421 /* We've built up a constructor call RET.  Complain if it delegates to the
10422    constructor we're currently compiling.  */
10423 
10424 static void
check_self_delegation(tree ret)10425 check_self_delegation (tree ret)
10426 {
10427   if (TREE_CODE (ret) == TARGET_EXPR)
10428     ret = TARGET_EXPR_INITIAL (ret);
10429   tree fn = cp_get_callee_fndecl_nofold (ret);
10430   if (fn && DECL_ABSTRACT_ORIGIN (fn) == current_function_decl)
10431     error ("constructor delegates to itself");
10432 }
10433 
10434 /* Build a call to a constructor, destructor, or an assignment
10435    operator for INSTANCE, an expression with class type.  NAME
10436    indicates the special member function to call; *ARGS are the
10437    arguments.  ARGS may be NULL.  This may change ARGS.  BINFO
10438    indicates the base of INSTANCE that is to be passed as the `this'
10439    parameter to the member function called.
10440 
10441    FLAGS are the LOOKUP_* flags to use when processing the call.
10442 
10443    If NAME indicates a complete object constructor, INSTANCE may be
10444    NULL_TREE.  In this case, the caller will call build_cplus_new to
10445    store the newly constructed object into a VAR_DECL.  */
10446 
10447 tree
build_special_member_call(tree instance,tree name,vec<tree,va_gc> ** args,tree binfo,int flags,tsubst_flags_t complain)10448 build_special_member_call (tree instance, tree name, vec<tree, va_gc> **args,
10449 			   tree binfo, int flags, tsubst_flags_t complain)
10450 {
10451   tree fns;
10452   /* The type of the subobject to be constructed or destroyed.  */
10453   tree class_type;
10454   vec<tree, va_gc> *allocated = NULL;
10455   tree ret;
10456 
10457   gcc_assert (IDENTIFIER_CDTOR_P (name) || name == assign_op_identifier);
10458 
10459   if (error_operand_p (instance))
10460     return error_mark_node;
10461 
10462   if (IDENTIFIER_DTOR_P (name))
10463     {
10464       gcc_assert (args == NULL || vec_safe_is_empty (*args));
10465       if (!type_build_dtor_call (TREE_TYPE (instance)))
10466 	/* Shortcut to avoid lazy destructor declaration.  */
10467 	return build_trivial_dtor_call (instance);
10468     }
10469 
10470   if (TYPE_P (binfo))
10471     {
10472       /* Resolve the name.  */
10473       if (!complete_type_or_maybe_complain (binfo, NULL_TREE, complain))
10474 	return error_mark_node;
10475 
10476       binfo = TYPE_BINFO (binfo);
10477     }
10478 
10479   gcc_assert (binfo != NULL_TREE);
10480 
10481   class_type = BINFO_TYPE (binfo);
10482 
10483   /* Handle the special case where INSTANCE is NULL_TREE.  */
10484   if (name == complete_ctor_identifier && !instance)
10485     instance = build_dummy_object (class_type);
10486   else
10487     {
10488       /* Convert to the base class, if necessary.  */
10489       if (!same_type_ignoring_top_level_qualifiers_p
10490 	  (TREE_TYPE (instance), BINFO_TYPE (binfo)))
10491 	{
10492 	  if (IDENTIFIER_CDTOR_P (name))
10493 	    /* For constructors and destructors, either the base is
10494 	       non-virtual, or it is virtual but we are doing the
10495 	       conversion from a constructor or destructor for the
10496 	       complete object.  In either case, we can convert
10497 	       statically.  */
10498 	    instance = convert_to_base_statically (instance, binfo);
10499 	  else
10500 	    {
10501 	      /* However, for assignment operators, we must convert
10502 		 dynamically if the base is virtual.  */
10503 	      gcc_checking_assert (name == assign_op_identifier);
10504 	      instance = build_base_path (PLUS_EXPR, instance,
10505 					  binfo, /*nonnull=*/1, complain);
10506 	    }
10507 	}
10508     }
10509 
10510   gcc_assert (instance != NULL_TREE);
10511 
10512   /* In C++17, "If the initializer expression is a prvalue and the
10513      cv-unqualified version of the source type is the same class as the class
10514      of the destination, the initializer expression is used to initialize the
10515      destination object."  Handle that here to avoid doing overload
10516      resolution.  */
10517   if (cxx_dialect >= cxx17
10518       && args && vec_safe_length (*args) == 1
10519       && !unsafe_return_slot_p (instance))
10520     {
10521       tree arg = (**args)[0];
10522 
10523       if (BRACE_ENCLOSED_INITIALIZER_P (arg)
10524 	  && !TYPE_HAS_LIST_CTOR (class_type)
10525 	  && !CONSTRUCTOR_IS_DESIGNATED_INIT (arg)
10526 	  && CONSTRUCTOR_NELTS (arg) == 1)
10527 	arg = CONSTRUCTOR_ELT (arg, 0)->value;
10528 
10529       if ((TREE_CODE (arg) == TARGET_EXPR
10530 	   || TREE_CODE (arg) == CONSTRUCTOR)
10531 	  && (same_type_ignoring_top_level_qualifiers_p
10532 	      (class_type, TREE_TYPE (arg))))
10533 	{
10534 	  if (is_dummy_object (instance))
10535 	    return arg;
10536 	  else if (TREE_CODE (arg) == TARGET_EXPR)
10537 	    TARGET_EXPR_DIRECT_INIT_P (arg) = true;
10538 
10539 	  if ((complain & tf_error)
10540 	      && (flags & LOOKUP_DELEGATING_CONS))
10541 	    check_self_delegation (arg);
10542 	  /* Avoid change of behavior on Wunused-var-2.C.  */
10543 	  instance = mark_lvalue_use (instance);
10544 	  return build2 (INIT_EXPR, class_type, instance, arg);
10545 	}
10546     }
10547 
10548   fns = lookup_fnfields (binfo, name, 1, complain);
10549 
10550   /* When making a call to a constructor or destructor for a subobject
10551      that uses virtual base classes, pass down a pointer to a VTT for
10552      the subobject.  */
10553   if ((name == base_ctor_identifier
10554        || name == base_dtor_identifier)
10555       && CLASSTYPE_VBASECLASSES (class_type))
10556     {
10557       tree vtt;
10558       tree sub_vtt;
10559 
10560       /* If the current function is a complete object constructor
10561 	 or destructor, then we fetch the VTT directly.
10562 	 Otherwise, we look it up using the VTT we were given.  */
10563       vtt = DECL_CHAIN (CLASSTYPE_VTABLES (current_class_type));
10564       vtt = decay_conversion (vtt, complain);
10565       if (vtt == error_mark_node)
10566 	return error_mark_node;
10567       vtt = build_if_in_charge (vtt, current_vtt_parm);
10568       if (BINFO_SUBVTT_INDEX (binfo))
10569 	sub_vtt = fold_build_pointer_plus (vtt, BINFO_SUBVTT_INDEX (binfo));
10570       else
10571 	sub_vtt = vtt;
10572 
10573       if (args == NULL)
10574 	{
10575 	  allocated = make_tree_vector ();
10576 	  args = &allocated;
10577 	}
10578 
10579       vec_safe_insert (*args, 0, sub_vtt);
10580     }
10581 
10582   ret = build_new_method_call (instance, fns, args,
10583 			       TYPE_BINFO (BINFO_TYPE (binfo)),
10584 			       flags, /*fn=*/NULL,
10585 			       complain);
10586 
10587   if (allocated != NULL)
10588     release_tree_vector (allocated);
10589 
10590   if ((complain & tf_error)
10591       && (flags & LOOKUP_DELEGATING_CONS)
10592       && name == complete_ctor_identifier)
10593     check_self_delegation (ret);
10594 
10595   return ret;
10596 }
10597 
10598 /* Return the NAME, as a C string.  The NAME indicates a function that
10599    is a member of TYPE.  *FREE_P is set to true if the caller must
10600    free the memory returned.
10601 
10602    Rather than go through all of this, we should simply set the names
10603    of constructors and destructors appropriately, and dispense with
10604    ctor_identifier, dtor_identifier, etc.  */
10605 
10606 static char *
name_as_c_string(tree name,tree type,bool * free_p)10607 name_as_c_string (tree name, tree type, bool *free_p)
10608 {
10609   const char *pretty_name;
10610 
10611   /* Assume that we will not allocate memory.  */
10612   *free_p = false;
10613   /* Constructors and destructors are special.  */
10614   if (IDENTIFIER_CDTOR_P (name))
10615     {
10616       pretty_name
10617 	= identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type)));
10618       /* For a destructor, add the '~'.  */
10619       if (IDENTIFIER_DTOR_P (name))
10620 	{
10621 	  pretty_name = concat ("~", pretty_name, NULL);
10622 	  /* Remember that we need to free the memory allocated.  */
10623 	  *free_p = true;
10624 	}
10625     }
10626   else if (IDENTIFIER_CONV_OP_P (name))
10627     {
10628       pretty_name = concat ("operator ",
10629 			    type_as_string_translate (TREE_TYPE (name),
10630 						      TFF_PLAIN_IDENTIFIER),
10631 			    NULL);
10632       /* Remember that we need to free the memory allocated.  */
10633       *free_p = true;
10634     }
10635   else
10636     pretty_name = identifier_to_locale (IDENTIFIER_POINTER (name));
10637 
10638   return CONST_CAST (char *, pretty_name);
10639 }
10640 
10641 /* If CANDIDATES contains exactly one candidate, return it, otherwise
10642    return NULL.  */
10643 
10644 static z_candidate *
single_z_candidate(z_candidate * candidates)10645 single_z_candidate (z_candidate *candidates)
10646 {
10647   if (candidates == NULL)
10648     return NULL;
10649 
10650   if (candidates->next)
10651     return NULL;
10652 
10653   return candidates;
10654 }
10655 
10656 /* If CANDIDATE is invalid due to a bad argument type, return the
10657    pertinent conversion_info.
10658 
10659    Otherwise, return NULL.  */
10660 
10661 static const conversion_info *
maybe_get_bad_conversion_for_unmatched_call(const z_candidate * candidate)10662 maybe_get_bad_conversion_for_unmatched_call (const z_candidate *candidate)
10663 {
10664   /* Must be an rr_arg_conversion or rr_bad_arg_conversion.  */
10665   rejection_reason *r = candidate->reason;
10666 
10667   if (r == NULL)
10668     return NULL;
10669 
10670   switch (r->code)
10671     {
10672     default:
10673       return NULL;
10674 
10675     case rr_arg_conversion:
10676       return &r->u.conversion;
10677 
10678     case rr_bad_arg_conversion:
10679       return &r->u.bad_conversion;
10680     }
10681 }
10682 
10683 /* Issue an error and note complaining about a bad argument type at a
10684    callsite with a single candidate FNDECL.
10685 
10686    ARG_LOC is the location of the argument (or UNKNOWN_LOCATION, in which
10687    case input_location is used).
10688    FROM_TYPE is the type of the actual argument; TO_TYPE is the type of
10689    the formal parameter.  */
10690 
10691 void
complain_about_bad_argument(location_t arg_loc,tree from_type,tree to_type,tree fndecl,int parmnum)10692 complain_about_bad_argument (location_t arg_loc,
10693 			     tree from_type, tree to_type,
10694 			     tree fndecl, int parmnum)
10695 {
10696   auto_diagnostic_group d;
10697   range_label_for_type_mismatch rhs_label (from_type, to_type);
10698   range_label *label = &rhs_label;
10699   if (arg_loc == UNKNOWN_LOCATION)
10700     {
10701       arg_loc = input_location;
10702       label = NULL;
10703     }
10704   gcc_rich_location richloc (arg_loc, label);
10705   error_at (&richloc,
10706 	    "cannot convert %qH to %qI",
10707 	    from_type, to_type);
10708   maybe_inform_about_fndecl_for_bogus_argument_init (fndecl,
10709 						     parmnum);
10710 }
10711 
10712 /* Subroutine of build_new_method_call_1, for where there are no viable
10713    candidates for the call.  */
10714 
10715 static void
complain_about_no_candidates_for_method_call(tree instance,z_candidate * candidates,tree explicit_targs,tree basetype,tree optype,tree name,bool skip_first_for_error,vec<tree,va_gc> * user_args)10716 complain_about_no_candidates_for_method_call (tree instance,
10717 					      z_candidate *candidates,
10718 					      tree explicit_targs,
10719 					      tree basetype,
10720 					      tree optype, tree name,
10721 					      bool skip_first_for_error,
10722 					      vec<tree, va_gc> *user_args)
10723 {
10724   auto_diagnostic_group d;
10725   if (!COMPLETE_OR_OPEN_TYPE_P (basetype))
10726     cxx_incomplete_type_error (instance, basetype);
10727   else if (optype)
10728     error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
10729 	   basetype, optype, build_tree_list_vec (user_args),
10730 	   TREE_TYPE (instance));
10731   else
10732     {
10733       /* Special-case for when there's a single candidate that's failing
10734 	 due to a bad argument type.  */
10735       if (z_candidate *candidate = single_z_candidate (candidates))
10736 	  if (const conversion_info *conv
10737 		= maybe_get_bad_conversion_for_unmatched_call (candidate))
10738 	    {
10739 	      tree from_type = conv->from;
10740 	      if (!TYPE_P (conv->from))
10741 		from_type = lvalue_type (conv->from);
10742 	      complain_about_bad_argument (conv->loc,
10743 					   from_type, conv->to_type,
10744 					   candidate->fn, conv->n_arg);
10745 	      return;
10746 	    }
10747 
10748       tree arglist = build_tree_list_vec (user_args);
10749       tree errname = name;
10750       bool twiddle = false;
10751       if (IDENTIFIER_CDTOR_P (errname))
10752 	{
10753 	  twiddle = IDENTIFIER_DTOR_P (errname);
10754 	  errname = constructor_name (basetype);
10755 	}
10756       if (explicit_targs)
10757 	errname = lookup_template_function (errname, explicit_targs);
10758       if (skip_first_for_error)
10759 	arglist = TREE_CHAIN (arglist);
10760       error ("no matching function for call to %<%T::%s%E(%A)%#V%>",
10761 	     basetype, &"~"[!twiddle], errname, arglist,
10762 	     TREE_TYPE (instance));
10763     }
10764   print_z_candidates (location_of (name), candidates);
10765 }
10766 
10767 /* Build a call to "INSTANCE.FN (ARGS)".  If FN_P is non-NULL, it will
10768    be set, upon return, to the function called.  ARGS may be NULL.
10769    This may change ARGS.  */
10770 
10771 tree
build_new_method_call(tree instance,tree fns,vec<tree,va_gc> ** args,tree conversion_path,int flags,tree * fn_p,tsubst_flags_t complain)10772 build_new_method_call (tree instance, tree fns, vec<tree, va_gc> **args,
10773 		       tree conversion_path, int flags,
10774 		       tree *fn_p, tsubst_flags_t complain)
10775 {
10776   struct z_candidate *candidates = 0, *cand;
10777   tree explicit_targs = NULL_TREE;
10778   tree basetype = NULL_TREE;
10779   tree access_binfo;
10780   tree optype;
10781   tree first_mem_arg = NULL_TREE;
10782   tree name;
10783   bool skip_first_for_error;
10784   vec<tree, va_gc> *user_args;
10785   tree call;
10786   tree fn;
10787   int template_only = 0;
10788   bool any_viable_p;
10789   tree orig_instance;
10790   tree orig_fns;
10791   vec<tree, va_gc> *orig_args = NULL;
10792   void *p;
10793 
10794   auto_cond_timevar tv (TV_OVERLOAD);
10795 
10796   gcc_assert (instance != NULL_TREE);
10797 
10798   /* We don't know what function we're going to call, yet.  */
10799   if (fn_p)
10800     *fn_p = NULL_TREE;
10801 
10802   if (error_operand_p (instance)
10803       || !fns || error_operand_p (fns))
10804     return error_mark_node;
10805 
10806   if (!BASELINK_P (fns))
10807     {
10808       if (complain & tf_error)
10809 	error ("call to non-function %qD", fns);
10810       return error_mark_node;
10811     }
10812 
10813   orig_instance = instance;
10814   orig_fns = fns;
10815 
10816   /* Dismantle the baselink to collect all the information we need.  */
10817   if (!conversion_path)
10818     conversion_path = BASELINK_BINFO (fns);
10819   access_binfo = BASELINK_ACCESS_BINFO (fns);
10820   optype = BASELINK_OPTYPE (fns);
10821   fns = BASELINK_FUNCTIONS (fns);
10822   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10823     {
10824       explicit_targs = TREE_OPERAND (fns, 1);
10825       fns = TREE_OPERAND (fns, 0);
10826       template_only = 1;
10827     }
10828   gcc_assert (OVL_P (fns));
10829   fn = OVL_FIRST (fns);
10830   name = DECL_NAME (fn);
10831 
10832   basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
10833   gcc_assert (CLASS_TYPE_P (basetype));
10834 
10835   user_args = args == NULL ? NULL : *args;
10836   /* Under DR 147 A::A() is an invalid constructor call,
10837      not a functional cast.  */
10838   if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
10839     {
10840       if (! (complain & tf_error))
10841 	return error_mark_node;
10842 
10843       basetype = DECL_CONTEXT (fn);
10844       name = constructor_name (basetype);
10845       auto_diagnostic_group d;
10846       if (permerror (input_location,
10847 		     "cannot call constructor %<%T::%D%> directly",
10848 		     basetype, name))
10849 	inform (input_location, "for a function-style cast, remove the "
10850 		"redundant %<::%D%>", name);
10851       call = build_functional_cast (input_location, basetype,
10852 				    build_tree_list_vec (user_args),
10853 				    complain);
10854       return call;
10855     }
10856 
10857   if (processing_template_decl)
10858     {
10859       orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
10860       instance = build_non_dependent_expr (instance);
10861       if (args != NULL)
10862 	make_args_non_dependent (*args);
10863     }
10864 
10865   /* Process the argument list.  */
10866   if (args != NULL && *args != NULL)
10867     {
10868       *args = resolve_args (*args, complain);
10869       if (*args == NULL)
10870 	return error_mark_node;
10871       user_args = *args;
10872     }
10873 
10874   /* Consider the object argument to be used even if we end up selecting a
10875      static member function.  */
10876   instance = mark_type_use (instance);
10877 
10878   /* Figure out whether to skip the first argument for the error
10879      message we will display to users if an error occurs.  We don't
10880      want to display any compiler-generated arguments.  The "this"
10881      pointer hasn't been added yet.  However, we must remove the VTT
10882      pointer if this is a call to a base-class constructor or
10883      destructor.  */
10884   skip_first_for_error = false;
10885   if (IDENTIFIER_CDTOR_P (name))
10886     {
10887       /* Callers should explicitly indicate whether they want to ctor
10888 	 the complete object or just the part without virtual bases.  */
10889       gcc_assert (name != ctor_identifier);
10890 
10891       /* Remove the VTT pointer, if present.  */
10892       if ((name == base_ctor_identifier || name == base_dtor_identifier)
10893 	  && CLASSTYPE_VBASECLASSES (basetype))
10894 	skip_first_for_error = true;
10895 
10896       /* It's OK to call destructors and constructors on cv-qualified
10897 	 objects.  Therefore, convert the INSTANCE to the unqualified
10898 	 type, if necessary.  */
10899       if (!same_type_p (basetype, TREE_TYPE (instance)))
10900 	{
10901 	  instance = build_this (instance);
10902 	  instance = build_nop (build_pointer_type (basetype), instance);
10903 	  instance = build_fold_indirect_ref (instance);
10904 	}
10905     }
10906   else
10907     gcc_assert (!DECL_DESTRUCTOR_P (fn) && !DECL_CONSTRUCTOR_P (fn));
10908 
10909   /* For the overload resolution we need to find the actual `this`
10910      that would be captured if the call turns out to be to a
10911      non-static member function.  Do not actually capture it at this
10912      point.  */
10913   if (DECL_CONSTRUCTOR_P (fn))
10914     /* Constructors don't use the enclosing 'this'.  */
10915     first_mem_arg = instance;
10916   else
10917     first_mem_arg = maybe_resolve_dummy (instance, false);
10918 
10919   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
10920   p = conversion_obstack_alloc (0);
10921 
10922   /* The number of arguments artificial parms in ARGS; we subtract one because
10923      there's no 'this' in ARGS.  */
10924   unsigned skip = num_artificial_parms_for (fn) - 1;
10925 
10926   /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
10927      initializer, not T({ }).  */
10928   if (DECL_CONSTRUCTOR_P (fn)
10929       && vec_safe_length (user_args) > skip
10930       && DIRECT_LIST_INIT_P ((*user_args)[skip]))
10931     {
10932       tree init_list = (*user_args)[skip];
10933       tree init = NULL_TREE;
10934 
10935       gcc_assert (user_args->length () == skip + 1
10936 		  && !(flags & LOOKUP_ONLYCONVERTING));
10937 
10938       /* If the initializer list has no elements and T is a class type with
10939 	 a default constructor, the object is value-initialized.  Handle
10940 	 this here so we don't need to handle it wherever we use
10941 	 build_special_member_call.  */
10942       if (CONSTRUCTOR_NELTS (init_list) == 0
10943 	  && TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
10944 	  /* For a user-provided default constructor, use the normal
10945 	     mechanisms so that protected access works.  */
10946 	  && type_has_non_user_provided_default_constructor (basetype)
10947 	  && !processing_template_decl)
10948 	init = build_value_init (basetype, complain);
10949 
10950       /* If BASETYPE is an aggregate, we need to do aggregate
10951 	 initialization.  */
10952       else if (CP_AGGREGATE_TYPE_P (basetype))
10953 	{
10954 	  init = reshape_init (basetype, init_list, complain);
10955 	  init = digest_init (basetype, init, complain);
10956 	}
10957 
10958       if (init)
10959 	{
10960 	  if (is_dummy_object (instance))
10961 	    return get_target_expr_sfinae (init, complain);
10962 	  init = build2 (INIT_EXPR, TREE_TYPE (instance), instance, init);
10963 	  TREE_SIDE_EFFECTS (init) = true;
10964 	  return init;
10965 	}
10966 
10967       /* Otherwise go ahead with overload resolution.  */
10968       add_list_candidates (fns, first_mem_arg, user_args,
10969 			   basetype, explicit_targs, template_only,
10970 			   conversion_path, access_binfo, flags,
10971 			   &candidates, complain);
10972     }
10973   else
10974     add_candidates (fns, first_mem_arg, user_args, optype,
10975 		    explicit_targs, template_only, conversion_path,
10976 		    access_binfo, flags, &candidates, complain);
10977 
10978   any_viable_p = false;
10979   candidates = splice_viable (candidates, false, &any_viable_p);
10980 
10981   if (!any_viable_p)
10982     {
10983       /* [dcl.init], 17.6.2.2:
10984 
10985 	 Otherwise, if no constructor is viable, the destination type is
10986 	 a (possibly cv-qualified) aggregate class A, and the initializer
10987 	 is a parenthesized expression-list, the object is initialized as
10988 	 follows...
10989 
10990 	 We achieve this by building up a CONSTRUCTOR, as for list-init,
10991 	 and setting CONSTRUCTOR_IS_PAREN_INIT to distinguish between
10992 	 the two.  */
10993       if (DECL_CONSTRUCTOR_P (fn)
10994 	  && !(flags & LOOKUP_ONLYCONVERTING)
10995 	  && cxx_dialect >= cxx20
10996 	  && CP_AGGREGATE_TYPE_P (basetype)
10997 	  && !vec_safe_is_empty (user_args))
10998 	{
10999 	  /* Create a CONSTRUCTOR from ARGS, e.g. {1, 2} from <1, 2>.  */
11000 	  tree ctor = build_constructor_from_vec (init_list_type_node,
11001 						  user_args);
11002 	  CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
11003 	  CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
11004 	  if (is_dummy_object (instance))
11005 	    return ctor;
11006 	  else
11007 	    {
11008 	      ctor = digest_init (basetype, ctor, complain);
11009 	      if (ctor == error_mark_node)
11010 		return error_mark_node;
11011 	      ctor = build2 (INIT_EXPR, TREE_TYPE (instance), instance, ctor);
11012 	      TREE_SIDE_EFFECTS (ctor) = true;
11013 	      return ctor;
11014 	    }
11015 	}
11016       if (complain & tf_error)
11017 	complain_about_no_candidates_for_method_call (instance, candidates,
11018 						      explicit_targs, basetype,
11019 						      optype, name,
11020 						      skip_first_for_error,
11021 						      user_args);
11022       call = error_mark_node;
11023     }
11024   else
11025     {
11026       cand = tourney (candidates, complain);
11027       if (cand == 0)
11028 	{
11029 	  char *pretty_name;
11030 	  bool free_p;
11031 	  tree arglist;
11032 
11033 	  if (complain & tf_error)
11034 	    {
11035 	      pretty_name = name_as_c_string (name, basetype, &free_p);
11036 	      arglist = build_tree_list_vec (user_args);
11037 	      if (skip_first_for_error)
11038 		arglist = TREE_CHAIN (arglist);
11039 	      auto_diagnostic_group d;
11040 	      if (!any_strictly_viable (candidates))
11041 		error ("no matching function for call to %<%s(%A)%>",
11042 		       pretty_name, arglist);
11043 	      else
11044 		error ("call of overloaded %<%s(%A)%> is ambiguous",
11045 		       pretty_name, arglist);
11046 	      print_z_candidates (location_of (name), candidates);
11047 	      if (free_p)
11048 		free (pretty_name);
11049 	    }
11050 	  call = error_mark_node;
11051 	  if (fn_p)
11052 	    *fn_p = error_mark_node;
11053 	}
11054       else
11055 	{
11056 	  fn = cand->fn;
11057 	  call = NULL_TREE;
11058 
11059 	  if (!(flags & LOOKUP_NONVIRTUAL)
11060 	      && DECL_PURE_VIRTUAL_P (fn)
11061 	      && instance == current_class_ref
11062 	      && (complain & tf_warning))
11063 	    {
11064 	      /* This is not an error, it is runtime undefined
11065 		 behavior.  */
11066 	      if (!current_function_decl)
11067 		warning (0, "pure virtual %q#D called from "
11068 			 "non-static data member initializer", fn);
11069 	      else if (DECL_CONSTRUCTOR_P (current_function_decl)
11070 		       || DECL_DESTRUCTOR_P (current_function_decl))
11071 		warning (0, (DECL_CONSTRUCTOR_P (current_function_decl)
11072 			     ? G_("pure virtual %q#D called from constructor")
11073 			     : G_("pure virtual %q#D called from destructor")),
11074 			 fn);
11075 	    }
11076 
11077 	  if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
11078 	      && !DECL_CONSTRUCTOR_P (fn)
11079 	      && is_dummy_object (instance))
11080 	    {
11081 	      instance = maybe_resolve_dummy (instance, true);
11082 	      if (instance == error_mark_node)
11083 		call = error_mark_node;
11084 	      else if (!is_dummy_object (instance))
11085 		{
11086 		  /* We captured 'this' in the current lambda now that
11087 		     we know we really need it.  */
11088 		  cand->first_arg = instance;
11089 		}
11090 	      else if (any_dependent_bases_p ())
11091 		/* We can't tell until instantiation time whether we can use
11092 		   *this as the implicit object argument.  */;
11093 	      else
11094 		{
11095 		  if (complain & tf_error)
11096 		    error ("cannot call member function %qD without object",
11097 			   fn);
11098 		  call = error_mark_node;
11099 		}
11100 	    }
11101 
11102 	  if (call != error_mark_node)
11103 	    {
11104 	      /* Now we know what function is being called.  */
11105 	      if (fn_p)
11106 		*fn_p = fn;
11107 	      /* Build the actual CALL_EXPR.  */
11108 	      call = build_over_call (cand, flags, complain);
11109 	      /* In an expression of the form `a->f()' where `f' turns
11110 		 out to be a static member function, `a' is
11111 		 none-the-less evaluated.  */
11112 	      if (TREE_CODE (TREE_TYPE (fn)) != METHOD_TYPE
11113 		  && !is_dummy_object (instance)
11114 		  && TREE_SIDE_EFFECTS (instance))
11115 		{
11116 		  /* But avoid the implicit lvalue-rvalue conversion when 'a'
11117 		     is volatile.  */
11118 		  tree a = instance;
11119 		  if (TREE_THIS_VOLATILE (a))
11120 		    a = build_this (a);
11121 		  if (TREE_SIDE_EFFECTS (a))
11122 		    call = build2 (COMPOUND_EXPR, TREE_TYPE (call), a, call);
11123 		}
11124 	      else if (call != error_mark_node
11125 		       && DECL_DESTRUCTOR_P (cand->fn)
11126 		       && !VOID_TYPE_P (TREE_TYPE (call)))
11127 		/* An explicit call of the form "x->~X()" has type
11128 		   "void".  However, on platforms where destructors
11129 		   return "this" (i.e., those where
11130 		   targetm.cxx.cdtor_returns_this is true), such calls
11131 		   will appear to have a return value of pointer type
11132 		   to the low-level call machinery.  We do not want to
11133 		   change the low-level machinery, since we want to be
11134 		   able to optimize "delete f()" on such platforms as
11135 		   "operator delete(~X(f()))" (rather than generating
11136 		   "t = f(), ~X(t), operator delete (t)").  */
11137 		call = build_nop (void_type_node, call);
11138 	    }
11139 	}
11140     }
11141 
11142   if (processing_template_decl && call != error_mark_node)
11143     {
11144       bool cast_to_void = false;
11145 
11146       if (TREE_CODE (call) == COMPOUND_EXPR)
11147 	call = TREE_OPERAND (call, 1);
11148       else if (TREE_CODE (call) == NOP_EXPR)
11149 	{
11150 	  cast_to_void = true;
11151 	  call = TREE_OPERAND (call, 0);
11152 	}
11153       if (INDIRECT_REF_P (call))
11154 	call = TREE_OPERAND (call, 0);
11155       call = (build_min_non_dep_call_vec
11156 	      (call,
11157 	       build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
11158 			  orig_instance, orig_fns, NULL_TREE),
11159 	       orig_args));
11160       SET_EXPR_LOCATION (call, input_location);
11161       call = convert_from_reference (call);
11162       if (cast_to_void)
11163 	call = build_nop (void_type_node, call);
11164     }
11165 
11166  /* Free all the conversions we allocated.  */
11167   obstack_free (&conversion_obstack, p);
11168 
11169   if (orig_args != NULL)
11170     release_tree_vector (orig_args);
11171 
11172   return call;
11173 }
11174 
11175 /* Returns true iff standard conversion sequence ICS1 is a proper
11176    subsequence of ICS2.  */
11177 
11178 static bool
is_subseq(conversion * ics1,conversion * ics2)11179 is_subseq (conversion *ics1, conversion *ics2)
11180 {
11181   /* We can assume that a conversion of the same code
11182      between the same types indicates a subsequence since we only get
11183      here if the types we are converting from are the same.  */
11184 
11185   while (ics1->kind == ck_rvalue
11186 	 || ics1->kind == ck_lvalue)
11187     ics1 = next_conversion (ics1);
11188 
11189   while (1)
11190     {
11191       while (ics2->kind == ck_rvalue
11192 	     || ics2->kind == ck_lvalue)
11193 	ics2 = next_conversion (ics2);
11194 
11195       if (ics2->kind == ck_user
11196 	  || !has_next (ics2->kind))
11197 	/* At this point, ICS1 cannot be a proper subsequence of
11198 	   ICS2.  We can get a USER_CONV when we are comparing the
11199 	   second standard conversion sequence of two user conversion
11200 	   sequences.  */
11201 	return false;
11202 
11203       ics2 = next_conversion (ics2);
11204 
11205       while (ics2->kind == ck_rvalue
11206 	     || ics2->kind == ck_lvalue)
11207 	ics2 = next_conversion (ics2);
11208 
11209       if (ics2->kind == ics1->kind
11210 	  && same_type_p (ics2->type, ics1->type)
11211 	  && (ics1->kind == ck_identity
11212 	      || same_type_p (next_conversion (ics2)->type,
11213 			      next_conversion (ics1)->type)))
11214 	return true;
11215     }
11216 }
11217 
11218 /* Returns nonzero iff DERIVED is derived from BASE.  The inputs may
11219    be any _TYPE nodes.  */
11220 
11221 bool
is_properly_derived_from(tree derived,tree base)11222 is_properly_derived_from (tree derived, tree base)
11223 {
11224   if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
11225     return false;
11226 
11227   /* We only allow proper derivation here.  The DERIVED_FROM_P macro
11228      considers every class derived from itself.  */
11229   return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
11230 	  && DERIVED_FROM_P (base, derived));
11231 }
11232 
11233 /* We build the ICS for an implicit object parameter as a pointer
11234    conversion sequence.  However, such a sequence should be compared
11235    as if it were a reference conversion sequence.  If ICS is the
11236    implicit conversion sequence for an implicit object parameter,
11237    modify it accordingly.  */
11238 
11239 static void
maybe_handle_implicit_object(conversion ** ics)11240 maybe_handle_implicit_object (conversion **ics)
11241 {
11242   if ((*ics)->this_p)
11243     {
11244       /* [over.match.funcs]
11245 
11246 	 For non-static member functions, the type of the
11247 	 implicit object parameter is "reference to cv X"
11248 	 where X is the class of which the function is a
11249 	 member and cv is the cv-qualification on the member
11250 	 function declaration.  */
11251       conversion *t = *ics;
11252       tree reference_type;
11253 
11254       /* The `this' parameter is a pointer to a class type.  Make the
11255 	 implicit conversion talk about a reference to that same class
11256 	 type.  */
11257       reference_type = TREE_TYPE (t->type);
11258       reference_type = build_reference_type (reference_type);
11259 
11260       if (t->kind == ck_qual)
11261 	t = next_conversion (t);
11262       if (t->kind == ck_ptr)
11263 	t = next_conversion (t);
11264       t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
11265       t = direct_reference_binding (reference_type, t);
11266       t->this_p = 1;
11267       t->rvaluedness_matches_p = 0;
11268       *ics = t;
11269     }
11270 }
11271 
11272 /* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
11273    and return the initial reference binding conversion. Otherwise,
11274    leave *ICS unchanged and return NULL.  */
11275 
11276 static conversion *
maybe_handle_ref_bind(conversion ** ics)11277 maybe_handle_ref_bind (conversion **ics)
11278 {
11279   if ((*ics)->kind == ck_ref_bind)
11280     {
11281       conversion *old_ics = *ics;
11282       *ics = next_conversion (old_ics);
11283       (*ics)->user_conv_p = old_ics->user_conv_p;
11284       return old_ics;
11285     }
11286 
11287   return NULL;
11288 }
11289 
11290 /* Get the expression at the beginning of the conversion chain C.  */
11291 
11292 static tree
conv_get_original_expr(conversion * c)11293 conv_get_original_expr (conversion *c)
11294 {
11295   for (; c; c = next_conversion (c))
11296     if (c->kind == ck_identity || c->kind == ck_ambig || c->kind == ck_aggr)
11297       return c->u.expr;
11298   return NULL_TREE;
11299 }
11300 
11301 /* Return a tree representing the number of elements initialized by the
11302    list-initialization C.  The caller must check that C converts to an
11303    array type.  */
11304 
11305 static tree
nelts_initialized_by_list_init(conversion * c)11306 nelts_initialized_by_list_init (conversion *c)
11307 {
11308   /* If the array we're converting to has a dimension, we'll use that.  */
11309   if (TYPE_DOMAIN (c->type))
11310     return array_type_nelts_top (c->type);
11311   else
11312     {
11313       /* Otherwise, we look at how many elements the constructor we're
11314 	 initializing from has.  */
11315       tree ctor = conv_get_original_expr (c);
11316       return size_int (CONSTRUCTOR_NELTS (ctor));
11317     }
11318 }
11319 
11320 /* True iff C is a conversion that binds a reference or a pointer to
11321    an array of unknown bound.  */
11322 
11323 static inline bool
conv_binds_to_array_of_unknown_bound(conversion * c)11324 conv_binds_to_array_of_unknown_bound (conversion *c)
11325 {
11326   /* ck_ref_bind won't have the reference stripped.  */
11327   tree type = non_reference (c->type);
11328   /* ck_qual won't have the pointer stripped.  */
11329   type = strip_pointer_operator (type);
11330   return (TREE_CODE (type) == ARRAY_TYPE
11331 	  && TYPE_DOMAIN (type) == NULL_TREE);
11332 }
11333 
11334 /* Compare two implicit conversion sequences according to the rules set out in
11335    [over.ics.rank].  Return values:
11336 
11337       1: ics1 is better than ics2
11338      -1: ics2 is better than ics1
11339       0: ics1 and ics2 are indistinguishable */
11340 
11341 static int
compare_ics(conversion * ics1,conversion * ics2)11342 compare_ics (conversion *ics1, conversion *ics2)
11343 {
11344   tree from_type1;
11345   tree from_type2;
11346   tree to_type1;
11347   tree to_type2;
11348   tree deref_from_type1 = NULL_TREE;
11349   tree deref_from_type2 = NULL_TREE;
11350   tree deref_to_type1 = NULL_TREE;
11351   tree deref_to_type2 = NULL_TREE;
11352   conversion_rank rank1, rank2;
11353 
11354   /* REF_BINDING is nonzero if the result of the conversion sequence
11355      is a reference type.   In that case REF_CONV is the reference
11356      binding conversion. */
11357   conversion *ref_conv1;
11358   conversion *ref_conv2;
11359 
11360   /* Compare badness before stripping the reference conversion.  */
11361   if (ics1->bad_p > ics2->bad_p)
11362     return -1;
11363   else if (ics1->bad_p < ics2->bad_p)
11364     return 1;
11365 
11366   /* Handle implicit object parameters.  */
11367   maybe_handle_implicit_object (&ics1);
11368   maybe_handle_implicit_object (&ics2);
11369 
11370   /* Handle reference parameters.  */
11371   ref_conv1 = maybe_handle_ref_bind (&ics1);
11372   ref_conv2 = maybe_handle_ref_bind (&ics2);
11373 
11374   /* List-initialization sequence L1 is a better conversion sequence than
11375      list-initialization sequence L2 if L1 converts to
11376      std::initializer_list<X> for some X and L2 does not.  */
11377   if (ics1->kind == ck_list && ics2->kind != ck_list)
11378     return 1;
11379   if (ics2->kind == ck_list && ics1->kind != ck_list)
11380     return -1;
11381 
11382   /* [over.ics.rank]
11383 
11384      When  comparing  the  basic forms of implicit conversion sequences (as
11385      defined in _over.best.ics_)
11386 
11387      --a standard conversion sequence (_over.ics.scs_) is a better
11388        conversion sequence than a user-defined conversion sequence
11389        or an ellipsis conversion sequence, and
11390 
11391      --a user-defined conversion sequence (_over.ics.user_) is a
11392        better conversion sequence than an ellipsis conversion sequence
11393        (_over.ics.ellipsis_).  */
11394   /* Use BAD_CONVERSION_RANK because we already checked for a badness
11395      mismatch.  If both ICS are bad, we try to make a decision based on
11396      what would have happened if they'd been good.  This is not an
11397      extension, we'll still give an error when we build up the call; this
11398      just helps us give a more helpful error message.  */
11399   rank1 = BAD_CONVERSION_RANK (ics1);
11400   rank2 = BAD_CONVERSION_RANK (ics2);
11401 
11402   if (rank1 > rank2)
11403     return -1;
11404   else if (rank1 < rank2)
11405     return 1;
11406 
11407   if (ics1->ellipsis_p)
11408     /* Both conversions are ellipsis conversions.  */
11409     return 0;
11410 
11411   /* User-defined  conversion sequence U1 is a better conversion sequence
11412      than another user-defined conversion sequence U2 if they contain the
11413      same user-defined conversion operator or constructor and if the sec-
11414      ond standard conversion sequence of U1 is  better  than  the  second
11415      standard conversion sequence of U2.  */
11416 
11417   /* Handle list-conversion with the same code even though it isn't always
11418      ranked as a user-defined conversion and it doesn't have a second
11419      standard conversion sequence; it will still have the desired effect.
11420      Specifically, we need to do the reference binding comparison at the
11421      end of this function.  */
11422 
11423   if (ics1->user_conv_p || ics1->kind == ck_list
11424       || ics1->kind == ck_aggr || ics2->kind == ck_aggr)
11425     {
11426       conversion *t1 = strip_standard_conversion (ics1);
11427       conversion *t2 = strip_standard_conversion (ics2);
11428 
11429       if (!t1 || !t2 || t1->kind != t2->kind)
11430 	return 0;
11431       else if (t1->kind == ck_user)
11432 	{
11433 	  tree f1 = t1->cand ? t1->cand->fn : t1->type;
11434 	  tree f2 = t2->cand ? t2->cand->fn : t2->type;
11435 	  if (f1 != f2)
11436 	    return 0;
11437 	}
11438       /* List-initialization sequence L1 is a better conversion sequence than
11439 	 list-initialization sequence L2 if
11440 
11441 	 -- L1 and L2 convert to arrays of the same element type, and either
11442 	 the number of elements n1 initialized by L1 is less than the number
11443 	 of elements n2 initialized by L2, or n1=n2 and L2 converts to an array
11444 	 of unknown bound and L1 does not.  (Added in CWG 1307 and extended by
11445 	 P0388R4.)  */
11446       else if (t1->kind == ck_aggr
11447 	       && TREE_CODE (t1->type) == ARRAY_TYPE
11448 	       && TREE_CODE (t2->type) == ARRAY_TYPE)
11449 	{
11450 	  /* The type of the array elements must be the same.  */
11451 	  if (!same_type_p (TREE_TYPE (t1->type), TREE_TYPE (t2->type)))
11452 	    return 0;
11453 
11454 	  tree n1 = nelts_initialized_by_list_init (t1);
11455 	  tree n2 = nelts_initialized_by_list_init (t2);
11456 	  if (tree_int_cst_lt (n1, n2))
11457 	    return 1;
11458 	  else if (tree_int_cst_lt (n2, n1))
11459 	    return -1;
11460 	  /* The n1 == n2 case.  */
11461 	  bool c1 = conv_binds_to_array_of_unknown_bound (t1);
11462 	  bool c2 = conv_binds_to_array_of_unknown_bound (t2);
11463 	  if (c1 && !c2)
11464 	    return -1;
11465 	  else if (!c1 && c2)
11466 	    return 1;
11467 	  else
11468 	    return 0;
11469 	}
11470       else
11471 	{
11472 	  /* For ambiguous or aggregate conversions, use the target type as
11473 	     a proxy for the conversion function.  */
11474 	  if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
11475 	    return 0;
11476 	}
11477 
11478       /* We can just fall through here, after setting up
11479 	 FROM_TYPE1 and FROM_TYPE2.  */
11480       from_type1 = t1->type;
11481       from_type2 = t2->type;
11482     }
11483   else
11484     {
11485       conversion *t1;
11486       conversion *t2;
11487 
11488       /* We're dealing with two standard conversion sequences.
11489 
11490 	 [over.ics.rank]
11491 
11492 	 Standard conversion sequence S1 is a better conversion
11493 	 sequence than standard conversion sequence S2 if
11494 
11495 	 --S1 is a proper subsequence of S2 (comparing the conversion
11496 	   sequences in the canonical form defined by _over.ics.scs_,
11497 	   excluding any Lvalue Transformation; the identity
11498 	   conversion sequence is considered to be a subsequence of
11499 	   any non-identity conversion sequence */
11500 
11501       t1 = ics1;
11502       while (t1->kind != ck_identity)
11503 	t1 = next_conversion (t1);
11504       from_type1 = t1->type;
11505 
11506       t2 = ics2;
11507       while (t2->kind != ck_identity)
11508 	t2 = next_conversion (t2);
11509       from_type2 = t2->type;
11510     }
11511 
11512   /* One sequence can only be a subsequence of the other if they start with
11513      the same type.  They can start with different types when comparing the
11514      second standard conversion sequence in two user-defined conversion
11515      sequences.  */
11516   if (same_type_p (from_type1, from_type2))
11517     {
11518       if (is_subseq (ics1, ics2))
11519 	return 1;
11520       if (is_subseq (ics2, ics1))
11521 	return -1;
11522     }
11523 
11524   /* [over.ics.rank]
11525 
11526      Or, if not that,
11527 
11528      --the rank of S1 is better than the rank of S2 (by the rules
11529        defined below):
11530 
11531     Standard conversion sequences are ordered by their ranks: an Exact
11532     Match is a better conversion than a Promotion, which is a better
11533     conversion than a Conversion.
11534 
11535     Two conversion sequences with the same rank are indistinguishable
11536     unless one of the following rules applies:
11537 
11538     --A conversion that does not a convert a pointer, pointer to member,
11539       or std::nullptr_t to bool is better than one that does.
11540 
11541     The ICS_STD_RANK automatically handles the pointer-to-bool rule,
11542     so that we do not have to check it explicitly.  */
11543   if (ics1->rank < ics2->rank)
11544     return 1;
11545   else if (ics2->rank < ics1->rank)
11546     return -1;
11547 
11548   to_type1 = ics1->type;
11549   to_type2 = ics2->type;
11550 
11551   /* A conversion from scalar arithmetic type to complex is worse than a
11552      conversion between scalar arithmetic types.  */
11553   if (same_type_p (from_type1, from_type2)
11554       && ARITHMETIC_TYPE_P (from_type1)
11555       && ARITHMETIC_TYPE_P (to_type1)
11556       && ARITHMETIC_TYPE_P (to_type2)
11557       && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
11558 	  != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
11559     {
11560       if (TREE_CODE (to_type1) == COMPLEX_TYPE)
11561 	return -1;
11562       else
11563 	return 1;
11564     }
11565 
11566   if (TYPE_PTR_P (from_type1)
11567       && TYPE_PTR_P (from_type2)
11568       && TYPE_PTR_P (to_type1)
11569       && TYPE_PTR_P (to_type2))
11570     {
11571       deref_from_type1 = TREE_TYPE (from_type1);
11572       deref_from_type2 = TREE_TYPE (from_type2);
11573       deref_to_type1 = TREE_TYPE (to_type1);
11574       deref_to_type2 = TREE_TYPE (to_type2);
11575     }
11576   /* The rules for pointers to members A::* are just like the rules
11577      for pointers A*, except opposite: if B is derived from A then
11578      A::* converts to B::*, not vice versa.  For that reason, we
11579      switch the from_ and to_ variables here.  */
11580   else if ((TYPE_PTRDATAMEM_P (from_type1) && TYPE_PTRDATAMEM_P (from_type2)
11581 	    && TYPE_PTRDATAMEM_P (to_type1) && TYPE_PTRDATAMEM_P (to_type2))
11582 	   || (TYPE_PTRMEMFUNC_P (from_type1)
11583 	       && TYPE_PTRMEMFUNC_P (from_type2)
11584 	       && TYPE_PTRMEMFUNC_P (to_type1)
11585 	       && TYPE_PTRMEMFUNC_P (to_type2)))
11586     {
11587       deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
11588       deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
11589       deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
11590       deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
11591     }
11592 
11593   if (deref_from_type1 != NULL_TREE
11594       && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
11595       && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
11596     {
11597       /* This was one of the pointer or pointer-like conversions.
11598 
11599 	 [over.ics.rank]
11600 
11601 	 --If class B is derived directly or indirectly from class A,
11602 	   conversion of B* to A* is better than conversion of B* to
11603 	   void*, and conversion of A* to void* is better than
11604 	   conversion of B* to void*.  */
11605       if (VOID_TYPE_P (deref_to_type1)
11606 	  && VOID_TYPE_P (deref_to_type2))
11607 	{
11608 	  if (is_properly_derived_from (deref_from_type1,
11609 					deref_from_type2))
11610 	    return -1;
11611 	  else if (is_properly_derived_from (deref_from_type2,
11612 					     deref_from_type1))
11613 	    return 1;
11614 	}
11615       else if (VOID_TYPE_P (deref_to_type1)
11616 	       || VOID_TYPE_P (deref_to_type2))
11617 	{
11618 	  if (same_type_p (deref_from_type1, deref_from_type2))
11619 	    {
11620 	      if (VOID_TYPE_P (deref_to_type2))
11621 		{
11622 		  if (is_properly_derived_from (deref_from_type1,
11623 						deref_to_type1))
11624 		    return 1;
11625 		}
11626 	      /* We know that DEREF_TO_TYPE1 is `void' here.  */
11627 	      else if (is_properly_derived_from (deref_from_type1,
11628 						 deref_to_type2))
11629 		return -1;
11630 	    }
11631 	}
11632       else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
11633 	       && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
11634 	{
11635 	  /* [over.ics.rank]
11636 
11637 	     --If class B is derived directly or indirectly from class A
11638 	       and class C is derived directly or indirectly from B,
11639 
11640 	     --conversion of C* to B* is better than conversion of C* to
11641 	       A*,
11642 
11643 	     --conversion of B* to A* is better than conversion of C* to
11644 	       A*  */
11645 	  if (same_type_p (deref_from_type1, deref_from_type2))
11646 	    {
11647 	      if (is_properly_derived_from (deref_to_type1,
11648 					    deref_to_type2))
11649 		return 1;
11650 	      else if (is_properly_derived_from (deref_to_type2,
11651 						 deref_to_type1))
11652 		return -1;
11653 	    }
11654 	  else if (same_type_p (deref_to_type1, deref_to_type2))
11655 	    {
11656 	      if (is_properly_derived_from (deref_from_type2,
11657 					    deref_from_type1))
11658 		return 1;
11659 	      else if (is_properly_derived_from (deref_from_type1,
11660 						 deref_from_type2))
11661 		return -1;
11662 	    }
11663 	}
11664     }
11665   else if (CLASS_TYPE_P (non_reference (from_type1))
11666 	   && same_type_p (from_type1, from_type2))
11667     {
11668       tree from = non_reference (from_type1);
11669 
11670       /* [over.ics.rank]
11671 
11672 	 --binding of an expression of type C to a reference of type
11673 	   B& is better than binding an expression of type C to a
11674 	   reference of type A&
11675 
11676 	 --conversion of C to B is better than conversion of C to A,  */
11677       if (is_properly_derived_from (from, to_type1)
11678 	  && is_properly_derived_from (from, to_type2))
11679 	{
11680 	  if (is_properly_derived_from (to_type1, to_type2))
11681 	    return 1;
11682 	  else if (is_properly_derived_from (to_type2, to_type1))
11683 	    return -1;
11684 	}
11685     }
11686   else if (CLASS_TYPE_P (non_reference (to_type1))
11687 	   && same_type_p (to_type1, to_type2))
11688     {
11689       tree to = non_reference (to_type1);
11690 
11691       /* [over.ics.rank]
11692 
11693 	 --binding of an expression of type B to a reference of type
11694 	   A& is better than binding an expression of type C to a
11695 	   reference of type A&,
11696 
11697 	 --conversion of B to A is better than conversion of C to A  */
11698       if (is_properly_derived_from (from_type1, to)
11699 	  && is_properly_derived_from (from_type2, to))
11700 	{
11701 	  if (is_properly_derived_from (from_type2, from_type1))
11702 	    return 1;
11703 	  else if (is_properly_derived_from (from_type1, from_type2))
11704 	    return -1;
11705 	}
11706     }
11707 
11708   /* [over.ics.rank]
11709 
11710      --S1 and S2 differ only in their qualification conversion and  yield
11711        similar  types  T1 and T2 (_conv.qual_), respectively, and the cv-
11712        qualification signature of type T1 is a proper subset of  the  cv-
11713        qualification signature of type T2  */
11714   if (ics1->kind == ck_qual
11715       && ics2->kind == ck_qual
11716       && same_type_p (from_type1, from_type2))
11717     {
11718       int result = comp_cv_qual_signature (to_type1, to_type2);
11719       if (result != 0)
11720 	return result;
11721     }
11722 
11723   /* [over.ics.rank]
11724 
11725      --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
11726      to an implicit object parameter of a non-static member function
11727      declared without a ref-qualifier, and either S1 binds an lvalue
11728      reference to an lvalue and S2 binds an rvalue reference or S1 binds an
11729      rvalue reference to an rvalue and S2 binds an lvalue reference (C++0x
11730      draft standard, 13.3.3.2)
11731 
11732      --S1 and S2 are reference bindings (_dcl.init.ref_), and the
11733      types to which the references refer are the same type except for
11734      top-level cv-qualifiers, and the type to which the reference
11735      initialized by S2 refers is more cv-qualified than the type to
11736      which the reference initialized by S1 refers.
11737 
11738      DR 1328 [over.match.best]: the context is an initialization by
11739      conversion function for direct reference binding (13.3.1.6) of a
11740      reference to function type, the return type of F1 is the same kind of
11741      reference (i.e. lvalue or rvalue) as the reference being initialized,
11742      and the return type of F2 is not.  */
11743 
11744   if (ref_conv1 && ref_conv2)
11745     {
11746       if (!ref_conv1->this_p && !ref_conv2->this_p
11747 	  && (ref_conv1->rvaluedness_matches_p
11748 	      != ref_conv2->rvaluedness_matches_p)
11749 	  && (same_type_p (ref_conv1->type, ref_conv2->type)
11750 	      || (TYPE_REF_IS_RVALUE (ref_conv1->type)
11751 		  != TYPE_REF_IS_RVALUE (ref_conv2->type))))
11752 	{
11753 	  if (ref_conv1->bad_p
11754 	      && !same_type_p (TREE_TYPE (ref_conv1->type),
11755 			       TREE_TYPE (ref_conv2->type)))
11756 	    /* Don't prefer a bad conversion that drops cv-quals to a bad
11757 	       conversion with the wrong rvalueness.  */
11758 	    return 0;
11759 	  return (ref_conv1->rvaluedness_matches_p
11760 		  - ref_conv2->rvaluedness_matches_p);
11761 	}
11762 
11763       if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
11764 	{
11765 	  /* Per P0388R4:
11766 
11767 	    void f (int(&)[]),     // (1)
11768 		 f (int(&)[1]),    // (2)
11769 		 f (int*);	   // (3)
11770 
11771 	    (2) is better than (1), but (3) should be equal to (1) and to
11772 	    (2).  For that reason we don't use ck_qual for (1) which would
11773 	    give it the cr_exact rank while (3) remains ck_identity.
11774 	    Therefore we compare (1) and (2) here.  For (1) we'll have
11775 
11776 	      ck_ref_bind <- ck_identity
11777 		int[] &	       int[1]
11778 
11779 	    so to handle this we must look at ref_conv.  */
11780 	  bool c1 = conv_binds_to_array_of_unknown_bound (ref_conv1);
11781 	  bool c2 = conv_binds_to_array_of_unknown_bound (ref_conv2);
11782 	  if (c1 && !c2)
11783 	    return -1;
11784 	  else if (!c1 && c2)
11785 	    return 1;
11786 
11787 	  int q1 = cp_type_quals (TREE_TYPE (ref_conv1->type));
11788 	  int q2 = cp_type_quals (TREE_TYPE (ref_conv2->type));
11789 	  if (ref_conv1->bad_p)
11790 	    {
11791 	      /* Prefer the one that drops fewer cv-quals.  */
11792 	      tree ftype = next_conversion (ref_conv1)->type;
11793 	      int fquals = cp_type_quals (ftype);
11794 	      q1 ^= fquals;
11795 	      q2 ^= fquals;
11796 	    }
11797 	  return comp_cv_qualification (q2, q1);
11798 	}
11799     }
11800 
11801   /* [over.ics.rank]
11802 
11803      Per CWG 1601:
11804      -- A conversion that promotes an enumeration whose underlying type
11805      is fixed to its underlying type is better than one that promotes to
11806      the promoted underlying type, if the two are different.  */
11807   if (ics1->rank == cr_promotion
11808       && ics2->rank == cr_promotion
11809       && UNSCOPED_ENUM_P (from_type1)
11810       && ENUM_FIXED_UNDERLYING_TYPE_P (from_type1)
11811       && same_type_p (from_type1, from_type2))
11812     {
11813       tree utype = ENUM_UNDERLYING_TYPE (from_type1);
11814       tree prom = type_promotes_to (from_type1);
11815       if (!same_type_p (utype, prom))
11816 	{
11817 	  if (same_type_p (to_type1, utype)
11818 	      && same_type_p (to_type2, prom))
11819 	    return 1;
11820 	  else if (same_type_p (to_type2, utype)
11821 		   && same_type_p (to_type1, prom))
11822 	    return -1;
11823 	}
11824     }
11825 
11826   /* Neither conversion sequence is better than the other.  */
11827   return 0;
11828 }
11829 
11830 /* The source type for this standard conversion sequence.  */
11831 
11832 static tree
source_type(conversion * t)11833 source_type (conversion *t)
11834 {
11835   return strip_standard_conversion (t)->type;
11836 }
11837 
11838 /* Note a warning about preferring WINNER to LOSER.  We do this by storing
11839    a pointer to LOSER and re-running joust to produce the warning if WINNER
11840    is actually used.  */
11841 
11842 static void
add_warning(struct z_candidate * winner,struct z_candidate * loser)11843 add_warning (struct z_candidate *winner, struct z_candidate *loser)
11844 {
11845   candidate_warning *cw = (candidate_warning *)
11846     conversion_obstack_alloc (sizeof (candidate_warning));
11847   cw->loser = loser;
11848   cw->next = winner->warnings;
11849   winner->warnings = cw;
11850 }
11851 
11852 /* CAND is a constructor candidate in joust in C++17 and up.  If it copies a
11853    prvalue returned from a conversion function, replace CAND with the candidate
11854    for the conversion and return true.  Otherwise, return false.  */
11855 
11856 static bool
joust_maybe_elide_copy(z_candidate * & cand)11857 joust_maybe_elide_copy (z_candidate *&cand)
11858 {
11859   tree fn = cand->fn;
11860   if (!DECL_COPY_CONSTRUCTOR_P (fn) && !DECL_MOVE_CONSTRUCTOR_P (fn))
11861     return false;
11862   conversion *conv = cand->convs[0];
11863   gcc_checking_assert (conv->kind == ck_ref_bind);
11864   conv = next_conversion (conv);
11865   if (conv->kind == ck_user && !TYPE_REF_P (conv->type))
11866     {
11867       gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
11868 			   (conv->type, DECL_CONTEXT (fn)));
11869       z_candidate *uc = conv->cand;
11870       if (DECL_CONV_FN_P (uc->fn))
11871 	{
11872 	  cand = uc;
11873 	  return true;
11874 	}
11875     }
11876   return false;
11877 }
11878 
11879 /* True if the defining declarations of the two candidates have equivalent
11880    parameters.  */
11881 
11882 bool
cand_parms_match(z_candidate * c1,z_candidate * c2)11883 cand_parms_match (z_candidate *c1, z_candidate *c2)
11884 {
11885   tree fn1 = c1->fn;
11886   tree fn2 = c2->fn;
11887   if (fn1 == fn2)
11888     return true;
11889   if (identifier_p (fn1) || identifier_p (fn2))
11890     return false;
11891   /* We don't look at c1->template_decl because that's only set for primary
11892      templates, not e.g. non-template member functions of class templates.  */
11893   tree t1 = most_general_template (fn1);
11894   tree t2 = most_general_template (fn2);
11895   if (t1 || t2)
11896     {
11897       if (!t1 || !t2)
11898 	return false;
11899       if (t1 == t2)
11900 	return true;
11901       fn1 = DECL_TEMPLATE_RESULT (t1);
11902       fn2 = DECL_TEMPLATE_RESULT (t2);
11903     }
11904   return compparms (TYPE_ARG_TYPES (TREE_TYPE (fn1)),
11905 		    TYPE_ARG_TYPES (TREE_TYPE (fn2)));
11906 }
11907 
11908 /* Compare two candidates for overloading as described in
11909    [over.match.best].  Return values:
11910 
11911       1: cand1 is better than cand2
11912      -1: cand2 is better than cand1
11913       0: cand1 and cand2 are indistinguishable */
11914 
11915 static int
joust(struct z_candidate * cand1,struct z_candidate * cand2,bool warn,tsubst_flags_t complain)11916 joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn,
11917        tsubst_flags_t complain)
11918 {
11919   int winner = 0;
11920   int off1 = 0, off2 = 0;
11921   size_t i;
11922   size_t len;
11923 
11924   /* Candidates that involve bad conversions are always worse than those
11925      that don't.  */
11926   if (cand1->viable > cand2->viable)
11927     return 1;
11928   if (cand1->viable < cand2->viable)
11929     return -1;
11930 
11931   /* If we have two pseudo-candidates for conversions to the same type,
11932      or two candidates for the same function, arbitrarily pick one.  */
11933   if (cand1->fn == cand2->fn
11934       && cand1->reversed () == cand2->reversed ()
11935       && (IS_TYPE_OR_DECL_P (cand1->fn)))
11936     return 1;
11937 
11938   /* Prefer a non-deleted function over an implicitly deleted move
11939      constructor or assignment operator.  This differs slightly from the
11940      wording for issue 1402 (which says the move op is ignored by overload
11941      resolution), but this way produces better error messages.  */
11942   if (TREE_CODE (cand1->fn) == FUNCTION_DECL
11943       && TREE_CODE (cand2->fn) == FUNCTION_DECL
11944       && DECL_DELETED_FN (cand1->fn) != DECL_DELETED_FN (cand2->fn))
11945     {
11946       if (DECL_DELETED_FN (cand1->fn) && DECL_DEFAULTED_FN (cand1->fn)
11947 	  && move_fn_p (cand1->fn))
11948 	return -1;
11949       if (DECL_DELETED_FN (cand2->fn) && DECL_DEFAULTED_FN (cand2->fn)
11950 	  && move_fn_p (cand2->fn))
11951 	return 1;
11952     }
11953 
11954   /* a viable function F1
11955      is defined to be a better function than another viable function F2  if
11956      for  all arguments i, ICSi(F1) is not a worse conversion sequence than
11957      ICSi(F2), and then */
11958 
11959   /* for some argument j, ICSj(F1) is a better conversion  sequence  than
11960      ICSj(F2) */
11961 
11962   /* For comparing static and non-static member functions, we ignore
11963      the implicit object parameter of the non-static function.  The
11964      standard says to pretend that the static function has an object
11965      parm, but that won't work with operator overloading.  */
11966   len = cand1->num_convs;
11967   if (len != cand2->num_convs)
11968     {
11969       int static_1 = DECL_STATIC_FUNCTION_P (cand1->fn);
11970       int static_2 = DECL_STATIC_FUNCTION_P (cand2->fn);
11971 
11972       if (DECL_CONSTRUCTOR_P (cand1->fn)
11973 	  && is_list_ctor (cand1->fn) != is_list_ctor (cand2->fn))
11974 	/* We're comparing a near-match list constructor and a near-match
11975 	   non-list constructor.  Just treat them as unordered.  */
11976 	return 0;
11977 
11978       gcc_assert (static_1 != static_2);
11979 
11980       if (static_1)
11981 	off2 = 1;
11982       else
11983 	{
11984 	  off1 = 1;
11985 	  --len;
11986 	}
11987     }
11988 
11989   /* Handle C++17 copy elision in [over.match.ctor] (direct-init) context.  The
11990      standard currently says that only constructors are candidates, but if one
11991      copies a prvalue returned by a conversion function we want to treat the
11992      conversion as the candidate instead.
11993 
11994      Clang does something similar, as discussed at
11995      http://lists.isocpp.org/core/2017/10/3166.php
11996      http://lists.isocpp.org/core/2019/03/5721.php  */
11997   int elided_tiebreaker = 0;
11998   if (len == 1 && cxx_dialect >= cxx17
11999       && DECL_P (cand1->fn)
12000       && DECL_COMPLETE_CONSTRUCTOR_P (cand1->fn)
12001       && !(cand1->flags & LOOKUP_ONLYCONVERTING))
12002     {
12003       bool elided1 = joust_maybe_elide_copy (cand1);
12004       bool elided2 = joust_maybe_elide_copy (cand2);
12005       /* As a tiebreaker below we will prefer a constructor to a conversion
12006 	 operator exposed this way.  */
12007       elided_tiebreaker = elided2 - elided1;
12008     }
12009 
12010   for (i = 0; i < len; ++i)
12011     {
12012       conversion *t1 = cand1->convs[i + off1];
12013       conversion *t2 = cand2->convs[i + off2];
12014       int comp = compare_ics (t1, t2);
12015 
12016       if (comp != 0)
12017 	{
12018 	  if ((complain & tf_warning)
12019 	      && warn_sign_promo
12020 	      && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
12021 		  == cr_std + cr_promotion)
12022 	      && t1->kind == ck_std
12023 	      && t2->kind == ck_std
12024 	      && TREE_CODE (t1->type) == INTEGER_TYPE
12025 	      && TREE_CODE (t2->type) == INTEGER_TYPE
12026 	      && (TYPE_PRECISION (t1->type)
12027 		  == TYPE_PRECISION (t2->type))
12028 	      && (TYPE_UNSIGNED (next_conversion (t1)->type)
12029 		  || (TREE_CODE (next_conversion (t1)->type)
12030 		      == ENUMERAL_TYPE)))
12031 	    {
12032 	      tree type = next_conversion (t1)->type;
12033 	      tree type1, type2;
12034 	      struct z_candidate *w, *l;
12035 	      if (comp > 0)
12036 		type1 = t1->type, type2 = t2->type,
12037 		  w = cand1, l = cand2;
12038 	      else
12039 		type1 = t2->type, type2 = t1->type,
12040 		  w = cand2, l = cand1;
12041 
12042 	      if (warn)
12043 		{
12044 		  warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
12045 			   type, type1, type2);
12046 		  warning (OPT_Wsign_promo, "  in call to %qD", w->fn);
12047 		}
12048 	      else
12049 		add_warning (w, l);
12050 	    }
12051 
12052 	  if (winner && comp != winner)
12053 	    {
12054 	      /* Ambiguity between normal and reversed comparison operators
12055 		 with the same parameter types; prefer the normal one.  */
12056 	      if ((cand1->reversed () != cand2->reversed ())
12057 		  && cand_parms_match (cand1, cand2))
12058 		return cand1->reversed () ? -1 : 1;
12059 
12060 	      winner = 0;
12061 	      goto tweak;
12062 	    }
12063 	  winner = comp;
12064 	}
12065     }
12066 
12067   /* warn about confusing overload resolution for user-defined conversions,
12068      either between a constructor and a conversion op, or between two
12069      conversion ops.  */
12070   if ((complain & tf_warning)
12071       /* In C++17, the constructor might have been elided, which means that
12072 	 an originally null ->second_conv could become non-null.  */
12073       && winner && warn_conversion && cand1->second_conv && cand2->second_conv
12074       && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
12075       && winner != compare_ics (cand1->second_conv, cand2->second_conv))
12076     {
12077       struct z_candidate *w, *l;
12078       bool give_warning = false;
12079 
12080       if (winner == 1)
12081 	w = cand1, l = cand2;
12082       else
12083 	w = cand2, l = cand1;
12084 
12085       /* We don't want to complain about `X::operator T1 ()'
12086 	 beating `X::operator T2 () const', when T2 is a no less
12087 	 cv-qualified version of T1.  */
12088       if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
12089 	  && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
12090 	{
12091 	  tree t = TREE_TYPE (TREE_TYPE (l->fn));
12092 	  tree f = TREE_TYPE (TREE_TYPE (w->fn));
12093 
12094 	  if (TREE_CODE (t) == TREE_CODE (f) && INDIRECT_TYPE_P (t))
12095 	    {
12096 	      t = TREE_TYPE (t);
12097 	      f = TREE_TYPE (f);
12098 	    }
12099 	  if (!comp_ptr_ttypes (t, f))
12100 	    give_warning = true;
12101 	}
12102       else
12103 	give_warning = true;
12104 
12105       if (!give_warning)
12106 	/*NOP*/;
12107       else if (warn)
12108 	{
12109 	  tree source = source_type (w->convs[0]);
12110 	  if (INDIRECT_TYPE_P (source))
12111 	    source = TREE_TYPE (source);
12112 	  auto_diagnostic_group d;
12113 	  if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
12114 	      && warning (OPT_Wconversion, "  for conversion from %qH to %qI",
12115 			  source, w->second_conv->type))
12116 	    {
12117 	      inform (input_location, "  because conversion sequence "
12118 		      "for the argument is better");
12119 	    }
12120 	}
12121       else
12122 	add_warning (w, l);
12123     }
12124 
12125   if (winner)
12126     return winner;
12127 
12128   /* Put this tiebreaker first, so that we don't try to look at second_conv of
12129      a constructor candidate that doesn't have one.  */
12130   if (elided_tiebreaker)
12131     return elided_tiebreaker;
12132 
12133   /* DR 495 moved this tiebreaker above the template ones.  */
12134   /* or, if not that,
12135      the  context  is  an  initialization by user-defined conversion (see
12136      _dcl.init_  and  _over.match.user_)  and  the  standard   conversion
12137      sequence  from  the return type of F1 to the destination type (i.e.,
12138      the type of the entity being initialized)  is  a  better  conversion
12139      sequence  than the standard conversion sequence from the return type
12140      of F2 to the destination type.  */
12141 
12142   if (cand1->second_conv)
12143     {
12144       winner = compare_ics (cand1->second_conv, cand2->second_conv);
12145       if (winner)
12146 	return winner;
12147     }
12148 
12149   /* or, if not that,
12150      F1 is a non-template function and F2 is a template function
12151      specialization.  */
12152 
12153   if (!cand1->template_decl && cand2->template_decl)
12154     return 1;
12155   else if (cand1->template_decl && !cand2->template_decl)
12156     return -1;
12157 
12158   /* or, if not that,
12159      F1 and F2 are template functions and the function template for F1 is
12160      more specialized than the template for F2 according to the partial
12161      ordering rules.  */
12162 
12163   if (cand1->template_decl && cand2->template_decl)
12164     {
12165       winner = more_specialized_fn
12166 	(TI_TEMPLATE (cand1->template_decl),
12167 	 TI_TEMPLATE (cand2->template_decl),
12168 	 /* [temp.func.order]: The presence of unused ellipsis and default
12169 	    arguments has no effect on the partial ordering of function
12170 	    templates.   add_function_candidate() will not have
12171 	    counted the "this" argument for constructors.  */
12172 	 cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
12173       if (winner)
12174 	return winner;
12175     }
12176 
12177   /* Concepts: F1 and F2 are non-template functions with the same
12178      parameter-type-lists, and F1 is more constrained than F2 according to the
12179      partial ordering of constraints described in 13.5.4.  */
12180 
12181   if (flag_concepts && DECL_P (cand1->fn) && DECL_P (cand2->fn)
12182       && !cand1->template_decl && !cand2->template_decl
12183       && cand_parms_match (cand1, cand2))
12184     {
12185       winner = more_constrained (cand1->fn, cand2->fn);
12186       if (winner)
12187 	return winner;
12188     }
12189 
12190   /* F2 is a rewritten candidate (12.4.1.2) and F1 is not, or F1 and F2 are
12191      rewritten candidates, and F2 is a synthesized candidate with reversed
12192      order of parameters and F1 is not.  */
12193   if (cand1->rewritten ())
12194     {
12195       if (!cand2->rewritten ())
12196 	return -1;
12197       if (!cand1->reversed () && cand2->reversed ())
12198 	return 1;
12199       if (cand1->reversed () && !cand2->reversed ())
12200 	return -1;
12201     }
12202   else if (cand2->rewritten ())
12203     return 1;
12204 
12205   /* F1 is generated from a deduction-guide (13.3.1.8) and F2 is not */
12206   if (deduction_guide_p (cand1->fn))
12207     {
12208       gcc_assert (deduction_guide_p (cand2->fn));
12209       /* We distinguish between candidates from an explicit deduction guide and
12210 	 candidates built from a constructor based on DECL_ARTIFICIAL.  */
12211       int art1 = DECL_ARTIFICIAL (cand1->fn);
12212       int art2 = DECL_ARTIFICIAL (cand2->fn);
12213       if (art1 != art2)
12214 	return art2 - art1;
12215 
12216       if (art1)
12217 	{
12218 	  /* Prefer the special copy guide over a declared copy/move
12219 	     constructor.  */
12220 	  if (copy_guide_p (cand1->fn))
12221 	    return 1;
12222 	  if (copy_guide_p (cand2->fn))
12223 	    return -1;
12224 
12225 	  /* Prefer a candidate generated from a non-template constructor.  */
12226 	  int tg1 = template_guide_p (cand1->fn);
12227 	  int tg2 = template_guide_p (cand2->fn);
12228 	  if (tg1 != tg2)
12229 	    return tg2 - tg1;
12230 	}
12231     }
12232 
12233   /* F1 is a member of a class D, F2 is a member of a base class B of D, and
12234      for all arguments the corresponding parameters of F1 and F2 have the same
12235      type (CWG 2273/2277). */
12236   if (DECL_P (cand1->fn) && DECL_CLASS_SCOPE_P (cand1->fn)
12237       && !DECL_CONV_FN_P (cand1->fn)
12238       && DECL_P (cand2->fn) && DECL_CLASS_SCOPE_P (cand2->fn)
12239       && !DECL_CONV_FN_P (cand2->fn))
12240     {
12241       tree base1 = DECL_CONTEXT (strip_inheriting_ctors (cand1->fn));
12242       tree base2 = DECL_CONTEXT (strip_inheriting_ctors (cand2->fn));
12243 
12244       bool used1 = false;
12245       bool used2 = false;
12246       if (base1 == base2)
12247 	/* No difference.  */;
12248       else if (DERIVED_FROM_P (base1, base2))
12249 	used1 = true;
12250       else if (DERIVED_FROM_P (base2, base1))
12251 	used2 = true;
12252 
12253       if (int diff = used2 - used1)
12254 	{
12255 	  for (i = 0; i < len; ++i)
12256 	    {
12257 	      conversion *t1 = cand1->convs[i + off1];
12258 	      conversion *t2 = cand2->convs[i + off2];
12259 	      if (!same_type_p (t1->type, t2->type))
12260 		break;
12261 	    }
12262 	  if (i == len)
12263 	    return diff;
12264 	}
12265     }
12266 
12267   /* Check whether we can discard a builtin candidate, either because we
12268      have two identical ones or matching builtin and non-builtin candidates.
12269 
12270      (Pedantically in the latter case the builtin which matched the user
12271      function should not be added to the overload set, but we spot it here.
12272 
12273      [over.match.oper]
12274      ... the builtin candidates include ...
12275      - do not have the same parameter type list as any non-template
12276        non-member candidate.  */
12277 
12278   if (identifier_p (cand1->fn) || identifier_p (cand2->fn))
12279     {
12280       for (i = 0; i < len; ++i)
12281 	if (!same_type_p (cand1->convs[i]->type,
12282 			  cand2->convs[i]->type))
12283 	  break;
12284       if (i == cand1->num_convs)
12285 	{
12286 	  if (cand1->fn == cand2->fn)
12287 	    /* Two built-in candidates; arbitrarily pick one.  */
12288 	    return 1;
12289 	  else if (identifier_p (cand1->fn))
12290 	    /* cand1 is built-in; prefer cand2.  */
12291 	    return -1;
12292 	  else
12293 	    /* cand2 is built-in; prefer cand1.  */
12294 	    return 1;
12295 	}
12296     }
12297 
12298   /* For candidates of a multi-versioned function,  make the version with
12299      the highest priority win.  This version will be checked for dispatching
12300      first.  If this version can be inlined into the caller, the front-end
12301      will simply make a direct call to this function.  */
12302 
12303   if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12304       && DECL_FUNCTION_VERSIONED (cand1->fn)
12305       && TREE_CODE (cand2->fn) == FUNCTION_DECL
12306       && DECL_FUNCTION_VERSIONED (cand2->fn))
12307     {
12308       tree f1 = TREE_TYPE (cand1->fn);
12309       tree f2 = TREE_TYPE (cand2->fn);
12310       tree p1 = TYPE_ARG_TYPES (f1);
12311       tree p2 = TYPE_ARG_TYPES (f2);
12312 
12313       /* Check if cand1->fn and cand2->fn are versions of the same function.  It
12314          is possible that cand1->fn and cand2->fn are function versions but of
12315          different functions.  Check types to see if they are versions of the same
12316          function.  */
12317       if (compparms (p1, p2)
12318 	  && same_type_p (TREE_TYPE (f1), TREE_TYPE (f2)))
12319 	{
12320 	  /* Always make the version with the higher priority, more
12321 	     specialized, win.  */
12322 	  gcc_assert (targetm.compare_version_priority);
12323 	  if (targetm.compare_version_priority (cand1->fn, cand2->fn) >= 0)
12324 	    return 1;
12325 	  else
12326 	    return -1;
12327 	}
12328     }
12329 
12330   /* If the two function declarations represent the same function (this can
12331      happen with declarations in multiple scopes and arg-dependent lookup),
12332      arbitrarily choose one.  But first make sure the default args we're
12333      using match.  */
12334   if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
12335       && equal_functions (cand1->fn, cand2->fn))
12336     {
12337       tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
12338       tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
12339 
12340       gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
12341 
12342       for (i = 0; i < len; ++i)
12343 	{
12344 	  /* Don't crash if the fn is variadic.  */
12345 	  if (!parms1)
12346 	    break;
12347 	  parms1 = TREE_CHAIN (parms1);
12348 	  parms2 = TREE_CHAIN (parms2);
12349 	}
12350 
12351       if (off1)
12352 	parms1 = TREE_CHAIN (parms1);
12353       else if (off2)
12354 	parms2 = TREE_CHAIN (parms2);
12355 
12356       for (; parms1; ++i)
12357 	{
12358 	  if (!cp_tree_equal (TREE_PURPOSE (parms1),
12359 			      TREE_PURPOSE (parms2)))
12360 	    {
12361 	      if (warn)
12362 		{
12363 		  if (complain & tf_error)
12364 		    {
12365 		      auto_diagnostic_group d;
12366 		      if (permerror (input_location,
12367 				     "default argument mismatch in "
12368 				     "overload resolution"))
12369 			{
12370 			  inform (DECL_SOURCE_LOCATION (cand1->fn),
12371 				  " candidate 1: %q#F", cand1->fn);
12372 			  inform (DECL_SOURCE_LOCATION (cand2->fn),
12373 				  " candidate 2: %q#F", cand2->fn);
12374 			}
12375 		    }
12376 		  else
12377 		    return 0;
12378 		}
12379 	      else
12380 		add_warning (cand1, cand2);
12381 	      break;
12382 	    }
12383 	  parms1 = TREE_CHAIN (parms1);
12384 	  parms2 = TREE_CHAIN (parms2);
12385 	}
12386 
12387       return 1;
12388     }
12389 
12390 tweak:
12391 
12392   /* Extension: If the worst conversion for one candidate is better than the
12393      worst conversion for the other, take the first.  */
12394   if (!pedantic && (complain & tf_warning_or_error))
12395     {
12396       conversion_rank rank1 = cr_identity, rank2 = cr_identity;
12397       struct z_candidate *w = 0, *l = 0;
12398 
12399       for (i = 0; i < len; ++i)
12400 	{
12401 	  if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
12402 	    rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
12403 	  if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
12404 	    rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
12405 	}
12406       if (rank1 < rank2)
12407 	winner = 1, w = cand1, l = cand2;
12408       if (rank1 > rank2)
12409 	winner = -1, w = cand2, l = cand1;
12410       if (winner)
12411 	{
12412 	  /* Don't choose a deleted function over ambiguity.  */
12413 	  if (DECL_P (w->fn) && DECL_DELETED_FN (w->fn))
12414 	    return 0;
12415 	  if (warn)
12416 	    {
12417 	      auto_diagnostic_group d;
12418 	      if (pedwarn (input_location, 0,
12419 			   "ISO C++ says that these are ambiguous, even "
12420 			   "though the worst conversion for the first is "
12421 			   "better than the worst conversion for the second:"))
12422 		{
12423 		  print_z_candidate (input_location, N_("candidate 1:"), w);
12424 		  print_z_candidate (input_location, N_("candidate 2:"), l);
12425 		}
12426 	    }
12427 	  else
12428 	    add_warning (w, l);
12429 	  return winner;
12430 	}
12431     }
12432 
12433   gcc_assert (!winner);
12434   return 0;
12435 }
12436 
12437 /* Given a list of candidates for overloading, find the best one, if any.
12438    This algorithm has a worst case of O(2n) (winner is last), and a best
12439    case of O(n/2) (totally ambiguous); much better than a sorting
12440    algorithm.  */
12441 
12442 static struct z_candidate *
tourney(struct z_candidate * candidates,tsubst_flags_t complain)12443 tourney (struct z_candidate *candidates, tsubst_flags_t complain)
12444 {
12445   struct z_candidate *champ = candidates, *challenger;
12446   int fate;
12447   int champ_compared_to_predecessor = 0;
12448 
12449   /* Walk through the list once, comparing each current champ to the next
12450      candidate, knocking out a candidate or two with each comparison.  */
12451 
12452   for (challenger = champ->next; challenger; )
12453     {
12454       fate = joust (champ, challenger, 0, complain);
12455       if (fate == 1)
12456 	challenger = challenger->next;
12457       else
12458 	{
12459 	  if (fate == 0)
12460 	    {
12461 	      champ = challenger->next;
12462 	      if (champ == 0)
12463 		return NULL;
12464 	      champ_compared_to_predecessor = 0;
12465 	    }
12466 	  else
12467 	    {
12468 	      champ = challenger;
12469 	      champ_compared_to_predecessor = 1;
12470 	    }
12471 
12472 	  challenger = champ->next;
12473 	}
12474     }
12475 
12476   /* Make sure the champ is better than all the candidates it hasn't yet
12477      been compared to.  */
12478 
12479   for (challenger = candidates;
12480        challenger != champ
12481 	 && !(champ_compared_to_predecessor && challenger->next == champ);
12482        challenger = challenger->next)
12483     {
12484       fate = joust (champ, challenger, 0, complain);
12485       if (fate != 1)
12486 	return NULL;
12487     }
12488 
12489   return champ;
12490 }
12491 
12492 /* Returns nonzero if things of type FROM can be converted to TO.  */
12493 
12494 bool
can_convert(tree to,tree from,tsubst_flags_t complain)12495 can_convert (tree to, tree from, tsubst_flags_t complain)
12496 {
12497   tree arg = NULL_TREE;
12498   /* implicit_conversion only considers user-defined conversions
12499      if it has an expression for the call argument list.  */
12500   if (CLASS_TYPE_P (from) || CLASS_TYPE_P (to))
12501     arg = build_stub_object (from);
12502   return can_convert_arg (to, from, arg, LOOKUP_IMPLICIT, complain);
12503 }
12504 
12505 /* Returns nonzero if things of type FROM can be converted to TO with a
12506    standard conversion.  */
12507 
12508 bool
can_convert_standard(tree to,tree from,tsubst_flags_t complain)12509 can_convert_standard (tree to, tree from, tsubst_flags_t complain)
12510 {
12511   return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT, complain);
12512 }
12513 
12514 /* Returns nonzero if ARG (of type FROM) can be converted to TO.  */
12515 
12516 bool
can_convert_arg(tree to,tree from,tree arg,int flags,tsubst_flags_t complain)12517 can_convert_arg (tree to, tree from, tree arg, int flags,
12518 		 tsubst_flags_t complain)
12519 {
12520   conversion *t;
12521   void *p;
12522   bool ok_p;
12523 
12524   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
12525   p = conversion_obstack_alloc (0);
12526   /* We want to discard any access checks done for this test,
12527      as we might not be in the appropriate access context and
12528      we'll do the check again when we actually perform the
12529      conversion.  */
12530   push_deferring_access_checks (dk_deferred);
12531 
12532   t  = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
12533 			    flags, complain);
12534   ok_p = (t && !t->bad_p);
12535 
12536   /* Discard the access checks now.  */
12537   pop_deferring_access_checks ();
12538   /* Free all the conversions we allocated.  */
12539   obstack_free (&conversion_obstack, p);
12540 
12541   return ok_p;
12542 }
12543 
12544 /* Like can_convert_arg, but allows dubious conversions as well.  */
12545 
12546 bool
can_convert_arg_bad(tree to,tree from,tree arg,int flags,tsubst_flags_t complain)12547 can_convert_arg_bad (tree to, tree from, tree arg, int flags,
12548 		     tsubst_flags_t complain)
12549 {
12550   conversion *t;
12551   void *p;
12552 
12553   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
12554   p = conversion_obstack_alloc (0);
12555   /* Try to perform the conversion.  */
12556   t  = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
12557 			    flags, complain);
12558   /* Free all the conversions we allocated.  */
12559   obstack_free (&conversion_obstack, p);
12560 
12561   return t != NULL;
12562 }
12563 
12564 /* Convert EXPR to TYPE.  Return the converted expression.
12565 
12566    Note that we allow bad conversions here because by the time we get to
12567    this point we are committed to doing the conversion.  If we end up
12568    doing a bad conversion, convert_like will complain.  */
12569 
12570 tree
perform_implicit_conversion_flags(tree type,tree expr,tsubst_flags_t complain,int flags)12571 perform_implicit_conversion_flags (tree type, tree expr,
12572 				   tsubst_flags_t complain, int flags)
12573 {
12574   conversion *conv;
12575   void *p;
12576   location_t loc = cp_expr_loc_or_input_loc (expr);
12577 
12578   if (TYPE_REF_P (type))
12579     expr = mark_lvalue_use (expr);
12580   else
12581     expr = mark_rvalue_use (expr);
12582 
12583   if (error_operand_p (expr))
12584     return error_mark_node;
12585 
12586   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
12587   p = conversion_obstack_alloc (0);
12588 
12589   conv = implicit_conversion (type, TREE_TYPE (expr), expr,
12590 			      /*c_cast_p=*/false,
12591 			      flags, complain);
12592 
12593   if (!conv)
12594     {
12595       if (complain & tf_error)
12596 	implicit_conversion_error (loc, type, expr);
12597       expr = error_mark_node;
12598     }
12599   else if (processing_template_decl && conv->kind != ck_identity)
12600     {
12601       /* In a template, we are only concerned about determining the
12602 	 type of non-dependent expressions, so we do not have to
12603 	 perform the actual conversion.  But for initializers, we
12604 	 need to be able to perform it at instantiation
12605 	 (or instantiate_non_dependent_expr) time.  */
12606       expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
12607       if (!(flags & LOOKUP_ONLYCONVERTING))
12608 	IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
12609       if (flags & LOOKUP_NO_NARROWING)
12610 	IMPLICIT_CONV_EXPR_BRACED_INIT (expr) = true;
12611     }
12612   else
12613     {
12614       /* Give a conversion call the same location as expr.  */
12615       iloc_sentinel il (loc);
12616       expr = convert_like (conv, expr, complain);
12617     }
12618 
12619   /* Free all the conversions we allocated.  */
12620   obstack_free (&conversion_obstack, p);
12621 
12622   return expr;
12623 }
12624 
12625 tree
perform_implicit_conversion(tree type,tree expr,tsubst_flags_t complain)12626 perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
12627 {
12628   return perform_implicit_conversion_flags (type, expr, complain,
12629 					    LOOKUP_IMPLICIT);
12630 }
12631 
12632 /* Convert EXPR to TYPE (as a direct-initialization) if that is
12633    permitted.  If the conversion is valid, the converted expression is
12634    returned.  Otherwise, NULL_TREE is returned, except in the case
12635    that TYPE is a class type; in that case, an error is issued.  If
12636    C_CAST_P is true, then this direct-initialization is taking
12637    place as part of a static_cast being attempted as part of a C-style
12638    cast.  */
12639 
12640 tree
perform_direct_initialization_if_possible(tree type,tree expr,bool c_cast_p,tsubst_flags_t complain)12641 perform_direct_initialization_if_possible (tree type,
12642 					   tree expr,
12643 					   bool c_cast_p,
12644                                            tsubst_flags_t complain)
12645 {
12646   conversion *conv;
12647   void *p;
12648 
12649   if (type == error_mark_node || error_operand_p (expr))
12650     return error_mark_node;
12651   /* [dcl.init]
12652 
12653      If the destination type is a (possibly cv-qualified) class type:
12654 
12655      -- If the initialization is direct-initialization ...,
12656      constructors are considered.
12657 
12658        -- If overload resolution is successful, the selected constructor
12659        is called to initialize the object, with the initializer expression
12660        or expression-list as its argument(s).
12661 
12662        -- Otherwise, if no constructor is viable, the destination type is
12663        a (possibly cv-qualified) aggregate class A, and the initializer is
12664        a parenthesized expression-list, the object is initialized as
12665        follows...  */
12666   if (CLASS_TYPE_P (type))
12667     {
12668       releasing_vec args (make_tree_vector_single (expr));
12669       expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
12670 					&args, type, LOOKUP_NORMAL, complain);
12671       return build_cplus_new (type, expr, complain);
12672     }
12673 
12674   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
12675   p = conversion_obstack_alloc (0);
12676 
12677   conv = implicit_conversion (type, TREE_TYPE (expr), expr,
12678 			      c_cast_p,
12679 			      LOOKUP_NORMAL, complain);
12680   if (!conv || conv->bad_p)
12681     expr = NULL_TREE;
12682   else if (processing_template_decl && conv->kind != ck_identity)
12683     {
12684       /* In a template, we are only concerned about determining the
12685 	 type of non-dependent expressions, so we do not have to
12686 	 perform the actual conversion.  But for initializers, we
12687 	 need to be able to perform it at instantiation
12688 	 (or instantiate_non_dependent_expr) time.  */
12689       expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
12690       IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
12691     }
12692   else
12693     expr = convert_like (conv, expr, NULL_TREE, 0,
12694 			 /*issue_conversion_warnings=*/false,
12695 			 c_cast_p, complain);
12696 
12697   /* Free all the conversions we allocated.  */
12698   obstack_free (&conversion_obstack, p);
12699 
12700   return expr;
12701 }
12702 
12703 /* When initializing a reference that lasts longer than a full-expression,
12704    this special rule applies:
12705 
12706      [class.temporary]
12707 
12708      The temporary to which the reference is bound or the temporary
12709      that is the complete object to which the reference is bound
12710      persists for the lifetime of the reference.
12711 
12712      The temporaries created during the evaluation of the expression
12713      initializing the reference, except the temporary to which the
12714      reference is bound, are destroyed at the end of the
12715      full-expression in which they are created.
12716 
12717    In that case, we store the converted expression into a new
12718    VAR_DECL in a new scope.
12719 
12720    However, we want to be careful not to create temporaries when
12721    they are not required.  For example, given:
12722 
12723      struct B {};
12724      struct D : public B {};
12725      D f();
12726      const B& b = f();
12727 
12728    there is no need to copy the return value from "f"; we can just
12729    extend its lifetime.  Similarly, given:
12730 
12731      struct S {};
12732      struct T { operator S(); };
12733      T t;
12734      const S& s = t;
12735 
12736   we can extend the lifetime of the return value of the conversion
12737   operator.
12738 
12739   The next several functions are involved in this lifetime extension.  */
12740 
12741 /* DECL is a VAR_DECL or FIELD_DECL whose type is a REFERENCE_TYPE.  The
12742    reference is being bound to a temporary.  Create and return a new
12743    VAR_DECL with the indicated TYPE; this variable will store the value to
12744    which the reference is bound.  */
12745 
12746 tree
make_temporary_var_for_ref_to_temp(tree decl,tree type)12747 make_temporary_var_for_ref_to_temp (tree decl, tree type)
12748 {
12749   tree var = create_temporary_var (type);
12750 
12751   /* Register the variable.  */
12752   if (VAR_P (decl)
12753       && (TREE_STATIC (decl) || CP_DECL_THREAD_LOCAL_P (decl)))
12754     {
12755       /* Namespace-scope or local static; give it a mangled name.  */
12756 
12757       /* If an initializer is visible to multiple translation units, those
12758 	 translation units must agree on the addresses of the
12759 	 temporaries. Therefore the temporaries must be given a consistent name
12760 	 and vague linkage. The mangled name of a temporary is the name of the
12761 	 non-temporary object in whose initializer they appear, prefixed with
12762 	 GR and suffixed with a sequence number mangled using the usual rules
12763 	 for a seq-id. Temporaries are numbered with a pre-order, depth-first,
12764 	 left-to-right walk of the complete initializer.  */
12765       copy_linkage (var, decl);
12766 
12767       tree name = mangle_ref_init_variable (decl);
12768       DECL_NAME (var) = name;
12769       SET_DECL_ASSEMBLER_NAME (var, name);
12770     }
12771   else
12772     /* Create a new cleanup level if necessary.  */
12773     maybe_push_cleanup_level (type);
12774 
12775   return pushdecl (var);
12776 }
12777 
12778 /* EXPR is the initializer for a variable DECL of reference or
12779    std::initializer_list type.  Create, push and return a new VAR_DECL
12780    for the initializer so that it will live as long as DECL.  Any
12781    cleanup for the new variable is returned through CLEANUP, and the
12782    code to initialize the new variable is returned through INITP.  */
12783 
12784 static tree
set_up_extended_ref_temp(tree decl,tree expr,vec<tree,va_gc> ** cleanups,tree * initp,tree * cond_guard)12785 set_up_extended_ref_temp (tree decl, tree expr, vec<tree, va_gc> **cleanups,
12786 			  tree *initp, tree *cond_guard)
12787 {
12788   tree init;
12789   tree type;
12790   tree var;
12791 
12792   /* Create the temporary variable.  */
12793   type = TREE_TYPE (expr);
12794   var = make_temporary_var_for_ref_to_temp (decl, type);
12795   layout_decl (var, 0);
12796   /* If the rvalue is the result of a function call it will be
12797      a TARGET_EXPR.  If it is some other construct (such as a
12798      member access expression where the underlying object is
12799      itself the result of a function call), turn it into a
12800      TARGET_EXPR here.  It is important that EXPR be a
12801      TARGET_EXPR below since otherwise the INIT_EXPR will
12802      attempt to make a bitwise copy of EXPR to initialize
12803      VAR.  */
12804   if (TREE_CODE (expr) != TARGET_EXPR)
12805     expr = get_target_expr (expr);
12806   else if (TREE_ADDRESSABLE (expr))
12807     TREE_ADDRESSABLE (var) = 1;
12808 
12809   if (TREE_CODE (decl) == FIELD_DECL
12810       && extra_warnings && !warning_suppressed_p (decl))
12811     {
12812       warning (OPT_Wextra, "a temporary bound to %qD only persists "
12813 	       "until the constructor exits", decl);
12814       suppress_warning (decl);
12815     }
12816 
12817   /* Recursively extend temps in this initializer.  */
12818   TARGET_EXPR_INITIAL (expr)
12819     = extend_ref_init_temps (decl, TARGET_EXPR_INITIAL (expr), cleanups,
12820 			     cond_guard);
12821 
12822   /* Any reference temp has a non-trivial initializer.  */
12823   DECL_NONTRIVIALLY_INITIALIZED_P (var) = true;
12824 
12825   /* If the initializer is constant, put it in DECL_INITIAL so we get
12826      static initialization and use in constant expressions.  */
12827   init = maybe_constant_init (expr);
12828   /* As in store_init_value.  */
12829   init = cp_fully_fold (init);
12830   if (TREE_CONSTANT (init))
12831     {
12832       if (literal_type_p (type) && CP_TYPE_CONST_NON_VOLATILE_P (type))
12833 	{
12834 	  /* 5.19 says that a constant expression can include an
12835 	     lvalue-rvalue conversion applied to "a glvalue of literal type
12836 	     that refers to a non-volatile temporary object initialized
12837 	     with a constant expression".  Rather than try to communicate
12838 	     that this VAR_DECL is a temporary, just mark it constexpr.  */
12839 	  DECL_DECLARED_CONSTEXPR_P (var) = true;
12840 	  DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var) = true;
12841 	  TREE_CONSTANT (var) = true;
12842 	  TREE_READONLY (var) = true;
12843 	}
12844       DECL_INITIAL (var) = init;
12845       init = NULL_TREE;
12846     }
12847   else
12848     /* Create the INIT_EXPR that will initialize the temporary
12849        variable.  */
12850     init = split_nonconstant_init (var, expr);
12851   if (at_function_scope_p ())
12852     {
12853       add_decl_expr (var);
12854 
12855       if (TREE_STATIC (var))
12856 	init = add_stmt_to_compound (init, register_dtor_fn (var));
12857       else
12858 	{
12859 	  tree cleanup = cxx_maybe_build_cleanup (var, tf_warning_or_error);
12860 	  if (cleanup)
12861 	    {
12862 	      if (cond_guard && cleanup != error_mark_node)
12863 		{
12864 		  if (*cond_guard == NULL_TREE)
12865 		    {
12866 		      *cond_guard = build_local_temp (boolean_type_node);
12867 		      add_decl_expr (*cond_guard);
12868 		      tree set = cp_build_modify_expr (UNKNOWN_LOCATION,
12869 						       *cond_guard, NOP_EXPR,
12870 						       boolean_false_node,
12871 						       tf_warning_or_error);
12872 		      finish_expr_stmt (set);
12873 		    }
12874 		  cleanup = build3 (COND_EXPR, void_type_node,
12875 				    *cond_guard, cleanup, NULL_TREE);
12876 		}
12877 	      vec_safe_push (*cleanups, cleanup);
12878 	    }
12879 	}
12880 
12881       /* We must be careful to destroy the temporary only
12882 	 after its initialization has taken place.  If the
12883 	 initialization throws an exception, then the
12884 	 destructor should not be run.  We cannot simply
12885 	 transform INIT into something like:
12886 
12887 	 (INIT, ({ CLEANUP_STMT; }))
12888 
12889 	 because emit_local_var always treats the
12890 	 initializer as a full-expression.  Thus, the
12891 	 destructor would run too early; it would run at the
12892 	 end of initializing the reference variable, rather
12893 	 than at the end of the block enclosing the
12894 	 reference variable.
12895 
12896 	 The solution is to pass back a cleanup expression
12897 	 which the caller is responsible for attaching to
12898 	 the statement tree.  */
12899     }
12900   else
12901     {
12902       rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
12903       if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
12904 	{
12905 	  if (CP_DECL_THREAD_LOCAL_P (var))
12906 	    tls_aggregates = tree_cons (NULL_TREE, var,
12907 					tls_aggregates);
12908 	  else
12909 	    static_aggregates = tree_cons (NULL_TREE, var,
12910 					   static_aggregates);
12911 	}
12912       else
12913 	/* Check whether the dtor is callable.  */
12914 	cxx_maybe_build_cleanup (var, tf_warning_or_error);
12915     }
12916   /* Avoid -Wunused-variable warning (c++/38958).  */
12917   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
12918       && VAR_P (decl))
12919     TREE_USED (decl) = DECL_READ_P (decl) = true;
12920 
12921   *initp = init;
12922   return var;
12923 }
12924 
12925 /* Convert EXPR to the indicated reference TYPE, in a way suitable for
12926    initializing a variable of that TYPE.  */
12927 
12928 tree
initialize_reference(tree type,tree expr,int flags,tsubst_flags_t complain)12929 initialize_reference (tree type, tree expr,
12930 		      int flags, tsubst_flags_t complain)
12931 {
12932   conversion *conv;
12933   void *p;
12934   location_t loc = cp_expr_loc_or_input_loc (expr);
12935 
12936   if (type == error_mark_node || error_operand_p (expr))
12937     return error_mark_node;
12938 
12939   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
12940   p = conversion_obstack_alloc (0);
12941 
12942   conv = reference_binding (type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
12943 			    flags, complain);
12944   /* If this conversion failed, we're in C++20, and we have something like
12945      A& a(b) where A is an aggregate, try again, this time as A& a{b}.  */
12946   if ((!conv || conv->bad_p)
12947       && (flags & LOOKUP_AGGREGATE_PAREN_INIT))
12948     {
12949       tree e = build_constructor_single (init_list_type_node, NULL_TREE, expr);
12950       CONSTRUCTOR_IS_DIRECT_INIT (e) = true;
12951       CONSTRUCTOR_IS_PAREN_INIT (e) = true;
12952       conversion *c = reference_binding (type, TREE_TYPE (e), e,
12953 					 /*c_cast_p=*/false, flags, complain);
12954       /* If this worked, use it.  */
12955       if (c && !c->bad_p)
12956 	expr = e, conv = c;
12957     }
12958   if (!conv || conv->bad_p)
12959     {
12960       if (complain & tf_error)
12961 	{
12962 	  if (conv)
12963 	    convert_like (conv, expr, complain);
12964 	  else if (!CP_TYPE_CONST_P (TREE_TYPE (type))
12965 		   && !TYPE_REF_IS_RVALUE (type)
12966 		   && !lvalue_p (expr))
12967 	    error_at (loc, "invalid initialization of non-const reference of "
12968 		      "type %qH from an rvalue of type %qI",
12969 		      type, TREE_TYPE (expr));
12970 	  else
12971 	    error_at (loc, "invalid initialization of reference of type "
12972 		      "%qH from expression of type %qI", type,
12973 		      TREE_TYPE (expr));
12974 	}
12975       return error_mark_node;
12976     }
12977 
12978   if (conv->kind == ck_ref_bind)
12979     /* Perform the conversion.  */
12980     expr = convert_like (conv, expr, complain);
12981   else if (conv->kind == ck_ambig)
12982     /* We gave an error in build_user_type_conversion_1.  */
12983     expr = error_mark_node;
12984   else
12985     gcc_unreachable ();
12986 
12987   /* Free all the conversions we allocated.  */
12988   obstack_free (&conversion_obstack, p);
12989 
12990   return expr;
12991 }
12992 
12993 /* If *P is an xvalue expression, prevent temporary lifetime extension if it
12994    gets used to initialize a reference.  */
12995 
12996 static tree
prevent_lifetime_extension(tree t)12997 prevent_lifetime_extension (tree t)
12998 {
12999   tree *p = &t;
13000   while (TREE_CODE (*p) == COMPOUND_EXPR)
13001     p = &TREE_OPERAND (*p, 1);
13002   while (handled_component_p (*p))
13003     p = &TREE_OPERAND (*p, 0);
13004   /* Change a TARGET_EXPR from prvalue to xvalue.  */
13005   if (TREE_CODE (*p) == TARGET_EXPR)
13006     *p = build2 (COMPOUND_EXPR, TREE_TYPE (*p), *p,
13007 		 move (TARGET_EXPR_SLOT (*p)));
13008   return t;
13009 }
13010 
13011 /* Subroutine of extend_ref_init_temps.  Possibly extend one initializer,
13012    which is bound either to a reference or a std::initializer_list.  */
13013 
13014 static tree
extend_ref_init_temps_1(tree decl,tree init,vec<tree,va_gc> ** cleanups,tree * cond_guard)13015 extend_ref_init_temps_1 (tree decl, tree init, vec<tree, va_gc> **cleanups,
13016 			 tree *cond_guard)
13017 {
13018   tree sub = init;
13019   tree *p;
13020   STRIP_NOPS (sub);
13021   if (TREE_CODE (sub) == COMPOUND_EXPR)
13022     {
13023       TREE_OPERAND (sub, 1)
13024 	= extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
13025 				   cond_guard);
13026       return init;
13027     }
13028   if (TREE_CODE (sub) == COND_EXPR)
13029     {
13030       tree cur_cond_guard = NULL_TREE;
13031       if (TREE_OPERAND (sub, 1))
13032 	TREE_OPERAND (sub, 1)
13033 	  = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
13034 				     &cur_cond_guard);
13035       if (cur_cond_guard)
13036 	{
13037 	  tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
13038 					   NOP_EXPR, boolean_true_node,
13039 					   tf_warning_or_error);
13040 	  TREE_OPERAND (sub, 1)
13041 	    = cp_build_compound_expr (set, TREE_OPERAND (sub, 1),
13042 				      tf_warning_or_error);
13043 	}
13044       cur_cond_guard = NULL_TREE;
13045       if (TREE_OPERAND (sub, 2))
13046 	TREE_OPERAND (sub, 2)
13047 	  = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 2), cleanups,
13048 				     &cur_cond_guard);
13049       if (cur_cond_guard)
13050 	{
13051 	  tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
13052 					   NOP_EXPR, boolean_true_node,
13053 					   tf_warning_or_error);
13054 	  TREE_OPERAND (sub, 2)
13055 	    = cp_build_compound_expr (set, TREE_OPERAND (sub, 2),
13056 				      tf_warning_or_error);
13057 	}
13058       return init;
13059     }
13060   if (TREE_CODE (sub) != ADDR_EXPR)
13061     return init;
13062   /* Deal with binding to a subobject.  */
13063   for (p = &TREE_OPERAND (sub, 0);
13064        TREE_CODE (*p) == COMPONENT_REF || TREE_CODE (*p) == ARRAY_REF; )
13065     p = &TREE_OPERAND (*p, 0);
13066   if (TREE_CODE (*p) == TARGET_EXPR)
13067     {
13068       tree subinit = NULL_TREE;
13069       *p = set_up_extended_ref_temp (decl, *p, cleanups, &subinit, cond_guard);
13070       recompute_tree_invariant_for_addr_expr (sub);
13071       if (init != sub)
13072 	init = fold_convert (TREE_TYPE (init), sub);
13073       if (subinit)
13074 	init = build2 (COMPOUND_EXPR, TREE_TYPE (init), subinit, init);
13075     }
13076   return init;
13077 }
13078 
13079 /* INIT is part of the initializer for DECL.  If there are any
13080    reference or initializer lists being initialized, extend their
13081    lifetime to match that of DECL.  */
13082 
13083 tree
extend_ref_init_temps(tree decl,tree init,vec<tree,va_gc> ** cleanups,tree * cond_guard)13084 extend_ref_init_temps (tree decl, tree init, vec<tree, va_gc> **cleanups,
13085 		       tree *cond_guard)
13086 {
13087   tree type = TREE_TYPE (init);
13088   if (processing_template_decl)
13089     return init;
13090   if (TYPE_REF_P (type))
13091     init = extend_ref_init_temps_1 (decl, init, cleanups, cond_guard);
13092   else
13093     {
13094       tree ctor = init;
13095       if (TREE_CODE (ctor) == TARGET_EXPR)
13096 	ctor = TARGET_EXPR_INITIAL (ctor);
13097       if (TREE_CODE (ctor) == CONSTRUCTOR)
13098 	{
13099 	  /* [dcl.init] When initializing an aggregate from a parenthesized list
13100 	     of values... a temporary object bound to a reference does not have
13101 	     its lifetime extended.  */
13102 	  if (CONSTRUCTOR_IS_PAREN_INIT (ctor))
13103 	    return init;
13104 
13105 	  if (is_std_init_list (type))
13106 	    {
13107 	      /* The temporary array underlying a std::initializer_list
13108 		 is handled like a reference temporary.  */
13109 	      tree array = CONSTRUCTOR_ELT (ctor, 0)->value;
13110 	      array = extend_ref_init_temps_1 (decl, array, cleanups,
13111 					       cond_guard);
13112 	      CONSTRUCTOR_ELT (ctor, 0)->value = array;
13113 	    }
13114 	  else
13115 	    {
13116 	      unsigned i;
13117 	      constructor_elt *p;
13118 	      vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
13119 	      FOR_EACH_VEC_SAFE_ELT (elts, i, p)
13120 		p->value = extend_ref_init_temps (decl, p->value, cleanups,
13121 						  cond_guard);
13122 	    }
13123 	  recompute_constructor_flags (ctor);
13124 	  if (decl_maybe_constant_var_p (decl) && TREE_CONSTANT (ctor))
13125 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
13126 	}
13127     }
13128 
13129   return init;
13130 }
13131 
13132 /* Returns true iff an initializer for TYPE could contain temporaries that
13133    need to be extended because they are bound to references or
13134    std::initializer_list.  */
13135 
13136 bool
type_has_extended_temps(tree type)13137 type_has_extended_temps (tree type)
13138 {
13139   type = strip_array_types (type);
13140   if (TYPE_REF_P (type))
13141     return true;
13142   if (CLASS_TYPE_P (type))
13143     {
13144       if (is_std_init_list (type))
13145 	return true;
13146       for (tree f = next_initializable_field (TYPE_FIELDS (type));
13147 	   f; f = next_initializable_field (DECL_CHAIN (f)))
13148 	if (type_has_extended_temps (TREE_TYPE (f)))
13149 	  return true;
13150     }
13151   return false;
13152 }
13153 
13154 /* Returns true iff TYPE is some variant of std::initializer_list.  */
13155 
13156 bool
is_std_init_list(tree type)13157 is_std_init_list (tree type)
13158 {
13159   if (!TYPE_P (type))
13160     return false;
13161   if (cxx_dialect == cxx98)
13162     return false;
13163   /* Look through typedefs.  */
13164   type = TYPE_MAIN_VARIANT (type);
13165   return (CLASS_TYPE_P (type)
13166 	  && CP_TYPE_CONTEXT (type) == std_node
13167 	  && init_list_identifier == DECL_NAME (TYPE_NAME (type)));
13168 }
13169 
13170 /* Returns true iff DECL is a list constructor: i.e. a constructor which
13171    will accept an argument list of a single std::initializer_list<T>.  */
13172 
13173 bool
is_list_ctor(tree decl)13174 is_list_ctor (tree decl)
13175 {
13176   tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
13177   tree arg;
13178 
13179   if (!args || args == void_list_node)
13180     return false;
13181 
13182   arg = non_reference (TREE_VALUE (args));
13183   if (!is_std_init_list (arg))
13184     return false;
13185 
13186   args = TREE_CHAIN (args);
13187 
13188   if (args && args != void_list_node && !TREE_PURPOSE (args))
13189     /* There are more non-defaulted parms.  */
13190     return false;
13191 
13192   return true;
13193 }
13194 
13195 #include "gt-cp-call.h"
13196