xref: /netbsd-src/external/gpl3/gcc/dist/gcc/cp/call.cc (revision 0a3071956a3a9fdebdbf7f338cf2d439b45fc728)
1 /* Functions related to invoking -*- C++ -*- methods and overloaded functions.
2    Copyright (C) 1987-2022 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 *
arity_rejection(tree first_arg,int expected,int actual,bool least_p=false)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 
1685        We strip_top_quals here which is also what standard_conversion
1686        does.  Failure to do so would confuse comp_cv_qual_signature
1687        into thinking that in
1688 
1689 	 void f(const int * const &); // #1
1690 	 void f(const int *); // #2
1691 	 int *x;
1692 	 f(x);
1693 
1694        #2 is a better match than #1 even though they're ambiguous (97296).  */
1695     conv = build_conv (ck_qual, strip_top_quals (t), conv);
1696 
1697   return build_conv (ck_ref_bind, type, conv);
1698 }
1699 
1700 /* Returns the conversion path from type FROM to reference type TO for
1701    purposes of reference binding.  For lvalue binding, either pass a
1702    reference type to FROM or an lvalue expression to EXPR.  If the
1703    reference will be bound to a temporary, NEED_TEMPORARY_P is set for
1704    the conversion returned.  If C_CAST_P is true, this
1705    conversion is coming from a C-style cast.  */
1706 
1707 static conversion *
reference_binding(tree rto,tree rfrom,tree expr,bool c_cast_p,int flags,tsubst_flags_t complain)1708 reference_binding (tree rto, tree rfrom, tree expr, bool c_cast_p, int flags,
1709 		   tsubst_flags_t complain)
1710 {
1711   conversion *conv = NULL;
1712   tree to = TREE_TYPE (rto);
1713   tree from = rfrom;
1714   tree tfrom;
1715   bool related_p;
1716   bool compatible_p;
1717   cp_lvalue_kind gl_kind;
1718   bool is_lvalue;
1719 
1720   if (TREE_CODE (to) == FUNCTION_TYPE && expr && type_unknown_p (expr))
1721     {
1722       expr = instantiate_type (to, expr, tf_none);
1723       if (expr == error_mark_node)
1724 	return NULL;
1725       from = TREE_TYPE (expr);
1726     }
1727 
1728   bool copy_list_init = false;
1729   if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1730     {
1731       maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
1732       /* DR 1288: Otherwise, if the initializer list has a single element
1733 	 of type E and ... [T's] referenced type is reference-related to E,
1734 	 the object or reference is initialized from that element...
1735 
1736 	 ??? With P0388R4, we should bind 't' directly to U{}:
1737 	   using U = A[2];
1738 	   A (&&t)[] = {U{}};
1739 	 because A[] and A[2] are reference-related.  But we don't do it
1740 	 because grok_reference_init has deduced the array size (to 1), and
1741 	 A[1] and A[2] aren't reference-related.  */
1742       if (CONSTRUCTOR_NELTS (expr) == 1
1743 	  && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
1744 	{
1745 	  tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
1746 	  if (error_operand_p (elt))
1747 	    return NULL;
1748 	  tree etype = TREE_TYPE (elt);
1749 	  if (reference_related_p (to, etype))
1750 	    {
1751 	      expr = elt;
1752 	      from = etype;
1753 	      goto skip;
1754 	    }
1755 	}
1756       /* Otherwise, if T is a reference type, a prvalue temporary of the type
1757 	 referenced by T is copy-list-initialized, and the reference is bound
1758 	 to that temporary. */
1759       copy_list_init = true;
1760     skip:;
1761     }
1762 
1763   if (TYPE_REF_P (from))
1764     {
1765       from = TREE_TYPE (from);
1766       if (!TYPE_REF_IS_RVALUE (rfrom)
1767 	  || TREE_CODE (from) == FUNCTION_TYPE)
1768 	gl_kind = clk_ordinary;
1769       else
1770 	gl_kind = clk_rvalueref;
1771     }
1772   else if (expr)
1773     gl_kind = lvalue_kind (expr);
1774   else if (CLASS_TYPE_P (from)
1775 	   || TREE_CODE (from) == ARRAY_TYPE)
1776     gl_kind = clk_class;
1777   else
1778     gl_kind = clk_none;
1779 
1780   /* Don't allow a class prvalue when LOOKUP_NO_TEMP_BIND.  */
1781   if ((flags & LOOKUP_NO_TEMP_BIND)
1782       && (gl_kind & clk_class))
1783     gl_kind = clk_none;
1784 
1785   /* Same mask as real_lvalue_p.  */
1786   is_lvalue = gl_kind && !(gl_kind & (clk_rvalueref|clk_class));
1787 
1788   tfrom = from;
1789   if ((gl_kind & clk_bitfield) != 0)
1790     tfrom = unlowered_expr_type (expr);
1791 
1792   /* Figure out whether or not the types are reference-related and
1793      reference compatible.  We have to do this after stripping
1794      references from FROM.  */
1795   related_p = reference_related_p (to, tfrom);
1796   /* If this is a C cast, first convert to an appropriately qualified
1797      type, so that we can later do a const_cast to the desired type.  */
1798   if (related_p && c_cast_p
1799       && !at_least_as_qualified_p (to, tfrom))
1800     to = cp_build_qualified_type (to, cp_type_quals (tfrom));
1801   compatible_p = reference_compatible_p (to, tfrom);
1802 
1803   /* Directly bind reference when target expression's type is compatible with
1804      the reference and expression is an lvalue. In DR391, the wording in
1805      [8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
1806      const and rvalue references to rvalues of compatible class type.
1807      We should also do direct bindings for non-class xvalues.  */
1808   if ((related_p || compatible_p) && gl_kind)
1809     {
1810       /* [dcl.init.ref]
1811 
1812 	 If the initializer expression
1813 
1814 	 -- is an lvalue (but not an lvalue for a bit-field), and "cv1 T1"
1815 	    is reference-compatible with "cv2 T2,"
1816 
1817 	 the reference is bound directly to the initializer expression
1818 	 lvalue.
1819 
1820 	 [...]
1821 	 If the initializer expression is an rvalue, with T2 a class type,
1822 	 and "cv1 T1" is reference-compatible with "cv2 T2", the reference
1823 	 is bound to the object represented by the rvalue or to a sub-object
1824 	 within that object.  */
1825 
1826       conv = build_identity_conv (tfrom, expr);
1827       conv = direct_reference_binding (rto, conv);
1828 
1829       if (TYPE_REF_P (rfrom))
1830 	/* Handle rvalue reference to function properly.  */
1831 	conv->rvaluedness_matches_p
1832 	  = (TYPE_REF_IS_RVALUE (rto) == TYPE_REF_IS_RVALUE (rfrom));
1833       else
1834 	conv->rvaluedness_matches_p
1835           = (TYPE_REF_IS_RVALUE (rto) == !is_lvalue);
1836 
1837       if ((gl_kind & clk_bitfield) != 0
1838 	  || ((gl_kind & clk_packed) != 0 && !TYPE_PACKED (to)))
1839 	/* For the purposes of overload resolution, we ignore the fact
1840 	   this expression is a bitfield or packed field. (In particular,
1841 	   [over.ics.ref] says specifically that a function with a
1842 	   non-const reference parameter is viable even if the
1843 	   argument is a bitfield.)
1844 
1845 	   However, when we actually call the function we must create
1846 	   a temporary to which to bind the reference.  If the
1847 	   reference is volatile, or isn't const, then we cannot make
1848 	   a temporary, so we just issue an error when the conversion
1849 	   actually occurs.  */
1850 	conv->need_temporary_p = true;
1851 
1852       /* Don't allow binding of lvalues (other than function lvalues) to
1853 	 rvalue references.  */
1854       if (is_lvalue && TYPE_REF_IS_RVALUE (rto)
1855 	  && TREE_CODE (to) != FUNCTION_TYPE)
1856 	conv->bad_p = true;
1857 
1858       /* Nor the reverse.  */
1859       if (!is_lvalue && !TYPE_REF_IS_RVALUE (rto)
1860 	  /* Unless it's really an lvalue.  */
1861 	  && !(cxx_dialect >= cxx20
1862 	       && (gl_kind & clk_implicit_rval))
1863 	  && (!CP_TYPE_CONST_NON_VOLATILE_P (to)
1864 	      || (flags & LOOKUP_NO_RVAL_BIND))
1865 	  && TREE_CODE (to) != FUNCTION_TYPE)
1866 	conv->bad_p = true;
1867 
1868       if (!compatible_p)
1869 	conv->bad_p = true;
1870 
1871       return conv;
1872     }
1873   /* [class.conv.fct] A conversion function is never used to convert a
1874      (possibly cv-qualified) object to the (possibly cv-qualified) same
1875      object type (or a reference to it), to a (possibly cv-qualified) base
1876      class of that type (or a reference to it).... */
1877   else if (CLASS_TYPE_P (from) && !related_p
1878 	   && !(flags & LOOKUP_NO_CONVERSION))
1879     {
1880       /* [dcl.init.ref]
1881 
1882 	 If the initializer expression
1883 
1884 	 -- has a class type (i.e., T2 is a class type) can be
1885 	    implicitly converted to an lvalue of type "cv3 T3," where
1886 	    "cv1 T1" is reference-compatible with "cv3 T3".  (this
1887 	    conversion is selected by enumerating the applicable
1888 	    conversion functions (_over.match.ref_) and choosing the
1889 	    best one through overload resolution.  (_over.match_).
1890 
1891 	the reference is bound to the lvalue result of the conversion
1892 	in the second case.  */
1893       z_candidate *cand = build_user_type_conversion_1 (rto, expr, flags,
1894 							complain);
1895       if (cand)
1896 	return cand->second_conv;
1897     }
1898 
1899   /* From this point on, we conceptually need temporaries, even if we
1900      elide them.  Only the cases above are "direct bindings".  */
1901   if (flags & LOOKUP_NO_TEMP_BIND)
1902     return NULL;
1903 
1904   /* [over.ics.rank]
1905 
1906      When a parameter of reference type is not bound directly to an
1907      argument expression, the conversion sequence is the one required
1908      to convert the argument expression to the underlying type of the
1909      reference according to _over.best.ics_.  Conceptually, this
1910      conversion sequence corresponds to copy-initializing a temporary
1911      of the underlying type with the argument expression.  Any
1912      difference in top-level cv-qualification is subsumed by the
1913      initialization itself and does not constitute a conversion.  */
1914 
1915   /* [dcl.init.ref]
1916 
1917      Otherwise, the reference shall be an lvalue reference to a
1918      non-volatile const type, or the reference shall be an rvalue
1919      reference.
1920 
1921      We try below to treat this as a bad conversion to improve diagnostics,
1922      but if TO is an incomplete class, we need to reject this conversion
1923      now to avoid unnecessary instantiation.  */
1924   if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto)
1925       && !COMPLETE_TYPE_P (to))
1926     return NULL;
1927 
1928   /* We're generating a temporary now, but don't bind any more in the
1929      conversion (specifically, don't slice the temporary returned by a
1930      conversion operator).  */
1931   flags |= LOOKUP_NO_TEMP_BIND;
1932 
1933   /* Core issue 899: When [copy-]initializing a temporary to be bound
1934      to the first parameter of a copy constructor (12.8) called with
1935      a single argument in the context of direct-initialization,
1936      explicit conversion functions are also considered.
1937 
1938      So don't set LOOKUP_ONLYCONVERTING in that case.  */
1939   if (!(flags & LOOKUP_COPY_PARM))
1940     flags |= LOOKUP_ONLYCONVERTING;
1941 
1942   if (!conv)
1943     conv = implicit_conversion (to, from, expr, c_cast_p,
1944 				flags, complain);
1945   if (!conv)
1946     return NULL;
1947 
1948   if (conv->user_conv_p)
1949     {
1950       if (copy_list_init)
1951 	/* Remember this was copy-list-initialization.  */
1952 	conv->need_temporary_p = true;
1953 
1954       /* If initializing the temporary used a conversion function,
1955 	 recalculate the second conversion sequence.  */
1956       for (conversion *t = conv; t; t = next_conversion (t))
1957 	if (t->kind == ck_user
1958 	    && DECL_CONV_FN_P (t->cand->fn))
1959 	  {
1960 	    tree ftype = TREE_TYPE (TREE_TYPE (t->cand->fn));
1961 	    /* A prvalue of non-class type is cv-unqualified.  */
1962 	    if (!TYPE_REF_P (ftype) && !CLASS_TYPE_P (ftype))
1963 	      ftype = cv_unqualified (ftype);
1964 	    int sflags = (flags|LOOKUP_NO_CONVERSION)&~LOOKUP_NO_TEMP_BIND;
1965 	    conversion *new_second
1966 	      = reference_binding (rto, ftype, NULL_TREE, c_cast_p,
1967 				   sflags, complain);
1968 	    if (!new_second)
1969 	      return NULL;
1970 	    return merge_conversion_sequences (t, new_second);
1971 	  }
1972     }
1973 
1974   conv = build_conv (ck_ref_bind, rto, conv);
1975   /* This reference binding, unlike those above, requires the
1976      creation of a temporary.  */
1977   conv->need_temporary_p = true;
1978   conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
1979 
1980   /* [dcl.init.ref]
1981 
1982      Otherwise, the reference shall be an lvalue reference to a
1983      non-volatile const type, or the reference shall be an rvalue
1984      reference.  */
1985   if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto))
1986     conv->bad_p = true;
1987 
1988   /* [dcl.init.ref]
1989 
1990      Otherwise, a temporary of type "cv1 T1" is created and
1991      initialized from the initializer expression using the rules for a
1992      non-reference copy initialization.  If T1 is reference-related to
1993      T2, cv1 must be the same cv-qualification as, or greater
1994      cv-qualification than, cv2; otherwise, the program is ill-formed.  */
1995   if (related_p && !at_least_as_qualified_p (to, from))
1996     conv->bad_p = true;
1997 
1998   return conv;
1999 }
2000 
2001 /* Most of the implementation of implicit_conversion, with the same
2002    parameters.  */
2003 
2004 static conversion *
implicit_conversion_1(tree to,tree from,tree expr,bool c_cast_p,int flags,tsubst_flags_t complain)2005 implicit_conversion_1 (tree to, tree from, tree expr, bool c_cast_p,
2006 		       int flags, tsubst_flags_t complain)
2007 {
2008   conversion *conv;
2009 
2010   if (from == error_mark_node || to == error_mark_node
2011       || expr == error_mark_node)
2012     return NULL;
2013 
2014   /* Other flags only apply to the primary function in overload
2015      resolution, or after we've chosen one.  */
2016   flags &= (LOOKUP_ONLYCONVERTING|LOOKUP_NO_CONVERSION|LOOKUP_COPY_PARM
2017 	    |LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND|LOOKUP_PREFER_RVALUE
2018 	    |LOOKUP_NO_NARROWING|LOOKUP_PROTECT|LOOKUP_NO_NON_INTEGRAL);
2019 
2020   /* FIXME: actually we don't want warnings either, but we can't just
2021      have 'complain &= ~(tf_warning|tf_error)' because it would cause
2022      the regression of, eg, g++.old-deja/g++.benjamin/16077.C.
2023      We really ought not to issue that warning until we've committed
2024      to that conversion.  */
2025   complain &= ~tf_error;
2026 
2027   /* Call reshape_init early to remove redundant braces.  */
2028   if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr)
2029       && CLASS_TYPE_P (to)
2030       && COMPLETE_TYPE_P (complete_type (to))
2031       && !CLASSTYPE_NON_AGGREGATE (to))
2032     {
2033       expr = reshape_init (to, expr, complain);
2034       if (expr == error_mark_node)
2035 	return NULL;
2036       from = TREE_TYPE (expr);
2037     }
2038 
2039   if (TYPE_REF_P (to))
2040     conv = reference_binding (to, from, expr, c_cast_p, flags, complain);
2041   else
2042     conv = standard_conversion (to, from, expr, c_cast_p, flags, complain);
2043 
2044   if (conv)
2045     return conv;
2046 
2047   if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
2048     {
2049       if (is_std_init_list (to) && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2050 	return build_list_conv (to, expr, flags, complain);
2051 
2052       /* As an extension, allow list-initialization of _Complex.  */
2053       if (TREE_CODE (to) == COMPLEX_TYPE
2054 	  && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2055 	{
2056 	  conv = build_complex_conv (to, expr, flags, complain);
2057 	  if (conv)
2058 	    return conv;
2059 	}
2060 
2061       /* Allow conversion from an initializer-list with one element to a
2062 	 scalar type.  */
2063       if (SCALAR_TYPE_P (to))
2064 	{
2065 	  int nelts = CONSTRUCTOR_NELTS (expr);
2066 	  tree elt;
2067 
2068 	  if (nelts == 0)
2069 	    elt = build_value_init (to, tf_none);
2070 	  else if (nelts == 1 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2071 	    elt = CONSTRUCTOR_ELT (expr, 0)->value;
2072 	  else
2073 	    elt = error_mark_node;
2074 
2075 	  conv = implicit_conversion (to, TREE_TYPE (elt), elt,
2076 				      c_cast_p, flags, complain);
2077 	  if (conv)
2078 	    {
2079 	      conv->check_narrowing = true;
2080 	      if (BRACE_ENCLOSED_INITIALIZER_P (elt))
2081 		/* Too many levels of braces, i.e. '{{1}}'.  */
2082 		conv->bad_p = true;
2083 	      return conv;
2084 	    }
2085 	}
2086       else if (TREE_CODE (to) == ARRAY_TYPE)
2087 	return build_array_conv (to, expr, flags, complain);
2088     }
2089 
2090   if (expr != NULL_TREE
2091       && (MAYBE_CLASS_TYPE_P (from)
2092 	  || MAYBE_CLASS_TYPE_P (to))
2093       && (flags & LOOKUP_NO_CONVERSION) == 0)
2094     {
2095       struct z_candidate *cand;
2096 
2097       if (CLASS_TYPE_P (to)
2098 	  && BRACE_ENCLOSED_INITIALIZER_P (expr)
2099 	  && !CLASSTYPE_NON_AGGREGATE (complete_type (to)))
2100 	return build_aggr_conv (to, expr, flags, complain);
2101 
2102       cand = build_user_type_conversion_1 (to, expr, flags, complain);
2103       if (cand)
2104 	{
2105 	  if (BRACE_ENCLOSED_INITIALIZER_P (expr)
2106 	      && CONSTRUCTOR_NELTS (expr) == 1
2107 	      && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
2108 	      && !is_list_ctor (cand->fn))
2109 	    {
2110 	      /* "If C is not an initializer-list constructor and the
2111 		 initializer list has a single element of type cv U, where U is
2112 		 X or a class derived from X, the implicit conversion sequence
2113 		 has Exact Match rank if U is X, or Conversion rank if U is
2114 		 derived from X."  */
2115 	      tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
2116 	      tree elttype = TREE_TYPE (elt);
2117 	      if (reference_related_p (to, elttype))
2118 		return implicit_conversion (to, elttype, elt,
2119 					    c_cast_p, flags, complain);
2120 	    }
2121 	  conv = cand->second_conv;
2122 	}
2123 
2124       /* We used to try to bind a reference to a temporary here, but that
2125 	 is now handled after the recursive call to this function at the end
2126 	 of reference_binding.  */
2127       return conv;
2128     }
2129 
2130   return NULL;
2131 }
2132 
2133 /* Returns the implicit conversion sequence (see [over.ics]) from type
2134    FROM to type TO.  The optional expression EXPR may affect the
2135    conversion.  FLAGS are the usual overloading flags.  If C_CAST_P is
2136    true, this conversion is coming from a C-style cast.  */
2137 
2138 static conversion *
implicit_conversion(tree to,tree from,tree expr,bool c_cast_p,int flags,tsubst_flags_t complain)2139 implicit_conversion (tree to, tree from, tree expr, bool c_cast_p,
2140 		     int flags, tsubst_flags_t complain)
2141 {
2142   conversion *conv = implicit_conversion_1 (to, from, expr, c_cast_p,
2143 					    flags, complain);
2144   if (!conv || conv->bad_p)
2145     return conv;
2146   if (conv_is_prvalue (conv)
2147       && CLASS_TYPE_P (conv->type)
2148       && CLASSTYPE_PURE_VIRTUALS (conv->type))
2149     conv->bad_p = true;
2150   return conv;
2151 }
2152 
2153 /* Like implicit_conversion, but return NULL if the conversion is bad.
2154 
2155    This is not static so that check_non_deducible_conversion can call it within
2156    add_template_candidate_real as part of overload resolution; it should not be
2157    called outside of overload resolution.  */
2158 
2159 conversion *
good_conversion(tree to,tree from,tree expr,int flags,tsubst_flags_t complain)2160 good_conversion (tree to, tree from, tree expr,
2161 		 int flags, tsubst_flags_t complain)
2162 {
2163   conversion *c = implicit_conversion (to, from, expr, /*cast*/false,
2164 				       flags, complain);
2165   if (c && c->bad_p)
2166     c = NULL;
2167   return c;
2168 }
2169 
2170 /* Add a new entry to the list of candidates.  Used by the add_*_candidate
2171    functions.  ARGS will not be changed until a single candidate is
2172    selected.  */
2173 
2174 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)2175 add_candidate (struct z_candidate **candidates,
2176 	       tree fn, tree first_arg, const vec<tree, va_gc> *args,
2177 	       size_t num_convs, conversion **convs,
2178 	       tree access_path, tree conversion_path,
2179 	       int viable, struct rejection_reason *reason,
2180 	       int flags)
2181 {
2182   struct z_candidate *cand = (struct z_candidate *)
2183     conversion_obstack_alloc (sizeof (struct z_candidate));
2184 
2185   cand->fn = fn;
2186   cand->first_arg = first_arg;
2187   cand->args = args;
2188   cand->convs = convs;
2189   cand->num_convs = num_convs;
2190   cand->access_path = access_path;
2191   cand->conversion_path = conversion_path;
2192   cand->viable = viable;
2193   cand->reason = reason;
2194   cand->next = *candidates;
2195   cand->flags = flags;
2196   *candidates = cand;
2197 
2198   if (convs && cand->reversed ())
2199     /* Swap the conversions for comparison in joust; we'll swap them back
2200        before build_over_call.  */
2201     std::swap (convs[0], convs[1]);
2202 
2203   return cand;
2204 }
2205 
2206 /* Return the number of remaining arguments in the parameter list
2207    beginning with ARG.  */
2208 
2209 int
remaining_arguments(tree arg)2210 remaining_arguments (tree arg)
2211 {
2212   int n;
2213 
2214   for (n = 0; arg != NULL_TREE && arg != void_list_node;
2215        arg = TREE_CHAIN (arg))
2216     n++;
2217 
2218   return n;
2219 }
2220 
2221 /* [over.match.copy]: When initializing a temporary object (12.2) to be bound
2222    to the first parameter of a constructor where the parameter is of type
2223    "reference to possibly cv-qualified T" and the constructor is called with a
2224    single argument in the context of direct-initialization of an object of type
2225    "cv2 T", explicit conversion functions are also considered.
2226 
2227    So set LOOKUP_COPY_PARM to let reference_binding know that
2228    it's being called in that context.  */
2229 
2230 int
conv_flags(int i,int nargs,tree fn,tree arg,int flags)2231 conv_flags (int i, int nargs, tree fn, tree arg, int flags)
2232 {
2233   int lflags = flags;
2234   tree t;
2235   if (i == 0 && nargs == 1 && DECL_CONSTRUCTOR_P (fn)
2236       && (t = FUNCTION_FIRST_USER_PARMTYPE (fn))
2237       && (same_type_ignoring_top_level_qualifiers_p
2238 	  (non_reference (TREE_VALUE (t)), DECL_CONTEXT (fn))))
2239     {
2240       if (!(flags & LOOKUP_ONLYCONVERTING))
2241 	lflags |= LOOKUP_COPY_PARM;
2242       if ((flags & LOOKUP_LIST_INIT_CTOR)
2243 	  && BRACE_ENCLOSED_INITIALIZER_P (arg))
2244 	lflags |= LOOKUP_NO_CONVERSION;
2245     }
2246   else
2247     lflags |= LOOKUP_ONLYCONVERTING;
2248 
2249   return lflags;
2250 }
2251 
2252 /* Build an appropriate 'this' conversion for the method FN and class
2253    type CTYPE from the value ARG (having type ARGTYPE) to the type PARMTYPE.
2254    This function modifies PARMTYPE, ARGTYPE and ARG.  */
2255 
2256 static conversion *
build_this_conversion(tree fn,tree ctype,tree & parmtype,tree & argtype,tree & arg,int flags,tsubst_flags_t complain)2257 build_this_conversion (tree fn, tree ctype,
2258 		       tree& parmtype, tree& argtype, tree& arg,
2259 		       int flags, tsubst_flags_t complain)
2260 {
2261   gcc_assert (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2262 	      && !DECL_CONSTRUCTOR_P (fn));
2263 
2264   /* The type of the implicit object parameter ('this') for
2265      overload resolution is not always the same as for the
2266      function itself; conversion functions are considered to
2267      be members of the class being converted, and functions
2268      introduced by a using-declaration are considered to be
2269      members of the class that uses them.
2270 
2271      Since build_over_call ignores the ICS for the `this'
2272      parameter, we can just change the parm type.  */
2273   parmtype = cp_build_qualified_type (ctype,
2274 				      cp_type_quals (TREE_TYPE (parmtype)));
2275   bool this_p = true;
2276   if (FUNCTION_REF_QUALIFIED (TREE_TYPE (fn)))
2277     {
2278       /* If the function has a ref-qualifier, the implicit
2279 	 object parameter has reference type.  */
2280       bool rv = FUNCTION_RVALUE_QUALIFIED (TREE_TYPE (fn));
2281       parmtype = cp_build_reference_type (parmtype, rv);
2282       /* The special handling of 'this' conversions in compare_ics
2283 	 does not apply if there is a ref-qualifier.  */
2284       this_p = false;
2285     }
2286   else
2287     {
2288       parmtype = build_pointer_type (parmtype);
2289       /* We don't use build_this here because we don't want to
2290 	 capture the object argument until we've chosen a
2291 	 non-static member function.  */
2292       arg = build_address (arg);
2293       argtype = lvalue_type (arg);
2294     }
2295   flags |= LOOKUP_ONLYCONVERTING;
2296   conversion *t = implicit_conversion (parmtype, argtype, arg,
2297 				       /*c_cast_p=*/false, flags, complain);
2298   t->this_p = this_p;
2299   return t;
2300 }
2301 
2302 /* Create an overload candidate for the function or method FN called
2303    with the argument list FIRST_ARG/ARGS and add it to CANDIDATES.
2304    FLAGS is passed on to implicit_conversion.
2305 
2306    This does not change ARGS.
2307 
2308    CTYPE, if non-NULL, is the type we want to pretend this function
2309    comes from for purposes of overload resolution.
2310 
2311    SHORTCUT_BAD_CONVS controls how we handle "bad" argument conversions.
2312    If true, we stop computing conversions upon seeing the first bad
2313    conversion.  This is used by add_candidates to avoid computing
2314    more conversions than necessary in the presence of a strictly viable
2315    candidate, while preserving the defacto behavior of overload resolution
2316    when it turns out there are only non-strictly viable candidates.  */
2317 
2318 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)2319 add_function_candidate (struct z_candidate **candidates,
2320 			tree fn, tree ctype, tree first_arg,
2321 			const vec<tree, va_gc> *args, tree access_path,
2322 			tree conversion_path, int flags,
2323 			conversion **convs,
2324 			bool shortcut_bad_convs,
2325 			tsubst_flags_t complain)
2326 {
2327   tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
2328   int i, len;
2329   tree parmnode;
2330   tree orig_first_arg = first_arg;
2331   int skip;
2332   int viable = 1;
2333   struct rejection_reason *reason = NULL;
2334 
2335   /* The `this', `in_chrg' and VTT arguments to constructors are not
2336      considered in overload resolution.  */
2337   if (DECL_CONSTRUCTOR_P (fn))
2338     {
2339       if (ctor_omit_inherited_parms (fn))
2340 	/* Bring back parameters omitted from an inherited ctor.  */
2341 	parmlist = FUNCTION_FIRST_USER_PARMTYPE (DECL_ORIGIN (fn));
2342       else
2343 	parmlist = skip_artificial_parms_for (fn, parmlist);
2344       skip = num_artificial_parms_for (fn);
2345       if (skip > 0 && first_arg != NULL_TREE)
2346 	{
2347 	  --skip;
2348 	  first_arg = NULL_TREE;
2349 	}
2350     }
2351   else
2352     skip = 0;
2353 
2354   len = vec_safe_length (args) - skip + (first_arg != NULL_TREE ? 1 : 0);
2355   if (!convs)
2356     convs = alloc_conversions (len);
2357 
2358   /* 13.3.2 - Viable functions [over.match.viable]
2359      First, to be a viable function, a candidate function shall have enough
2360      parameters to agree in number with the arguments in the list.
2361 
2362      We need to check this first; otherwise, checking the ICSes might cause
2363      us to produce an ill-formed template instantiation.  */
2364 
2365   parmnode = parmlist;
2366   for (i = 0; i < len; ++i)
2367     {
2368       if (parmnode == NULL_TREE || parmnode == void_list_node)
2369 	break;
2370       parmnode = TREE_CHAIN (parmnode);
2371     }
2372 
2373   if ((i < len && parmnode)
2374       || !sufficient_parms_p (parmnode))
2375     {
2376       int remaining = remaining_arguments (parmnode);
2377       viable = 0;
2378       reason = arity_rejection (first_arg, i + remaining, len);
2379     }
2380 
2381   /* An inherited constructor (12.6.3 [class.inhctor.init]) that has a first
2382      parameter of type "reference to cv C" (including such a constructor
2383      instantiated from a template) is excluded from the set of candidate
2384      functions when used to construct an object of type D with an argument list
2385      containing a single argument if C is reference-related to D.  */
2386   if (viable && len == 1 && parmlist && DECL_CONSTRUCTOR_P (fn)
2387       && flag_new_inheriting_ctors
2388       && DECL_INHERITED_CTOR (fn))
2389     {
2390       tree ptype = non_reference (TREE_VALUE (parmlist));
2391       tree dtype = DECL_CONTEXT (fn);
2392       tree btype = DECL_INHERITED_CTOR_BASE (fn);
2393       if (reference_related_p (ptype, dtype)
2394 	  && reference_related_p (btype, ptype))
2395 	{
2396 	  viable = false;
2397 	  reason = inherited_ctor_rejection ();
2398 	}
2399     }
2400 
2401   /* Second, for a function to be viable, its constraints must be
2402      satisfied. */
2403   if (flag_concepts && viable && !constraints_satisfied_p (fn))
2404     {
2405       reason = constraint_failure ();
2406       viable = false;
2407     }
2408 
2409   /* When looking for a function from a subobject from an implicit
2410      copy/move constructor/operator=, don't consider anything that takes (a
2411      reference to) an unrelated type.  See c++/44909 and core 1092.  */
2412   if (viable && parmlist && (flags & LOOKUP_DEFAULTED))
2413     {
2414       if (DECL_CONSTRUCTOR_P (fn))
2415 	i = 1;
2416       else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
2417 	       && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR))
2418 	i = 2;
2419       else
2420 	i = 0;
2421       if (i && len == i)
2422 	{
2423 	  parmnode = chain_index (i-1, parmlist);
2424 	  if (!reference_related_p (non_reference (TREE_VALUE (parmnode)),
2425 				    ctype))
2426 	    viable = 0;
2427 	}
2428 
2429       /* This only applies at the top level.  */
2430       flags &= ~LOOKUP_DEFAULTED;
2431     }
2432 
2433   if (! viable)
2434     goto out;
2435 
2436   /* Third, for F to be a viable function, there shall exist for each
2437      argument an implicit conversion sequence that converts that argument
2438      to the corresponding parameter of F.  */
2439 
2440   parmnode = parmlist;
2441 
2442   for (i = 0; i < len; ++i)
2443     {
2444       tree argtype, to_type;
2445       tree arg;
2446 
2447       if (parmnode == void_list_node)
2448 	break;
2449 
2450       if (convs[i])
2451 	{
2452 	  /* Already set during deduction.  */
2453 	  parmnode = TREE_CHAIN (parmnode);
2454 	  continue;
2455 	}
2456 
2457       if (i == 0 && first_arg != NULL_TREE)
2458 	arg = first_arg;
2459       else
2460 	arg = CONST_CAST_TREE (
2461 		(*args)[i + skip - (first_arg != NULL_TREE ? 1 : 0)]);
2462       argtype = lvalue_type (arg);
2463 
2464       conversion *t;
2465       if (parmnode)
2466 	{
2467 	  tree parmtype = TREE_VALUE (parmnode);
2468 	  if (i == 0
2469 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2470 	      && !DECL_CONSTRUCTOR_P (fn))
2471 	    t = build_this_conversion (fn, ctype, parmtype, argtype, arg,
2472 				       flags, complain);
2473 	  else
2474 	    {
2475 	      int lflags = conv_flags (i, len-skip, fn, arg, flags);
2476 	      t = implicit_conversion (parmtype, argtype, arg,
2477 				       /*c_cast_p=*/false, lflags, complain);
2478 	    }
2479 	  to_type = parmtype;
2480 	  parmnode = TREE_CHAIN (parmnode);
2481 	}
2482       else
2483 	{
2484 	  t = build_identity_conv (argtype, arg);
2485 	  t->ellipsis_p = true;
2486 	  to_type = argtype;
2487 	}
2488 
2489       convs[i] = t;
2490       if (! t)
2491 	{
2492 	  viable = 0;
2493 	  reason = arg_conversion_rejection (first_arg, i, argtype, to_type,
2494 					     EXPR_LOCATION (arg));
2495 	  break;
2496 	}
2497 
2498       if (t->bad_p)
2499 	{
2500 	  viable = -1;
2501 	  reason = bad_arg_conversion_rejection (first_arg, i, arg, to_type,
2502 						 EXPR_LOCATION (arg));
2503 	  if (shortcut_bad_convs)
2504 	    break;
2505 	}
2506     }
2507 
2508  out:
2509   return add_candidate (candidates, fn, orig_first_arg, args, len, convs,
2510 			access_path, conversion_path, viable, reason, flags);
2511 }
2512 
2513 /* Create an overload candidate for the conversion function FN which will
2514    be invoked for expression OBJ, producing a pointer-to-function which
2515    will in turn be called with the argument list FIRST_ARG/ARGLIST,
2516    and add it to CANDIDATES.  This does not change ARGLIST.  FLAGS is
2517    passed on to implicit_conversion.
2518 
2519    Actually, we don't really care about FN; we care about the type it
2520    converts to.  There may be multiple conversion functions that will
2521    convert to that type, and we rely on build_user_type_conversion_1 to
2522    choose the best one; so when we create our candidate, we record the type
2523    instead of the function.  */
2524 
2525 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)2526 add_conv_candidate (struct z_candidate **candidates, tree fn, tree obj,
2527 		    const vec<tree, va_gc> *arglist,
2528 		    tree access_path, tree conversion_path,
2529 		    tsubst_flags_t complain)
2530 {
2531   tree totype = TREE_TYPE (TREE_TYPE (fn));
2532   int i, len, viable, flags;
2533   tree parmlist, parmnode;
2534   conversion **convs;
2535   struct rejection_reason *reason;
2536 
2537   for (parmlist = totype; TREE_CODE (parmlist) != FUNCTION_TYPE; )
2538     parmlist = TREE_TYPE (parmlist);
2539   parmlist = TYPE_ARG_TYPES (parmlist);
2540 
2541   len = vec_safe_length (arglist) + 1;
2542   convs = alloc_conversions (len);
2543   parmnode = parmlist;
2544   viable = 1;
2545   flags = LOOKUP_IMPLICIT;
2546   reason = NULL;
2547 
2548   /* Don't bother looking up the same type twice.  */
2549   if (*candidates && (*candidates)->fn == totype)
2550     return NULL;
2551 
2552   for (i = 0; i < len; ++i)
2553     {
2554       tree arg, argtype, convert_type = NULL_TREE;
2555       conversion *t;
2556 
2557       if (i == 0)
2558 	arg = obj;
2559       else
2560 	arg = (*arglist)[i - 1];
2561       argtype = lvalue_type (arg);
2562 
2563       if (i == 0)
2564 	{
2565 	  t = build_identity_conv (argtype, NULL_TREE);
2566 	  t = build_conv (ck_user, totype, t);
2567 	  /* Leave the 'cand' field null; we'll figure out the conversion in
2568 	     convert_like if this candidate is chosen.  */
2569 	  convert_type = totype;
2570 	}
2571       else if (parmnode == void_list_node)
2572 	break;
2573       else if (parmnode)
2574 	{
2575 	  t = implicit_conversion (TREE_VALUE (parmnode), argtype, arg,
2576 				   /*c_cast_p=*/false, flags, complain);
2577 	  convert_type = TREE_VALUE (parmnode);
2578 	}
2579       else
2580 	{
2581 	  t = build_identity_conv (argtype, arg);
2582 	  t->ellipsis_p = true;
2583 	  convert_type = argtype;
2584 	}
2585 
2586       convs[i] = t;
2587       if (! t)
2588 	break;
2589 
2590       if (t->bad_p)
2591 	{
2592 	  viable = -1;
2593 	  reason = bad_arg_conversion_rejection (NULL_TREE, i, arg, convert_type,
2594 						 EXPR_LOCATION (arg));
2595 	}
2596 
2597       if (i == 0)
2598 	continue;
2599 
2600       if (parmnode)
2601 	parmnode = TREE_CHAIN (parmnode);
2602     }
2603 
2604   if (i < len
2605       || ! sufficient_parms_p (parmnode))
2606     {
2607       int remaining = remaining_arguments (parmnode);
2608       viable = 0;
2609       reason = arity_rejection (NULL_TREE, i + remaining, len);
2610     }
2611 
2612   return add_candidate (candidates, totype, obj, arglist, len, convs,
2613 			access_path, conversion_path, viable, reason, flags);
2614 }
2615 
2616 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)2617 build_builtin_candidate (struct z_candidate **candidates, tree fnname,
2618 			 tree type1, tree type2, const vec<tree,va_gc> &args,
2619 			 tree *argtypes, int flags, tsubst_flags_t complain)
2620 {
2621   conversion *t;
2622   conversion **convs;
2623   size_t num_convs;
2624   int viable = 1;
2625   tree types[2];
2626   struct rejection_reason *reason = NULL;
2627 
2628   types[0] = type1;
2629   types[1] = type2;
2630 
2631   num_convs = args.length ();
2632   convs = alloc_conversions (num_convs);
2633 
2634   /* TRUTH_*_EXPR do "contextual conversion to bool", which means explicit
2635      conversion ops are allowed.  We handle that here by just checking for
2636      boolean_type_node because other operators don't ask for it.  COND_EXPR
2637      also does contextual conversion to bool for the first operand, but we
2638      handle that in build_conditional_expr, and type1 here is operand 2.  */
2639   if (type1 != boolean_type_node)
2640     flags |= LOOKUP_ONLYCONVERTING;
2641 
2642   for (unsigned i = 0; i < 2 && i < num_convs; ++i)
2643     {
2644       t = implicit_conversion (types[i], argtypes[i], args[i],
2645 			       /*c_cast_p=*/false, flags, complain);
2646       if (! t)
2647 	{
2648 	  viable = 0;
2649 	  /* We need something for printing the candidate.  */
2650 	  t = build_identity_conv (types[i], NULL_TREE);
2651 	  reason = arg_conversion_rejection (NULL_TREE, i, argtypes[i],
2652 					     types[i], EXPR_LOCATION (args[i]));
2653 	}
2654       else if (t->bad_p)
2655 	{
2656 	  viable = 0;
2657 	  reason = bad_arg_conversion_rejection (NULL_TREE, i, args[i],
2658 						 types[i],
2659 						 EXPR_LOCATION (args[i]));
2660 	}
2661       convs[i] = t;
2662     }
2663 
2664   /* For COND_EXPR we rearranged the arguments; undo that now.  */
2665   if (num_convs == 3)
2666     {
2667       convs[2] = convs[1];
2668       convs[1] = convs[0];
2669       t = implicit_conversion (boolean_type_node, argtypes[2], args[2],
2670 			       /*c_cast_p=*/false, flags,
2671 			       complain);
2672       if (t)
2673 	convs[0] = t;
2674       else
2675 	{
2676 	  viable = 0;
2677 	  reason = arg_conversion_rejection (NULL_TREE, 0, argtypes[2],
2678 					     boolean_type_node,
2679 					     EXPR_LOCATION (args[2]));
2680 	}
2681     }
2682 
2683   add_candidate (candidates, fnname, /*first_arg=*/NULL_TREE, /*args=*/NULL,
2684 		 num_convs, convs,
2685 		 /*access_path=*/NULL_TREE,
2686 		 /*conversion_path=*/NULL_TREE,
2687 		 viable, reason, flags);
2688 }
2689 
2690 static bool
is_complete(tree t)2691 is_complete (tree t)
2692 {
2693   return COMPLETE_TYPE_P (complete_type (t));
2694 }
2695 
2696 /* Returns nonzero if TYPE is a promoted arithmetic type.  */
2697 
2698 static bool
promoted_arithmetic_type_p(tree type)2699 promoted_arithmetic_type_p (tree type)
2700 {
2701   /* [over.built]
2702 
2703      In this section, the term promoted integral type is used to refer
2704      to those integral types which are preserved by integral promotion
2705      (including e.g.  int and long but excluding e.g.  char).
2706      Similarly, the term promoted arithmetic type refers to promoted
2707      integral types plus floating types.  */
2708   return ((CP_INTEGRAL_TYPE_P (type)
2709 	   && same_type_p (type_promotes_to (type), type))
2710 	  || TREE_CODE (type) == REAL_TYPE);
2711 }
2712 
2713 /* Create any builtin operator overload candidates for the operator in
2714    question given the converted operand types TYPE1 and TYPE2.  The other
2715    args are passed through from add_builtin_candidates to
2716    build_builtin_candidate.
2717 
2718    TYPE1 and TYPE2 may not be permissible, and we must filter them.
2719    If CODE is requires candidates operands of the same type of the kind
2720    of which TYPE1 and TYPE2 are, we add both candidates
2721    CODE (TYPE1, TYPE1) and CODE (TYPE2, TYPE2).  */
2722 
2723 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)2724 add_builtin_candidate (struct z_candidate **candidates, enum tree_code code,
2725 		       enum tree_code code2, tree fnname, tree type1,
2726 		       tree type2, vec<tree,va_gc> &args, tree *argtypes,
2727 		       int flags, tsubst_flags_t complain)
2728 {
2729   switch (code)
2730     {
2731     case POSTINCREMENT_EXPR:
2732     case POSTDECREMENT_EXPR:
2733       args[1] = integer_zero_node;
2734       type2 = integer_type_node;
2735       break;
2736     default:
2737       break;
2738     }
2739 
2740   switch (code)
2741     {
2742 
2743 /* 4 For every pair (T, VQ), where T is an arithmetic type other than bool,
2744      and  VQ  is  either  volatile or empty, there exist candidate operator
2745      functions of the form
2746 	     VQ T&   operator++(VQ T&);
2747 	     T       operator++(VQ T&, int);
2748    5 For every pair (T, VQ), where T is an arithmetic type other than bool,
2749      and VQ is either volatile or empty, there exist candidate operator
2750      functions of the form
2751 	     VQ T&   operator--(VQ T&);
2752 	     T       operator--(VQ T&, int);
2753    6 For every pair (T, VQ), where T is a cv-qualified or cv-unqualified object
2754      type, and VQ is either volatile or empty, there exist candidate operator
2755      functions of the form
2756 	     T*VQ&   operator++(T*VQ&);
2757 	     T*VQ&   operator--(T*VQ&);
2758 	     T*      operator++(T*VQ&, int);
2759 	     T*      operator--(T*VQ&, int);  */
2760 
2761     case POSTDECREMENT_EXPR:
2762     case PREDECREMENT_EXPR:
2763       if (TREE_CODE (type1) == BOOLEAN_TYPE)
2764 	return;
2765       /* FALLTHRU */
2766     case POSTINCREMENT_EXPR:
2767     case PREINCREMENT_EXPR:
2768       /* P0002R1, Remove deprecated operator++(bool) added "other than bool"
2769 	 to p4.  */
2770       if (TREE_CODE (type1) == BOOLEAN_TYPE && cxx_dialect >= cxx17)
2771 	return;
2772       if (ARITHMETIC_TYPE_P (type1) || TYPE_PTROB_P (type1))
2773 	{
2774 	  type1 = build_reference_type (type1);
2775 	  break;
2776 	}
2777       return;
2778 
2779 /* 7 For every cv-qualified or cv-unqualified object type T, there
2780      exist candidate operator functions of the form
2781 
2782 	     T&      operator*(T*);
2783 
2784 
2785    8 For every function type T that does not have cv-qualifiers or
2786      a ref-qualifier, there exist candidate operator functions of the form
2787 	     T&      operator*(T*);  */
2788 
2789     case INDIRECT_REF:
2790       if (TYPE_PTR_P (type1)
2791 	  && (TYPE_PTROB_P (type1)
2792 	      || TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE))
2793 	break;
2794       return;
2795 
2796 /* 9 For every type T, there exist candidate operator functions of the form
2797 	     T*      operator+(T*);
2798 
2799    10 For every floating-point or promoted integral type T, there exist
2800       candidate operator functions of the form
2801 	     T       operator+(T);
2802 	     T       operator-(T);  */
2803 
2804     case UNARY_PLUS_EXPR: /* unary + */
2805       if (TYPE_PTR_P (type1))
2806 	break;
2807       /* FALLTHRU */
2808     case NEGATE_EXPR:
2809       if (ARITHMETIC_TYPE_P (type1))
2810 	break;
2811       return;
2812 
2813 /* 11 For every promoted integral type T,  there  exist  candidate  operator
2814       functions of the form
2815 	     T       operator~(T);  */
2816 
2817     case BIT_NOT_EXPR:
2818       if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1))
2819 	break;
2820       return;
2821 
2822 /* 12 For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, C1
2823      is the same type as C2 or is a derived class of C2, and T is an object
2824      type or a function type there exist candidate operator functions of the
2825      form
2826 	     CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
2827      where CV12 is the union of CV1 and CV2.  */
2828 
2829     case MEMBER_REF:
2830       if (TYPE_PTR_P (type1) && TYPE_PTRMEM_P (type2))
2831 	{
2832 	  tree c1 = TREE_TYPE (type1);
2833 	  tree c2 = TYPE_PTRMEM_CLASS_TYPE (type2);
2834 
2835 	  if (CLASS_TYPE_P (c1) && DERIVED_FROM_P (c2, c1)
2836 	      && (TYPE_PTRMEMFUNC_P (type2)
2837 		  || is_complete (TYPE_PTRMEM_POINTED_TO_TYPE (type2))))
2838 	    break;
2839 	}
2840       return;
2841 
2842 /* 13 For every pair of types L and R, where each of L and R is a floating-point
2843       or promoted integral type, there exist candidate operator functions of the
2844       form
2845 	     LR      operator*(L, R);
2846 	     LR      operator/(L, R);
2847 	     LR      operator+(L, R);
2848 	     LR      operator-(L, R);
2849 	     bool    operator<(L, R);
2850 	     bool    operator>(L, R);
2851 	     bool    operator<=(L, R);
2852 	     bool    operator>=(L, R);
2853 	     bool    operator==(L, R);
2854 	     bool    operator!=(L, R);
2855       where  LR  is  the  result of the usual arithmetic conversions between
2856       types L and R.
2857 
2858    14 For every integral type T there exists a candidate operator function of
2859       the form
2860 
2861        std::strong_ordering operator<=>(T, T);
2862 
2863    15 For every pair of floating-point types L and R, there exists a candidate
2864       operator function of the form
2865 
2866        std::partial_ordering operator<=>(L, R);
2867 
2868    16 For every cv-qualified or cv-unqualified object type T there exist
2869       candidate operator functions of the form
2870 	     T*      operator+(T*, std::ptrdiff_t);
2871 	     T&      operator[](T*, std::ptrdiff_t);
2872 	     T*      operator-(T*, std::ptrdiff_t);
2873 	     T*      operator+(std::ptrdiff_t, T*);
2874 	     T&      operator[](std::ptrdiff_t, T*);
2875 
2876    17 For every T, where T is a pointer to object type, there exist candidate
2877       operator functions of the form
2878 	     std::ptrdiff_t operator-(T, T);
2879 
2880    18 For every T, where T is an enumeration type or a pointer type, there
2881       exist candidate operator functions of the form
2882 	     bool    operator<(T, T);
2883 	     bool    operator>(T, T);
2884 	     bool    operator<=(T, T);
2885 	     bool    operator>=(T, T);
2886 	     bool    operator==(T, T);
2887 	     bool    operator!=(T, T);
2888 	     R       operator<=>(T, T);
2889 
2890       where R is the result type specified in [expr.spaceship].
2891 
2892    19 For every T, where T is a pointer-to-member type or std::nullptr_t,
2893       there exist candidate operator functions of the form
2894 	     bool    operator==(T, T);
2895 	     bool    operator!=(T, T);  */
2896 
2897     case MINUS_EXPR:
2898       if (TYPE_PTROB_P (type1) && TYPE_PTROB_P (type2))
2899 	break;
2900       if (TYPE_PTROB_P (type1)
2901 	  && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2902 	{
2903 	  type2 = ptrdiff_type_node;
2904 	  break;
2905 	}
2906       /* FALLTHRU */
2907     case MULT_EXPR:
2908     case TRUNC_DIV_EXPR:
2909       if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2910 	break;
2911       return;
2912 
2913       /* This isn't exactly what's specified above for operator<=>, but it's
2914 	 close enough.  In particular, we don't care about the return type
2915 	 specified above; it doesn't participate in overload resolution and it
2916 	 doesn't affect the semantics of the built-in operator.  */
2917     case SPACESHIP_EXPR:
2918     case EQ_EXPR:
2919     case NE_EXPR:
2920       if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
2921 	  || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2)))
2922 	break;
2923       if (NULLPTR_TYPE_P (type1) && NULLPTR_TYPE_P (type2))
2924 	break;
2925       if (TYPE_PTRMEM_P (type1) && null_ptr_cst_p (args[1]))
2926 	{
2927 	  type2 = type1;
2928 	  break;
2929 	}
2930       if (TYPE_PTRMEM_P (type2) && null_ptr_cst_p (args[0]))
2931 	{
2932 	  type1 = type2;
2933 	  break;
2934 	}
2935       /* Fall through.  */
2936     case LT_EXPR:
2937     case GT_EXPR:
2938     case LE_EXPR:
2939     case GE_EXPR:
2940     case MAX_EXPR:
2941     case MIN_EXPR:
2942       if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2943 	break;
2944       if (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
2945 	break;
2946       if (TREE_CODE (type1) == ENUMERAL_TYPE
2947 	  && TREE_CODE (type2) == ENUMERAL_TYPE)
2948 	break;
2949       if (TYPE_PTR_P (type1)
2950 	  && null_ptr_cst_p (args[1]))
2951 	{
2952 	  type2 = type1;
2953 	  break;
2954 	}
2955       if (null_ptr_cst_p (args[0])
2956 	  && TYPE_PTR_P (type2))
2957 	{
2958 	  type1 = type2;
2959 	  break;
2960 	}
2961       return;
2962 
2963     case PLUS_EXPR:
2964       if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2965 	break;
2966       /* FALLTHRU */
2967     case ARRAY_REF:
2968       if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && TYPE_PTROB_P (type2))
2969 	{
2970 	  type1 = ptrdiff_type_node;
2971 	  break;
2972 	}
2973       if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2974 	{
2975 	  type2 = ptrdiff_type_node;
2976 	  break;
2977 	}
2978       return;
2979 
2980 /* 18For  every pair of promoted integral types L and R, there exist candi-
2981      date operator functions of the form
2982 	     LR      operator%(L, R);
2983 	     LR      operator&(L, R);
2984 	     LR      operator^(L, R);
2985 	     LR      operator|(L, R);
2986 	     L       operator<<(L, R);
2987 	     L       operator>>(L, R);
2988      where LR is the result of the  usual  arithmetic  conversions  between
2989      types L and R.  */
2990 
2991     case TRUNC_MOD_EXPR:
2992     case BIT_AND_EXPR:
2993     case BIT_IOR_EXPR:
2994     case BIT_XOR_EXPR:
2995     case LSHIFT_EXPR:
2996     case RSHIFT_EXPR:
2997       if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2998 	break;
2999       return;
3000 
3001 /* 19For  every  triple  L, VQ, R), where L is an arithmetic or enumeration
3002      type, VQ is either volatile or empty, and R is a  promoted  arithmetic
3003      type, there exist candidate operator functions of the form
3004 	     VQ L&   operator=(VQ L&, R);
3005 	     VQ L&   operator*=(VQ L&, R);
3006 	     VQ L&   operator/=(VQ L&, R);
3007 	     VQ L&   operator+=(VQ L&, R);
3008 	     VQ L&   operator-=(VQ L&, R);
3009 
3010    20For  every  pair T, VQ), where T is any type and VQ is either volatile
3011      or empty, there exist candidate operator functions of the form
3012 	     T*VQ&   operator=(T*VQ&, T*);
3013 
3014    21For every pair T, VQ), where T is a pointer to member type and  VQ  is
3015      either  volatile or empty, there exist candidate operator functions of
3016      the form
3017 	     VQ T&   operator=(VQ T&, T);
3018 
3019    22For every triple  T,  VQ,  I),  where  T  is  a  cv-qualified  or  cv-
3020      unqualified  complete object type, VQ is either volatile or empty, and
3021      I is a promoted integral type, there exist  candidate  operator  func-
3022      tions of the form
3023 	     T*VQ&   operator+=(T*VQ&, I);
3024 	     T*VQ&   operator-=(T*VQ&, I);
3025 
3026    23For  every  triple  L,  VQ,  R), where L is an integral or enumeration
3027      type, VQ is either volatile or empty, and R  is  a  promoted  integral
3028      type, there exist candidate operator functions of the form
3029 
3030 	     VQ L&   operator%=(VQ L&, R);
3031 	     VQ L&   operator<<=(VQ L&, R);
3032 	     VQ L&   operator>>=(VQ L&, R);
3033 	     VQ L&   operator&=(VQ L&, R);
3034 	     VQ L&   operator^=(VQ L&, R);
3035 	     VQ L&   operator|=(VQ L&, R);  */
3036 
3037     case MODIFY_EXPR:
3038       switch (code2)
3039 	{
3040 	case PLUS_EXPR:
3041 	case MINUS_EXPR:
3042 	  if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3043 	    {
3044 	      type2 = ptrdiff_type_node;
3045 	      break;
3046 	    }
3047 	  /* FALLTHRU */
3048 	case MULT_EXPR:
3049 	case TRUNC_DIV_EXPR:
3050 	  if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3051 	    break;
3052 	  return;
3053 
3054 	case TRUNC_MOD_EXPR:
3055 	case BIT_AND_EXPR:
3056 	case BIT_IOR_EXPR:
3057 	case BIT_XOR_EXPR:
3058 	case LSHIFT_EXPR:
3059 	case RSHIFT_EXPR:
3060 	  if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3061 	    break;
3062 	  return;
3063 
3064 	case NOP_EXPR:
3065 	  if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3066 	    break;
3067 	  if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3068 	      || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3069 	      || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3070 	      || ((TYPE_PTRMEMFUNC_P (type1)
3071 		   || TYPE_PTR_P (type1))
3072 		  && null_ptr_cst_p (args[1])))
3073 	    {
3074 	      type2 = type1;
3075 	      break;
3076 	    }
3077 	  return;
3078 
3079 	default:
3080 	  gcc_unreachable ();
3081 	}
3082       type1 = build_reference_type (type1);
3083       break;
3084 
3085     case COND_EXPR:
3086       /* [over.built]
3087 
3088 	 For every pair of promoted arithmetic types L and R, there
3089 	 exist candidate operator functions of the form
3090 
3091 	 LR operator?(bool, L, R);
3092 
3093 	 where LR is the result of the usual arithmetic conversions
3094 	 between types L and R.
3095 
3096 	 For every type T, where T is a pointer or pointer-to-member
3097 	 type, there exist candidate operator functions of the form T
3098 	 operator?(bool, T, T);  */
3099 
3100       if (promoted_arithmetic_type_p (type1)
3101 	  && promoted_arithmetic_type_p (type2))
3102 	/* That's OK.  */
3103 	break;
3104 
3105       /* Otherwise, the types should be pointers.  */
3106       if (!TYPE_PTR_OR_PTRMEM_P (type1) || !TYPE_PTR_OR_PTRMEM_P (type2))
3107 	return;
3108 
3109       /* We don't check that the two types are the same; the logic
3110 	 below will actually create two candidates; one in which both
3111 	 parameter types are TYPE1, and one in which both parameter
3112 	 types are TYPE2.  */
3113       break;
3114 
3115     case REALPART_EXPR:
3116     case IMAGPART_EXPR:
3117       if (ARITHMETIC_TYPE_P (type1))
3118 	break;
3119       return;
3120 
3121     default:
3122       gcc_unreachable ();
3123     }
3124 
3125   /* Make sure we don't create builtin candidates with dependent types.  */
3126   bool u1 = uses_template_parms (type1);
3127   bool u2 = type2 ? uses_template_parms (type2) : false;
3128   if (u1 || u2)
3129     {
3130       /* Try to recover if one of the types is non-dependent.  But if
3131 	 there's only one type, there's nothing we can do.  */
3132       if (!type2)
3133 	return;
3134       /* And we lose if both are dependent.  */
3135       if (u1 && u2)
3136 	return;
3137       /* Or if they have different forms.  */
3138       if (TREE_CODE (type1) != TREE_CODE (type2))
3139 	return;
3140 
3141       if (u1 && !u2)
3142 	type1 = type2;
3143       else if (u2 && !u1)
3144 	type2 = type1;
3145     }
3146 
3147   /* If we're dealing with two pointer types or two enumeral types,
3148      we need candidates for both of them.  */
3149   if (type2 && !same_type_p (type1, type2)
3150       && TREE_CODE (type1) == TREE_CODE (type2)
3151       && (TYPE_REF_P (type1)
3152 	  || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3153 	  || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3154 	  || TYPE_PTRMEMFUNC_P (type1)
3155 	  || MAYBE_CLASS_TYPE_P (type1)
3156 	  || TREE_CODE (type1) == ENUMERAL_TYPE))
3157     {
3158       if (TYPE_PTR_OR_PTRMEM_P (type1))
3159 	{
3160 	  tree cptype = composite_pointer_type (input_location,
3161 						type1, type2,
3162 						error_mark_node,
3163 						error_mark_node,
3164 						CPO_CONVERSION,
3165 						tf_none);
3166 	  if (cptype != error_mark_node)
3167 	    {
3168 	      build_builtin_candidate
3169 		(candidates, fnname, cptype, cptype, args, argtypes,
3170 		 flags, complain);
3171 	      return;
3172 	    }
3173 	}
3174 
3175       build_builtin_candidate
3176 	(candidates, fnname, type1, type1, args, argtypes, flags, complain);
3177       build_builtin_candidate
3178 	(candidates, fnname, type2, type2, args, argtypes, flags, complain);
3179       return;
3180     }
3181 
3182   build_builtin_candidate
3183     (candidates, fnname, type1, type2, args, argtypes, flags, complain);
3184 }
3185 
3186 tree
type_decays_to(tree type)3187 type_decays_to (tree type)
3188 {
3189   if (TREE_CODE (type) == ARRAY_TYPE)
3190     return build_pointer_type (TREE_TYPE (type));
3191   if (TREE_CODE (type) == FUNCTION_TYPE)
3192     return build_pointer_type (type);
3193   return type;
3194 }
3195 
3196 /* There are three conditions of builtin candidates:
3197 
3198    1) bool-taking candidates.  These are the same regardless of the input.
3199    2) pointer-pair taking candidates.  These are generated for each type
3200       one of the input types converts to.
3201    3) arithmetic candidates.  According to the standard, we should generate
3202       all of these, but I'm trying not to...
3203 
3204    Here we generate a superset of the possible candidates for this particular
3205    case.  That is a subset of the full set the standard defines, plus some
3206    other cases which the standard disallows. add_builtin_candidate will
3207    filter out the invalid set.  */
3208 
3209 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)3210 add_builtin_candidates (struct z_candidate **candidates, enum tree_code code,
3211 			enum tree_code code2, tree fnname,
3212 			vec<tree, va_gc> *argv,
3213 			int flags, tsubst_flags_t complain)
3214 {
3215   int ref1;
3216   int enum_p = 0;
3217   tree type, argtypes[3], t;
3218   /* TYPES[i] is the set of possible builtin-operator parameter types
3219      we will consider for the Ith argument.  */
3220   vec<tree, va_gc> *types[2];
3221   unsigned ix;
3222   vec<tree, va_gc> &args = *argv;
3223   unsigned len = args.length ();
3224 
3225   for (unsigned i = 0; i < len; ++i)
3226     {
3227       if (args[i])
3228 	argtypes[i] = unlowered_expr_type (args[i]);
3229       else
3230 	argtypes[i] = NULL_TREE;
3231     }
3232 
3233   switch (code)
3234     {
3235 /* 4 For every pair T, VQ), where T is an arithmetic or  enumeration  type,
3236      and  VQ  is  either  volatile or empty, there exist candidate operator
3237      functions of the form
3238 		 VQ T&   operator++(VQ T&);  */
3239 
3240     case POSTINCREMENT_EXPR:
3241     case PREINCREMENT_EXPR:
3242     case POSTDECREMENT_EXPR:
3243     case PREDECREMENT_EXPR:
3244     case MODIFY_EXPR:
3245       ref1 = 1;
3246       break;
3247 
3248 /* 24There also exist candidate operator functions of the form
3249 	     bool    operator!(bool);
3250 	     bool    operator&&(bool, bool);
3251 	     bool    operator||(bool, bool);  */
3252 
3253     case TRUTH_NOT_EXPR:
3254       build_builtin_candidate
3255 	(candidates, fnname, boolean_type_node,
3256 	 NULL_TREE, args, argtypes, flags, complain);
3257       return;
3258 
3259     case TRUTH_ORIF_EXPR:
3260     case TRUTH_ANDIF_EXPR:
3261       build_builtin_candidate
3262 	(candidates, fnname, boolean_type_node,
3263 	 boolean_type_node, args, argtypes, flags, complain);
3264       return;
3265 
3266     case ADDR_EXPR:
3267     case COMPOUND_EXPR:
3268     case COMPONENT_REF:
3269     case CO_AWAIT_EXPR:
3270       return;
3271 
3272     case COND_EXPR:
3273     case EQ_EXPR:
3274     case NE_EXPR:
3275     case LT_EXPR:
3276     case LE_EXPR:
3277     case GT_EXPR:
3278     case GE_EXPR:
3279     case SPACESHIP_EXPR:
3280       enum_p = 1;
3281       /* Fall through.  */
3282 
3283     default:
3284       ref1 = 0;
3285     }
3286 
3287   types[0] = make_tree_vector ();
3288   types[1] = make_tree_vector ();
3289 
3290   if (len == 3)
3291     len = 2;
3292   for (unsigned i = 0; i < len; ++i)
3293     {
3294       if (MAYBE_CLASS_TYPE_P (argtypes[i]))
3295 	{
3296 	  tree convs;
3297 
3298 	  if (i == 0 && code == MODIFY_EXPR && code2 == NOP_EXPR)
3299 	    return;
3300 
3301 	  convs = lookup_conversions (argtypes[i]);
3302 
3303 	  if (code == COND_EXPR)
3304 	    {
3305 	      if (lvalue_p (args[i]))
3306 		vec_safe_push (types[i], build_reference_type (argtypes[i]));
3307 
3308 	      vec_safe_push (types[i], TYPE_MAIN_VARIANT (argtypes[i]));
3309 	    }
3310 
3311 	  else if (! convs)
3312 	    return;
3313 
3314 	  for (; convs; convs = TREE_CHAIN (convs))
3315 	    {
3316 	      type = TREE_TYPE (convs);
3317 
3318 	      if (i == 0 && ref1
3319 		  && (!TYPE_REF_P (type)
3320 		      || CP_TYPE_CONST_P (TREE_TYPE (type))))
3321 		continue;
3322 
3323 	      if (code == COND_EXPR && TYPE_REF_P (type))
3324 		vec_safe_push (types[i], type);
3325 
3326 	      type = non_reference (type);
3327 	      if (i != 0 || ! ref1)
3328 		{
3329 		  type = cv_unqualified (type_decays_to (type));
3330 		  if (enum_p && TREE_CODE (type) == ENUMERAL_TYPE)
3331 		    vec_safe_push (types[i], type);
3332 		  if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3333 		    type = type_promotes_to (type);
3334 		}
3335 
3336 	      if (! vec_member (type, types[i]))
3337 		vec_safe_push (types[i], type);
3338 	    }
3339 	}
3340       else
3341 	{
3342 	  if (code == COND_EXPR && lvalue_p (args[i]))
3343 	    vec_safe_push (types[i], build_reference_type (argtypes[i]));
3344 	  type = non_reference (argtypes[i]);
3345 	  if (i != 0 || ! ref1)
3346 	    {
3347 	      type = cv_unqualified (type_decays_to (type));
3348 	      if (enum_p && UNSCOPED_ENUM_P (type))
3349 		vec_safe_push (types[i], type);
3350 	      if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3351 		type = type_promotes_to (type);
3352 	    }
3353 	  vec_safe_push (types[i], type);
3354 	}
3355     }
3356 
3357   /* Run through the possible parameter types of both arguments,
3358      creating candidates with those parameter types.  */
3359   FOR_EACH_VEC_ELT_REVERSE (*(types[0]), ix, t)
3360     {
3361       unsigned jx;
3362       tree u;
3363 
3364       if (!types[1]->is_empty ())
3365 	FOR_EACH_VEC_ELT_REVERSE (*(types[1]), jx, u)
3366 	  add_builtin_candidate
3367 	    (candidates, code, code2, fnname, t,
3368 	     u, args, argtypes, flags, complain);
3369       else
3370 	add_builtin_candidate
3371 	  (candidates, code, code2, fnname, t,
3372 	   NULL_TREE, args, argtypes, flags, complain);
3373     }
3374 
3375   release_tree_vector (types[0]);
3376   release_tree_vector (types[1]);
3377 }
3378 
3379 
3380 /* If TMPL can be successfully instantiated as indicated by
3381    EXPLICIT_TARGS and ARGLIST, adds the instantiation to CANDIDATES.
3382 
3383    TMPL is the template.  EXPLICIT_TARGS are any explicit template
3384    arguments.  ARGLIST is the arguments provided at the call-site.
3385    This does not change ARGLIST.  The RETURN_TYPE is the desired type
3386    for conversion operators.  If OBJ is NULL_TREE, FLAGS and CTYPE are
3387    as for add_function_candidate.  If an OBJ is supplied, FLAGS and
3388    CTYPE are ignored, and OBJ is as for add_conv_candidate.
3389 
3390    SHORTCUT_BAD_CONVS is as in add_function_candidate.  */
3391 
3392 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)3393 add_template_candidate_real (struct z_candidate **candidates, tree tmpl,
3394 			     tree ctype, tree explicit_targs, tree first_arg,
3395 			     const vec<tree, va_gc> *arglist, tree return_type,
3396 			     tree access_path, tree conversion_path,
3397 			     int flags, tree obj, unification_kind_t strict,
3398 			     bool shortcut_bad_convs, tsubst_flags_t complain)
3399 {
3400   int ntparms = DECL_NTPARMS (tmpl);
3401   tree targs = make_tree_vec (ntparms);
3402   unsigned int len = vec_safe_length (arglist);
3403   unsigned int nargs = (first_arg == NULL_TREE ? 0 : 1) + len;
3404   unsigned int skip_without_in_chrg = 0;
3405   tree first_arg_without_in_chrg = first_arg;
3406   tree *args_without_in_chrg;
3407   unsigned int nargs_without_in_chrg;
3408   unsigned int ia, ix;
3409   tree arg;
3410   struct z_candidate *cand;
3411   tree fn;
3412   struct rejection_reason *reason = NULL;
3413   int errs;
3414   conversion **convs = NULL;
3415 
3416   /* We don't do deduction on the in-charge parameter, the VTT
3417      parameter or 'this'.  */
3418   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl))
3419     {
3420       if (first_arg_without_in_chrg != NULL_TREE)
3421 	first_arg_without_in_chrg = NULL_TREE;
3422       else if (return_type && strict == DEDUCE_CALL)
3423 	/* We're deducing for a call to the result of a template conversion
3424 	   function, so the args don't contain 'this'; leave them alone.  */;
3425       else
3426 	++skip_without_in_chrg;
3427     }
3428 
3429   if ((DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (tmpl)
3430        || DECL_BASE_CONSTRUCTOR_P (tmpl))
3431       && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (tmpl)))
3432     {
3433       if (first_arg_without_in_chrg != NULL_TREE)
3434 	first_arg_without_in_chrg = NULL_TREE;
3435       else
3436 	++skip_without_in_chrg;
3437     }
3438 
3439   if (len < skip_without_in_chrg)
3440     return NULL;
3441 
3442   if (DECL_CONSTRUCTOR_P (tmpl) && nargs == 2
3443       && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (first_arg),
3444 						    TREE_TYPE ((*arglist)[0])))
3445     {
3446       /* 12.8/6 says, "A declaration of a constructor for a class X is
3447 	 ill-formed if its first parameter is of type (optionally cv-qualified)
3448 	 X and either there are no other parameters or else all other
3449 	 parameters have default arguments. A member function template is never
3450 	 instantiated to produce such a constructor signature."
3451 
3452 	 So if we're trying to copy an object of the containing class, don't
3453 	 consider a template constructor that has a first parameter type that
3454 	 is just a template parameter, as we would deduce a signature that we
3455 	 would then reject in the code below.  */
3456       if (tree firstparm = FUNCTION_FIRST_USER_PARMTYPE (tmpl))
3457 	{
3458 	  firstparm = TREE_VALUE (firstparm);
3459 	  if (PACK_EXPANSION_P (firstparm))
3460 	    firstparm = PACK_EXPANSION_PATTERN (firstparm);
3461 	  if (TREE_CODE (firstparm) == TEMPLATE_TYPE_PARM)
3462 	    {
3463 	      gcc_assert (!explicit_targs);
3464 	      reason = invalid_copy_with_fn_template_rejection ();
3465 	      goto fail;
3466 	    }
3467 	}
3468     }
3469 
3470   nargs_without_in_chrg = ((first_arg_without_in_chrg != NULL_TREE ? 1 : 0)
3471 			   + (len - skip_without_in_chrg));
3472   args_without_in_chrg = XALLOCAVEC (tree, nargs_without_in_chrg);
3473   ia = 0;
3474   if (first_arg_without_in_chrg != NULL_TREE)
3475     {
3476       args_without_in_chrg[ia] = first_arg_without_in_chrg;
3477       ++ia;
3478     }
3479   for (ix = skip_without_in_chrg;
3480        vec_safe_iterate (arglist, ix, &arg);
3481        ++ix)
3482     {
3483       args_without_in_chrg[ia] = arg;
3484       ++ia;
3485     }
3486   gcc_assert (ia == nargs_without_in_chrg);
3487 
3488   if (!obj && explicit_targs)
3489     {
3490       /* Check that there's no obvious arity mismatch before proceeding with
3491 	 deduction.  This avoids substituting explicit template arguments
3492 	 into the template (which could result in an error outside the
3493 	 immediate context) when the resulting candidate would be unviable
3494 	 anyway.  */
3495       int min_arity = 0, max_arity = 0;
3496       tree parms = TYPE_ARG_TYPES (TREE_TYPE (tmpl));
3497       parms = skip_artificial_parms_for (tmpl, parms);
3498       for (; parms != void_list_node; parms = TREE_CHAIN (parms))
3499 	{
3500 	  if (!parms || PACK_EXPANSION_P (TREE_VALUE (parms)))
3501 	    {
3502 	      max_arity = -1;
3503 	      break;
3504 	    }
3505 	  if (TREE_PURPOSE (parms))
3506 	    /* A parameter with a default argument.  */
3507 	    ++max_arity;
3508 	  else
3509 	    ++min_arity, ++max_arity;
3510 	}
3511       if (ia < (unsigned)min_arity)
3512 	{
3513 	  /* Too few arguments.  */
3514 	  reason = arity_rejection (NULL_TREE, min_arity, ia,
3515 				    /*least_p=*/(max_arity == -1));
3516 	  goto fail;
3517 	}
3518       else if (max_arity != -1 && ia > (unsigned)max_arity)
3519 	{
3520 	  /* Too many arguments.  */
3521 	  reason = arity_rejection (NULL_TREE, max_arity, ia);
3522 	  goto fail;
3523 	}
3524     }
3525 
3526   errs = errorcount+sorrycount;
3527   if (!obj)
3528     {
3529       convs = alloc_conversions (nargs);
3530 
3531       if (shortcut_bad_convs
3532 	  && DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl)
3533 	  && !DECL_CONSTRUCTOR_P (tmpl))
3534 	{
3535 	  /* Check the 'this' conversion before proceeding with deduction.
3536 	     This is effectively an extension of the DR 1391 resolution
3537 	     that we perform in check_non_deducible_conversions, though it's
3538 	     convenient to do this extra check here instead of there.  */
3539 	  tree parmtype = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (tmpl)));
3540 	  tree argtype = lvalue_type (first_arg);
3541 	  tree arg = first_arg;
3542 	  conversion *t = build_this_conversion (tmpl, ctype,
3543 						 parmtype, argtype, arg,
3544 						 flags, complain);
3545 	  convs[0] = t;
3546 	  if (t->bad_p)
3547 	    {
3548 	      reason = bad_arg_conversion_rejection (first_arg, 0,
3549 						     arg, parmtype,
3550 						     EXPR_LOCATION (arg));
3551 	      goto fail;
3552 	    }
3553 	}
3554     }
3555   fn = fn_type_unification (tmpl, explicit_targs, targs,
3556 			    args_without_in_chrg,
3557 			    nargs_without_in_chrg,
3558 			    return_type, strict, flags, convs,
3559 			    false, complain & tf_decltype);
3560 
3561   if (fn == error_mark_node)
3562     {
3563       /* Don't repeat unification later if it already resulted in errors.  */
3564       if (errorcount+sorrycount == errs)
3565 	reason = template_unification_rejection (tmpl, explicit_targs,
3566 						 targs, args_without_in_chrg,
3567 						 nargs_without_in_chrg,
3568 						 return_type, strict, flags);
3569       else
3570 	reason = template_unification_error_rejection ();
3571       goto fail;
3572     }
3573 
3574   /* Now the explicit specifier might have been deduced; check if this
3575      declaration is explicit.  If it is and we're ignoring non-converting
3576      constructors, don't add this function to the set of candidates.  */
3577   if ((flags & LOOKUP_ONLYCONVERTING) && DECL_NONCONVERTING_P (fn))
3578     return NULL;
3579 
3580   if (DECL_CONSTRUCTOR_P (fn) && nargs == 2)
3581     {
3582       tree arg_types = FUNCTION_FIRST_USER_PARMTYPE (fn);
3583       if (arg_types && same_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (arg_types)),
3584 				    ctype))
3585 	{
3586 	  /* We're trying to produce a constructor with a prohibited signature,
3587 	     as discussed above; handle here any cases we didn't catch then,
3588 	     such as X(X<T>).  */
3589 	  reason = invalid_copy_with_fn_template_rejection ();
3590 	  goto fail;
3591 	}
3592     }
3593 
3594   if (obj != NULL_TREE)
3595     /* Aha, this is a conversion function.  */
3596     cand = add_conv_candidate (candidates, fn, obj, arglist,
3597 			       access_path, conversion_path, complain);
3598   else
3599     cand = add_function_candidate (candidates, fn, ctype,
3600 				   first_arg, arglist, access_path,
3601 				   conversion_path, flags, convs,
3602 				   shortcut_bad_convs, complain);
3603   if (DECL_TI_TEMPLATE (fn) != tmpl)
3604     /* This situation can occur if a member template of a template
3605        class is specialized.  Then, instantiate_template might return
3606        an instantiation of the specialization, in which case the
3607        DECL_TI_TEMPLATE field will point at the original
3608        specialization.  For example:
3609 
3610 	 template <class T> struct S { template <class U> void f(U);
3611 				       template <> void f(int) {}; };
3612 	 S<double> sd;
3613 	 sd.f(3);
3614 
3615        Here, TMPL will be template <class U> S<double>::f(U).
3616        And, instantiate template will give us the specialization
3617        template <> S<double>::f(int).  But, the DECL_TI_TEMPLATE field
3618        for this will point at template <class T> template <> S<T>::f(int),
3619        so that we can find the definition.  For the purposes of
3620        overload resolution, however, we want the original TMPL.  */
3621     cand->template_decl = build_template_info (tmpl, targs);
3622   else
3623     cand->template_decl = DECL_TEMPLATE_INFO (fn);
3624   cand->explicit_targs = explicit_targs;
3625 
3626   return cand;
3627  fail:
3628   int viable = (reason->code == rr_bad_arg_conversion ? -1 : 0);
3629   return add_candidate (candidates, tmpl, first_arg, arglist, nargs, convs,
3630 			access_path, conversion_path, viable, reason, flags);
3631 }
3632 
3633 
3634 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)3635 add_template_candidate (struct z_candidate **candidates, tree tmpl, tree ctype,
3636 			tree explicit_targs, tree first_arg,
3637 			const vec<tree, va_gc> *arglist, tree return_type,
3638 			tree access_path, tree conversion_path, int flags,
3639 			unification_kind_t strict, bool shortcut_bad_convs,
3640 			tsubst_flags_t complain)
3641 {
3642   return
3643     add_template_candidate_real (candidates, tmpl, ctype,
3644 				 explicit_targs, first_arg, arglist,
3645 				 return_type, access_path, conversion_path,
3646 				 flags, NULL_TREE, strict, shortcut_bad_convs,
3647 				 complain);
3648 }
3649 
3650 /* Create an overload candidate for the conversion function template TMPL,
3651    returning RETURN_TYPE, which will be invoked for expression OBJ to produce a
3652    pointer-to-function which will in turn be called with the argument list
3653    ARGLIST, and add it to CANDIDATES.  This does not change ARGLIST.  FLAGS is
3654    passed on to implicit_conversion.  */
3655 
3656 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)3657 add_template_conv_candidate (struct z_candidate **candidates, tree tmpl,
3658 			     tree obj,
3659 			     const vec<tree, va_gc> *arglist,
3660 			     tree return_type, tree access_path,
3661 			     tree conversion_path, tsubst_flags_t complain)
3662 {
3663   /* Making this work broke PR 71117 and 85118, so until the committee resolves
3664      core issue 2189, let's disable this candidate if there are any call
3665      operators.  */
3666   if (*candidates)
3667     return NULL;
3668 
3669   return
3670     add_template_candidate_real (candidates, tmpl, NULL_TREE, NULL_TREE,
3671 				 NULL_TREE, arglist, return_type, access_path,
3672 				 conversion_path, 0, obj, DEDUCE_CALL,
3673 				 /*shortcut_bad_convs=*/false, complain);
3674 }
3675 
3676 /* The CANDS are the set of candidates that were considered for
3677    overload resolution.  Return the set of viable candidates, or CANDS
3678    if none are viable.  If any of the candidates were viable, set
3679    *ANY_VIABLE_P to true.  STRICT_P is true if a candidate should be
3680    considered viable only if it is strictly viable.  */
3681 
3682 static struct z_candidate*
splice_viable(struct z_candidate * cands,bool strict_p,bool * any_viable_p)3683 splice_viable (struct z_candidate *cands,
3684 	       bool strict_p,
3685 	       bool *any_viable_p)
3686 {
3687   struct z_candidate *viable;
3688   struct z_candidate **last_viable;
3689   struct z_candidate **cand;
3690   bool found_strictly_viable = false;
3691 
3692   /* Be strict inside templates, since build_over_call won't actually
3693      do the conversions to get pedwarns.  */
3694   if (processing_template_decl)
3695     strict_p = true;
3696 
3697   viable = NULL;
3698   last_viable = &viable;
3699   *any_viable_p = false;
3700 
3701   cand = &cands;
3702   while (*cand)
3703     {
3704       struct z_candidate *c = *cand;
3705       if (!strict_p
3706 	  && (c->viable == 1 || TREE_CODE (c->fn) == TEMPLATE_DECL))
3707 	{
3708 	  /* Be strict in the presence of a viable candidate.  Also if
3709 	     there are template candidates, so that we get deduction errors
3710 	     for them instead of silently preferring a bad conversion.  */
3711 	  strict_p = true;
3712 	  if (viable && !found_strictly_viable)
3713 	    {
3714 	      /* Put any spliced near matches back onto the main list so
3715 		 that we see them if there is no strict match.  */
3716 	      *any_viable_p = false;
3717 	      *last_viable = cands;
3718 	      cands = viable;
3719 	      viable = NULL;
3720 	      last_viable = &viable;
3721 	    }
3722 	}
3723 
3724       if (strict_p ? c->viable == 1 : c->viable)
3725 	{
3726 	  *last_viable = c;
3727 	  *cand = c->next;
3728 	  c->next = NULL;
3729 	  last_viable = &c->next;
3730 	  *any_viable_p = true;
3731 	  if (c->viable == 1)
3732 	    found_strictly_viable = true;
3733 	}
3734       else
3735 	cand = &c->next;
3736     }
3737 
3738   return viable ? viable : cands;
3739 }
3740 
3741 static bool
any_strictly_viable(struct z_candidate * cands)3742 any_strictly_viable (struct z_candidate *cands)
3743 {
3744   for (; cands; cands = cands->next)
3745     if (cands->viable == 1)
3746       return true;
3747   return false;
3748 }
3749 
3750 /* OBJ is being used in an expression like "OBJ.f (...)".  In other
3751    words, it is about to become the "this" pointer for a member
3752    function call.  Take the address of the object.  */
3753 
3754 static tree
build_this(tree obj)3755 build_this (tree obj)
3756 {
3757   /* In a template, we are only concerned about the type of the
3758      expression, so we can take a shortcut.  */
3759   if (processing_template_decl)
3760     return build_address (obj);
3761 
3762   return cp_build_addr_expr (obj, tf_warning_or_error);
3763 }
3764 
3765 /* Returns true iff functions are equivalent. Equivalent functions are
3766    not '==' only if one is a function-local extern function or if
3767    both are extern "C".  */
3768 
3769 static inline int
equal_functions(tree fn1,tree fn2)3770 equal_functions (tree fn1, tree fn2)
3771 {
3772   if (TREE_CODE (fn1) != TREE_CODE (fn2))
3773     return 0;
3774   if (TREE_CODE (fn1) == TEMPLATE_DECL)
3775     return fn1 == fn2;
3776   if (DECL_LOCAL_DECL_P (fn1) || DECL_LOCAL_DECL_P (fn2)
3777       || DECL_EXTERN_C_FUNCTION_P (fn1))
3778     return decls_match (fn1, fn2);
3779   return fn1 == fn2;
3780 }
3781 
3782 /* Print information about a candidate FN being rejected due to INFO.  */
3783 
3784 static void
print_conversion_rejection(location_t loc,struct conversion_info * info,tree fn)3785 print_conversion_rejection (location_t loc, struct conversion_info *info,
3786 			    tree fn)
3787 {
3788   tree from = info->from;
3789   if (!TYPE_P (from))
3790     from = lvalue_type (from);
3791   if (info->n_arg == -1)
3792     {
3793       /* Conversion of implicit `this' argument failed.  */
3794       if (!TYPE_P (info->from))
3795 	/* A bad conversion for 'this' must be discarding cv-quals.  */
3796 	inform (loc, "  passing %qT as %<this%> "
3797 		"argument discards qualifiers",
3798 		from);
3799       else
3800 	inform (loc, "  no known conversion for implicit "
3801 		"%<this%> parameter from %qH to %qI",
3802 		from, info->to_type);
3803     }
3804   else if (!TYPE_P (info->from))
3805     {
3806       if (info->n_arg >= 0)
3807 	inform (loc, "  conversion of argument %d would be ill-formed:",
3808 		info->n_arg + 1);
3809       perform_implicit_conversion (info->to_type, info->from,
3810 				   tf_warning_or_error);
3811     }
3812   else if (info->n_arg == -2)
3813     /* Conversion of conversion function return value failed.  */
3814     inform (loc, "  no known conversion from %qH to %qI",
3815 	    from, info->to_type);
3816   else
3817     {
3818       if (TREE_CODE (fn) == FUNCTION_DECL)
3819 	loc = get_fndecl_argument_location (fn, info->n_arg);
3820       inform (loc, "  no known conversion for argument %d from %qH to %qI",
3821 	      info->n_arg + 1, from, info->to_type);
3822     }
3823 }
3824 
3825 /* Print information about a candidate with WANT parameters and we found
3826    HAVE.  */
3827 
3828 static void
print_arity_information(location_t loc,unsigned int have,unsigned int want,bool least_p)3829 print_arity_information (location_t loc, unsigned int have, unsigned int want,
3830 			 bool least_p)
3831 {
3832   if (least_p)
3833     inform_n (loc, want,
3834 	      "  candidate expects at least %d argument, %d provided",
3835 	      "  candidate expects at least %d arguments, %d provided",
3836 	      want, have);
3837   else
3838     inform_n (loc, want,
3839 	      "  candidate expects %d argument, %d provided",
3840 	      "  candidate expects %d arguments, %d provided",
3841 	      want, have);
3842 }
3843 
3844 /* Print information about one overload candidate CANDIDATE.  MSGSTR
3845    is the text to print before the candidate itself.
3846 
3847    NOTE: Unlike most diagnostic functions in GCC, MSGSTR is expected
3848    to have been run through gettext by the caller.  This wart makes
3849    life simpler in print_z_candidates and for the translators.  */
3850 
3851 static void
print_z_candidate(location_t loc,const char * msgstr,struct z_candidate * candidate)3852 print_z_candidate (location_t loc, const char *msgstr,
3853 		   struct z_candidate *candidate)
3854 {
3855   const char *msg = (msgstr == NULL
3856 		     ? ""
3857 		     : ACONCAT ((_(msgstr), " ", NULL)));
3858   tree fn = candidate->fn;
3859   if (flag_new_inheriting_ctors)
3860     fn = strip_inheriting_ctors (fn);
3861   location_t cloc = location_of (fn);
3862 
3863   if (identifier_p (fn))
3864     {
3865       cloc = loc;
3866       if (candidate->num_convs == 3)
3867 	inform (cloc, "%s%<%D(%T, %T, %T)%> (built-in)", msg, fn,
3868 		candidate->convs[0]->type,
3869 		candidate->convs[1]->type,
3870 		candidate->convs[2]->type);
3871       else if (candidate->num_convs == 2)
3872 	inform (cloc, "%s%<%D(%T, %T)%> (built-in)", msg, fn,
3873 		candidate->convs[0]->type,
3874 		candidate->convs[1]->type);
3875       else
3876 	inform (cloc, "%s%<%D(%T)%> (built-in)", msg, fn,
3877 		candidate->convs[0]->type);
3878     }
3879   else if (TYPE_P (fn))
3880     inform (cloc, "%s%qT (conversion)", msg, fn);
3881   else if (candidate->viable == -1)
3882     inform (cloc, "%s%#qD (near match)", msg, fn);
3883   else if (DECL_DELETED_FN (fn))
3884     inform (cloc, "%s%#qD (deleted)", msg, fn);
3885   else if (candidate->reversed ())
3886     inform (cloc, "%s%#qD (reversed)", msg, fn);
3887   else if (candidate->rewritten ())
3888     inform (cloc, "%s%#qD (rewritten)", msg, fn);
3889   else
3890     inform (cloc, "%s%#qD", msg, fn);
3891   if (fn != candidate->fn)
3892     {
3893       cloc = location_of (candidate->fn);
3894       inform (cloc, "  inherited here");
3895     }
3896   /* Give the user some information about why this candidate failed.  */
3897   if (candidate->reason != NULL)
3898     {
3899       struct rejection_reason *r = candidate->reason;
3900 
3901       switch (r->code)
3902 	{
3903 	case rr_arity:
3904 	  print_arity_information (cloc, r->u.arity.actual,
3905 				   r->u.arity.expected,
3906 				   r->u.arity.least_p);
3907 	  break;
3908 	case rr_arg_conversion:
3909 	  print_conversion_rejection (cloc, &r->u.conversion, fn);
3910 	  break;
3911 	case rr_bad_arg_conversion:
3912 	  print_conversion_rejection (cloc, &r->u.bad_conversion, fn);
3913 	  break;
3914 	case rr_explicit_conversion:
3915 	  inform (cloc, "  return type %qT of explicit conversion function "
3916 		  "cannot be converted to %qT with a qualification "
3917 		  "conversion", r->u.conversion.from,
3918 		  r->u.conversion.to_type);
3919 	  break;
3920 	case rr_template_conversion:
3921 	  inform (cloc, "  conversion from return type %qT of template "
3922 		  "conversion function specialization to %qT is not an "
3923 		  "exact match", r->u.conversion.from,
3924 		  r->u.conversion.to_type);
3925 	  break;
3926 	case rr_template_unification:
3927 	  /* We use template_unification_error_rejection if unification caused
3928 	     actual non-SFINAE errors, in which case we don't need to repeat
3929 	     them here.  */
3930 	  if (r->u.template_unification.tmpl == NULL_TREE)
3931 	    {
3932 	      inform (cloc, "  substitution of deduced template arguments "
3933 		      "resulted in errors seen above");
3934 	      break;
3935 	    }
3936 	  /* Re-run template unification with diagnostics.  */
3937 	  inform (cloc, "  template argument deduction/substitution failed:");
3938 	  fn_type_unification (r->u.template_unification.tmpl,
3939 			       r->u.template_unification.explicit_targs,
3940 			       (make_tree_vec
3941 				(r->u.template_unification.num_targs)),
3942 			       r->u.template_unification.args,
3943 			       r->u.template_unification.nargs,
3944 			       r->u.template_unification.return_type,
3945 			       r->u.template_unification.strict,
3946 			       r->u.template_unification.flags,
3947 			       NULL, true, false);
3948 	  break;
3949 	case rr_invalid_copy:
3950 	  inform (cloc,
3951 		  "  a constructor taking a single argument of its own "
3952 		  "class type is invalid");
3953 	  break;
3954 	case rr_constraint_failure:
3955 	  diagnose_constraints (cloc, fn, NULL_TREE);
3956 	  break;
3957 	case rr_inherited_ctor:
3958 	  inform (cloc, "  an inherited constructor is not a candidate for "
3959 		  "initialization from an expression of the same or derived "
3960 		  "type");
3961 	  break;
3962 	case rr_none:
3963 	default:
3964 	  /* This candidate didn't have any issues or we failed to
3965 	     handle a particular code.  Either way...  */
3966 	  gcc_unreachable ();
3967 	}
3968     }
3969 }
3970 
3971 static void
print_z_candidates(location_t loc,struct z_candidate * candidates)3972 print_z_candidates (location_t loc, struct z_candidate *candidates)
3973 {
3974   struct z_candidate *cand1;
3975   struct z_candidate **cand2;
3976 
3977   if (!candidates)
3978     return;
3979 
3980   /* Remove non-viable deleted candidates.  */
3981   cand1 = candidates;
3982   for (cand2 = &cand1; *cand2; )
3983     {
3984       if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
3985 	  && !(*cand2)->viable
3986 	  && DECL_DELETED_FN ((*cand2)->fn))
3987 	*cand2 = (*cand2)->next;
3988       else
3989 	cand2 = &(*cand2)->next;
3990     }
3991   /* ...if there are any non-deleted ones.  */
3992   if (cand1)
3993     candidates = cand1;
3994 
3995   /* There may be duplicates in the set of candidates.  We put off
3996      checking this condition as long as possible, since we have no way
3997      to eliminate duplicates from a set of functions in less than n^2
3998      time.  Now we are about to emit an error message, so it is more
3999      permissible to go slowly.  */
4000   for (cand1 = candidates; cand1; cand1 = cand1->next)
4001     {
4002       tree fn = cand1->fn;
4003       /* Skip builtin candidates and conversion functions.  */
4004       if (!DECL_P (fn))
4005 	continue;
4006       cand2 = &cand1->next;
4007       while (*cand2)
4008 	{
4009 	  if (DECL_P ((*cand2)->fn)
4010 	      && equal_functions (fn, (*cand2)->fn))
4011 	    *cand2 = (*cand2)->next;
4012 	  else
4013 	    cand2 = &(*cand2)->next;
4014 	}
4015     }
4016 
4017   for (; candidates; candidates = candidates->next)
4018     print_z_candidate (loc, N_("candidate:"), candidates);
4019 }
4020 
4021 /* USER_SEQ is a user-defined conversion sequence, beginning with a
4022    USER_CONV.  STD_SEQ is the standard conversion sequence applied to
4023    the result of the conversion function to convert it to the final
4024    desired type.  Merge the two sequences into a single sequence,
4025    and return the merged sequence.  */
4026 
4027 static conversion *
merge_conversion_sequences(conversion * user_seq,conversion * std_seq)4028 merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
4029 {
4030   conversion **t;
4031   bool bad = user_seq->bad_p;
4032 
4033   gcc_assert (user_seq->kind == ck_user);
4034 
4035   /* Find the end of the second conversion sequence.  */
4036   for (t = &std_seq; (*t)->kind != ck_identity; t = &((*t)->u.next))
4037     {
4038       /* The entire sequence is a user-conversion sequence.  */
4039       (*t)->user_conv_p = true;
4040       if (bad)
4041 	(*t)->bad_p = true;
4042     }
4043 
4044   if ((*t)->rvaluedness_matches_p)
4045     /* We're binding a reference directly to the result of the conversion.
4046        build_user_type_conversion_1 stripped the REFERENCE_TYPE from the return
4047        type, but we want it back.  */
4048     user_seq->type = TREE_TYPE (TREE_TYPE (user_seq->cand->fn));
4049 
4050   /* Replace the identity conversion with the user conversion
4051      sequence.  */
4052   *t = user_seq;
4053 
4054   return std_seq;
4055 }
4056 
4057 /* Handle overload resolution for initializing an object of class type from
4058    an initializer list.  First we look for a suitable constructor that
4059    takes a std::initializer_list; if we don't find one, we then look for a
4060    non-list constructor.
4061 
4062    Parameters are as for add_candidates, except that the arguments are in
4063    the form of a CONSTRUCTOR (the initializer list) rather than a vector, and
4064    the RETURN_TYPE parameter is replaced by TOTYPE, the desired type.  */
4065 
4066 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)4067 add_list_candidates (tree fns, tree first_arg,
4068 		     const vec<tree, va_gc> *args, tree totype,
4069 		     tree explicit_targs, bool template_only,
4070 		     tree conversion_path, tree access_path,
4071 		     int flags,
4072 		     struct z_candidate **candidates,
4073 		     tsubst_flags_t complain)
4074 {
4075   gcc_assert (*candidates == NULL);
4076 
4077   /* We're looking for a ctor for list-initialization.  */
4078   flags |= LOOKUP_LIST_INIT_CTOR;
4079   /* And we don't allow narrowing conversions.  We also use this flag to
4080      avoid the copy constructor call for copy-list-initialization.  */
4081   flags |= LOOKUP_NO_NARROWING;
4082 
4083   unsigned nart = num_artificial_parms_for (OVL_FIRST (fns)) - 1;
4084   tree init_list = (*args)[nart];
4085 
4086   /* Always use the default constructor if the list is empty (DR 990).  */
4087   if (CONSTRUCTOR_NELTS (init_list) == 0
4088       && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
4089     ;
4090   /* If the class has a list ctor, try passing the list as a single
4091      argument first, but only consider list ctors.  */
4092   else if (TYPE_HAS_LIST_CTOR (totype))
4093     {
4094       flags |= LOOKUP_LIST_ONLY;
4095       add_candidates (fns, first_arg, args, NULL_TREE,
4096 		      explicit_targs, template_only, conversion_path,
4097 		      access_path, flags, candidates, complain);
4098       if (any_strictly_viable (*candidates))
4099 	return;
4100     }
4101   else if (CONSTRUCTOR_IS_DESIGNATED_INIT (init_list)
4102 	   && !CP_AGGREGATE_TYPE_P (totype))
4103     {
4104       if (complain & tf_error)
4105 	error ("designated initializers cannot be used with a "
4106 	       "non-aggregate type %qT", totype);
4107       return;
4108     }
4109 
4110   /* Expand the CONSTRUCTOR into a new argument vec.  */
4111   vec<tree, va_gc> *new_args;
4112   vec_alloc (new_args, nart + CONSTRUCTOR_NELTS (init_list));
4113   for (unsigned i = 0; i < nart; ++i)
4114     new_args->quick_push ((*args)[i]);
4115   for (unsigned i = 0; i < CONSTRUCTOR_NELTS (init_list); ++i)
4116     new_args->quick_push (CONSTRUCTOR_ELT (init_list, i)->value);
4117 
4118   /* We aren't looking for list-ctors anymore.  */
4119   flags &= ~LOOKUP_LIST_ONLY;
4120   /* We allow more user-defined conversions within an init-list.  */
4121   flags &= ~LOOKUP_NO_CONVERSION;
4122 
4123   add_candidates (fns, first_arg, new_args, NULL_TREE,
4124 		  explicit_targs, template_only, conversion_path,
4125 		  access_path, flags, candidates, complain);
4126 }
4127 
4128 /* Returns the best overload candidate to perform the requested
4129    conversion.  This function is used for three the overloading situations
4130    described in [over.match.copy], [over.match.conv], and [over.match.ref].
4131    If TOTYPE is a REFERENCE_TYPE, we're trying to find a direct binding as
4132    per [dcl.init.ref], so we ignore temporary bindings.  */
4133 
4134 static struct z_candidate *
build_user_type_conversion_1(tree totype,tree expr,int flags,tsubst_flags_t complain)4135 build_user_type_conversion_1 (tree totype, tree expr, int flags,
4136 			      tsubst_flags_t complain)
4137 {
4138   struct z_candidate *candidates, *cand;
4139   tree fromtype;
4140   tree ctors = NULL_TREE;
4141   tree conv_fns = NULL_TREE;
4142   conversion *conv = NULL;
4143   tree first_arg = NULL_TREE;
4144   vec<tree, va_gc> *args = NULL;
4145   bool any_viable_p;
4146   int convflags;
4147 
4148   if (!expr)
4149     return NULL;
4150 
4151   fromtype = TREE_TYPE (expr);
4152 
4153   /* We represent conversion within a hierarchy using RVALUE_CONV and
4154      BASE_CONV, as specified by [over.best.ics]; these become plain
4155      constructor calls, as specified in [dcl.init].  */
4156   gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
4157 	      || !DERIVED_FROM_P (totype, fromtype));
4158 
4159   if (CLASS_TYPE_P (totype))
4160     /* Use lookup_fnfields_slot instead of lookup_fnfields to avoid
4161        creating a garbage BASELINK; constructors can't be inherited.  */
4162     ctors = get_class_binding (totype, complete_ctor_identifier);
4163 
4164   tree to_nonref = non_reference (totype);
4165   if (MAYBE_CLASS_TYPE_P (fromtype))
4166     {
4167       if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
4168 	  (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
4169 	   && DERIVED_FROM_P (to_nonref, fromtype)))
4170 	{
4171 	  /* [class.conv.fct] A conversion function is never used to
4172 	     convert a (possibly cv-qualified) object to the (possibly
4173 	     cv-qualified) same object type (or a reference to it), to a
4174 	     (possibly cv-qualified) base class of that type (or a
4175 	     reference to it)...  */
4176 	}
4177       else
4178 	conv_fns = lookup_conversions (fromtype);
4179     }
4180 
4181   candidates = 0;
4182   flags |= LOOKUP_NO_CONVERSION;
4183   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4184     flags |= LOOKUP_NO_NARROWING;
4185   /* Prevent add_candidates from treating a non-strictly viable candidate
4186      as unviable.  */
4187   complain |= tf_conv;
4188 
4189   /* It's OK to bind a temporary for converting constructor arguments, but
4190      not in converting the return value of a conversion operator.  */
4191   convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION
4192 	       | (flags & LOOKUP_NO_NARROWING));
4193   flags &= ~LOOKUP_NO_TEMP_BIND;
4194 
4195   if (ctors)
4196     {
4197       int ctorflags = flags;
4198 
4199       first_arg = build_dummy_object (totype);
4200 
4201       /* We should never try to call the abstract or base constructor
4202 	 from here.  */
4203       gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_FIRST (ctors))
4204 		  && !DECL_HAS_VTT_PARM_P (OVL_FIRST (ctors)));
4205 
4206       args = make_tree_vector_single (expr);
4207       if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4208 	{
4209 	  /* List-initialization.  */
4210 	  add_list_candidates (ctors, first_arg, args, totype, NULL_TREE,
4211 			       false, TYPE_BINFO (totype), TYPE_BINFO (totype),
4212 			       ctorflags, &candidates, complain);
4213 	}
4214       else
4215 	{
4216 	  add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
4217 			  TYPE_BINFO (totype), TYPE_BINFO (totype),
4218 			  ctorflags, &candidates, complain);
4219 	}
4220 
4221       for (cand = candidates; cand; cand = cand->next)
4222 	{
4223 	  cand->second_conv = build_identity_conv (totype, NULL_TREE);
4224 
4225 	  /* If totype isn't a reference, and LOOKUP_ONLYCONVERTING is
4226 	     set, then this is copy-initialization.  In that case, "The
4227 	     result of the call is then used to direct-initialize the
4228 	     object that is the destination of the copy-initialization."
4229 	     [dcl.init]
4230 
4231 	     We represent this in the conversion sequence with an
4232 	     rvalue conversion, which means a constructor call.  */
4233 	  if (!TYPE_REF_P (totype)
4234 	      && cxx_dialect < cxx17
4235 	      && (flags & LOOKUP_ONLYCONVERTING)
4236 	      && !(convflags & LOOKUP_NO_TEMP_BIND))
4237 	    cand->second_conv
4238 	      = build_conv (ck_rvalue, totype, cand->second_conv);
4239 	}
4240     }
4241 
4242   if (conv_fns)
4243     {
4244       if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4245 	first_arg = CONSTRUCTOR_ELT (expr, 0)->value;
4246       else
4247 	first_arg = expr;
4248     }
4249 
4250   for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
4251     {
4252       tree conversion_path = TREE_PURPOSE (conv_fns);
4253       struct z_candidate *old_candidates;
4254 
4255       /* If LOOKUP_NO_CONVERSION, don't consider a conversion function that
4256 	 would need an addional user-defined conversion, i.e. if the return
4257 	 type differs in class-ness from the desired type.  So we avoid
4258 	 considering operator bool when calling a copy constructor.
4259 
4260 	 This optimization avoids the failure in PR97600, and is allowed by
4261 	 [temp.inst]/9: "If the function selected by overload resolution can be
4262 	 determined without instantiating a class template definition, it is
4263 	 unspecified whether that instantiation actually takes place."	*/
4264       tree convtype = non_reference (TREE_TYPE (conv_fns));
4265       if ((flags & LOOKUP_NO_CONVERSION)
4266 	  && !WILDCARD_TYPE_P (convtype)
4267 	  && (CLASS_TYPE_P (to_nonref)
4268 	      != CLASS_TYPE_P (convtype)))
4269 	continue;
4270 
4271       /* If we are called to convert to a reference type, we are trying to
4272 	 find a direct binding, so don't even consider temporaries.  If
4273 	 we don't find a direct binding, the caller will try again to
4274 	 look for a temporary binding.  */
4275       if (TYPE_REF_P (totype))
4276 	convflags |= LOOKUP_NO_TEMP_BIND;
4277 
4278       old_candidates = candidates;
4279       add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
4280 		      NULL_TREE, false,
4281 		      conversion_path, TYPE_BINFO (fromtype),
4282 		      flags, &candidates, complain);
4283 
4284       for (cand = candidates; cand != old_candidates; cand = cand->next)
4285 	{
4286 	  if (cand->viable == 0)
4287 	    /* Already rejected, don't change to -1.  */
4288 	    continue;
4289 
4290 	  tree rettype = TREE_TYPE (TREE_TYPE (cand->fn));
4291 	  conversion *ics
4292 	    = implicit_conversion (totype,
4293 				   rettype,
4294 				   0,
4295 				   /*c_cast_p=*/false, convflags,
4296 				   complain);
4297 
4298 	  /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
4299 	     copy-initialization.  In that case, "The result of the
4300 	     call is then used to direct-initialize the object that is
4301 	     the destination of the copy-initialization."  [dcl.init]
4302 
4303 	     We represent this in the conversion sequence with an
4304 	     rvalue conversion, which means a constructor call.  But
4305 	     don't add a second rvalue conversion if there's already
4306 	     one there.  Which there really shouldn't be, but it's
4307 	     harmless since we'd add it here anyway. */
4308 	  if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
4309 	      && !(convflags & LOOKUP_NO_TEMP_BIND))
4310 	    ics = build_conv (ck_rvalue, totype, ics);
4311 
4312 	  cand->second_conv = ics;
4313 
4314 	  if (!ics)
4315 	    {
4316 	      cand->viable = 0;
4317 	      cand->reason = arg_conversion_rejection (NULL_TREE, -2,
4318 						       rettype, totype,
4319 						       EXPR_LOCATION (expr));
4320 	    }
4321 	  else if (TYPE_REF_P (totype) && !ics->rvaluedness_matches_p
4322 		   /* Limit this to non-templates for now (PR90546).  */
4323 		   && !cand->template_decl
4324 		   && TREE_CODE (TREE_TYPE (totype)) != FUNCTION_TYPE)
4325 	    {
4326 	      /* If we are called to convert to a reference type, we are trying
4327 		 to find a direct binding per [over.match.ref], so rvaluedness
4328 		 must match for non-functions.  */
4329 	      cand->viable = 0;
4330 	    }
4331 	  else if (DECL_NONCONVERTING_P (cand->fn)
4332 		   && ics->rank > cr_exact)
4333 	    {
4334 	      /* 13.3.1.5: For direct-initialization, those explicit
4335 		 conversion functions that are not hidden within S and
4336 		 yield type T or a type that can be converted to type T
4337 		 with a qualification conversion (4.4) are also candidate
4338 		 functions.  */
4339 	      /* 13.3.1.6 doesn't have a parallel restriction, but it should;
4340 		 I've raised this issue with the committee. --jason 9/2011 */
4341 	      cand->viable = -1;
4342 	      cand->reason = explicit_conversion_rejection (rettype, totype);
4343 	    }
4344 	  else if (cand->viable == 1 && ics->bad_p)
4345 	    {
4346 	      cand->viable = -1;
4347 	      cand->reason
4348 		= bad_arg_conversion_rejection (NULL_TREE, -2,
4349 						rettype, totype,
4350 						EXPR_LOCATION (expr));
4351 	    }
4352 	  else if (primary_template_specialization_p (cand->fn)
4353 		   && ics->rank > cr_exact)
4354 	    {
4355 	      /* 13.3.3.1.2: If the user-defined conversion is specified by
4356 		 a specialization of a conversion function template, the
4357 		 second standard conversion sequence shall have exact match
4358 		 rank.  */
4359 	      cand->viable = -1;
4360 	      cand->reason = template_conversion_rejection (rettype, totype);
4361 	    }
4362 	}
4363     }
4364 
4365   candidates = splice_viable (candidates, false, &any_viable_p);
4366   if (!any_viable_p)
4367     {
4368       if (args)
4369 	release_tree_vector (args);
4370       return NULL;
4371     }
4372 
4373   cand = tourney (candidates, complain);
4374   if (cand == NULL)
4375     {
4376       if (complain & tf_error)
4377 	{
4378 	  auto_diagnostic_group d;
4379 	  error_at (cp_expr_loc_or_input_loc (expr),
4380 		    "conversion from %qH to %qI is ambiguous",
4381 		    fromtype, totype);
4382 	  print_z_candidates (location_of (expr), candidates);
4383 	}
4384 
4385       cand = candidates;	/* any one will do */
4386       cand->second_conv = build_ambiguous_conv (totype, expr);
4387       cand->second_conv->user_conv_p = true;
4388       if (!any_strictly_viable (candidates))
4389 	cand->second_conv->bad_p = true;
4390       if (flags & LOOKUP_ONLYCONVERTING)
4391 	cand->second_conv->need_temporary_p = true;
4392       /* If there are viable candidates, don't set ICS_BAD_FLAG; an
4393 	 ambiguous conversion is no worse than another user-defined
4394 	 conversion.  */
4395 
4396       return cand;
4397     }
4398 
4399   tree convtype;
4400   if (!DECL_CONSTRUCTOR_P (cand->fn))
4401     convtype = non_reference (TREE_TYPE (TREE_TYPE (cand->fn)));
4402   else if (cand->second_conv->kind == ck_rvalue)
4403     /* DR 5: [in the first step of copy-initialization]...if the function
4404        is a constructor, the call initializes a temporary of the
4405        cv-unqualified version of the destination type. */
4406     convtype = cv_unqualified (totype);
4407   else
4408     convtype = totype;
4409   /* Build the user conversion sequence.  */
4410   conv = build_conv
4411     (ck_user,
4412      convtype,
4413      build_identity_conv (TREE_TYPE (expr), expr));
4414   conv->cand = cand;
4415   if (cand->viable == -1)
4416     conv->bad_p = true;
4417 
4418   /* We're performing the maybe-rvalue overload resolution and
4419      a conversion function is in play.  Reject converting the return
4420      value of the conversion function to a base class.  */
4421   if ((flags & LOOKUP_PREFER_RVALUE) && !DECL_CONSTRUCTOR_P (cand->fn))
4422     for (conversion *t = cand->second_conv; t; t = next_conversion (t))
4423       if (t->kind == ck_base)
4424 	return NULL;
4425 
4426   /* Remember that this was a list-initialization.  */
4427   if (flags & LOOKUP_NO_NARROWING)
4428     conv->check_narrowing = true;
4429 
4430   /* Combine it with the second conversion sequence.  */
4431   cand->second_conv = merge_conversion_sequences (conv,
4432 						  cand->second_conv);
4433 
4434   return cand;
4435 }
4436 
4437 /* Wrapper for above. */
4438 
4439 tree
build_user_type_conversion(tree totype,tree expr,int flags,tsubst_flags_t complain)4440 build_user_type_conversion (tree totype, tree expr, int flags,
4441 			    tsubst_flags_t complain)
4442 {
4443   struct z_candidate *cand;
4444   tree ret;
4445 
4446   auto_cond_timevar tv (TV_OVERLOAD);
4447   cand = build_user_type_conversion_1 (totype, expr, flags, complain);
4448 
4449   if (cand)
4450     {
4451       if (cand->second_conv->kind == ck_ambig)
4452 	ret = error_mark_node;
4453       else
4454         {
4455           expr = convert_like (cand->second_conv, expr, complain);
4456           ret = convert_from_reference (expr);
4457         }
4458     }
4459   else
4460     ret = NULL_TREE;
4461 
4462   return ret;
4463 }
4464 
4465 /* Give a helpful diagnostic when implicit_conversion fails.  */
4466 
4467 static void
implicit_conversion_error(location_t loc,tree type,tree expr)4468 implicit_conversion_error (location_t loc, tree type, tree expr)
4469 {
4470   tsubst_flags_t complain = tf_warning_or_error;
4471 
4472   /* If expr has unknown type, then it is an overloaded function.
4473      Call instantiate_type to get good error messages.  */
4474   if (TREE_TYPE (expr) == unknown_type_node)
4475     instantiate_type (type, expr, complain);
4476   else if (invalid_nonstatic_memfn_p (loc, expr, complain))
4477     /* We gave an error.  */;
4478   else if (BRACE_ENCLOSED_INITIALIZER_P (expr)
4479 	   && CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
4480 	   && !CP_AGGREGATE_TYPE_P (type))
4481     error_at (loc, "designated initializers cannot be used with a "
4482 	      "non-aggregate type %qT", type);
4483   else
4484     {
4485       range_label_for_type_mismatch label (TREE_TYPE (expr), type);
4486       gcc_rich_location rich_loc (loc, &label);
4487       error_at (&rich_loc, "could not convert %qE from %qH to %qI",
4488 		expr, TREE_TYPE (expr), type);
4489     }
4490 }
4491 
4492 /* Worker for build_converted_constant_expr.  */
4493 
4494 static tree
build_converted_constant_expr_internal(tree type,tree expr,int flags,tsubst_flags_t complain)4495 build_converted_constant_expr_internal (tree type, tree expr,
4496 					int flags, tsubst_flags_t complain)
4497 {
4498   conversion *conv;
4499   void *p;
4500   tree t;
4501   location_t loc = cp_expr_loc_or_input_loc (expr);
4502 
4503   if (error_operand_p (expr))
4504     return error_mark_node;
4505 
4506   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
4507   p = conversion_obstack_alloc (0);
4508 
4509   conv = implicit_conversion (type, TREE_TYPE (expr), expr,
4510 			      /*c_cast_p=*/false, flags, complain);
4511 
4512   /* A converted constant expression of type T is an expression, implicitly
4513      converted to type T, where the converted expression is a constant
4514      expression and the implicit conversion sequence contains only
4515 
4516        * user-defined conversions,
4517        * lvalue-to-rvalue conversions (7.1),
4518        * array-to-pointer conversions (7.2),
4519        * function-to-pointer conversions (7.3),
4520        * qualification conversions (7.5),
4521        * integral promotions (7.6),
4522        * integral conversions (7.8) other than narrowing conversions (11.6.4),
4523        * null pointer conversions (7.11) from std::nullptr_t,
4524        * null member pointer conversions (7.12) from std::nullptr_t, and
4525        * function pointer conversions (7.13),
4526 
4527      and where the reference binding (if any) binds directly.  */
4528 
4529   for (conversion *c = conv;
4530        c && c->kind != ck_identity;
4531        c = next_conversion (c))
4532     {
4533       switch (c->kind)
4534 	{
4535 	  /* A conversion function is OK.  If it isn't constexpr, we'll
4536 	     complain later that the argument isn't constant.  */
4537 	case ck_user:
4538 	  /* List-initialization is OK.  */
4539 	case ck_aggr:
4540 	  /* The lvalue-to-rvalue conversion is OK.  */
4541 	case ck_rvalue:
4542 	  /* Array-to-pointer and function-to-pointer.  */
4543 	case ck_lvalue:
4544 	  /* Function pointer conversions.  */
4545 	case ck_fnptr:
4546 	  /* Qualification conversions.  */
4547 	case ck_qual:
4548 	  break;
4549 
4550 	case ck_ref_bind:
4551 	  if (c->need_temporary_p)
4552 	    {
4553 	      if (complain & tf_error)
4554 		error_at (loc, "initializing %qH with %qI in converted "
4555 			  "constant expression does not bind directly",
4556 			  type, next_conversion (c)->type);
4557 	      conv = NULL;
4558 	    }
4559 	  break;
4560 
4561 	case ck_base:
4562 	case ck_pmem:
4563 	case ck_ptr:
4564 	case ck_std:
4565 	  t = next_conversion (c)->type;
4566 	  if (INTEGRAL_OR_ENUMERATION_TYPE_P (t)
4567 	      && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4568 	    /* Integral promotion or conversion.  */
4569 	    break;
4570 	  if (NULLPTR_TYPE_P (t))
4571 	    /* Conversion from nullptr to pointer or pointer-to-member.  */
4572 	    break;
4573 
4574 	  if (complain & tf_error)
4575 	    error_at (loc, "conversion from %qH to %qI in a "
4576 		      "converted constant expression", t, type);
4577 	  /* fall through.  */
4578 
4579 	default:
4580 	  conv = NULL;
4581 	  break;
4582 	}
4583     }
4584 
4585   /* Avoid confusing convert_nontype_argument by introducing
4586      a redundant conversion to the same reference type.  */
4587   if (conv && conv->kind == ck_ref_bind
4588       && REFERENCE_REF_P (expr))
4589     {
4590       tree ref = TREE_OPERAND (expr, 0);
4591       if (same_type_p (type, TREE_TYPE (ref)))
4592 	return ref;
4593     }
4594 
4595   if (conv)
4596     {
4597       /* Don't copy a class in a template.  */
4598       if (CLASS_TYPE_P (type) && conv->kind == ck_rvalue
4599 	  && processing_template_decl)
4600 	conv = next_conversion (conv);
4601 
4602       /* Issuing conversion warnings for value-dependent expressions is
4603 	 likely too noisy.  */
4604       warning_sentinel w (warn_conversion);
4605       conv->check_narrowing = true;
4606       conv->check_narrowing_const_only = true;
4607       expr = convert_like (conv, expr, complain);
4608     }
4609   else
4610     {
4611       if (complain & tf_error)
4612 	implicit_conversion_error (loc, type, expr);
4613       expr = error_mark_node;
4614     }
4615 
4616   /* Free all the conversions we allocated.  */
4617   obstack_free (&conversion_obstack, p);
4618 
4619   return expr;
4620 }
4621 
4622 /* Subroutine of convert_nontype_argument.
4623 
4624    EXPR is an expression used in a context that requires a converted
4625    constant-expression, such as a template non-type parameter.  Do any
4626    necessary conversions (that are permitted for converted
4627    constant-expressions) to convert it to the desired type.
4628 
4629    This function doesn't consider explicit conversion functions.  If
4630    you mean to use "a contextually converted constant expression of type
4631    bool", use build_converted_constant_bool_expr.
4632 
4633    If conversion is successful, returns the converted expression;
4634    otherwise, returns error_mark_node.  */
4635 
4636 tree
build_converted_constant_expr(tree type,tree expr,tsubst_flags_t complain)4637 build_converted_constant_expr (tree type, tree expr, tsubst_flags_t complain)
4638 {
4639   return build_converted_constant_expr_internal (type, expr, LOOKUP_IMPLICIT,
4640 						 complain);
4641 }
4642 
4643 /* Used to create "a contextually converted constant expression of type
4644    bool".  This differs from build_converted_constant_expr in that it
4645    also considers explicit conversion functions.  */
4646 
4647 tree
build_converted_constant_bool_expr(tree expr,tsubst_flags_t complain)4648 build_converted_constant_bool_expr (tree expr, tsubst_flags_t complain)
4649 {
4650   return build_converted_constant_expr_internal (boolean_type_node, expr,
4651 						 LOOKUP_NORMAL, complain);
4652 }
4653 
4654 /* Do any initial processing on the arguments to a function call.  */
4655 
4656 vec<tree, va_gc> *
resolve_args(vec<tree,va_gc> * args,tsubst_flags_t complain)4657 resolve_args (vec<tree, va_gc> *args, tsubst_flags_t complain)
4658 {
4659   unsigned int ix;
4660   tree arg;
4661 
4662   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
4663     {
4664       if (error_operand_p (arg))
4665 	return NULL;
4666       else if (VOID_TYPE_P (TREE_TYPE (arg)))
4667 	{
4668 	  if (complain & tf_error)
4669 	    error_at (cp_expr_loc_or_input_loc (arg),
4670 		      "invalid use of void expression");
4671 	  return NULL;
4672 	}
4673       else if (invalid_nonstatic_memfn_p (EXPR_LOCATION (arg), arg, complain))
4674 	return NULL;
4675 
4676       /* Force auto deduction now.  Omit tf_warning to avoid redundant
4677 	 deprecated warning on deprecated-14.C.  */
4678       if (!mark_single_function (arg, complain & ~tf_warning))
4679 	return NULL;
4680     }
4681   return args;
4682 }
4683 
4684 /* Perform overload resolution on FN, which is called with the ARGS.
4685 
4686    Return the candidate function selected by overload resolution, or
4687    NULL if the event that overload resolution failed.  In the case
4688    that overload resolution fails, *CANDIDATES will be the set of
4689    candidates considered, and ANY_VIABLE_P will be set to true or
4690    false to indicate whether or not any of the candidates were
4691    viable.
4692 
4693    The ARGS should already have gone through RESOLVE_ARGS before this
4694    function is called.  */
4695 
4696 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)4697 perform_overload_resolution (tree fn,
4698 			     const vec<tree, va_gc> *args,
4699 			     struct z_candidate **candidates,
4700 			     bool *any_viable_p, tsubst_flags_t complain)
4701 {
4702   struct z_candidate *cand;
4703   tree explicit_targs;
4704   int template_only;
4705 
4706   auto_cond_timevar tv (TV_OVERLOAD);
4707 
4708   explicit_targs = NULL_TREE;
4709   template_only = 0;
4710 
4711   *candidates = NULL;
4712   *any_viable_p = true;
4713 
4714   /* Check FN.  */
4715   gcc_assert (OVL_P (fn) || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
4716 
4717   if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4718     {
4719       explicit_targs = TREE_OPERAND (fn, 1);
4720       fn = TREE_OPERAND (fn, 0);
4721       template_only = 1;
4722     }
4723 
4724   /* Add the various candidate functions.  */
4725   add_candidates (fn, NULL_TREE, args, NULL_TREE,
4726 		  explicit_targs, template_only,
4727 		  /*conversion_path=*/NULL_TREE,
4728 		  /*access_path=*/NULL_TREE,
4729 		  LOOKUP_NORMAL,
4730 		  candidates, complain);
4731 
4732   *candidates = splice_viable (*candidates, false, any_viable_p);
4733   if (*any_viable_p)
4734     cand = tourney (*candidates, complain);
4735   else
4736     cand = NULL;
4737 
4738   return cand;
4739 }
4740 
4741 /* Print an error message about being unable to build a call to FN with
4742    ARGS.  ANY_VIABLE_P indicates whether any candidate functions could
4743    be located; CANDIDATES is a possibly empty list of such
4744    functions.  */
4745 
4746 static void
print_error_for_call_failure(tree fn,const vec<tree,va_gc> * args,struct z_candidate * candidates)4747 print_error_for_call_failure (tree fn, const vec<tree, va_gc> *args,
4748 			      struct z_candidate *candidates)
4749 {
4750   tree targs = NULL_TREE;
4751   if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4752     {
4753       targs = TREE_OPERAND (fn, 1);
4754       fn = TREE_OPERAND (fn, 0);
4755     }
4756   tree name = OVL_NAME (fn);
4757   location_t loc = location_of (name);
4758   if (targs)
4759     name = lookup_template_function (name, targs);
4760 
4761   auto_diagnostic_group d;
4762   if (!any_strictly_viable (candidates))
4763     error_at (loc, "no matching function for call to %<%D(%A)%>",
4764 	      name, build_tree_list_vec (args));
4765   else
4766     error_at (loc, "call of overloaded %<%D(%A)%> is ambiguous",
4767 	      name, build_tree_list_vec (args));
4768   if (candidates)
4769     print_z_candidates (loc, candidates);
4770 }
4771 
4772 /* Perform overload resolution on the set of deduction guides DGUIDES
4773    using ARGS.  Returns the selected deduction guide, or error_mark_node
4774    if overload resolution fails.  */
4775 
4776 tree
perform_dguide_overload_resolution(tree dguides,const vec<tree,va_gc> * args,tsubst_flags_t complain)4777 perform_dguide_overload_resolution (tree dguides, const vec<tree, va_gc> *args,
4778 				    tsubst_flags_t complain)
4779 {
4780   z_candidate *candidates;
4781   bool any_viable_p;
4782   tree result;
4783 
4784   gcc_assert (deduction_guide_p (OVL_FIRST (dguides)));
4785 
4786   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
4787   void *p = conversion_obstack_alloc (0);
4788 
4789   z_candidate *cand = perform_overload_resolution (dguides, args, &candidates,
4790 						   &any_viable_p, complain);
4791   if (!cand)
4792     {
4793       if (complain & tf_error)
4794 	print_error_for_call_failure (dguides, args, candidates);
4795       result = error_mark_node;
4796     }
4797   else
4798     result = cand->fn;
4799 
4800   /* Free all the conversions we allocated.  */
4801   obstack_free (&conversion_obstack, p);
4802 
4803   return result;
4804 }
4805 
4806 /* Return an expression for a call to FN (a namespace-scope function,
4807    or a static member function) with the ARGS.  This may change
4808    ARGS.  */
4809 
4810 tree
build_new_function_call(tree fn,vec<tree,va_gc> ** args,tsubst_flags_t complain)4811 build_new_function_call (tree fn, vec<tree, va_gc> **args,
4812 			 tsubst_flags_t complain)
4813 {
4814   struct z_candidate *candidates, *cand;
4815   bool any_viable_p;
4816   void *p;
4817   tree result;
4818 
4819   if (args != NULL && *args != NULL)
4820     {
4821       *args = resolve_args (*args, complain);
4822       if (*args == NULL)
4823 	return error_mark_node;
4824     }
4825 
4826   if (flag_tm)
4827     tm_malloc_replacement (fn);
4828 
4829   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
4830   p = conversion_obstack_alloc (0);
4831 
4832   cand = perform_overload_resolution (fn, *args, &candidates, &any_viable_p,
4833 				      complain);
4834 
4835   if (!cand)
4836     {
4837       if (complain & tf_error)
4838 	{
4839 	  // If there is a single (non-viable) function candidate,
4840 	  // let the error be diagnosed by cp_build_function_call_vec.
4841 	  if (!any_viable_p && candidates && ! candidates->next
4842 	      && (TREE_CODE (candidates->fn) == FUNCTION_DECL))
4843 	    return cp_build_function_call_vec (candidates->fn, args, complain);
4844 
4845 	  // Otherwise, emit notes for non-viable candidates.
4846 	  print_error_for_call_failure (fn, *args, candidates);
4847 	}
4848       result = error_mark_node;
4849     }
4850   else
4851     {
4852       result = build_over_call (cand, LOOKUP_NORMAL, complain);
4853     }
4854 
4855   if (flag_coroutines
4856       && result
4857       && TREE_CODE (result) == CALL_EXPR
4858       && DECL_BUILT_IN_CLASS (TREE_OPERAND (CALL_EXPR_FN (result), 0))
4859 	  == BUILT_IN_NORMAL)
4860    result = coro_validate_builtin_call (result);
4861 
4862   /* Free all the conversions we allocated.  */
4863   obstack_free (&conversion_obstack, p);
4864 
4865   return result;
4866 }
4867 
4868 /* Build a call to a global operator new.  FNNAME is the name of the
4869    operator (either "operator new" or "operator new[]") and ARGS are
4870    the arguments provided.  This may change ARGS.  *SIZE points to the
4871    total number of bytes required by the allocation, and is updated if
4872    that is changed here.  *COOKIE_SIZE is non-NULL if a cookie should
4873    be used.  If this function determines that no cookie should be
4874    used, after all, *COOKIE_SIZE is set to NULL_TREE.  If SIZE_CHECK
4875    is not NULL_TREE, it is evaluated before calculating the final
4876    array size, and if it fails, the array size is replaced with
4877    (size_t)-1 (usually triggering a std::bad_alloc exception).  If FN
4878    is non-NULL, it will be set, upon return, to the allocation
4879    function called.  */
4880 
4881 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)4882 build_operator_new_call (tree fnname, vec<tree, va_gc> **args,
4883 			 tree *size, tree *cookie_size,
4884 			 tree align_arg, tree size_check,
4885 			 tree *fn, tsubst_flags_t complain)
4886 {
4887   tree original_size = *size;
4888   tree fns;
4889   struct z_candidate *candidates;
4890   struct z_candidate *cand = NULL;
4891   bool any_viable_p;
4892 
4893   if (fn)
4894     *fn = NULL_TREE;
4895   /* Set to (size_t)-1 if the size check fails.  */
4896   if (size_check != NULL_TREE)
4897     {
4898       tree errval = TYPE_MAX_VALUE (sizetype);
4899       if (cxx_dialect >= cxx11 && flag_exceptions)
4900 	errval = throw_bad_array_new_length ();
4901       *size = fold_build3 (COND_EXPR, sizetype, size_check,
4902 			   original_size, errval);
4903     }
4904   vec_safe_insert (*args, 0, *size);
4905   *args = resolve_args (*args, complain);
4906   if (*args == NULL)
4907     return error_mark_node;
4908 
4909   /* Based on:
4910 
4911        [expr.new]
4912 
4913        If this lookup fails to find the name, or if the allocated type
4914        is not a class type, the allocation function's name is looked
4915        up in the global scope.
4916 
4917      we disregard block-scope declarations of "operator new".  */
4918   fns = lookup_qualified_name (global_namespace, fnname);
4919 
4920   if (align_arg)
4921     {
4922       vec<tree, va_gc>* align_args
4923 	= vec_copy_and_insert (*args, align_arg, 1);
4924       cand = perform_overload_resolution (fns, align_args, &candidates,
4925 					  &any_viable_p, tf_none);
4926       if (cand)
4927 	*args = align_args;
4928       /* If no aligned allocation function matches, try again without the
4929 	 alignment.  */
4930     }
4931 
4932   /* Figure out what function is being called.  */
4933   if (!cand)
4934     cand = perform_overload_resolution (fns, *args, &candidates, &any_viable_p,
4935 					complain);
4936 
4937   /* If no suitable function could be found, issue an error message
4938      and give up.  */
4939   if (!cand)
4940     {
4941       if (complain & tf_error)
4942 	print_error_for_call_failure (fns, *args, candidates);
4943       return error_mark_node;
4944     }
4945 
4946    /* If a cookie is required, add some extra space.  Whether
4947       or not a cookie is required cannot be determined until
4948       after we know which function was called.  */
4949    if (*cookie_size)
4950      {
4951        bool use_cookie = true;
4952        tree arg_types;
4953 
4954        arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
4955        /* Skip the size_t parameter.  */
4956        arg_types = TREE_CHAIN (arg_types);
4957        /* Check the remaining parameters (if any).  */
4958        if (arg_types
4959 	   && TREE_CHAIN (arg_types) == void_list_node
4960 	   && same_type_p (TREE_VALUE (arg_types),
4961 			   ptr_type_node))
4962 	 use_cookie = false;
4963        /* If we need a cookie, adjust the number of bytes allocated.  */
4964        if (use_cookie)
4965 	 {
4966 	   /* Update the total size.  */
4967 	   *size = size_binop (PLUS_EXPR, original_size, *cookie_size);
4968 	   if (size_check)
4969 	     {
4970 	       /* Set to (size_t)-1 if the size check fails.  */
4971 	       gcc_assert (size_check != NULL_TREE);
4972 	       *size = fold_build3 (COND_EXPR, sizetype, size_check,
4973 				    *size, TYPE_MAX_VALUE (sizetype));
4974 	    }
4975 	   /* Update the argument list to reflect the adjusted size.  */
4976 	   (**args)[0] = *size;
4977 	 }
4978        else
4979 	 *cookie_size = NULL_TREE;
4980      }
4981 
4982    /* Tell our caller which function we decided to call.  */
4983    if (fn)
4984      *fn = cand->fn;
4985 
4986    /* Build the CALL_EXPR.  */
4987    tree ret = build_over_call (cand, LOOKUP_NORMAL, complain);
4988 
4989    /* Set this flag for all callers of this function.  In addition to
4990       new-expressions, this is called for allocating coroutine state; treat
4991       that as an implicit new-expression.  */
4992    tree call = extract_call_expr (ret);
4993    if (TREE_CODE (call) == CALL_EXPR)
4994      CALL_FROM_NEW_OR_DELETE_P (call) = 1;
4995 
4996    return ret;
4997 }
4998 
4999 /* Build a new call to operator().  This may change ARGS.  */
5000 
5001 tree
build_op_call(tree obj,vec<tree,va_gc> ** args,tsubst_flags_t complain)5002 build_op_call (tree obj, vec<tree, va_gc> **args, tsubst_flags_t complain)
5003 {
5004   struct z_candidate *candidates = 0, *cand;
5005   tree fns, convs, first_mem_arg = NULL_TREE;
5006   bool any_viable_p;
5007   tree result = NULL_TREE;
5008   void *p;
5009 
5010   auto_cond_timevar tv (TV_OVERLOAD);
5011 
5012   obj = mark_lvalue_use (obj);
5013 
5014   if (error_operand_p (obj))
5015     return error_mark_node;
5016 
5017   tree type = TREE_TYPE (obj);
5018 
5019   obj = prep_operand (obj);
5020 
5021   if (TYPE_PTRMEMFUNC_P (type))
5022     {
5023       if (complain & tf_error)
5024         /* It's no good looking for an overloaded operator() on a
5025            pointer-to-member-function.  */
5026 	error ("pointer-to-member function %qE cannot be called without "
5027 	       "an object; consider using %<.*%> or %<->*%>", obj);
5028       return error_mark_node;
5029     }
5030 
5031   if (TYPE_BINFO (type))
5032     {
5033       fns = lookup_fnfields (TYPE_BINFO (type), call_op_identifier, 1, complain);
5034       if (fns == error_mark_node)
5035 	return error_mark_node;
5036     }
5037   else
5038     fns = NULL_TREE;
5039 
5040   if (args != NULL && *args != NULL)
5041     {
5042       *args = resolve_args (*args, complain);
5043       if (*args == NULL)
5044 	return error_mark_node;
5045     }
5046 
5047   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
5048   p = conversion_obstack_alloc (0);
5049 
5050   if (fns)
5051     {
5052       first_mem_arg = obj;
5053 
5054       add_candidates (BASELINK_FUNCTIONS (fns),
5055 		      first_mem_arg, *args, NULL_TREE,
5056 		      NULL_TREE, false,
5057 		      BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
5058 		      LOOKUP_NORMAL, &candidates, complain);
5059     }
5060 
5061   convs = lookup_conversions (type);
5062 
5063   for (; convs; convs = TREE_CHAIN (convs))
5064     {
5065       tree totype = TREE_TYPE (convs);
5066 
5067       if (TYPE_PTRFN_P (totype)
5068 	  || TYPE_REFFN_P (totype)
5069 	  || (TYPE_REF_P (totype)
5070 	      && TYPE_PTRFN_P (TREE_TYPE (totype))))
5071 	for (tree fn : ovl_range (TREE_VALUE (convs)))
5072 	  {
5073 	    if (DECL_NONCONVERTING_P (fn))
5074 	      continue;
5075 
5076 	    if (TREE_CODE (fn) == TEMPLATE_DECL)
5077 	      add_template_conv_candidate
5078 		(&candidates, fn, obj, *args, totype,
5079 		 /*access_path=*/NULL_TREE,
5080 		 /*conversion_path=*/NULL_TREE, complain);
5081 	    else
5082 	      add_conv_candidate (&candidates, fn, obj,
5083 				  *args, /*conversion_path=*/NULL_TREE,
5084 				  /*access_path=*/NULL_TREE, complain);
5085 	  }
5086     }
5087 
5088   /* Be strict here because if we choose a bad conversion candidate, the
5089      errors we get won't mention the call context.  */
5090   candidates = splice_viable (candidates, true, &any_viable_p);
5091   if (!any_viable_p)
5092     {
5093       if (complain & tf_error)
5094         {
5095           auto_diagnostic_group d;
5096           error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
5097 		 build_tree_list_vec (*args));
5098           print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5099         }
5100       result = error_mark_node;
5101     }
5102   else
5103     {
5104       cand = tourney (candidates, complain);
5105       if (cand == 0)
5106 	{
5107           if (complain & tf_error)
5108             {
5109               auto_diagnostic_group d;
5110               error ("call of %<(%T) (%A)%> is ambiguous",
5111                      TREE_TYPE (obj), build_tree_list_vec (*args));
5112               print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5113             }
5114 	  result = error_mark_node;
5115 	}
5116       else if (TREE_CODE (cand->fn) == FUNCTION_DECL
5117 	       && DECL_OVERLOADED_OPERATOR_P (cand->fn)
5118 	       && DECL_OVERLOADED_OPERATOR_IS (cand->fn, CALL_EXPR))
5119 	result = build_over_call (cand, LOOKUP_NORMAL, complain);
5120       else
5121 	{
5122 	  if (TREE_CODE (cand->fn) == FUNCTION_DECL)
5123 	    obj = convert_like_with_context (cand->convs[0], obj, cand->fn,
5124 					     -1, complain);
5125 	  else
5126 	    {
5127 	      gcc_checking_assert (TYPE_P (cand->fn));
5128 	      obj = convert_like (cand->convs[0], obj, complain);
5129 	    }
5130 	  obj = convert_from_reference (obj);
5131 	  result = cp_build_function_call_vec (obj, args, complain);
5132 	}
5133     }
5134 
5135   /* Free all the conversions we allocated.  */
5136   obstack_free (&conversion_obstack, p);
5137 
5138   return result;
5139 }
5140 
5141 /* Called by op_error to prepare format strings suitable for the error
5142    function.  It concatenates a prefix (controlled by MATCH), ERRMSG,
5143    and a suffix (controlled by NTYPES).  */
5144 
5145 static const char *
op_error_string(const char * errmsg,int ntypes,bool match)5146 op_error_string (const char *errmsg, int ntypes, bool match)
5147 {
5148   const char *msg;
5149 
5150   const char *msgp = concat (match ? G_("ambiguous overload for ")
5151 			           : G_("no match for "), errmsg, NULL);
5152 
5153   if (ntypes == 3)
5154     msg = concat (msgp, G_(" (operand types are %qT, %qT, and %qT)"), NULL);
5155   else if (ntypes == 2)
5156     msg = concat (msgp, G_(" (operand types are %qT and %qT)"), NULL);
5157   else
5158     msg = concat (msgp, G_(" (operand type is %qT)"), NULL);
5159 
5160   return msg;
5161 }
5162 
5163 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)5164 op_error (const op_location_t &loc,
5165 	  enum tree_code code, enum tree_code code2,
5166 	  tree arg1, tree arg2, tree arg3, bool match)
5167 {
5168   bool assop = code == MODIFY_EXPR;
5169   const char *opname = OVL_OP_INFO (assop, assop ? code2 : code)->name;
5170 
5171   switch (code)
5172     {
5173     case COND_EXPR:
5174       if (flag_diagnostics_show_caret)
5175 	error_at (loc, op_error_string (G_("ternary %<operator?:%>"),
5176 					3, match),
5177 		  TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5178       else
5179 	error_at (loc, op_error_string (G_("ternary %<operator?:%> "
5180 					   "in %<%E ? %E : %E%>"), 3, match),
5181 		  arg1, arg2, arg3,
5182 		  TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5183       break;
5184 
5185     case POSTINCREMENT_EXPR:
5186     case POSTDECREMENT_EXPR:
5187       if (flag_diagnostics_show_caret)
5188 	error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5189 		  opname, TREE_TYPE (arg1));
5190       else
5191 	error_at (loc, op_error_string (G_("%<operator%s%> in %<%E%s%>"),
5192 					1, match),
5193 		  opname, arg1, opname, TREE_TYPE (arg1));
5194       break;
5195 
5196     case ARRAY_REF:
5197       if (flag_diagnostics_show_caret)
5198 	error_at (loc, op_error_string (G_("%<operator[]%>"), 2, match),
5199 		  TREE_TYPE (arg1), TREE_TYPE (arg2));
5200       else
5201 	error_at (loc, op_error_string (G_("%<operator[]%> in %<%E[%E]%>"),
5202 					2, match),
5203 		  arg1, arg2, TREE_TYPE (arg1), TREE_TYPE (arg2));
5204       break;
5205 
5206     case REALPART_EXPR:
5207     case IMAGPART_EXPR:
5208       if (flag_diagnostics_show_caret)
5209 	error_at (loc, op_error_string (G_("%qs"), 1, match),
5210 		  opname, TREE_TYPE (arg1));
5211       else
5212 	error_at (loc, op_error_string (G_("%qs in %<%s %E%>"), 1, match),
5213 		  opname, opname, arg1, TREE_TYPE (arg1));
5214       break;
5215 
5216     case CO_AWAIT_EXPR:
5217       if (flag_diagnostics_show_caret)
5218 	error_at (loc, op_error_string (G_("%<operator %s%>"), 1, match),
5219 		  opname, TREE_TYPE (arg1));
5220       else
5221 	error_at (loc, op_error_string (G_("%<operator %s%> in %<%s%E%>"),
5222 					  1, match),
5223 		   opname, opname, arg1, TREE_TYPE (arg1));
5224       break;
5225 
5226     default:
5227       if (arg2)
5228 	if (flag_diagnostics_show_caret)
5229 	  {
5230 	    binary_op_rich_location richloc (loc, arg1, arg2, true);
5231 	    error_at (&richloc,
5232 		      op_error_string (G_("%<operator%s%>"), 2, match),
5233 		      opname, TREE_TYPE (arg1), TREE_TYPE (arg2));
5234 	  }
5235 	else
5236 	  error_at (loc, op_error_string (G_("%<operator%s%> in %<%E %s %E%>"),
5237 					  2, match),
5238 		    opname, arg1, opname, arg2,
5239 		    TREE_TYPE (arg1), TREE_TYPE (arg2));
5240       else
5241 	if (flag_diagnostics_show_caret)
5242 	  error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5243 		    opname, TREE_TYPE (arg1));
5244 	else
5245 	  error_at (loc, op_error_string (G_("%<operator%s%> in %<%s%E%>"),
5246 					  1, match),
5247 		    opname, opname, arg1, TREE_TYPE (arg1));
5248       break;
5249     }
5250 }
5251 
5252 /* Return the implicit conversion sequence that could be used to
5253    convert E1 to E2 in [expr.cond].  */
5254 
5255 static conversion *
conditional_conversion(tree e1,tree e2,tsubst_flags_t complain)5256 conditional_conversion (tree e1, tree e2, tsubst_flags_t complain)
5257 {
5258   tree t1 = non_reference (TREE_TYPE (e1));
5259   tree t2 = non_reference (TREE_TYPE (e2));
5260   conversion *conv;
5261   bool good_base;
5262 
5263   /* [expr.cond]
5264 
5265      If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5266      implicitly converted (clause _conv_) to the type "lvalue reference to
5267      T2", subject to the constraint that in the conversion the
5268      reference must bind directly (_dcl.init.ref_) to an lvalue.
5269 
5270      If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5271      implicitly converted to the type "rvalue reference to T2", subject to
5272      the constraint that the reference must bind directly.  */
5273   if (glvalue_p (e2))
5274     {
5275       tree rtype = cp_build_reference_type (t2, !lvalue_p (e2));
5276       conv = implicit_conversion (rtype,
5277 				  t1,
5278 				  e1,
5279 				  /*c_cast_p=*/false,
5280 				  LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND
5281 				  |LOOKUP_ONLYCONVERTING,
5282 				  complain);
5283       if (conv && !conv->bad_p)
5284 	return conv;
5285     }
5286 
5287   /* If E2 is a prvalue or if neither of the conversions above can be done
5288      and at least one of the operands has (possibly cv-qualified) class
5289      type: */
5290   if (!CLASS_TYPE_P (t1) && !CLASS_TYPE_P (t2))
5291     return NULL;
5292 
5293   /* [expr.cond]
5294 
5295      If E1 and E2 have class type, and the underlying class types are
5296      the same or one is a base class of the other: E1 can be converted
5297      to match E2 if the class of T2 is the same type as, or a base
5298      class of, the class of T1, and the cv-qualification of T2 is the
5299      same cv-qualification as, or a greater cv-qualification than, the
5300      cv-qualification of T1.  If the conversion is applied, E1 is
5301      changed to an rvalue of type T2 that still refers to the original
5302      source class object (or the appropriate subobject thereof).  */
5303   if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
5304       && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
5305     {
5306       if (good_base && at_least_as_qualified_p (t2, t1))
5307 	{
5308 	  conv = build_identity_conv (t1, e1);
5309 	  if (!same_type_p (TYPE_MAIN_VARIANT (t1),
5310 			    TYPE_MAIN_VARIANT (t2)))
5311 	    conv = build_conv (ck_base, t2, conv);
5312 	  else
5313 	    conv = build_conv (ck_rvalue, t2, conv);
5314 	  return conv;
5315 	}
5316       else
5317 	return NULL;
5318     }
5319   else
5320     /* [expr.cond]
5321 
5322        Otherwise: E1 can be converted to match E2 if E1 can be implicitly
5323        converted to the type that expression E2 would have if E2 were
5324        converted to an rvalue (or the type it has, if E2 is an rvalue).  */
5325     return implicit_conversion (t2, t1, e1, /*c_cast_p=*/false,
5326 				LOOKUP_IMPLICIT, complain);
5327 }
5328 
5329 /* Implement [expr.cond].  ARG1, ARG2, and ARG3 are the three
5330    arguments to the conditional expression.  */
5331 
5332 tree
build_conditional_expr(const op_location_t & loc,tree arg1,tree arg2,tree arg3,tsubst_flags_t complain)5333 build_conditional_expr (const op_location_t &loc,
5334 			tree arg1, tree arg2, tree arg3,
5335 			tsubst_flags_t complain)
5336 {
5337   tree arg2_type;
5338   tree arg3_type;
5339   tree result = NULL_TREE;
5340   tree result_type = NULL_TREE;
5341   bool is_glvalue = true;
5342   struct z_candidate *candidates = 0;
5343   struct z_candidate *cand;
5344   void *p;
5345   tree orig_arg2, orig_arg3;
5346 
5347   auto_cond_timevar tv (TV_OVERLOAD);
5348 
5349   /* As a G++ extension, the second argument to the conditional can be
5350      omitted.  (So that `a ? : c' is roughly equivalent to `a ? a :
5351      c'.)  If the second operand is omitted, make sure it is
5352      calculated only once.  */
5353   if (!arg2)
5354     {
5355       if (complain & tf_error)
5356 	pedwarn (loc, OPT_Wpedantic,
5357 		 "ISO C++ forbids omitting the middle term of "
5358 		 "a %<?:%> expression");
5359 
5360       if ((complain & tf_warning) && !truth_value_p (TREE_CODE (arg1)))
5361 	warn_for_omitted_condop (loc, arg1);
5362 
5363       /* Make sure that lvalues remain lvalues.  See g++.oliva/ext1.C.  */
5364       if (glvalue_p (arg1))
5365 	{
5366 	  arg1 = cp_stabilize_reference (arg1);
5367 	  arg2 = arg1 = prevent_lifetime_extension (arg1);
5368 	}
5369       else
5370 	arg2 = arg1 = cp_save_expr (arg1);
5371     }
5372 
5373   /* If something has already gone wrong, just pass that fact up the
5374      tree.  */
5375   if (error_operand_p (arg1)
5376       || error_operand_p (arg2)
5377       || error_operand_p (arg3))
5378     return error_mark_node;
5379 
5380   orig_arg2 = arg2;
5381   orig_arg3 = arg3;
5382 
5383   if (gnu_vector_type_p (TREE_TYPE (arg1))
5384       && VECTOR_INTEGER_TYPE_P (TREE_TYPE (arg1)))
5385     {
5386       tree arg1_type = TREE_TYPE (arg1);
5387 
5388       /* If arg1 is another cond_expr choosing between -1 and 0,
5389 	 then we can use its comparison.  It may help to avoid
5390 	 additional comparison, produce more accurate diagnostics
5391 	 and enables folding.  */
5392       if (TREE_CODE (arg1) == VEC_COND_EXPR
5393 	  && integer_minus_onep (TREE_OPERAND (arg1, 1))
5394 	  && integer_zerop (TREE_OPERAND (arg1, 2)))
5395 	arg1 = TREE_OPERAND (arg1, 0);
5396 
5397       arg1 = force_rvalue (arg1, complain);
5398       arg2 = force_rvalue (arg2, complain);
5399       arg3 = force_rvalue (arg3, complain);
5400 
5401       /* force_rvalue can return error_mark on valid arguments.  */
5402       if (error_operand_p (arg1)
5403 	  || error_operand_p (arg2)
5404 	  || error_operand_p (arg3))
5405 	return error_mark_node;
5406 
5407       arg2_type = TREE_TYPE (arg2);
5408       arg3_type = TREE_TYPE (arg3);
5409 
5410       if (!VECTOR_TYPE_P (arg2_type)
5411 	  && !VECTOR_TYPE_P (arg3_type))
5412 	{
5413 	  /* Rely on the error messages of the scalar version.  */
5414 	  tree scal = build_conditional_expr (loc, integer_one_node,
5415 					      orig_arg2, orig_arg3, complain);
5416 	  if (scal == error_mark_node)
5417 	    return error_mark_node;
5418 	  tree stype = TREE_TYPE (scal);
5419 	  tree ctype = TREE_TYPE (arg1_type);
5420 	  if (TYPE_SIZE (stype) != TYPE_SIZE (ctype)
5421 	      || (!INTEGRAL_TYPE_P (stype) && !SCALAR_FLOAT_TYPE_P (stype)))
5422 	    {
5423 	      if (complain & tf_error)
5424 		error_at (loc, "inferred scalar type %qT is not an integer or "
5425 			  "floating-point type of the same size as %qT", stype,
5426 			  COMPARISON_CLASS_P (arg1)
5427 			  ? TREE_TYPE (TREE_TYPE (TREE_OPERAND (arg1, 0)))
5428 			  : ctype);
5429 	      return error_mark_node;
5430 	    }
5431 
5432 	  tree vtype = build_opaque_vector_type (stype,
5433 			 TYPE_VECTOR_SUBPARTS (arg1_type));
5434 	  /* We could pass complain & tf_warning to unsafe_conversion_p,
5435 	     but the warnings (like Wsign-conversion) have already been
5436 	     given by the scalar build_conditional_expr_1. We still check
5437 	     unsafe_conversion_p to forbid truncating long long -> float.  */
5438 	  if (unsafe_conversion_p (stype, arg2, NULL_TREE, false))
5439 	    {
5440 	      if (complain & tf_error)
5441 		error_at (loc, "conversion of scalar %qH to vector %qI "
5442 			       "involves truncation", arg2_type, vtype);
5443 	      return error_mark_node;
5444 	    }
5445 	  if (unsafe_conversion_p (stype, arg3, NULL_TREE, false))
5446 	    {
5447 	      if (complain & tf_error)
5448 		error_at (loc, "conversion of scalar %qH to vector %qI "
5449 			       "involves truncation", arg3_type, vtype);
5450 	      return error_mark_node;
5451 	    }
5452 
5453 	  arg2 = cp_convert (stype, arg2, complain);
5454 	  arg2 = save_expr (arg2);
5455 	  arg2 = build_vector_from_val (vtype, arg2);
5456 	  arg2_type = vtype;
5457 	  arg3 = cp_convert (stype, arg3, complain);
5458 	  arg3 = save_expr (arg3);
5459 	  arg3 = build_vector_from_val (vtype, arg3);
5460 	  arg3_type = vtype;
5461 	}
5462 
5463       if ((gnu_vector_type_p (arg2_type) && !VECTOR_TYPE_P (arg3_type))
5464 	  || (gnu_vector_type_p (arg3_type) && !VECTOR_TYPE_P (arg2_type)))
5465 	{
5466 	  enum stv_conv convert_flag =
5467 	    scalar_to_vector (loc, VEC_COND_EXPR, arg2, arg3,
5468 			      complain & tf_error);
5469 
5470 	  switch (convert_flag)
5471 	    {
5472 	      case stv_error:
5473 		return error_mark_node;
5474 	      case stv_firstarg:
5475 		{
5476 		  arg2 = save_expr (arg2);
5477 		  arg2 = convert (TREE_TYPE (arg3_type), arg2);
5478 		  arg2 = build_vector_from_val (arg3_type, arg2);
5479 		  arg2_type = TREE_TYPE (arg2);
5480 		  break;
5481 		}
5482 	      case stv_secondarg:
5483 		{
5484 		  arg3 = save_expr (arg3);
5485 		  arg3 = convert (TREE_TYPE (arg2_type), arg3);
5486 		  arg3 = build_vector_from_val (arg2_type, arg3);
5487 		  arg3_type = TREE_TYPE (arg3);
5488 		  break;
5489 		}
5490 	      default:
5491 		break;
5492 	    }
5493 	}
5494 
5495       if (!gnu_vector_type_p (arg2_type)
5496 	  || !gnu_vector_type_p (arg3_type)
5497 	  || !same_type_p (arg2_type, arg3_type)
5498 	  || maybe_ne (TYPE_VECTOR_SUBPARTS (arg1_type),
5499 		       TYPE_VECTOR_SUBPARTS (arg2_type))
5500 	  || TYPE_SIZE (arg1_type) != TYPE_SIZE (arg2_type))
5501 	{
5502 	  if (complain & tf_error)
5503 	    error_at (loc,
5504 		      "incompatible vector types in conditional expression: "
5505 		      "%qT, %qT and %qT", TREE_TYPE (arg1),
5506 		      TREE_TYPE (orig_arg2), TREE_TYPE (orig_arg3));
5507 	  return error_mark_node;
5508 	}
5509 
5510       if (!COMPARISON_CLASS_P (arg1))
5511 	{
5512 	  tree cmp_type = truth_type_for (arg1_type);
5513 	  arg1 = build2 (NE_EXPR, cmp_type, arg1, build_zero_cst (arg1_type));
5514 	}
5515       return build3_loc (loc, VEC_COND_EXPR, arg2_type, arg1, arg2, arg3);
5516     }
5517 
5518   /* [expr.cond]
5519 
5520      The first expression is implicitly converted to bool (clause
5521      _conv_).  */
5522   arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
5523 					    LOOKUP_NORMAL);
5524   if (error_operand_p (arg1))
5525     return error_mark_node;
5526 
5527   /* [expr.cond]
5528 
5529      If either the second or the third operand has type (possibly
5530      cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
5531      array-to-pointer (_conv.array_), and function-to-pointer
5532      (_conv.func_) standard conversions are performed on the second
5533      and third operands.  */
5534   arg2_type = unlowered_expr_type (arg2);
5535   arg3_type = unlowered_expr_type (arg3);
5536   if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
5537     {
5538       /* 'void' won't help in resolving an overloaded expression on the
5539 	 other side, so require it to resolve by itself.  */
5540       if (arg2_type == unknown_type_node)
5541 	{
5542 	  arg2 = resolve_nondeduced_context_or_error (arg2, complain);
5543 	  arg2_type = TREE_TYPE (arg2);
5544 	}
5545       if (arg3_type == unknown_type_node)
5546 	{
5547 	  arg3 = resolve_nondeduced_context_or_error (arg3, complain);
5548 	  arg3_type = TREE_TYPE (arg3);
5549 	}
5550 
5551       /* [expr.cond]
5552 
5553 	 One of the following shall hold:
5554 
5555 	 --The second or the third operand (but not both) is a
5556 	   throw-expression (_except.throw_); the result is of the type
5557 	   and value category of the other.
5558 
5559 	 --Both the second and the third operands have type void; the
5560 	   result is of type void and is a prvalue.  */
5561       if (TREE_CODE (arg2) == THROW_EXPR
5562 	  && TREE_CODE (arg3) != THROW_EXPR)
5563 	{
5564 	  result_type = arg3_type;
5565 	  is_glvalue = glvalue_p (arg3);
5566 	}
5567       else if (TREE_CODE (arg2) != THROW_EXPR
5568 	       && TREE_CODE (arg3) == THROW_EXPR)
5569 	{
5570 	  result_type = arg2_type;
5571 	  is_glvalue = glvalue_p (arg2);
5572 	}
5573       else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
5574 	{
5575 	  result_type = void_type_node;
5576 	  is_glvalue = false;
5577 	}
5578       else
5579 	{
5580           if (complain & tf_error)
5581             {
5582               if (VOID_TYPE_P (arg2_type))
5583                 error_at (cp_expr_loc_or_loc (arg3, loc),
5584 			  "second operand to the conditional operator "
5585 			  "is of type %<void%>, but the third operand is "
5586 			  "neither a throw-expression nor of type %<void%>");
5587               else
5588                 error_at (cp_expr_loc_or_loc (arg2, loc),
5589 			  "third operand to the conditional operator "
5590 			  "is of type %<void%>, but the second operand is "
5591 			  "neither a throw-expression nor of type %<void%>");
5592             }
5593 	  return error_mark_node;
5594 	}
5595 
5596       goto valid_operands;
5597     }
5598   /* [expr.cond]
5599 
5600      Otherwise, if the second and third operand have different types,
5601      and either has (possibly cv-qualified) class type, or if both are
5602      glvalues of the same value category and the same type except for
5603      cv-qualification, an attempt is made to convert each of those operands
5604      to the type of the other.  */
5605   else if (!same_type_p (arg2_type, arg3_type)
5606 	    && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)
5607 		|| (same_type_ignoring_top_level_qualifiers_p (arg2_type,
5608 							       arg3_type)
5609 		    && glvalue_p (arg2) && glvalue_p (arg3)
5610 		    && lvalue_p (arg2) == lvalue_p (arg3))))
5611     {
5612       conversion *conv2;
5613       conversion *conv3;
5614       bool converted = false;
5615 
5616       /* Get the high-water mark for the CONVERSION_OBSTACK.  */
5617       p = conversion_obstack_alloc (0);
5618 
5619       conv2 = conditional_conversion (arg2, arg3, complain);
5620       conv3 = conditional_conversion (arg3, arg2, complain);
5621 
5622       /* [expr.cond]
5623 
5624 	 If both can be converted, or one can be converted but the
5625 	 conversion is ambiguous, the program is ill-formed.  If
5626 	 neither can be converted, the operands are left unchanged and
5627 	 further checking is performed as described below.  If exactly
5628 	 one conversion is possible, that conversion is applied to the
5629 	 chosen operand and the converted operand is used in place of
5630 	 the original operand for the remainder of this section.  */
5631       if ((conv2 && !conv2->bad_p
5632 	   && conv3 && !conv3->bad_p)
5633 	  || (conv2 && conv2->kind == ck_ambig)
5634 	  || (conv3 && conv3->kind == ck_ambig))
5635 	{
5636 	  if (complain & tf_error)
5637 	    {
5638 	      error_at (loc, "operands to %<?:%> have different types "
5639 			"%qT and %qT",
5640 			arg2_type, arg3_type);
5641 	      if (conv2 && !conv2->bad_p && conv3 && !conv3->bad_p)
5642 		inform (loc, "  and each type can be converted to the other");
5643 	      else if (conv2 && conv2->kind == ck_ambig)
5644 		convert_like (conv2, arg2, complain);
5645 	      else
5646 		convert_like (conv3, arg3, complain);
5647 	    }
5648 	  result = error_mark_node;
5649 	}
5650       else if (conv2 && !conv2->bad_p)
5651 	{
5652 	  arg2 = convert_like (conv2, arg2, complain);
5653 	  arg2 = convert_from_reference (arg2);
5654 	  arg2_type = TREE_TYPE (arg2);
5655 	  /* Even if CONV2 is a valid conversion, the result of the
5656 	     conversion may be invalid.  For example, if ARG3 has type
5657 	     "volatile X", and X does not have a copy constructor
5658 	     accepting a "volatile X&", then even if ARG2 can be
5659 	     converted to X, the conversion will fail.  */
5660 	  if (error_operand_p (arg2))
5661 	    result = error_mark_node;
5662 	  converted = true;
5663 	}
5664       else if (conv3 && !conv3->bad_p)
5665 	{
5666 	  arg3 = convert_like (conv3, arg3, complain);
5667 	  arg3 = convert_from_reference (arg3);
5668 	  arg3_type = TREE_TYPE (arg3);
5669 	  if (error_operand_p (arg3))
5670 	    result = error_mark_node;
5671 	  converted = true;
5672 	}
5673 
5674       /* Free all the conversions we allocated.  */
5675       obstack_free (&conversion_obstack, p);
5676 
5677       if (result)
5678 	return result;
5679 
5680       /* If, after the conversion, both operands have class type,
5681 	 treat the cv-qualification of both operands as if it were the
5682 	 union of the cv-qualification of the operands.
5683 
5684 	 The standard is not clear about what to do in this
5685 	 circumstance.  For example, if the first operand has type
5686 	 "const X" and the second operand has a user-defined
5687 	 conversion to "volatile X", what is the type of the second
5688 	 operand after this step?  Making it be "const X" (matching
5689 	 the first operand) seems wrong, as that discards the
5690 	 qualification without actually performing a copy.  Leaving it
5691 	 as "volatile X" seems wrong as that will result in the
5692 	 conditional expression failing altogether, even though,
5693 	 according to this step, the one operand could be converted to
5694 	 the type of the other.  */
5695       if (converted
5696 	  && CLASS_TYPE_P (arg2_type)
5697 	  && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
5698 	arg2_type = arg3_type =
5699 	  cp_build_qualified_type (arg2_type,
5700 				   cp_type_quals (arg2_type)
5701 				   | cp_type_quals (arg3_type));
5702     }
5703 
5704   /* [expr.cond]
5705 
5706      If the second and third operands are glvalues of the same value
5707      category and have the same type, the result is of that type and
5708      value category.  */
5709   if (((lvalue_p (arg2) && lvalue_p (arg3))
5710        || (xvalue_p (arg2) && xvalue_p (arg3)))
5711       && same_type_p (arg2_type, arg3_type))
5712     {
5713       result_type = arg2_type;
5714       goto valid_operands;
5715     }
5716 
5717   /* [expr.cond]
5718 
5719      Otherwise, the result is an rvalue.  If the second and third
5720      operand do not have the same type, and either has (possibly
5721      cv-qualified) class type, overload resolution is used to
5722      determine the conversions (if any) to be applied to the operands
5723      (_over.match.oper_, _over.built_).  */
5724   is_glvalue = false;
5725   if (!same_type_p (arg2_type, arg3_type)
5726       && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
5727     {
5728       releasing_vec args;
5729       conversion *conv;
5730       bool any_viable_p;
5731 
5732       /* Rearrange the arguments so that add_builtin_candidate only has
5733 	 to know about two args.  In build_builtin_candidate, the
5734 	 arguments are unscrambled.  */
5735       args->quick_push (arg2);
5736       args->quick_push (arg3);
5737       args->quick_push (arg1);
5738       add_builtin_candidates (&candidates,
5739 			      COND_EXPR,
5740 			      NOP_EXPR,
5741 			      ovl_op_identifier (false, COND_EXPR),
5742 			      args,
5743 			      LOOKUP_NORMAL, complain);
5744 
5745       /* [expr.cond]
5746 
5747 	 If the overload resolution fails, the program is
5748 	 ill-formed.  */
5749       candidates = splice_viable (candidates, false, &any_viable_p);
5750       if (!any_viable_p)
5751 	{
5752           if (complain & tf_error)
5753 	    error_at (loc, "operands to %<?:%> have different types %qT and %qT",
5754 		      arg2_type, arg3_type);
5755 	  return error_mark_node;
5756 	}
5757       cand = tourney (candidates, complain);
5758       if (!cand)
5759 	{
5760           if (complain & tf_error)
5761             {
5762               auto_diagnostic_group d;
5763               op_error (loc, COND_EXPR, NOP_EXPR, arg1, arg2, arg3, FALSE);
5764               print_z_candidates (loc, candidates);
5765             }
5766 	  return error_mark_node;
5767 	}
5768 
5769       /* [expr.cond]
5770 
5771 	 Otherwise, the conversions thus determined are applied, and
5772 	 the converted operands are used in place of the original
5773 	 operands for the remainder of this section.  */
5774       conv = cand->convs[0];
5775       arg1 = convert_like (conv, arg1, complain);
5776       conv = cand->convs[1];
5777       arg2 = convert_like (conv, arg2, complain);
5778       arg2_type = TREE_TYPE (arg2);
5779       conv = cand->convs[2];
5780       arg3 = convert_like (conv, arg3, complain);
5781       arg3_type = TREE_TYPE (arg3);
5782     }
5783 
5784   /* [expr.cond]
5785 
5786      Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
5787      and function-to-pointer (_conv.func_) standard conversions are
5788      performed on the second and third operands.
5789 
5790      We need to force the lvalue-to-rvalue conversion here for class types,
5791      so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
5792      that isn't wrapped with a TARGET_EXPR plays havoc with exception
5793      regions.  */
5794 
5795   arg2 = force_rvalue (arg2, complain);
5796   if (!CLASS_TYPE_P (arg2_type))
5797     arg2_type = TREE_TYPE (arg2);
5798 
5799   arg3 = force_rvalue (arg3, complain);
5800   if (!CLASS_TYPE_P (arg3_type))
5801     arg3_type = TREE_TYPE (arg3);
5802 
5803   if (arg2 == error_mark_node || arg3 == error_mark_node)
5804     return error_mark_node;
5805 
5806   /* [expr.cond]
5807 
5808      After those conversions, one of the following shall hold:
5809 
5810      --The second and third operands have the same type; the result  is  of
5811        that type.  */
5812   if (same_type_p (arg2_type, arg3_type))
5813     result_type = arg2_type;
5814   /* [expr.cond]
5815 
5816      --The second and third operands have arithmetic or enumeration
5817        type; the usual arithmetic conversions are performed to bring
5818        them to a common type, and the result is of that type.  */
5819   else if ((ARITHMETIC_TYPE_P (arg2_type)
5820 	    || UNSCOPED_ENUM_P (arg2_type))
5821 	   && (ARITHMETIC_TYPE_P (arg3_type)
5822 	       || UNSCOPED_ENUM_P (arg3_type)))
5823     {
5824       /* In this case, there is always a common type.  */
5825       result_type = type_after_usual_arithmetic_conversions (arg2_type,
5826 							     arg3_type);
5827       if (complain & tf_warning)
5828 	do_warn_double_promotion (result_type, arg2_type, arg3_type,
5829 				  "implicit conversion from %qH to %qI to "
5830 				  "match other result of conditional",
5831 				  loc);
5832 
5833       if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
5834 	  && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
5835         {
5836 	  tree stripped_orig_arg2 = tree_strip_any_location_wrapper (orig_arg2);
5837 	  tree stripped_orig_arg3 = tree_strip_any_location_wrapper (orig_arg3);
5838 	  if (TREE_CODE (stripped_orig_arg2) == CONST_DECL
5839 	      && TREE_CODE (stripped_orig_arg3) == CONST_DECL
5840 	      && (DECL_CONTEXT (stripped_orig_arg2)
5841 		  == DECL_CONTEXT (stripped_orig_arg3)))
5842 	    /* Two enumerators from the same enumeration can have different
5843 	       types when the enumeration is still being defined.  */;
5844           else if (complain & tf_warning)
5845 	    warning_at (loc, OPT_Wenum_compare, "enumerated mismatch "
5846 			"in conditional expression: %qT vs %qT",
5847 			arg2_type, arg3_type);
5848         }
5849       else if ((complain & tf_warning)
5850 	       && warn_deprecated_enum_float_conv
5851 	       && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
5852 		    && TREE_CODE (arg3_type) == REAL_TYPE)
5853 		   || (TREE_CODE (arg2_type) == REAL_TYPE
5854 		       && TREE_CODE (arg3_type) == ENUMERAL_TYPE)))
5855 	{
5856 	  if (TREE_CODE (arg2_type) == ENUMERAL_TYPE)
5857 	    warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
5858 			"conditional expression between enumeration type "
5859 			"%qT and floating-point type %qT is deprecated",
5860 			arg2_type, arg3_type);
5861 	  else
5862 	    warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
5863 			"conditional expression between floating-point "
5864 			"type %qT and enumeration type %qT is deprecated",
5865 			arg2_type, arg3_type);
5866 	}
5867       else if ((extra_warnings || warn_enum_conversion)
5868 	       && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
5869 		    && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
5870 		   || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
5871 		       && !same_type_p (arg2_type,
5872 					type_promotes_to (arg3_type)))))
5873 	{
5874 	  if (complain & tf_warning)
5875 	    {
5876 	      enum opt_code opt = (warn_enum_conversion
5877 				   ? OPT_Wenum_conversion
5878 				   : OPT_Wextra);
5879 	      warning_at (loc, opt, "enumerated and "
5880 			  "non-enumerated type in conditional expression");
5881 	    }
5882 	}
5883 
5884       arg2 = perform_implicit_conversion (result_type, arg2, complain);
5885       arg3 = perform_implicit_conversion (result_type, arg3, complain);
5886     }
5887   /* [expr.cond]
5888 
5889      --The second and third operands have pointer type, or one has
5890        pointer type and the other is a null pointer constant; pointer
5891        conversions (_conv.ptr_) and qualification conversions
5892        (_conv.qual_) are performed to bring them to their composite
5893        pointer type (_expr.rel_).  The result is of the composite
5894        pointer type.
5895 
5896      --The second and third operands have pointer to member type, or
5897        one has pointer to member type and the other is a null pointer
5898        constant; pointer to member conversions (_conv.mem_) and
5899        qualification conversions (_conv.qual_) are performed to bring
5900        them to a common type, whose cv-qualification shall match the
5901        cv-qualification of either the second or the third operand.
5902        The result is of the common type.  */
5903   else if ((null_ptr_cst_p (arg2)
5904 	    && TYPE_PTR_OR_PTRMEM_P (arg3_type))
5905 	   || (null_ptr_cst_p (arg3)
5906 	       && TYPE_PTR_OR_PTRMEM_P (arg2_type))
5907 	   || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
5908 	   || (TYPE_PTRDATAMEM_P (arg2_type) && TYPE_PTRDATAMEM_P (arg3_type))
5909 	   || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
5910     {
5911       result_type = composite_pointer_type (loc,
5912 					    arg2_type, arg3_type, arg2,
5913 					    arg3, CPO_CONDITIONAL_EXPR,
5914 					    complain);
5915       if (result_type == error_mark_node)
5916 	return error_mark_node;
5917       arg2 = perform_implicit_conversion (result_type, arg2, complain);
5918       arg3 = perform_implicit_conversion (result_type, arg3, complain);
5919     }
5920 
5921   if (!result_type)
5922     {
5923       if (complain & tf_error)
5924 	error_at (loc, "operands to %<?:%> have different types %qT and %qT",
5925 		  arg2_type, arg3_type);
5926       return error_mark_node;
5927     }
5928 
5929   if (arg2 == error_mark_node || arg3 == error_mark_node)
5930     return error_mark_node;
5931 
5932  valid_operands:
5933   if (processing_template_decl && is_glvalue)
5934     {
5935       /* Let lvalue_kind know this was a glvalue.  */
5936       tree arg = (result_type == arg2_type ? arg2 : arg3);
5937       result_type = cp_build_reference_type (result_type, xvalue_p (arg));
5938     }
5939 
5940   result = build3_loc (loc, COND_EXPR, result_type, arg1, arg2, arg3);
5941 
5942   /* If the ARG2 and ARG3 are the same and don't have side-effects,
5943      warn here, because the COND_EXPR will be turned into ARG2.  */
5944   if (warn_duplicated_branches
5945       && (complain & tf_warning)
5946       && (arg2 == arg3 || operand_equal_p (arg2, arg3,
5947 					   OEP_ADDRESS_OF_SAME_FIELD)))
5948     warning_at (EXPR_LOCATION (result), OPT_Wduplicated_branches,
5949 		"this condition has identical branches");
5950 
5951   /* We can't use result_type below, as fold might have returned a
5952      throw_expr.  */
5953 
5954   if (!is_glvalue)
5955     {
5956       /* Expand both sides into the same slot, hopefully the target of
5957 	 the ?: expression.  We used to check for TARGET_EXPRs here,
5958 	 but now we sometimes wrap them in NOP_EXPRs so the test would
5959 	 fail.  */
5960       if (CLASS_TYPE_P (TREE_TYPE (result)))
5961 	result = get_target_expr_sfinae (result, complain);
5962       /* If this expression is an rvalue, but might be mistaken for an
5963 	 lvalue, we must add a NON_LVALUE_EXPR.  */
5964       result = rvalue (result);
5965     }
5966   else
5967     result = force_paren_expr (result);
5968 
5969   return result;
5970 }
5971 
5972 /* OPERAND is an operand to an expression.  Perform necessary steps
5973    required before using it.  If OPERAND is NULL_TREE, NULL_TREE is
5974    returned.  */
5975 
5976 static tree
prep_operand(tree operand)5977 prep_operand (tree operand)
5978 {
5979   if (operand)
5980     {
5981       if (CLASS_TYPE_P (TREE_TYPE (operand))
5982 	  && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
5983 	/* Make sure the template type is instantiated now.  */
5984 	instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
5985     }
5986 
5987   return operand;
5988 }
5989 
5990 /* True iff CONV represents a conversion sequence which no other can be better
5991    than under [over.ics.rank]: in other words, a "conversion" to the exact same
5992    type (including binding to a reference to the same type).  This is stronger
5993    than the standard's "identity" category, which also includes reference
5994    bindings that add cv-qualifiers or change rvalueness.  */
5995 
5996 static bool
perfect_conversion_p(conversion * conv)5997 perfect_conversion_p (conversion *conv)
5998 {
5999   if (CONVERSION_RANK (conv) != cr_identity)
6000     return false;
6001   if (conv->kind == ck_ref_bind)
6002     {
6003       if (!conv->rvaluedness_matches_p)
6004 	return false;
6005       if (!same_type_p (TREE_TYPE (conv->type),
6006 			next_conversion (conv)->type))
6007 	return false;
6008     }
6009   if (conv->check_narrowing)
6010     /* Brace elision is imperfect.  */
6011     return false;
6012   return true;
6013 }
6014 
6015 /* True if CAND represents a perfect match, i.e. all perfect conversions, so no
6016    other candidate can be a better match.  Since the template/non-template
6017    tiebreaker comes immediately after the conversion comparison in
6018    [over.match.best], a perfect non-template candidate is better than all
6019    templates.  */
6020 
6021 static bool
perfect_candidate_p(z_candidate * cand)6022 perfect_candidate_p (z_candidate *cand)
6023 {
6024   if (cand->viable < 1)
6025     return false;
6026   /* CWG1402 makes an implicitly deleted move op worse than other
6027      candidates.  */
6028   if (DECL_DELETED_FN (cand->fn) && DECL_DEFAULTED_FN (cand->fn)
6029       && move_fn_p (cand->fn))
6030     return false;
6031   int len = cand->num_convs;
6032   for (int i = 0; i < len; ++i)
6033     if (!perfect_conversion_p (cand->convs[i]))
6034       return false;
6035   if (conversion *conv = cand->second_conv)
6036     if (!perfect_conversion_p (conv))
6037       return false;
6038   return true;
6039 }
6040 
6041 /* True iff one of CAND's argument conversions is NULL.  */
6042 
6043 static bool
missing_conversion_p(const z_candidate * cand)6044 missing_conversion_p (const z_candidate *cand)
6045 {
6046   for (unsigned i = 0; i < cand->num_convs; ++i)
6047     if (!cand->convs[i])
6048       return true;
6049   return false;
6050 }
6051 
6052 /* Add each of the viable functions in FNS (a FUNCTION_DECL or
6053    OVERLOAD) to the CANDIDATES, returning an updated list of
6054    CANDIDATES.  The ARGS are the arguments provided to the call;
6055    if FIRST_ARG is non-null it is the implicit object argument,
6056    otherwise the first element of ARGS is used if needed.  The
6057    EXPLICIT_TARGS are explicit template arguments provided.
6058    TEMPLATE_ONLY is true if only template functions should be
6059    considered.  CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
6060    add_function_candidate.  */
6061 
6062 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)6063 add_candidates (tree fns, tree first_arg, const vec<tree, va_gc> *args,
6064 		tree return_type,
6065 		tree explicit_targs, bool template_only,
6066 		tree conversion_path, tree access_path,
6067 		int flags,
6068 		struct z_candidate **candidates,
6069 		tsubst_flags_t complain)
6070 {
6071   tree ctype;
6072   const vec<tree, va_gc> *non_static_args;
6073   bool check_list_ctor = false;
6074   bool check_converting = false;
6075   unification_kind_t strict;
6076 
6077   if (!fns)
6078     return;
6079 
6080   /* Precalculate special handling of constructors and conversion ops.  */
6081   tree fn = OVL_FIRST (fns);
6082   if (DECL_CONV_FN_P (fn))
6083     {
6084       check_list_ctor = false;
6085       check_converting = (flags & LOOKUP_ONLYCONVERTING) != 0;
6086       if (flags & LOOKUP_NO_CONVERSION)
6087 	/* We're doing return_type(x).  */
6088 	strict = DEDUCE_CONV;
6089       else
6090 	/* We're doing x.operator return_type().  */
6091 	strict = DEDUCE_EXACT;
6092       /* [over.match.funcs] For conversion functions, the function
6093 	 is considered to be a member of the class of the implicit
6094 	 object argument for the purpose of defining the type of
6095 	 the implicit object parameter.  */
6096       ctype = TYPE_MAIN_VARIANT (TREE_TYPE (first_arg));
6097     }
6098   else
6099     {
6100       if (DECL_CONSTRUCTOR_P (fn))
6101 	{
6102 	  check_list_ctor = (flags & LOOKUP_LIST_ONLY) != 0;
6103 	  /* For list-initialization we consider explicit constructors
6104 	     and complain if one is chosen.  */
6105 	  check_converting
6106 	    = ((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
6107 	       == LOOKUP_ONLYCONVERTING);
6108 	}
6109       strict = DEDUCE_CALL;
6110       ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
6111     }
6112 
6113   if (first_arg)
6114     non_static_args = args;
6115   else
6116     /* Delay creating the implicit this parameter until it is needed.  */
6117     non_static_args = NULL;
6118 
6119   bool seen_strictly_viable = any_strictly_viable (*candidates);
6120   /* If there's a non-template perfect match, we don't need to consider
6121      templates.  So check non-templates first.  This optimization is only
6122      really needed for the defaulted copy constructor of tuple and the like
6123      (96926), but it seems like we might as well enable it more generally.  */
6124   bool seen_perfect = false;
6125   enum { templates, non_templates, either } which = either;
6126   if (template_only)
6127     which = templates;
6128   else /*if (flags & LOOKUP_DEFAULTED)*/
6129     which = non_templates;
6130 
6131   /* During overload resolution, we first consider each function under the
6132      assumption that we'll eventually find a strictly viable candidate.
6133      This allows us to circumvent our defacto behavior when checking
6134      argument conversions and shortcut consideration of the candidate
6135      upon encountering the first bad conversion.  If this assumption
6136      turns out to be false, and all candidates end up being non-strictly
6137      viable, then we reconsider such candidates under the defacto behavior.
6138      This trick is important for pruning member function overloads according
6139      to their const/ref-qualifiers (since all 'this' conversions are at
6140      worst bad) without breaking -fpermissive.  */
6141   tree bad_fns = NULL_TREE;
6142   bool shortcut_bad_convs = true;
6143 
6144  again:
6145   for (tree fn : lkp_range (fns))
6146     {
6147       if (check_converting && DECL_NONCONVERTING_P (fn))
6148 	continue;
6149       if (check_list_ctor && !is_list_ctor (fn))
6150 	continue;
6151       if (which == templates && TREE_CODE (fn) != TEMPLATE_DECL)
6152 	continue;
6153       if (which == non_templates && TREE_CODE (fn) == TEMPLATE_DECL)
6154 	continue;
6155 
6156       tree fn_first_arg = NULL_TREE;
6157       const vec<tree, va_gc> *fn_args = args;
6158 
6159       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
6160 	{
6161 	  /* Figure out where the object arg comes from.  If this
6162 	     function is a non-static member and we didn't get an
6163 	     implicit object argument, move it out of args.  */
6164 	  if (first_arg == NULL_TREE)
6165 	    {
6166 	      unsigned int ix;
6167 	      tree arg;
6168 	      vec<tree, va_gc> *tempvec;
6169 	      vec_alloc (tempvec, args->length () - 1);
6170 	      for (ix = 1; args->iterate (ix, &arg); ++ix)
6171 		tempvec->quick_push (arg);
6172 	      non_static_args = tempvec;
6173 	      first_arg = (*args)[0];
6174 	    }
6175 
6176 	  fn_first_arg = first_arg;
6177 	  fn_args = non_static_args;
6178 	}
6179 
6180       /* Don't bother reversing an operator with two identical parameters.  */
6181       else if (vec_safe_length (args) == 2 && (flags & LOOKUP_REVERSED))
6182 	{
6183 	  tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
6184 	  if (same_type_p (TREE_VALUE (parmlist),
6185 			   TREE_VALUE (TREE_CHAIN (parmlist))))
6186 	    continue;
6187 	}
6188 
6189       if (TREE_CODE (fn) == TEMPLATE_DECL)
6190 	{
6191 	  if (!add_template_candidate (candidates,
6192 				       fn,
6193 				       ctype,
6194 				       explicit_targs,
6195 				       fn_first_arg,
6196 				       fn_args,
6197 				       return_type,
6198 				       access_path,
6199 				       conversion_path,
6200 				       flags,
6201 				       strict,
6202 				       shortcut_bad_convs,
6203 				       complain))
6204 	    continue;
6205 	}
6206       else
6207 	{
6208 	  add_function_candidate (candidates,
6209 				  fn,
6210 				  ctype,
6211 				  fn_first_arg,
6212 				  fn_args,
6213 				  access_path,
6214 				  conversion_path,
6215 				  flags,
6216 				  NULL,
6217 				  shortcut_bad_convs,
6218 				  complain);
6219 	  if (perfect_candidate_p (*candidates))
6220 	    seen_perfect = true;
6221 	}
6222 
6223       z_candidate *cand = *candidates;
6224       if (cand->viable == 1)
6225 	seen_strictly_viable = true;
6226 
6227       if (cand->viable == -1
6228 	  && shortcut_bad_convs
6229 	  && missing_conversion_p (cand))
6230 	{
6231 	  /* This candidate has been tentatively marked non-strictly viable,
6232 	     and we didn't compute all argument conversions for it (having
6233 	     stopped at the first bad conversion).  Add the function to BAD_FNS
6234 	     to fully reconsider later if we don't find any strictly viable
6235 	     candidates.  */
6236 	  if (complain & (tf_error | tf_conv))
6237 	    {
6238 	      bad_fns = lookup_add (fn, bad_fns);
6239 	      *candidates = (*candidates)->next;
6240 	    }
6241 	  else
6242 	    /* But if we're in a SFINAE context, just mark this candidate as
6243 	       unviable outright and avoid potentially reconsidering it.
6244 	       This is safe to do because in a SFINAE context, performing a bad
6245 	       conversion is always an error (even with -fpermissive), so a
6246 	       non-strictly viable candidate is effectively unviable anyway.  */
6247 	    cand->viable = 0;
6248 	}
6249     }
6250   if (which == non_templates && !seen_perfect)
6251     {
6252       which = templates;
6253       goto again;
6254     }
6255   else if (which == templates
6256 	   && !seen_strictly_viable
6257 	   && shortcut_bad_convs
6258 	   && bad_fns)
6259     {
6260       /* None of the candidates are strictly viable, so consider again those
6261 	 functions in BAD_FNS, this time without shortcutting bad conversions
6262 	 so that all their argument conversions are computed.  */
6263       which = either;
6264       fns = bad_fns;
6265       shortcut_bad_convs = false;
6266       goto again;
6267     }
6268 }
6269 
6270 /* Returns 1 if P0145R2 says that the LHS of operator CODE is evaluated first,
6271    -1 if the RHS is evaluated first, or 0 if the order is unspecified.  */
6272 
6273 static int
op_is_ordered(tree_code code)6274 op_is_ordered (tree_code code)
6275 {
6276   switch (code)
6277     {
6278       // 5. b @= a
6279     case MODIFY_EXPR:
6280       return (flag_strong_eval_order > 1 ? -1 : 0);
6281 
6282       // 6. a[b]
6283     case ARRAY_REF:
6284       return (flag_strong_eval_order > 1 ? 1 : 0);
6285 
6286       // 1. a.b
6287       // Not overloadable (yet).
6288       // 2. a->b
6289       // Only one argument.
6290       // 3. a->*b
6291     case MEMBER_REF:
6292       // 7. a << b
6293     case LSHIFT_EXPR:
6294       // 8. a >> b
6295     case RSHIFT_EXPR:
6296       // a && b
6297       // Predates P0145R3.
6298     case TRUTH_ANDIF_EXPR:
6299       // a || b
6300       // Predates P0145R3.
6301     case TRUTH_ORIF_EXPR:
6302       // a , b
6303       // Predates P0145R3.
6304     case COMPOUND_EXPR:
6305       return (flag_strong_eval_order ? 1 : 0);
6306 
6307     default:
6308       return 0;
6309     }
6310 }
6311 
6312 /* Subroutine of build_new_op: Add to CANDIDATES all candidates for the
6313    operator indicated by CODE/CODE2.  This function calls itself recursively to
6314    handle C++20 rewritten comparison operator candidates.
6315 
6316    LOOKUPS, if non-NULL, is the set of pertinent namespace-scope operator
6317    overloads to consider.  This parameter is used when instantiating a
6318    dependent operator expression and has the same structure as
6319    DEPENDENT_OPERATOR_TYPE_SAVED_LOOKUPS.  */
6320 
6321 static tree
add_operator_candidates(z_candidate ** candidates,tree_code code,tree_code code2,vec<tree,va_gc> * arglist,tree lookups,int flags,tsubst_flags_t complain)6322 add_operator_candidates (z_candidate **candidates,
6323 			 tree_code code, tree_code code2,
6324 			 vec<tree, va_gc> *arglist, tree lookups,
6325 			 int flags, tsubst_flags_t complain)
6326 {
6327   z_candidate *start_candidates = *candidates;
6328   bool ismodop = code2 != ERROR_MARK;
6329   tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
6330 
6331   /* LOOKUP_REWRITTEN is set when we're looking for the == or <=> operator to
6332      rewrite from, and also when we're looking for the e.g. < operator to use
6333      on the result of <=>.  In the latter case, we don't want the flag set in
6334      the candidate, we just want to suppress looking for rewrites.  */
6335   bool rewritten = (flags & LOOKUP_REWRITTEN);
6336   if (rewritten && code != EQ_EXPR && code != SPACESHIP_EXPR)
6337     flags &= ~LOOKUP_REWRITTEN;
6338 
6339   bool memonly = false;
6340   switch (code)
6341     {
6342       /* =, ->, [], () must be non-static member functions.  */
6343     case MODIFY_EXPR:
6344       if (code2 != NOP_EXPR)
6345 	break;
6346       /* FALLTHRU */
6347     case COMPONENT_REF:
6348     case ARRAY_REF:
6349       memonly = true;
6350       break;
6351 
6352     default:
6353       break;
6354     }
6355 
6356   /* Add namespace-scope operators to the list of functions to
6357      consider.  */
6358   if (!memonly)
6359     {
6360       tree fns;
6361       if (!lookups)
6362 	fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
6363       /* If LOOKUPS is non-NULL, then we're instantiating a dependent operator
6364 	 expression, and LOOKUPS is the result of stage 1 name lookup.  */
6365       else if (tree found = purpose_member (fnname, lookups))
6366 	fns = TREE_VALUE (found);
6367       else
6368 	fns = NULL_TREE;
6369       fns = lookup_arg_dependent (fnname, fns, arglist);
6370       add_candidates (fns, NULL_TREE, arglist, NULL_TREE,
6371 		      NULL_TREE, false, NULL_TREE, NULL_TREE,
6372 		      flags, candidates, complain);
6373     }
6374 
6375   /* Add class-member operators to the candidate set.  */
6376   tree arg1_type = TREE_TYPE ((*arglist)[0]);
6377   unsigned nargs = arglist->length () > 1 ? 2 : 1;
6378   tree arg2_type = nargs > 1 ? TREE_TYPE ((*arglist)[1]) : NULL_TREE;
6379   if (CLASS_TYPE_P (arg1_type))
6380     {
6381       tree fns = lookup_fnfields (arg1_type, fnname, 1, complain);
6382       if (fns == error_mark_node)
6383 	return error_mark_node;
6384       if (fns)
6385 	add_candidates (BASELINK_FUNCTIONS (fns),
6386 			NULL_TREE, arglist, NULL_TREE,
6387 			NULL_TREE, false,
6388 			BASELINK_BINFO (fns),
6389 			BASELINK_ACCESS_BINFO (fns),
6390 			flags, candidates, complain);
6391     }
6392   /* Per [over.match.oper]3.2, if no operand has a class type, then
6393      only non-member functions that have type T1 or reference to
6394      cv-qualified-opt T1 for the first argument, if the first argument
6395      has an enumeration type, or T2 or reference to cv-qualified-opt
6396      T2 for the second argument, if the second argument has an
6397      enumeration type.  Filter out those that don't match.  */
6398   else if (! arg2_type || ! CLASS_TYPE_P (arg2_type))
6399     {
6400       struct z_candidate **candp, **next;
6401 
6402       for (candp = candidates; *candp != start_candidates; candp = next)
6403 	{
6404 	  unsigned i;
6405 	  z_candidate *cand = *candp;
6406 	  next = &cand->next;
6407 
6408 	  tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
6409 
6410 	  for (i = 0; i < nargs; ++i)
6411 	    {
6412 	      tree parmtype = TREE_VALUE (parmlist);
6413 	      tree argtype = unlowered_expr_type ((*arglist)[i]);
6414 
6415 	      if (TYPE_REF_P (parmtype))
6416 		parmtype = TREE_TYPE (parmtype);
6417 	      if (TREE_CODE (argtype) == ENUMERAL_TYPE
6418 		  && (same_type_ignoring_top_level_qualifiers_p
6419 		      (argtype, parmtype)))
6420 		break;
6421 
6422 	      parmlist = TREE_CHAIN (parmlist);
6423 	    }
6424 
6425 	  /* No argument has an appropriate type, so remove this
6426 	     candidate function from the list.  */
6427 	  if (i == nargs)
6428 	    {
6429 	      *candp = cand->next;
6430 	      next = candp;
6431 	    }
6432 	}
6433     }
6434 
6435   if (!rewritten)
6436     {
6437       /* The standard says to rewrite built-in candidates, too,
6438 	 but there's no point.  */
6439       add_builtin_candidates (candidates, code, code2, fnname, arglist,
6440 			      flags, complain);
6441 
6442       /* Maybe add C++20 rewritten comparison candidates.  */
6443       tree_code rewrite_code = ERROR_MARK;
6444       if (cxx_dialect >= cxx20
6445 	  && nargs == 2
6446 	  && (OVERLOAD_TYPE_P (arg1_type) || OVERLOAD_TYPE_P (arg2_type)))
6447 	switch (code)
6448 	  {
6449 	  case LT_EXPR:
6450 	  case LE_EXPR:
6451 	  case GT_EXPR:
6452 	  case GE_EXPR:
6453 	  case SPACESHIP_EXPR:
6454 	    rewrite_code = SPACESHIP_EXPR;
6455 	    break;
6456 
6457 	  case NE_EXPR:
6458 	  case EQ_EXPR:
6459 	    rewrite_code = EQ_EXPR;
6460 	    break;
6461 
6462 	  default:;
6463 	  }
6464 
6465       if (rewrite_code)
6466 	{
6467 	  flags |= LOOKUP_REWRITTEN;
6468 	  if (rewrite_code != code)
6469 	    /* Add rewritten candidates in same order.  */
6470 	    add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
6471 				     arglist, lookups, flags, complain);
6472 
6473 	  z_candidate *save_cand = *candidates;
6474 
6475 	  /* Add rewritten candidates in reverse order.  */
6476 	  flags |= LOOKUP_REVERSED;
6477 	  vec<tree,va_gc> *revlist = make_tree_vector ();
6478 	  revlist->quick_push ((*arglist)[1]);
6479 	  revlist->quick_push ((*arglist)[0]);
6480 	  add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
6481 				   revlist, lookups, flags, complain);
6482 
6483 	  /* Release the vec if we didn't add a candidate that uses it.  */
6484 	  for (z_candidate *c = *candidates; c != save_cand; c = c->next)
6485 	    if (c->args == revlist)
6486 	      {
6487 		revlist = NULL;
6488 		break;
6489 	      }
6490 	  release_tree_vector (revlist);
6491 	}
6492     }
6493 
6494   return NULL_TREE;
6495 }
6496 
6497 tree
build_new_op(const op_location_t & loc,enum tree_code code,int flags,tree arg1,tree arg2,tree arg3,tree lookups,tree * overload,tsubst_flags_t complain)6498 build_new_op (const op_location_t &loc, enum tree_code code, int flags,
6499 	      tree arg1, tree arg2, tree arg3, tree lookups,
6500 	      tree *overload, tsubst_flags_t complain)
6501 {
6502   struct z_candidate *candidates = 0, *cand;
6503   releasing_vec arglist;
6504   tree result = NULL_TREE;
6505   bool result_valid_p = false;
6506   enum tree_code code2 = ERROR_MARK;
6507   enum tree_code code_orig_arg1 = ERROR_MARK;
6508   enum tree_code code_orig_arg2 = ERROR_MARK;
6509   void *p;
6510   bool strict_p;
6511   bool any_viable_p;
6512 
6513   auto_cond_timevar tv (TV_OVERLOAD);
6514 
6515   if (error_operand_p (arg1)
6516       || error_operand_p (arg2)
6517       || error_operand_p (arg3))
6518     return error_mark_node;
6519 
6520   bool ismodop = code == MODIFY_EXPR;
6521   if (ismodop)
6522     {
6523       code2 = TREE_CODE (arg3);
6524       arg3 = NULL_TREE;
6525     }
6526 
6527   tree arg1_type = unlowered_expr_type (arg1);
6528   tree arg2_type = arg2 ? unlowered_expr_type (arg2) : NULL_TREE;
6529 
6530   arg1 = prep_operand (arg1);
6531 
6532   switch (code)
6533     {
6534     case NEW_EXPR:
6535     case VEC_NEW_EXPR:
6536     case VEC_DELETE_EXPR:
6537     case DELETE_EXPR:
6538       /* Use build_operator_new_call and build_op_delete_call instead.  */
6539       gcc_unreachable ();
6540 
6541     case CALL_EXPR:
6542       /* Use build_op_call instead.  */
6543       gcc_unreachable ();
6544 
6545     case TRUTH_ORIF_EXPR:
6546     case TRUTH_ANDIF_EXPR:
6547     case TRUTH_AND_EXPR:
6548     case TRUTH_OR_EXPR:
6549       /* These are saved for the sake of warn_logical_operator.  */
6550       code_orig_arg1 = TREE_CODE (arg1);
6551       code_orig_arg2 = TREE_CODE (arg2);
6552       break;
6553     case GT_EXPR:
6554     case LT_EXPR:
6555     case GE_EXPR:
6556     case LE_EXPR:
6557     case EQ_EXPR:
6558     case NE_EXPR:
6559       /* These are saved for the sake of maybe_warn_bool_compare.  */
6560       code_orig_arg1 = TREE_CODE (arg1_type);
6561       code_orig_arg2 = TREE_CODE (arg2_type);
6562       break;
6563 
6564     default:
6565       break;
6566     }
6567 
6568   arg2 = prep_operand (arg2);
6569   arg3 = prep_operand (arg3);
6570 
6571   if (code == COND_EXPR)
6572     /* Use build_conditional_expr instead.  */
6573     gcc_unreachable ();
6574   else if (! OVERLOAD_TYPE_P (arg1_type)
6575 	   && (! arg2 || ! OVERLOAD_TYPE_P (arg2_type)))
6576     goto builtin;
6577 
6578   if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
6579     {
6580       arg2 = integer_zero_node;
6581       arg2_type = integer_type_node;
6582     }
6583 
6584   arglist->quick_push (arg1);
6585   if (arg2 != NULL_TREE)
6586     arglist->quick_push (arg2);
6587   if (arg3 != NULL_TREE)
6588     arglist->quick_push (arg3);
6589 
6590   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
6591   p = conversion_obstack_alloc (0);
6592 
6593   result = add_operator_candidates (&candidates, code, code2, arglist,
6594 				    lookups, flags, complain);
6595   if (result == error_mark_node)
6596     goto user_defined_result_ready;
6597 
6598   switch (code)
6599     {
6600     case COMPOUND_EXPR:
6601     case ADDR_EXPR:
6602       /* For these, the built-in candidates set is empty
6603 	 [over.match.oper]/3.  We don't want non-strict matches
6604 	 because exact matches are always possible with built-in
6605 	 operators.  The built-in candidate set for COMPONENT_REF
6606 	 would be empty too, but since there are no such built-in
6607 	 operators, we accept non-strict matches for them.  */
6608       strict_p = true;
6609       break;
6610 
6611     default:
6612       strict_p = false;
6613       break;
6614     }
6615 
6616   candidates = splice_viable (candidates, strict_p, &any_viable_p);
6617   if (!any_viable_p)
6618     {
6619       switch (code)
6620 	{
6621 	case POSTINCREMENT_EXPR:
6622 	case POSTDECREMENT_EXPR:
6623 	  /* Don't try anything fancy if we're not allowed to produce
6624 	     errors.  */
6625 	  if (!(complain & tf_error))
6626 	    return error_mark_node;
6627 
6628 	  /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
6629 	     distinguish between prefix and postfix ++ and
6630 	     operator++() was used for both, so we allow this with
6631 	     -fpermissive.  */
6632 	  else
6633 	    {
6634 	      tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
6635 	      const char *msg = (flag_permissive)
6636 		? G_("no %<%D(int)%> declared for postfix %qs,"
6637 		     " trying prefix operator instead")
6638 		: G_("no %<%D(int)%> declared for postfix %qs");
6639 	      permerror (loc, msg, fnname, OVL_OP_INFO (false, code)->name);
6640 	    }
6641 
6642 	  if (!flag_permissive)
6643 	    return error_mark_node;
6644 
6645 	  if (code == POSTINCREMENT_EXPR)
6646 	    code = PREINCREMENT_EXPR;
6647 	  else
6648 	    code = PREDECREMENT_EXPR;
6649 	  result = build_new_op (loc, code, flags, arg1, NULL_TREE,
6650 				 NULL_TREE, lookups, overload, complain);
6651 	  break;
6652 
6653 	  /* The caller will deal with these.  */
6654 	case ADDR_EXPR:
6655 	case COMPOUND_EXPR:
6656 	case COMPONENT_REF:
6657 	case CO_AWAIT_EXPR:
6658 	  result = NULL_TREE;
6659 	  result_valid_p = true;
6660 	  break;
6661 
6662 	default:
6663 	  if (complain & tf_error)
6664 	    {
6665 		/* If one of the arguments of the operator represents
6666 		   an invalid use of member function pointer, try to report
6667 		   a meaningful error ...  */
6668 	      if (invalid_nonstatic_memfn_p (loc, arg1, tf_error)
6669 		    || invalid_nonstatic_memfn_p (loc, arg2, tf_error)
6670 		    || invalid_nonstatic_memfn_p (loc, arg3, tf_error))
6671 		  /* We displayed the error message.  */;
6672 		else
6673 		  {
6674 		    /* ... Otherwise, report the more generic
6675 		       "no matching operator found" error */
6676 		    auto_diagnostic_group d;
6677 		    op_error (loc, code, code2, arg1, arg2, arg3, FALSE);
6678 		    print_z_candidates (loc, candidates);
6679 		  }
6680 	    }
6681 	  result = error_mark_node;
6682 	  break;
6683 	}
6684     }
6685   else
6686     {
6687       cand = tourney (candidates, complain);
6688       if (cand == 0)
6689 	{
6690 	  if (complain & tf_error)
6691 	    {
6692 	      auto_diagnostic_group d;
6693 	      op_error (loc, code, code2, arg1, arg2, arg3, TRUE);
6694 	      print_z_candidates (loc, candidates);
6695 	    }
6696 	  result = error_mark_node;
6697 	  if (overload)
6698 	    *overload = error_mark_node;
6699 	}
6700       else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
6701 	{
6702 	  if (overload)
6703 	    *overload = cand->fn;
6704 
6705 	  if (resolve_args (arglist, complain) == NULL)
6706 	    result = error_mark_node;
6707 	  else
6708 	    {
6709 	      tsubst_flags_t ocomplain = complain;
6710 	      if (cand->rewritten ())
6711 		/* We'll wrap this call in another one.  */
6712 		ocomplain &= ~tf_decltype;
6713 	      if (cand->reversed ())
6714 		{
6715 		  /* We swapped these in add_candidate, swap them back now.  */
6716 		  std::swap (cand->convs[0], cand->convs[1]);
6717 		  if (cand->fn == current_function_decl)
6718 		    warning_at (loc, 0, "in C++20 this comparison calls the "
6719 				"current function recursively with reversed "
6720 				"arguments");
6721 		}
6722 	      result = build_over_call (cand, LOOKUP_NORMAL, ocomplain);
6723 	    }
6724 
6725 	  if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
6726 	    /* There won't be a CALL_EXPR.  */;
6727 	  else if (result && result != error_mark_node)
6728 	    {
6729 	      tree call = extract_call_expr (result);
6730 	      CALL_EXPR_OPERATOR_SYNTAX (call) = true;
6731 
6732 	      /* Specify evaluation order as per P0145R2.  */
6733 	      CALL_EXPR_ORDERED_ARGS (call) = false;
6734 	      switch (op_is_ordered (code))
6735 		{
6736 		case -1:
6737 		  CALL_EXPR_REVERSE_ARGS (call) = true;
6738 		  break;
6739 
6740 		case 1:
6741 		  CALL_EXPR_ORDERED_ARGS (call) = true;
6742 		  break;
6743 
6744 		default:
6745 		  break;
6746 		}
6747 	    }
6748 
6749 	  /* If this was a C++20 rewritten comparison, adjust the result.  */
6750 	  if (cand->rewritten ())
6751 	    {
6752 	      /* FIXME build_min_non_dep_op_overload can't handle rewrites.  */
6753 	      if (overload)
6754 		*overload = NULL_TREE;
6755 	      switch (code)
6756 		{
6757 		case EQ_EXPR:
6758 		  gcc_checking_assert (cand->reversed ());
6759 		  gcc_fallthrough ();
6760 		case NE_EXPR:
6761 		  /* If a rewritten operator== candidate is selected by
6762 		     overload resolution for an operator @, its return type
6763 		     shall be cv bool.... */
6764 		  if (TREE_CODE (TREE_TYPE (result)) != BOOLEAN_TYPE)
6765 		    {
6766 		      if (complain & tf_error)
6767 			{
6768 			  auto_diagnostic_group d;
6769 			  error_at (loc, "return type of %qD is not %qs",
6770 				    cand->fn, "bool");
6771 			  inform (loc, "used as rewritten candidate for "
6772 				  "comparison of %qT and %qT",
6773 				  arg1_type, arg2_type);
6774 			}
6775 		      result = error_mark_node;
6776 		    }
6777 		  else if (code == NE_EXPR)
6778 		    /* !(y == x) or !(x == y)  */
6779 		    result = build1_loc (loc, TRUTH_NOT_EXPR,
6780 					 boolean_type_node, result);
6781 		  break;
6782 
6783 		  /* If a rewritten operator<=> candidate is selected by
6784 		     overload resolution for an operator @, x @ y is
6785 		     interpreted as 0 @ (y <=> x) if the selected candidate is
6786 		     a synthesized candidate with reversed order of parameters,
6787 		     or (x <=> y) @ 0 otherwise, using the selected rewritten
6788 		     operator<=> candidate.  */
6789 		case SPACESHIP_EXPR:
6790 		  if (!cand->reversed ())
6791 		    /* We're in the build_new_op call below for an outer
6792 		       reversed call; we don't need to do anything more.  */
6793 		    break;
6794 		  gcc_fallthrough ();
6795 		case LT_EXPR:
6796 		case LE_EXPR:
6797 		case GT_EXPR:
6798 		case GE_EXPR:
6799 		  {
6800 		    tree lhs = result;
6801 		    tree rhs = integer_zero_node;
6802 		    if (cand->reversed ())
6803 		      std::swap (lhs, rhs);
6804 		    warning_sentinel ws (warn_zero_as_null_pointer_constant);
6805 		    result = build_new_op (loc, code,
6806 					   LOOKUP_NORMAL|LOOKUP_REWRITTEN,
6807 					   lhs, rhs, NULL_TREE, lookups,
6808 					   NULL, complain);
6809 		  }
6810 		  break;
6811 
6812 		default:
6813 		  gcc_unreachable ();
6814 		}
6815 	    }
6816 	}
6817       else
6818 	{
6819 	  /* Give any warnings we noticed during overload resolution.  */
6820 	  if (cand->warnings && (complain & tf_warning))
6821 	    {
6822 	      struct candidate_warning *w;
6823 	      for (w = cand->warnings; w; w = w->next)
6824 		joust (cand, w->loser, 1, complain);
6825 	    }
6826 
6827 	  /* Check for comparison of different enum types.  */
6828 	  switch (code)
6829 	    {
6830 	    case GT_EXPR:
6831 	    case LT_EXPR:
6832 	    case GE_EXPR:
6833 	    case LE_EXPR:
6834 	    case EQ_EXPR:
6835 	    case NE_EXPR:
6836 	      if (TREE_CODE (arg1_type) == ENUMERAL_TYPE
6837 		  && TREE_CODE (arg2_type) == ENUMERAL_TYPE
6838 		  && (TYPE_MAIN_VARIANT (arg1_type)
6839 		      != TYPE_MAIN_VARIANT (arg2_type))
6840 		  && (complain & tf_warning))
6841 		warning_at (loc, OPT_Wenum_compare,
6842 			    "comparison between %q#T and %q#T",
6843 			    arg1_type, arg2_type);
6844 	      break;
6845 	    default:
6846 	      break;
6847 	    }
6848 
6849 	  /* "If a built-in candidate is selected by overload resolution, the
6850 	     operands of class type are converted to the types of the
6851 	     corresponding parameters of the selected operation function,
6852 	     except that the second standard conversion sequence of a
6853 	     user-defined conversion sequence (12.3.3.1.2) is not applied."  */
6854 	  conversion *conv = cand->convs[0];
6855 	  if (conv->user_conv_p)
6856 	    {
6857 	      conv = strip_standard_conversion (conv);
6858 	      arg1 = convert_like (conv, arg1, complain);
6859 	    }
6860 
6861 	  if (arg2)
6862 	    {
6863 	      conv = cand->convs[1];
6864 	      if (conv->user_conv_p)
6865 		{
6866 		  conv = strip_standard_conversion (conv);
6867 		  arg2 = convert_like (conv, arg2, complain);
6868 		}
6869 	    }
6870 
6871 	  if (arg3)
6872 	    {
6873 	      conv = cand->convs[2];
6874 	      if (conv->user_conv_p)
6875 		{
6876 		  conv = strip_standard_conversion (conv);
6877 		  arg3 = convert_like (conv, arg3, complain);
6878 		}
6879 	    }
6880 	}
6881     }
6882 
6883  user_defined_result_ready:
6884 
6885   /* Free all the conversions we allocated.  */
6886   obstack_free (&conversion_obstack, p);
6887 
6888   if (result || result_valid_p)
6889     return result;
6890 
6891  builtin:
6892   switch (code)
6893     {
6894     case MODIFY_EXPR:
6895       return cp_build_modify_expr (loc, arg1, code2, arg2, complain);
6896 
6897     case INDIRECT_REF:
6898       return cp_build_indirect_ref (loc, arg1, RO_UNARY_STAR, complain);
6899 
6900     case TRUTH_ANDIF_EXPR:
6901     case TRUTH_ORIF_EXPR:
6902     case TRUTH_AND_EXPR:
6903     case TRUTH_OR_EXPR:
6904       if ((complain & tf_warning) && !processing_template_decl)
6905 	warn_logical_operator (loc, code, boolean_type_node,
6906 			       code_orig_arg1, arg1,
6907 			       code_orig_arg2, arg2);
6908       /* Fall through.  */
6909     case GT_EXPR:
6910     case LT_EXPR:
6911     case GE_EXPR:
6912     case LE_EXPR:
6913     case EQ_EXPR:
6914     case NE_EXPR:
6915       if ((complain & tf_warning)
6916 	  && ((code_orig_arg1 == BOOLEAN_TYPE)
6917 	      ^ (code_orig_arg2 == BOOLEAN_TYPE)))
6918 	maybe_warn_bool_compare (loc, code, arg1, arg2);
6919       if (complain & tf_warning && warn_tautological_compare)
6920 	warn_tautological_cmp (loc, code, arg1, arg2);
6921       /* Fall through.  */
6922     case SPACESHIP_EXPR:
6923     case PLUS_EXPR:
6924     case MINUS_EXPR:
6925     case MULT_EXPR:
6926     case TRUNC_DIV_EXPR:
6927     case MAX_EXPR:
6928     case MIN_EXPR:
6929     case LSHIFT_EXPR:
6930     case RSHIFT_EXPR:
6931     case TRUNC_MOD_EXPR:
6932     case BIT_AND_EXPR:
6933     case BIT_IOR_EXPR:
6934     case BIT_XOR_EXPR:
6935       return cp_build_binary_op (loc, code, arg1, arg2, complain);
6936 
6937     case UNARY_PLUS_EXPR:
6938     case NEGATE_EXPR:
6939     case BIT_NOT_EXPR:
6940     case TRUTH_NOT_EXPR:
6941     case PREINCREMENT_EXPR:
6942     case POSTINCREMENT_EXPR:
6943     case PREDECREMENT_EXPR:
6944     case POSTDECREMENT_EXPR:
6945     case REALPART_EXPR:
6946     case IMAGPART_EXPR:
6947     case ABS_EXPR:
6948     case CO_AWAIT_EXPR:
6949       return cp_build_unary_op (code, arg1, false, complain);
6950 
6951     case ARRAY_REF:
6952       return cp_build_array_ref (input_location, arg1, arg2, complain);
6953 
6954     case MEMBER_REF:
6955       return build_m_component_ref (cp_build_indirect_ref (loc, arg1,
6956 							   RO_ARROW_STAR,
6957                                                            complain),
6958                                     arg2, complain);
6959 
6960       /* The caller will deal with these.  */
6961     case ADDR_EXPR:
6962     case COMPONENT_REF:
6963     case COMPOUND_EXPR:
6964       return NULL_TREE;
6965 
6966     default:
6967       gcc_unreachable ();
6968     }
6969   return NULL_TREE;
6970 }
6971 
6972 /* Build a new call to operator[].  This may change ARGS.  */
6973 
6974 tree
build_op_subscript(const op_location_t & loc,tree obj,vec<tree,va_gc> ** args,tree * overload,tsubst_flags_t complain)6975 build_op_subscript (const op_location_t &loc, tree obj,
6976 		    vec<tree, va_gc> **args, tree *overload,
6977 		    tsubst_flags_t complain)
6978 {
6979   struct z_candidate *candidates = 0, *cand;
6980   tree fns, first_mem_arg = NULL_TREE;
6981   bool any_viable_p;
6982   tree result = NULL_TREE;
6983   void *p;
6984 
6985   auto_cond_timevar tv (TV_OVERLOAD);
6986 
6987   obj = mark_lvalue_use (obj);
6988 
6989   if (error_operand_p (obj))
6990     return error_mark_node;
6991 
6992   tree type = TREE_TYPE (obj);
6993 
6994   obj = prep_operand (obj);
6995 
6996   if (TYPE_BINFO (type))
6997     {
6998       fns = lookup_fnfields (TYPE_BINFO (type), ovl_op_identifier (ARRAY_REF),
6999 			     1, complain);
7000       if (fns == error_mark_node)
7001 	return error_mark_node;
7002     }
7003   else
7004     fns = NULL_TREE;
7005 
7006   if (args != NULL && *args != NULL)
7007     {
7008       *args = resolve_args (*args, complain);
7009       if (*args == NULL)
7010 	return error_mark_node;
7011     }
7012 
7013   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
7014   p = conversion_obstack_alloc (0);
7015 
7016   if (fns)
7017     {
7018       first_mem_arg = obj;
7019 
7020       add_candidates (BASELINK_FUNCTIONS (fns),
7021 		      first_mem_arg, *args, NULL_TREE,
7022 		      NULL_TREE, false,
7023 		      BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
7024 		      LOOKUP_NORMAL, &candidates, complain);
7025     }
7026 
7027   /* Be strict here because if we choose a bad conversion candidate, the
7028      errors we get won't mention the call context.  */
7029   candidates = splice_viable (candidates, true, &any_viable_p);
7030   if (!any_viable_p)
7031     {
7032       if (complain & tf_error)
7033 	{
7034 	  auto_diagnostic_group d;
7035 	  error ("no match for call to %<%T::operator[] (%A)%>",
7036 		 TREE_TYPE (obj), build_tree_list_vec (*args));
7037 	  print_z_candidates (loc, candidates);
7038 	}
7039       result = error_mark_node;
7040     }
7041   else
7042     {
7043       cand = tourney (candidates, complain);
7044       if (cand == 0)
7045 	{
7046 	  if (complain & tf_error)
7047 	    {
7048 	      auto_diagnostic_group d;
7049 	      error ("call of %<%T::operator[] (%A)%> is ambiguous",
7050 		     TREE_TYPE (obj), build_tree_list_vec (*args));
7051 	      print_z_candidates (loc, candidates);
7052 	    }
7053 	  result = error_mark_node;
7054 	}
7055       else if (TREE_CODE (cand->fn) == FUNCTION_DECL
7056 	       && DECL_OVERLOADED_OPERATOR_P (cand->fn)
7057 	       && DECL_OVERLOADED_OPERATOR_IS (cand->fn, ARRAY_REF))
7058 	{
7059 	  if (overload)
7060 	    *overload = cand->fn;
7061 	  result = build_over_call (cand, LOOKUP_NORMAL, complain);
7062 	  if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7063 	    /* There won't be a CALL_EXPR.  */;
7064 	  else if (result && result != error_mark_node)
7065 	    {
7066 	      tree call = extract_call_expr (result);
7067 	      CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7068 
7069 	      /* Specify evaluation order as per P0145R2.  */
7070 	      CALL_EXPR_ORDERED_ARGS (call) = op_is_ordered (ARRAY_REF) == 1;
7071 	    }
7072 	}
7073       else
7074 	gcc_unreachable ();
7075     }
7076 
7077   /* Free all the conversions we allocated.  */
7078   obstack_free (&conversion_obstack, p);
7079 
7080   return result;
7081 }
7082 
7083 /* CALL was returned by some call-building function; extract the actual
7084    CALL_EXPR from any bits that have been tacked on, e.g. by
7085    convert_from_reference.  */
7086 
7087 tree
extract_call_expr(tree call)7088 extract_call_expr (tree call)
7089 {
7090   while (TREE_CODE (call) == COMPOUND_EXPR)
7091     call = TREE_OPERAND (call, 1);
7092   if (REFERENCE_REF_P (call))
7093     call = TREE_OPERAND (call, 0);
7094   if (TREE_CODE (call) == TARGET_EXPR)
7095     call = TARGET_EXPR_INITIAL (call);
7096   if (cxx_dialect >= cxx20)
7097     switch (TREE_CODE (call))
7098       {
7099 	/* C++20 rewritten comparison operators.  */
7100       case TRUTH_NOT_EXPR:
7101 	call = TREE_OPERAND (call, 0);
7102 	break;
7103       case LT_EXPR:
7104       case LE_EXPR:
7105       case GT_EXPR:
7106       case GE_EXPR:
7107       case SPACESHIP_EXPR:
7108 	{
7109 	  tree op0 = TREE_OPERAND (call, 0);
7110 	  if (integer_zerop (op0))
7111 	    call = TREE_OPERAND (call, 1);
7112 	  else
7113 	    call = op0;
7114 	}
7115 	break;
7116       default:;
7117       }
7118 
7119   if (TREE_CODE (call) != CALL_EXPR
7120       && TREE_CODE (call) != AGGR_INIT_EXPR
7121       && call != error_mark_node)
7122     return NULL_TREE;
7123   return call;
7124 }
7125 
7126 /* Returns true if FN has two parameters, of which the second has type
7127    size_t.  */
7128 
7129 static bool
second_parm_is_size_t(tree fn)7130 second_parm_is_size_t (tree fn)
7131 {
7132   tree t = FUNCTION_ARG_CHAIN (fn);
7133   if (!t || !same_type_p (TREE_VALUE (t), size_type_node))
7134     return false;
7135   t = TREE_CHAIN (t);
7136   if (t == void_list_node)
7137     return true;
7138   return false;
7139 }
7140 
7141 /* True if T, an allocation function, has std::align_val_t as its second
7142    argument.  */
7143 
7144 bool
aligned_allocation_fn_p(tree t)7145 aligned_allocation_fn_p (tree t)
7146 {
7147   if (!aligned_new_threshold)
7148     return false;
7149 
7150   tree a = FUNCTION_ARG_CHAIN (t);
7151   return (a && same_type_p (TREE_VALUE (a), align_type_node));
7152 }
7153 
7154 /* True if T is std::destroying_delete_t.  */
7155 
7156 static bool
std_destroying_delete_t_p(tree t)7157 std_destroying_delete_t_p (tree t)
7158 {
7159   return (TYPE_CONTEXT (t) == std_node
7160 	  && id_equal (TYPE_IDENTIFIER (t), "destroying_delete_t"));
7161 }
7162 
7163 /* A deallocation function with at least two parameters whose second parameter
7164    type is of type std::destroying_delete_t is a destroying operator delete. A
7165    destroying operator delete shall be a class member function named operator
7166    delete. [ Note: Array deletion cannot use a destroying operator
7167    delete. --end note ] */
7168 
7169 tree
destroying_delete_p(tree t)7170 destroying_delete_p (tree t)
7171 {
7172   tree a = TYPE_ARG_TYPES (TREE_TYPE (t));
7173   if (!a || !TREE_CHAIN (a))
7174     return NULL_TREE;
7175   tree type = TREE_VALUE (TREE_CHAIN (a));
7176   return std_destroying_delete_t_p (type) ? type : NULL_TREE;
7177 }
7178 
7179 struct dealloc_info
7180 {
7181   bool sized;
7182   bool aligned;
7183   tree destroying;
7184 };
7185 
7186 /* Returns true iff T, an element of an OVERLOAD chain, is a usual deallocation
7187    function (3.7.4.2 [basic.stc.dynamic.deallocation]).  If so, and DI is
7188    non-null, also set *DI. */
7189 
7190 static bool
usual_deallocation_fn_p(tree t,dealloc_info * di)7191 usual_deallocation_fn_p (tree t, dealloc_info *di)
7192 {
7193   if (di) *di = dealloc_info();
7194 
7195   /* A template instance is never a usual deallocation function,
7196      regardless of its signature.  */
7197   if (TREE_CODE (t) == TEMPLATE_DECL
7198       || primary_template_specialization_p (t))
7199     return false;
7200 
7201   /* A usual deallocation function is a deallocation function whose parameters
7202      after the first are
7203      - optionally, a parameter of type std::destroying_delete_t, then
7204      - optionally, a parameter of type std::size_t, then
7205      - optionally, a parameter of type std::align_val_t.  */
7206   bool global = DECL_NAMESPACE_SCOPE_P (t);
7207   tree chain = FUNCTION_ARG_CHAIN (t);
7208   if (chain && destroying_delete_p (t))
7209     {
7210       if (di) di->destroying = TREE_VALUE (chain);
7211       chain = TREE_CHAIN (chain);
7212     }
7213   if (chain
7214       && (!global || flag_sized_deallocation)
7215       && same_type_p (TREE_VALUE (chain), size_type_node))
7216     {
7217       if (di) di->sized = true;
7218       chain = TREE_CHAIN (chain);
7219     }
7220   if (chain && aligned_new_threshold
7221       && same_type_p (TREE_VALUE (chain), align_type_node))
7222     {
7223       if (di) di->aligned = true;
7224       chain = TREE_CHAIN (chain);
7225     }
7226   return (chain == void_list_node);
7227 }
7228 
7229 /* Just return whether FN is a usual deallocation function.  */
7230 
7231 bool
usual_deallocation_fn_p(tree fn)7232 usual_deallocation_fn_p (tree fn)
7233 {
7234   return usual_deallocation_fn_p (fn, NULL);
7235 }
7236 
7237 /* Build a call to operator delete.  This has to be handled very specially,
7238    because the restrictions on what signatures match are different from all
7239    other call instances.  For a normal delete, only a delete taking (void *)
7240    or (void *, size_t) is accepted.  For a placement delete, only an exact
7241    match with the placement new is accepted.
7242 
7243    CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
7244    ADDR is the pointer to be deleted.
7245    SIZE is the size of the memory block to be deleted.
7246    GLOBAL_P is true if the delete-expression should not consider
7247    class-specific delete operators.
7248    PLACEMENT is the corresponding placement new call, or NULL_TREE.
7249 
7250    If this call to "operator delete" is being generated as part to
7251    deallocate memory allocated via a new-expression (as per [expr.new]
7252    which requires that if the initialization throws an exception then
7253    we call a deallocation function), then ALLOC_FN is the allocation
7254    function.  */
7255 
7256 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)7257 build_op_delete_call (enum tree_code code, tree addr, tree size,
7258 		      bool global_p, tree placement,
7259 		      tree alloc_fn, tsubst_flags_t complain)
7260 {
7261   tree fn = NULL_TREE;
7262   tree fns, fnname, type, t;
7263   dealloc_info di_fn = { };
7264 
7265   if (addr == error_mark_node)
7266     return error_mark_node;
7267 
7268   type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
7269 
7270   fnname = ovl_op_identifier (false, code);
7271 
7272   if (CLASS_TYPE_P (type)
7273       && COMPLETE_TYPE_P (complete_type (type))
7274       && !global_p)
7275     /* In [class.free]
7276 
7277        If the result of the lookup is ambiguous or inaccessible, or if
7278        the lookup selects a placement deallocation function, the
7279        program is ill-formed.
7280 
7281        Therefore, we ask lookup_fnfields to complain about ambiguity.  */
7282     {
7283       fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1, complain);
7284       if (fns == error_mark_node)
7285 	return error_mark_node;
7286     }
7287   else
7288     fns = NULL_TREE;
7289 
7290   if (fns == NULL_TREE)
7291     fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
7292 
7293   /* Strip const and volatile from addr.  */
7294   tree oaddr = addr;
7295   addr = cp_convert (ptr_type_node, addr, complain);
7296 
7297   tree excluded_destroying = NULL_TREE;
7298 
7299   if (placement)
7300     {
7301       /* "A declaration of a placement deallocation function matches the
7302 	 declaration of a placement allocation function if it has the same
7303 	 number of parameters and, after parameter transformations (8.3.5),
7304 	 all parameter types except the first are identical."
7305 
7306 	 So we build up the function type we want and ask instantiate_type
7307 	 to get it for us.  */
7308       t = FUNCTION_ARG_CHAIN (alloc_fn);
7309       t = tree_cons (NULL_TREE, ptr_type_node, t);
7310       t = build_function_type (void_type_node, t);
7311 
7312       fn = instantiate_type (t, fns, tf_none);
7313       if (fn == error_mark_node)
7314 	return NULL_TREE;
7315 
7316       fn = MAYBE_BASELINK_FUNCTIONS (fn);
7317 
7318       /* "If the lookup finds the two-parameter form of a usual deallocation
7319 	 function (3.7.4.2) and that function, considered as a placement
7320 	 deallocation function, would have been selected as a match for the
7321 	 allocation function, the program is ill-formed."  */
7322       if (second_parm_is_size_t (fn))
7323 	{
7324 	  const char *const msg1
7325 	    = G_("exception cleanup for this placement new selects "
7326 		 "non-placement %<operator delete%>");
7327 	  const char *const msg2
7328 	    = G_("%qD is a usual (non-placement) deallocation "
7329 		 "function in C++14 (or with %<-fsized-deallocation%>)");
7330 
7331 	  /* But if the class has an operator delete (void *), then that is
7332 	     the usual deallocation function, so we shouldn't complain
7333 	     about using the operator delete (void *, size_t).  */
7334 	  if (DECL_CLASS_SCOPE_P (fn))
7335 	    for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7336 	      {
7337 		if (usual_deallocation_fn_p (elt)
7338 		    && FUNCTION_ARG_CHAIN (elt) == void_list_node)
7339 		  goto ok;
7340 	      }
7341 	  /* Before C++14 a two-parameter global deallocation function is
7342 	     always a placement deallocation function, but warn if
7343 	     -Wc++14-compat.  */
7344 	  else if (!flag_sized_deallocation)
7345 	    {
7346 	      if (complain & tf_warning)
7347 		{
7348 		  auto_diagnostic_group d;
7349 		  if (warning (OPT_Wc__14_compat, msg1))
7350 		    inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7351 		}
7352 	      goto ok;
7353 	    }
7354 
7355 	  if (complain & tf_warning_or_error)
7356 	    {
7357 	      auto_diagnostic_group d;
7358 	      if (permerror (input_location, msg1))
7359 		{
7360 		  /* Only mention C++14 for namespace-scope delete.  */
7361 		  if (DECL_NAMESPACE_SCOPE_P (fn))
7362 		    inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7363 		  else
7364 		    inform (DECL_SOURCE_LOCATION (fn),
7365 			    "%qD is a usual (non-placement) deallocation "
7366 			    "function", fn);
7367 		}
7368 	    }
7369 	  else
7370 	    return error_mark_node;
7371 	ok:;
7372 	}
7373     }
7374   else
7375     /* "Any non-placement deallocation function matches a non-placement
7376        allocation function. If the lookup finds a single matching
7377        deallocation function, that function will be called; otherwise, no
7378        deallocation function will be called."  */
7379     for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7380       {
7381 	dealloc_info di_elt;
7382 	if (usual_deallocation_fn_p (elt, &di_elt))
7383 	  {
7384 	    /* If we're called for an EH cleanup in a new-expression, we can't
7385 	       use a destroying delete; the exception was thrown before the
7386 	       object was constructed.  */
7387 	    if (alloc_fn && di_elt.destroying)
7388 	      {
7389 		excluded_destroying = elt;
7390 		continue;
7391 	      }
7392 
7393 	    if (!fn)
7394 	      {
7395 		fn = elt;
7396 		di_fn = di_elt;
7397 		continue;
7398 	      }
7399 
7400 	    /* -- If any of the deallocation functions is a destroying
7401 	       operator delete, all deallocation functions that are not
7402 	       destroying operator deletes are eliminated from further
7403 	       consideration.  */
7404 	    if (di_elt.destroying != di_fn.destroying)
7405 	      {
7406 		if (di_elt.destroying)
7407 		  {
7408 		    fn = elt;
7409 		    di_fn = di_elt;
7410 		  }
7411 		continue;
7412 	      }
7413 
7414 	    /* -- If the type has new-extended alignment, a function with a
7415 	       parameter of type std::align_val_t is preferred; otherwise a
7416 	       function without such a parameter is preferred. If exactly one
7417 	       preferred function is found, that function is selected and the
7418 	       selection process terminates. If more than one preferred
7419 	       function is found, all non-preferred functions are eliminated
7420 	       from further consideration.  */
7421 	    if (aligned_new_threshold)
7422 	      {
7423 		bool want_align = type_has_new_extended_alignment (type);
7424 		if (di_elt.aligned != di_fn.aligned)
7425 		  {
7426 		    if (want_align == di_elt.aligned)
7427 		      {
7428 			fn = elt;
7429 			di_fn = di_elt;
7430 		      }
7431 		    continue;
7432 		  }
7433 	      }
7434 
7435 	    /* -- If the deallocation functions have class scope, the one
7436 	       without a parameter of type std::size_t is selected.  */
7437 	    bool want_size;
7438 	    if (DECL_CLASS_SCOPE_P (fn))
7439 	      want_size = false;
7440 
7441 	    /* -- If the type is complete and if, for the second alternative
7442 	       (delete array) only, the operand is a pointer to a class type
7443 	       with a non-trivial destructor or a (possibly multi-dimensional)
7444 	       array thereof, the function with a parameter of type std::size_t
7445 	       is selected.
7446 
7447 	       -- Otherwise, it is unspecified whether a deallocation function
7448 	       with a parameter of type std::size_t is selected.  */
7449 	    else
7450 	      {
7451 		want_size = COMPLETE_TYPE_P (type);
7452 		if (code == VEC_DELETE_EXPR
7453 		    && !TYPE_VEC_NEW_USES_COOKIE (type))
7454 		  /* We need a cookie to determine the array size.  */
7455 		  want_size = false;
7456 	      }
7457 	    gcc_assert (di_fn.sized != di_elt.sized);
7458 	    if (want_size == di_elt.sized)
7459 	      {
7460 		fn = elt;
7461 		di_fn = di_elt;
7462 	      }
7463 	  }
7464       }
7465 
7466   /* If we have a matching function, call it.  */
7467   if (fn)
7468     {
7469       gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
7470 
7471       /* If the FN is a member function, make sure that it is
7472 	 accessible.  */
7473       if (BASELINK_P (fns))
7474 	perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn,
7475 				       complain);
7476 
7477       /* Core issue 901: It's ok to new a type with deleted delete.  */
7478       if (DECL_DELETED_FN (fn) && alloc_fn)
7479 	return NULL_TREE;
7480 
7481       tree ret;
7482       if (placement)
7483 	{
7484 	  /* The placement args might not be suitable for overload
7485 	     resolution at this point, so build the call directly.  */
7486 	  int nargs = call_expr_nargs (placement);
7487 	  tree *argarray = XALLOCAVEC (tree, nargs);
7488 	  int i;
7489 	  argarray[0] = addr;
7490 	  for (i = 1; i < nargs; i++)
7491 	    argarray[i] = CALL_EXPR_ARG (placement, i);
7492 	  if (!mark_used (fn, complain) && !(complain & tf_error))
7493 	    return error_mark_node;
7494 	  ret = build_cxx_call (fn, nargs, argarray, complain);
7495 	}
7496       else
7497 	{
7498 	  tree destroying = di_fn.destroying;
7499 	  if (destroying)
7500 	    {
7501 	      /* Strip const and volatile from addr but retain the type of the
7502 		 object.  */
7503 	      tree rtype = TREE_TYPE (TREE_TYPE (oaddr));
7504 	      rtype = cv_unqualified (rtype);
7505 	      rtype = TYPE_POINTER_TO (rtype);
7506 	      addr = cp_convert (rtype, oaddr, complain);
7507 	      destroying = build_functional_cast (input_location,
7508 						  destroying, NULL_TREE,
7509 						  complain);
7510 	    }
7511 
7512 	  releasing_vec args;
7513 	  args->quick_push (addr);
7514 	  if (destroying)
7515 	    args->quick_push (destroying);
7516 	  if (di_fn.sized)
7517 	    args->quick_push (size);
7518 	  if (di_fn.aligned)
7519 	    {
7520 	      tree al = build_int_cst (align_type_node, TYPE_ALIGN_UNIT (type));
7521 	      args->quick_push (al);
7522 	    }
7523 	  ret = cp_build_function_call_vec (fn, &args, complain);
7524 	}
7525 
7526       /* Set this flag for all callers of this function.  In addition to
7527 	 delete-expressions, this is called for deallocating coroutine state;
7528 	 treat that as an implicit delete-expression.  This is also called for
7529 	 the delete if the constructor throws in a new-expression, and for a
7530 	 deleting destructor (which implements a delete-expression).  */
7531       /* But leave this flag off for destroying delete to avoid wrong
7532 	 assumptions in the optimizers.  */
7533       tree call = extract_call_expr (ret);
7534       if (TREE_CODE (call) == CALL_EXPR && !destroying_delete_p (fn))
7535 	CALL_FROM_NEW_OR_DELETE_P (call) = 1;
7536 
7537       return ret;
7538     }
7539 
7540   /* If there's only a destroying delete that we can't use because the
7541      object isn't constructed yet, and we used global new, use global
7542      delete as well.  */
7543   if (excluded_destroying
7544       && DECL_NAMESPACE_SCOPE_P (alloc_fn))
7545     return build_op_delete_call (code, addr, size, true, placement,
7546 				 alloc_fn, complain);
7547 
7548   /* [expr.new]
7549 
7550      If no unambiguous matching deallocation function can be found,
7551      propagating the exception does not cause the object's memory to
7552      be freed.  */
7553   if (alloc_fn)
7554     {
7555       if ((complain & tf_warning)
7556 	  && !placement)
7557 	{
7558 	  bool w = warning (0,
7559 			    "no corresponding deallocation function for %qD",
7560 			    alloc_fn);
7561 	  if (w && excluded_destroying)
7562 	    inform (DECL_SOURCE_LOCATION (excluded_destroying), "destroying "
7563 		    "delete %qD cannot be used to release the allocated memory"
7564 		    " if the initialization throws because the object is not "
7565 		    "constructed yet", excluded_destroying);
7566 	}
7567       return NULL_TREE;
7568     }
7569 
7570   if (complain & tf_error)
7571     error ("no suitable %<operator %s%> for %qT",
7572 	   OVL_OP_INFO (false, code)->name, type);
7573   return error_mark_node;
7574 }
7575 
7576 /* Issue diagnostics about a disallowed access of DECL, using DIAG_DECL
7577    in the diagnostics.
7578 
7579    If ISSUE_ERROR is true, then issue an error about the access, followed
7580    by a note showing the declaration.  Otherwise, just show the note.
7581 
7582    DIAG_DECL and DIAG_LOCATION will almost always be the same.
7583    DIAG_LOCATION is just another DECL.  NO_ACCESS_REASON is an optional
7584    parameter used to specify why DECL wasn't accessible (e.g. ak_private
7585    would be because DECL was private).  If not using NO_ACCESS_REASON,
7586    then it must be ak_none, and the access failure reason will be
7587    figured out by looking at the protection of DECL.  */
7588 
7589 void
complain_about_access(tree decl,tree diag_decl,tree diag_location,bool issue_error,access_kind no_access_reason)7590 complain_about_access (tree decl, tree diag_decl, tree diag_location,
7591 		       bool issue_error, access_kind no_access_reason)
7592 {
7593   /* If we have not already figured out why DECL is inaccessible...  */
7594   if (no_access_reason == ak_none)
7595     {
7596       /* Examine the access of DECL to find out why.  */
7597       if (TREE_PRIVATE (decl))
7598 	no_access_reason = ak_private;
7599       else if (TREE_PROTECTED (decl))
7600 	no_access_reason = ak_protected;
7601     }
7602 
7603   /* Now generate an error message depending on calculated access.  */
7604   if (no_access_reason == ak_private)
7605     {
7606       if (issue_error)
7607 	error ("%q#D is private within this context", diag_decl);
7608       inform (DECL_SOURCE_LOCATION (diag_location), "declared private here");
7609     }
7610   else if (no_access_reason == ak_protected)
7611     {
7612       if (issue_error)
7613 	error ("%q#D is protected within this context", diag_decl);
7614       inform (DECL_SOURCE_LOCATION (diag_location), "declared protected here");
7615     }
7616   /* Couldn't figure out why DECL is inaccesible, so just say it's
7617      inaccessible.  */
7618   else
7619     {
7620       if (issue_error)
7621 	error ("%q#D is inaccessible within this context", diag_decl);
7622       inform (DECL_SOURCE_LOCATION (diag_decl), "declared here");
7623     }
7624 }
7625 
7626 /* Initialize a temporary of type TYPE with EXPR.  The FLAGS are a
7627    bitwise or of LOOKUP_* values.  If any errors are warnings are
7628    generated, set *DIAGNOSTIC_FN to "error" or "warning",
7629    respectively.  If no diagnostics are generated, set *DIAGNOSTIC_FN
7630    to NULL.  */
7631 
7632 static tree
build_temp(tree expr,tree type,int flags,diagnostic_t * diagnostic_kind,tsubst_flags_t complain)7633 build_temp (tree expr, tree type, int flags,
7634 	    diagnostic_t *diagnostic_kind, tsubst_flags_t complain)
7635 {
7636   int savew, savee;
7637 
7638   *diagnostic_kind = DK_UNSPECIFIED;
7639 
7640   /* If the source is a packed field, calling the copy constructor will require
7641      binding the field to the reference parameter to the copy constructor, and
7642      we'll end up with an infinite loop.  If we can use a bitwise copy, then
7643      do that now.  */
7644   if ((lvalue_kind (expr) & clk_packed)
7645       && CLASS_TYPE_P (TREE_TYPE (expr))
7646       && !type_has_nontrivial_copy_init (TREE_TYPE (expr)))
7647     return get_target_expr_sfinae (expr, complain);
7648 
7649   /* In decltype, we might have decided not to wrap this call in a TARGET_EXPR.
7650      But it turns out to be a subexpression, so perform temporary
7651      materialization now.  */
7652   if (TREE_CODE (expr) == CALL_EXPR
7653       && CLASS_TYPE_P (type)
7654       && same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7655     expr = build_cplus_new (type, expr, complain);
7656 
7657   savew = warningcount + werrorcount, savee = errorcount;
7658   releasing_vec args (make_tree_vector_single (expr));
7659   expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
7660 				    &args, type, flags, complain);
7661   if (warningcount + werrorcount > savew)
7662     *diagnostic_kind = DK_WARNING;
7663   else if (errorcount > savee)
7664     *diagnostic_kind = DK_ERROR;
7665   return expr;
7666 }
7667 
7668 /* Get any location for EXPR, falling back to input_location.
7669 
7670    If the result is in a system header and is the virtual location for
7671    a token coming from the expansion of a macro, unwind it to the
7672    location of the expansion point of the macro (e.g. to avoid the
7673    diagnostic being suppressed for expansions of NULL where "NULL" is
7674    in a system header).  */
7675 
7676 static location_t
get_location_for_expr_unwinding_for_system_header(tree expr)7677 get_location_for_expr_unwinding_for_system_header (tree expr)
7678 {
7679   location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
7680   loc = expansion_point_location_if_in_system_header (loc);
7681   return loc;
7682 }
7683 
7684 /* Perform warnings about peculiar, but valid, conversions from/to NULL.
7685    Also handle a subset of zero as null warnings.
7686    EXPR is implicitly converted to type TOTYPE.
7687    FN and ARGNUM are used for diagnostics.  */
7688 
7689 static void
conversion_null_warnings(tree totype,tree expr,tree fn,int argnum)7690 conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
7691 {
7692   /* Issue warnings about peculiar, but valid, uses of NULL.  */
7693   if (TREE_CODE (totype) != BOOLEAN_TYPE
7694       && ARITHMETIC_TYPE_P (totype)
7695       && null_node_p (expr))
7696     {
7697       location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
7698       if (fn)
7699 	{
7700 	  auto_diagnostic_group d;
7701 	  if (warning_at (loc, OPT_Wconversion_null,
7702 			  "passing NULL to non-pointer argument %P of %qD",
7703 			  argnum, fn))
7704 	    inform (get_fndecl_argument_location (fn, argnum),
7705 		    "  declared here");
7706 	}
7707       else
7708 	warning_at (loc, OPT_Wconversion_null,
7709 		    "converting to non-pointer type %qT from NULL", totype);
7710     }
7711 
7712   /* Issue warnings if "false" is converted to a NULL pointer */
7713   else if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
7714 	   && TYPE_PTR_P (totype))
7715     {
7716       location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
7717       if (fn)
7718 	{
7719 	  auto_diagnostic_group d;
7720 	  if (warning_at (loc, OPT_Wconversion_null,
7721 			  "converting %<false%> to pointer type for argument "
7722 			  "%P of %qD", argnum, fn))
7723 	    inform (get_fndecl_argument_location (fn, argnum),
7724 		    "  declared here");
7725 	}
7726       else
7727 	warning_at (loc, OPT_Wconversion_null,
7728 		    "converting %<false%> to pointer type %qT", totype);
7729     }
7730   /* Handle zero as null pointer warnings for cases other
7731      than EQ_EXPR and NE_EXPR */
7732   else if ((TYPE_PTR_OR_PTRMEM_P (totype) || NULLPTR_TYPE_P (totype))
7733 	   && null_ptr_cst_p (expr))
7734     {
7735       location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
7736       maybe_warn_zero_as_null_pointer_constant (expr, loc);
7737     }
7738 }
7739 
7740 /* We gave a diagnostic during a conversion.  If this was in the second
7741    standard conversion sequence of a user-defined conversion sequence, say
7742    which user-defined conversion.  */
7743 
7744 static void
maybe_print_user_conv_context(conversion * convs)7745 maybe_print_user_conv_context (conversion *convs)
7746 {
7747   if (convs->user_conv_p)
7748     for (conversion *t = convs; t; t = next_conversion (t))
7749       if (t->kind == ck_user)
7750 	{
7751 	  print_z_candidate (0, N_("  after user-defined conversion:"),
7752 			     t->cand);
7753 	  break;
7754 	}
7755 }
7756 
7757 /* Locate the parameter with the given index within FNDECL.
7758    ARGNUM is zero based, -1 indicates the `this' argument of a method.
7759    Return the location of the FNDECL itself if there are problems.  */
7760 
7761 location_t
get_fndecl_argument_location(tree fndecl,int argnum)7762 get_fndecl_argument_location (tree fndecl, int argnum)
7763 {
7764   /* The locations of implicitly-declared functions are likely to be
7765      more meaningful than those of their parameters.  */
7766   if (DECL_ARTIFICIAL (fndecl))
7767     return DECL_SOURCE_LOCATION (fndecl);
7768 
7769   int i;
7770   tree param;
7771 
7772   /* Locate param by index within DECL_ARGUMENTS (fndecl).  */
7773   for (i = 0, param = FUNCTION_FIRST_USER_PARM (fndecl);
7774        i < argnum && param;
7775        i++, param = TREE_CHAIN (param))
7776     ;
7777 
7778   /* If something went wrong (e.g. if we have a builtin and thus no arguments),
7779      return the location of FNDECL.  */
7780   if (param == NULL)
7781     return DECL_SOURCE_LOCATION (fndecl);
7782 
7783   return DECL_SOURCE_LOCATION (param);
7784 }
7785 
7786 /* If FNDECL is non-NULL, issue a note highlighting ARGNUM
7787    within its declaration (or the fndecl itself if something went
7788    wrong).  */
7789 
7790 void
maybe_inform_about_fndecl_for_bogus_argument_init(tree fn,int argnum)7791 maybe_inform_about_fndecl_for_bogus_argument_init (tree fn, int argnum)
7792 {
7793   if (fn)
7794     inform (get_fndecl_argument_location (fn, argnum),
7795 	    "  initializing argument %P of %qD", argnum, fn);
7796 }
7797 
7798 /* Maybe warn about C++20 Conversions to arrays of unknown bound.  C is
7799    the conversion, EXPR is the expression we're converting.  */
7800 
7801 static void
maybe_warn_array_conv(location_t loc,conversion * c,tree expr)7802 maybe_warn_array_conv (location_t loc, conversion *c, tree expr)
7803 {
7804   if (cxx_dialect >= cxx20)
7805     return;
7806 
7807   tree type = TREE_TYPE (expr);
7808   type = strip_pointer_operator (type);
7809 
7810   if (TREE_CODE (type) != ARRAY_TYPE
7811       || TYPE_DOMAIN (type) == NULL_TREE)
7812     return;
7813 
7814   if (pedantic && conv_binds_to_array_of_unknown_bound (c))
7815     pedwarn (loc, OPT_Wc__20_extensions,
7816 	     "conversions to arrays of unknown bound "
7817 	     "are only available with %<-std=c++20%> or %<-std=gnu++20%>");
7818 }
7819 
7820 /* We call this recursively in convert_like_internal.  */
7821 static tree convert_like (conversion *, tree, tree, int, bool, bool,
7822 			  tsubst_flags_t);
7823 
7824 /* Perform the conversions in CONVS on the expression EXPR.  FN and
7825    ARGNUM are used for diagnostics.  ARGNUM is zero based, -1
7826    indicates the `this' argument of a method.  INNER is nonzero when
7827    being called to continue a conversion chain. It is negative when a
7828    reference binding will be applied, positive otherwise.  If
7829    ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
7830    conversions will be emitted if appropriate.  If C_CAST_P is true,
7831    this conversion is coming from a C-style cast; in that case,
7832    conversions to inaccessible bases are permitted.  */
7833 
7834 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)7835 convert_like_internal (conversion *convs, tree expr, tree fn, int argnum,
7836 		       bool issue_conversion_warnings, bool c_cast_p,
7837 		       tsubst_flags_t complain)
7838 {
7839   tree totype = convs->type;
7840   diagnostic_t diag_kind;
7841   int flags;
7842   location_t loc = cp_expr_loc_or_input_loc (expr);
7843 
7844   if (convs->bad_p && !(complain & tf_error))
7845     return error_mark_node;
7846 
7847   if (convs->bad_p
7848       && convs->kind != ck_user
7849       && convs->kind != ck_list
7850       && convs->kind != ck_ambig
7851       && (convs->kind != ck_ref_bind
7852 	  || (convs->user_conv_p && next_conversion (convs)->bad_p))
7853       && (convs->kind != ck_rvalue
7854 	  || SCALAR_TYPE_P (totype))
7855       && convs->kind != ck_base)
7856     {
7857       bool complained = false;
7858       conversion *t = convs;
7859 
7860       /* Give a helpful error if this is bad because of excess braces.  */
7861       if (BRACE_ENCLOSED_INITIALIZER_P (expr)
7862 	  && SCALAR_TYPE_P (totype)
7863 	  && CONSTRUCTOR_NELTS (expr) > 0
7864 	  && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
7865 	{
7866 	  complained = permerror (loc, "too many braces around initializer "
7867 				  "for %qT", totype);
7868 	  while (BRACE_ENCLOSED_INITIALIZER_P (expr)
7869 		 && CONSTRUCTOR_NELTS (expr) == 1)
7870 	    expr = CONSTRUCTOR_ELT (expr, 0)->value;
7871 	}
7872 
7873       /* Give a helpful error if this is bad because a conversion to bool
7874 	 from std::nullptr_t requires direct-initialization.  */
7875       if (NULLPTR_TYPE_P (TREE_TYPE (expr))
7876 	  && TREE_CODE (totype) == BOOLEAN_TYPE)
7877 	complained = permerror (loc, "converting to %qH from %qI requires "
7878 				"direct-initialization",
7879 				totype, TREE_TYPE (expr));
7880 
7881       for (; t ; t = next_conversion (t))
7882 	{
7883 	  if (t->kind == ck_user && t->cand->reason)
7884 	    {
7885 	      auto_diagnostic_group d;
7886 	      complained = permerror (loc, "invalid user-defined conversion "
7887 				      "from %qH to %qI", TREE_TYPE (expr),
7888 				      totype);
7889 	      if (complained)
7890 		print_z_candidate (loc, N_("candidate is:"), t->cand);
7891 	      expr = convert_like (t, expr, fn, argnum,
7892 				   /*issue_conversion_warnings=*/false,
7893 				   /*c_cast_p=*/false, complain);
7894 	      if (convs->kind == ck_ref_bind)
7895 		expr = convert_to_reference (totype, expr, CONV_IMPLICIT,
7896 					     LOOKUP_NORMAL, NULL_TREE,
7897 					     complain);
7898 	      else
7899 		expr = cp_convert (totype, expr, complain);
7900 	      if (complained)
7901 		maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
7902 	      return expr;
7903 	    }
7904 	  else if (t->kind == ck_user || !t->bad_p)
7905 	    {
7906 	      expr = convert_like (t, expr, fn, argnum,
7907 				   /*issue_conversion_warnings=*/false,
7908 				   /*c_cast_p=*/false, complain);
7909 	      break;
7910 	    }
7911 	  else if (t->kind == ck_ambig)
7912 	    return convert_like (t, expr, fn, argnum,
7913 				 /*issue_conversion_warnings=*/false,
7914 				 /*c_cast_p=*/false, complain);
7915 	  else if (t->kind == ck_identity)
7916 	    break;
7917 	}
7918       if (!complained && expr != error_mark_node)
7919 	{
7920 	  range_label_for_type_mismatch label (TREE_TYPE (expr), totype);
7921 	  gcc_rich_location richloc (loc, &label);
7922 	  complained = permerror (&richloc,
7923 				  "invalid conversion from %qH to %qI",
7924 				  TREE_TYPE (expr), totype);
7925 	}
7926       if (complained)
7927 	maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
7928 
7929       return cp_convert (totype, expr, complain);
7930     }
7931 
7932   if (issue_conversion_warnings && (complain & tf_warning))
7933     conversion_null_warnings (totype, expr, fn, argnum);
7934 
7935   switch (convs->kind)
7936     {
7937     case ck_user:
7938       {
7939 	struct z_candidate *cand = convs->cand;
7940 
7941 	if (cand == NULL)
7942 	  /* We chose the surrogate function from add_conv_candidate, now we
7943 	     actually need to build the conversion.  */
7944 	  cand = build_user_type_conversion_1 (totype, expr,
7945 					       LOOKUP_NO_CONVERSION, complain);
7946 
7947 	tree convfn = cand->fn;
7948 
7949 	/* When converting from an init list we consider explicit
7950 	   constructors, but actually trying to call one is an error.  */
7951 	if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn)
7952 	    && BRACE_ENCLOSED_INITIALIZER_P (expr)
7953 	    /* Unless this is for direct-list-initialization.  */
7954 	    && (!CONSTRUCTOR_IS_DIRECT_INIT (expr) || convs->need_temporary_p)
7955 	    /* And in C++98 a default constructor can't be explicit.  */
7956 	    && cxx_dialect >= cxx11)
7957 	  {
7958 	    if (!(complain & tf_error))
7959 	      return error_mark_node;
7960 	    location_t loc = location_of (expr);
7961 	    if (CONSTRUCTOR_NELTS (expr) == 0
7962 		&& FUNCTION_FIRST_USER_PARMTYPE (convfn) != void_list_node)
7963 	      {
7964 		auto_diagnostic_group d;
7965 		if (pedwarn (loc, 0, "converting to %qT from initializer list "
7966 			     "would use explicit constructor %qD",
7967 			     totype, convfn))
7968 		  inform (loc, "in C++11 and above a default constructor "
7969 			  "can be explicit");
7970 	      }
7971 	    else
7972 	      error ("converting to %qT from initializer list would use "
7973 		     "explicit constructor %qD", totype, convfn);
7974 	  }
7975 
7976 	/* If we're initializing from {}, it's value-initialization.  */
7977 	if (BRACE_ENCLOSED_INITIALIZER_P (expr)
7978 	    && CONSTRUCTOR_NELTS (expr) == 0
7979 	    && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype)
7980 	    && !processing_template_decl)
7981 	  {
7982 	    bool direct = CONSTRUCTOR_IS_DIRECT_INIT (expr);
7983 	    if (abstract_virtuals_error_sfinae (NULL_TREE, totype, complain))
7984 	      return error_mark_node;
7985 	    expr = build_value_init (totype, complain);
7986 	    expr = get_target_expr_sfinae (expr, complain);
7987 	    if (expr != error_mark_node)
7988 	      {
7989 		TARGET_EXPR_LIST_INIT_P (expr) = true;
7990 		TARGET_EXPR_DIRECT_INIT_P (expr) = direct;
7991 	      }
7992 	    return expr;
7993 	  }
7994 
7995 	/* We don't know here whether EXPR is being used as an lvalue or
7996 	   rvalue, but we know it's read.  */
7997 	mark_exp_read (expr);
7998 
7999 	/* Pass LOOKUP_NO_CONVERSION so rvalue/base handling knows not to allow
8000 	   any more UDCs.  */
8001 	expr = build_over_call (cand, LOOKUP_NORMAL|LOOKUP_NO_CONVERSION,
8002 				complain);
8003 
8004 	/* If this is a constructor or a function returning an aggr type,
8005 	   we need to build up a TARGET_EXPR.  */
8006 	if (DECL_CONSTRUCTOR_P (convfn))
8007 	  {
8008 	    expr = build_cplus_new (totype, expr, complain);
8009 
8010 	    /* Remember that this was list-initialization.  */
8011 	    if (convs->check_narrowing && expr != error_mark_node)
8012 	      TARGET_EXPR_LIST_INIT_P (expr) = true;
8013 	  }
8014 
8015 	return expr;
8016       }
8017     case ck_identity:
8018       if (BRACE_ENCLOSED_INITIALIZER_P (expr))
8019 	{
8020 	  int nelts = CONSTRUCTOR_NELTS (expr);
8021 	  if (nelts == 0)
8022 	    expr = build_value_init (totype, complain);
8023 	  else if (nelts == 1)
8024 	    expr = CONSTRUCTOR_ELT (expr, 0)->value;
8025 	  else
8026 	    gcc_unreachable ();
8027 	}
8028       expr = mark_use (expr, /*rvalue_p=*/!convs->rvaluedness_matches_p,
8029 		       /*read_p=*/true, UNKNOWN_LOCATION,
8030 		       /*reject_builtin=*/true);
8031 
8032       if (type_unknown_p (expr))
8033 	expr = instantiate_type (totype, expr, complain);
8034       if (expr == null_node
8035 	  && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
8036 	/* If __null has been converted to an integer type, we do not want to
8037 	   continue to warn about uses of EXPR as an integer, rather than as a
8038 	   pointer.  */
8039 	expr = build_int_cst (totype, 0);
8040       return expr;
8041     case ck_ambig:
8042       /* We leave bad_p off ck_ambig because overload resolution considers
8043 	 it valid, it just fails when we try to perform it.  So we need to
8044          check complain here, too.  */
8045       if (complain & tf_error)
8046 	{
8047 	  /* Call build_user_type_conversion again for the error.  */
8048 	  int flags = (convs->need_temporary_p
8049 		       ? LOOKUP_IMPLICIT : LOOKUP_NORMAL);
8050 	  build_user_type_conversion (totype, convs->u.expr, flags, complain);
8051 	  gcc_assert (seen_error ());
8052 	  maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8053 	}
8054       return error_mark_node;
8055 
8056     case ck_list:
8057       {
8058 	/* Conversion to std::initializer_list<T>.  */
8059 	tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
8060 	unsigned len = CONSTRUCTOR_NELTS (expr);
8061 	tree array;
8062 
8063 	if (len)
8064 	  {
8065 	    tree val; unsigned ix;
8066 
8067 	    tree new_ctor = build_constructor (init_list_type_node, NULL);
8068 
8069 	    /* Convert all the elements.  */
8070 	    FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
8071 	      {
8072 		tree sub = convert_like (convs->u.list[ix], val, fn,
8073 					 argnum, false, false, complain);
8074 		if (sub == error_mark_node)
8075 		  return sub;
8076 		if (!BRACE_ENCLOSED_INITIALIZER_P (val)
8077 		    && !check_narrowing (TREE_TYPE (sub), val, complain))
8078 		  return error_mark_node;
8079 		CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor),
8080 					NULL_TREE, sub);
8081 		if (!TREE_CONSTANT (sub))
8082 		  TREE_CONSTANT (new_ctor) = false;
8083 	      }
8084 	    /* Build up the array.  */
8085 	    elttype = cp_build_qualified_type
8086 	      (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
8087 	    array = build_array_of_n_type (elttype, len);
8088 	    array = finish_compound_literal (array, new_ctor, complain);
8089 	    /* Take the address explicitly rather than via decay_conversion
8090 	       to avoid the error about taking the address of a temporary.  */
8091 	    array = cp_build_addr_expr (array, complain);
8092 	  }
8093 	else
8094 	  array = nullptr_node;
8095 
8096 	array = cp_convert (build_pointer_type (elttype), array, complain);
8097 	if (array == error_mark_node)
8098 	  return error_mark_node;
8099 
8100 	/* Build up the initializer_list object.  Note: fail gracefully
8101 	   if the object cannot be completed because, for example, no
8102 	   definition is provided (c++/80956).  */
8103 	totype = complete_type_or_maybe_complain (totype, NULL_TREE, complain);
8104 	if (!totype)
8105 	  return error_mark_node;
8106 	tree field = next_initializable_field (TYPE_FIELDS (totype));
8107 	vec<constructor_elt, va_gc> *vec = NULL;
8108 	CONSTRUCTOR_APPEND_ELT (vec, field, array);
8109 	field = next_initializable_field (DECL_CHAIN (field));
8110 	CONSTRUCTOR_APPEND_ELT (vec, field, size_int (len));
8111 	tree new_ctor = build_constructor (totype, vec);
8112 	return get_target_expr_sfinae (new_ctor, complain);
8113       }
8114 
8115     case ck_aggr:
8116       if (TREE_CODE (totype) == COMPLEX_TYPE)
8117 	{
8118 	  tree real = CONSTRUCTOR_ELT (expr, 0)->value;
8119 	  tree imag = CONSTRUCTOR_ELT (expr, 1)->value;
8120 	  real = perform_implicit_conversion (TREE_TYPE (totype),
8121 					      real, complain);
8122 	  imag = perform_implicit_conversion (TREE_TYPE (totype),
8123 					      imag, complain);
8124 	  expr = build2 (COMPLEX_EXPR, totype, real, imag);
8125 	  return expr;
8126 	}
8127       expr = reshape_init (totype, expr, complain);
8128       expr = get_target_expr_sfinae (digest_init (totype, expr, complain),
8129 				     complain);
8130       if (expr != error_mark_node)
8131 	TARGET_EXPR_LIST_INIT_P (expr) = true;
8132       return expr;
8133 
8134     default:
8135       break;
8136     };
8137 
8138   conversion *nc = next_conversion (convs);
8139   if (convs->kind == ck_ref_bind && nc->kind == ck_qual
8140       && !convs->need_temporary_p)
8141     /* direct_reference_binding might have inserted a ck_qual under
8142        this ck_ref_bind for the benefit of conversion sequence ranking.
8143        Don't actually perform that conversion.  */
8144     nc = next_conversion (nc);
8145 
8146   expr = convert_like (nc, expr, fn, argnum,
8147 		       convs->kind == ck_ref_bind
8148 		       ? issue_conversion_warnings : false,
8149 		       c_cast_p, complain & ~tf_no_cleanup);
8150   if (expr == error_mark_node)
8151     return error_mark_node;
8152 
8153   switch (convs->kind)
8154     {
8155     case ck_rvalue:
8156       expr = decay_conversion (expr, complain);
8157       if (expr == error_mark_node)
8158 	{
8159 	  if (complain & tf_error)
8160 	    {
8161 	      auto_diagnostic_group d;
8162 	      maybe_print_user_conv_context (convs);
8163 	      maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8164 	    }
8165 	  return error_mark_node;
8166 	}
8167 
8168       if (! MAYBE_CLASS_TYPE_P (totype))
8169 	return expr;
8170 
8171       /* Don't introduce copies when passing arguments along to the inherited
8172 	 constructor.  */
8173       if (current_function_decl
8174 	  && flag_new_inheriting_ctors
8175 	  && DECL_INHERITED_CTOR (current_function_decl))
8176 	return expr;
8177 
8178       if (TREE_CODE (expr) == TARGET_EXPR
8179 	  && TARGET_EXPR_LIST_INIT_P (expr))
8180 	/* Copy-list-initialization doesn't actually involve a copy.  */
8181 	return expr;
8182 
8183       /* Fall through.  */
8184     case ck_base:
8185       if (convs->kind == ck_base && !convs->need_temporary_p)
8186 	{
8187 	  /* We are going to bind a reference directly to a base-class
8188 	     subobject of EXPR.  */
8189 	  /* Build an expression for `*((base*) &expr)'.  */
8190 	  expr = convert_to_base (expr, totype,
8191 				  !c_cast_p, /*nonnull=*/true, complain);
8192 	  return expr;
8193 	}
8194 
8195       /* Copy-initialization where the cv-unqualified version of the source
8196 	 type is the same class as, or a derived class of, the class of the
8197 	 destination [is treated as direct-initialization].  [dcl.init] */
8198       flags = LOOKUP_NORMAL;
8199       /* This conversion is being done in the context of a user-defined
8200 	 conversion (i.e. the second step of copy-initialization), so
8201 	 don't allow any more.  */
8202       if (convs->user_conv_p)
8203 	flags |= LOOKUP_NO_CONVERSION;
8204       /* We might be performing a conversion of the argument
8205 	 to the user-defined conversion, i.e., not a conversion of the
8206 	 result of the user-defined conversion.  In which case we skip
8207 	 explicit constructors.  */
8208       if (convs->copy_init_p)
8209 	flags |= LOOKUP_ONLYCONVERTING;
8210       if (convs->rvaluedness_matches_p)
8211 	/* standard_conversion got LOOKUP_PREFER_RVALUE.  */
8212 	flags |= LOOKUP_PREFER_RVALUE;
8213       expr = build_temp (expr, totype, flags, &diag_kind, complain);
8214       if (diag_kind && complain)
8215 	{
8216 	  auto_diagnostic_group d;
8217 	  maybe_print_user_conv_context (convs);
8218 	  maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8219 	}
8220 
8221       return build_cplus_new (totype, expr, complain);
8222 
8223     case ck_ref_bind:
8224       {
8225 	tree ref_type = totype;
8226 
8227 	if (convs->bad_p && !next_conversion (convs)->bad_p)
8228 	  {
8229 	    tree extype = TREE_TYPE (expr);
8230 	    auto_diagnostic_group d;
8231 	    if (TYPE_REF_IS_RVALUE (ref_type)
8232 		&& lvalue_p (expr))
8233 	      error_at (loc, "cannot bind rvalue reference of type %qH to "
8234                         "lvalue of type %qI", totype, extype);
8235 	    else if (!TYPE_REF_IS_RVALUE (ref_type) && !lvalue_p (expr)
8236 		     && !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (ref_type)))
8237 	      {
8238 		conversion *next = next_conversion (convs);
8239 		if (next->kind == ck_std)
8240 		  {
8241 		    next = next_conversion (next);
8242 		    error_at (loc, "cannot bind non-const lvalue reference of "
8243 			      "type %qH to a value of type %qI",
8244 			      totype, next->type);
8245 		  }
8246 		else if (!CP_TYPE_CONST_P (TREE_TYPE (ref_type)))
8247 		  error_at (loc, "cannot bind non-const lvalue reference of "
8248 			    "type %qH to an rvalue of type %qI", totype, extype);
8249 		else // extype is volatile
8250 		  error_at (loc, "cannot bind lvalue reference of type "
8251 			    "%qH to an rvalue of type %qI", totype,
8252 			    extype);
8253 	      }
8254 	    else if (!reference_compatible_p (TREE_TYPE (totype), extype))
8255 	      {
8256 		/* If we're converting from T[] to T[N], don't talk
8257 		   about discarding qualifiers.  (Converting from T[N] to
8258 		   T[] is allowed by P0388R4.)  */
8259 		if (TREE_CODE (extype) == ARRAY_TYPE
8260 		    && TYPE_DOMAIN (extype) == NULL_TREE
8261 		    && TREE_CODE (TREE_TYPE (totype)) == ARRAY_TYPE
8262 		    && TYPE_DOMAIN (TREE_TYPE (totype)) != NULL_TREE)
8263 		  error_at (loc, "cannot bind reference of type %qH to %qI "
8264 			    "due to different array bounds", totype, extype);
8265 		else
8266 		  error_at (loc, "binding reference of type %qH to %qI "
8267 			    "discards qualifiers", totype, extype);
8268 	      }
8269 	    else
8270 	      gcc_unreachable ();
8271 	    maybe_print_user_conv_context (convs);
8272 	    maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8273 
8274 	    return error_mark_node;
8275 	  }
8276 	else if (complain & tf_warning)
8277 	  maybe_warn_array_conv (loc, convs, expr);
8278 
8279 	/* If necessary, create a temporary.
8280 
8281            VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
8282            that need temporaries, even when their types are reference
8283            compatible with the type of reference being bound, so the
8284            upcoming call to cp_build_addr_expr doesn't fail.  */
8285 	if (convs->need_temporary_p
8286 	    || TREE_CODE (expr) == CONSTRUCTOR
8287 	    || TREE_CODE (expr) == VA_ARG_EXPR)
8288 	  {
8289 	    /* Otherwise, a temporary of type "cv1 T1" is created and
8290 	       initialized from the initializer expression using the rules
8291 	       for a non-reference copy-initialization (8.5).  */
8292 
8293 	    tree type = TREE_TYPE (ref_type);
8294 	    cp_lvalue_kind lvalue = lvalue_kind (expr);
8295 
8296 	    gcc_assert (similar_type_p (type, next_conversion (convs)->type));
8297 	    if (!CP_TYPE_CONST_NON_VOLATILE_P (type)
8298 		&& !TYPE_REF_IS_RVALUE (ref_type))
8299 	      {
8300 		/* If the reference is volatile or non-const, we
8301 		   cannot create a temporary.  */
8302 		if (complain & tf_error)
8303 		  {
8304 		    if (lvalue & clk_bitfield)
8305 		      error_at (loc, "cannot bind bit-field %qE to %qT",
8306 				expr, ref_type);
8307 		    else if (lvalue & clk_packed)
8308 		      error_at (loc, "cannot bind packed field %qE to %qT",
8309 				expr, ref_type);
8310 		    else
8311 		      error_at (loc, "cannot bind rvalue %qE to %qT",
8312 				expr, ref_type);
8313 		  }
8314 		return error_mark_node;
8315 	      }
8316 	    /* If the source is a packed field, and we must use a copy
8317 	       constructor, then building the target expr will require
8318 	       binding the field to the reference parameter to the
8319 	       copy constructor, and we'll end up with an infinite
8320 	       loop.  If we can use a bitwise copy, then we'll be
8321 	       OK.  */
8322 	    if ((lvalue & clk_packed)
8323 		&& CLASS_TYPE_P (type)
8324 		&& type_has_nontrivial_copy_init (type))
8325 	      {
8326 		error_at (loc, "cannot bind packed field %qE to %qT",
8327 			  expr, ref_type);
8328 		return error_mark_node;
8329 	      }
8330 	    if (lvalue & clk_bitfield)
8331 	      {
8332 		expr = convert_bitfield_to_declared_type (expr);
8333 		expr = fold_convert (type, expr);
8334 	      }
8335 
8336 	    /* Creating &TARGET_EXPR<> in a template would break when
8337 	       tsubsting the expression, so use an IMPLICIT_CONV_EXPR
8338 	       instead.  This can happen even when there's no class
8339 	       involved, e.g., when converting an integer to a reference
8340 	       type.  */
8341 	    if (processing_template_decl)
8342 	      return build1 (IMPLICIT_CONV_EXPR, totype, expr);
8343 	    expr = build_target_expr_with_type (expr, type, complain);
8344 	  }
8345 
8346 	/* Take the address of the thing to which we will bind the
8347 	   reference.  */
8348 	expr = cp_build_addr_expr (expr, complain);
8349 	if (expr == error_mark_node)
8350 	  return error_mark_node;
8351 
8352 	/* Convert it to a pointer to the type referred to by the
8353 	   reference.  This will adjust the pointer if a derived to
8354 	   base conversion is being performed.  */
8355 	expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
8356 			   expr, complain);
8357 	/* Convert the pointer to the desired reference type.  */
8358 	return build_nop (ref_type, expr);
8359       }
8360 
8361     case ck_lvalue:
8362       return decay_conversion (expr, complain);
8363 
8364     case ck_fnptr:
8365       /* ??? Should the address of a transaction-safe pointer point to the TM
8366         clone, and this conversion look up the primary function?  */
8367       return build_nop (totype, expr);
8368 
8369     case ck_qual:
8370       /* Warn about deprecated conversion if appropriate.  */
8371       if (complain & tf_warning)
8372 	{
8373 	  string_conv_p (totype, expr, 1);
8374 	  maybe_warn_array_conv (loc, convs, expr);
8375 	}
8376       break;
8377 
8378     case ck_ptr:
8379       if (convs->base_p)
8380 	expr = convert_to_base (expr, totype, !c_cast_p,
8381 				/*nonnull=*/false, complain);
8382       return build_nop (totype, expr);
8383 
8384     case ck_pmem:
8385       return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
8386 			     c_cast_p, complain);
8387 
8388     default:
8389       break;
8390     }
8391 
8392   if (convs->check_narrowing
8393       && !check_narrowing (totype, expr, complain,
8394 			   convs->check_narrowing_const_only))
8395     return error_mark_node;
8396 
8397   warning_sentinel w (warn_zero_as_null_pointer_constant);
8398   if (issue_conversion_warnings)
8399     expr = cp_convert_and_check (totype, expr, complain);
8400   else
8401     expr = cp_convert (totype, expr, complain);
8402 
8403   return expr;
8404 }
8405 
8406 /* Return true if converting FROM to TO is unsafe in a template.  */
8407 
8408 static bool
conv_unsafe_in_template_p(tree to,tree from)8409 conv_unsafe_in_template_p (tree to, tree from)
8410 {
8411   /* Converting classes involves TARGET_EXPR.  */
8412   if (CLASS_TYPE_P (to) || CLASS_TYPE_P (from))
8413     return true;
8414 
8415   /* Converting real to integer produces FIX_TRUNC_EXPR which tsubst
8416      doesn't handle.  */
8417   if (SCALAR_FLOAT_TYPE_P (from) && INTEGRAL_OR_ENUMERATION_TYPE_P (to))
8418     return true;
8419 
8420   /* Converting integer to real isn't a trivial conversion, either.  */
8421   if (INTEGRAL_OR_ENUMERATION_TYPE_P (from) && SCALAR_FLOAT_TYPE_P (to))
8422     return true;
8423 
8424   return false;
8425 }
8426 
8427 /* Wrapper for convert_like_internal that handles creating
8428    IMPLICIT_CONV_EXPR.  */
8429 
8430 static tree
convert_like(conversion * convs,tree expr,tree fn,int argnum,bool issue_conversion_warnings,bool c_cast_p,tsubst_flags_t complain)8431 convert_like (conversion *convs, tree expr, tree fn, int argnum,
8432 	      bool issue_conversion_warnings, bool c_cast_p,
8433 	      tsubst_flags_t complain)
8434 {
8435   /* Creating &TARGET_EXPR<> in a template breaks when substituting,
8436      and creating a CALL_EXPR in a template breaks in finish_call_expr
8437      so use an IMPLICIT_CONV_EXPR for this conversion.  We would have
8438      created such codes e.g. when calling a user-defined conversion
8439      function.  */
8440   tree conv_expr = NULL_TREE;
8441   if (processing_template_decl
8442       && convs->kind != ck_identity
8443       && conv_unsafe_in_template_p (convs->type, TREE_TYPE (expr)))
8444     {
8445       conv_expr = build1 (IMPLICIT_CONV_EXPR, convs->type, expr);
8446       if (convs->kind != ck_ref_bind)
8447 	conv_expr = convert_from_reference (conv_expr);
8448       if (!convs->bad_p)
8449 	return conv_expr;
8450       /* Do the normal processing to give the bad_p errors.  But we still
8451 	 need to return the IMPLICIT_CONV_EXPR, unless we're returning
8452 	 error_mark_node.  */
8453     }
8454   expr = convert_like_internal (convs, expr, fn, argnum,
8455 				issue_conversion_warnings, c_cast_p, complain);
8456   if (expr == error_mark_node)
8457     return error_mark_node;
8458   return conv_expr ? conv_expr : expr;
8459 }
8460 
8461 /* Convenience wrapper for convert_like.  */
8462 
8463 static inline tree
convert_like(conversion * convs,tree expr,tsubst_flags_t complain)8464 convert_like (conversion *convs, tree expr, tsubst_flags_t complain)
8465 {
8466   return convert_like (convs, expr, NULL_TREE, 0,
8467 		       /*issue_conversion_warnings=*/true,
8468 		       /*c_cast_p=*/false, complain);
8469 }
8470 
8471 /* Convenience wrapper for convert_like.  */
8472 
8473 static inline tree
convert_like_with_context(conversion * convs,tree expr,tree fn,int argnum,tsubst_flags_t complain)8474 convert_like_with_context (conversion *convs, tree expr, tree fn, int argnum,
8475 			   tsubst_flags_t complain)
8476 {
8477   return convert_like (convs, expr, fn, argnum,
8478 		       /*issue_conversion_warnings=*/true,
8479 		       /*c_cast_p=*/false, complain);
8480 }
8481 
8482 /* ARG is being passed to a varargs function.  Perform any conversions
8483    required.  Return the converted value.  */
8484 
8485 tree
convert_arg_to_ellipsis(tree arg,tsubst_flags_t complain)8486 convert_arg_to_ellipsis (tree arg, tsubst_flags_t complain)
8487 {
8488   tree arg_type = TREE_TYPE (arg);
8489   location_t loc = cp_expr_loc_or_input_loc (arg);
8490 
8491   /* [expr.call]
8492 
8493      If the argument has integral or enumeration type that is subject
8494      to the integral promotions (_conv.prom_), or a floating-point
8495      type that is subject to the floating-point promotion
8496      (_conv.fpprom_), the value of the argument is converted to the
8497      promoted type before the call.  */
8498   if (TREE_CODE (arg_type) == REAL_TYPE
8499       && (TYPE_PRECISION (arg_type)
8500 	  < TYPE_PRECISION (double_type_node))
8501       && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (arg_type)))
8502     {
8503       if ((complain & tf_warning)
8504 	  && warn_double_promotion && !c_inhibit_evaluation_warnings)
8505 	warning_at (loc, OPT_Wdouble_promotion,
8506 		    "implicit conversion from %qH to %qI when passing "
8507 		    "argument to function",
8508 		    arg_type, double_type_node);
8509       arg = mark_rvalue_use (arg);
8510       arg = convert_to_real_nofold (double_type_node, arg);
8511     }
8512   else if (NULLPTR_TYPE_P (arg_type))
8513     {
8514       arg = mark_rvalue_use (arg);
8515       if (TREE_SIDE_EFFECTS (arg))
8516 	{
8517 	  warning_sentinel w(warn_unused_result);
8518 	  arg = cp_build_compound_expr (arg, null_pointer_node, complain);
8519 	}
8520       else
8521 	arg = null_pointer_node;
8522     }
8523   else if (INTEGRAL_OR_ENUMERATION_TYPE_P (arg_type))
8524     {
8525       if (SCOPED_ENUM_P (arg_type))
8526 	{
8527 	  tree prom = cp_convert (ENUM_UNDERLYING_TYPE (arg_type), arg,
8528 				  complain);
8529 	  prom = cp_perform_integral_promotions (prom, complain);
8530 	  if (abi_version_crosses (6)
8531 	      && TYPE_MODE (TREE_TYPE (prom)) != TYPE_MODE (arg_type)
8532 	      && (complain & tf_warning))
8533 	    warning_at (loc, OPT_Wabi, "scoped enum %qT passed through %<...%>"
8534 			" as %qT before %<-fabi-version=6%>, %qT after",
8535 			arg_type,
8536 			TREE_TYPE (prom), ENUM_UNDERLYING_TYPE (arg_type));
8537 	  if (!abi_version_at_least (6))
8538 	    arg = prom;
8539 	}
8540       else
8541 	arg = cp_perform_integral_promotions (arg, complain);
8542     }
8543   else
8544     /* [expr.call]
8545 
8546        The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
8547        standard conversions are performed.  */
8548     arg = decay_conversion (arg, complain);
8549 
8550   arg = require_complete_type_sfinae (arg, complain);
8551   arg_type = TREE_TYPE (arg);
8552 
8553   if (arg != error_mark_node
8554       /* In a template (or ill-formed code), we can have an incomplete type
8555 	 even after require_complete_type_sfinae, in which case we don't know
8556 	 whether it has trivial copy or not.  */
8557       && COMPLETE_TYPE_P (arg_type)
8558       && !cp_unevaluated_operand)
8559     {
8560       /* [expr.call] 5.2.2/7:
8561 	 Passing a potentially-evaluated argument of class type (Clause 9)
8562 	 with a non-trivial copy constructor or a non-trivial destructor
8563 	 with no corresponding parameter is conditionally-supported, with
8564 	 implementation-defined semantics.
8565 
8566 	 We support it as pass-by-invisible-reference, just like a normal
8567 	 value parameter.
8568 
8569 	 If the call appears in the context of a sizeof expression,
8570 	 it is not potentially-evaluated.  */
8571       if (type_has_nontrivial_copy_init (arg_type)
8572 	  || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (arg_type))
8573 	{
8574 	  arg = force_rvalue (arg, complain);
8575 	  if (complain & tf_warning)
8576 	    warning (OPT_Wconditionally_supported,
8577 		     "passing objects of non-trivially-copyable "
8578 		     "type %q#T through %<...%> is conditionally supported",
8579 		     arg_type);
8580 	  return build1 (ADDR_EXPR, build_reference_type (arg_type), arg);
8581 	}
8582       /* Build up a real lvalue-to-rvalue conversion in case the
8583 	 copy constructor is trivial but not callable.  */
8584       else if (CLASS_TYPE_P (arg_type))
8585 	force_rvalue (arg, complain);
8586 
8587     }
8588 
8589   return arg;
8590 }
8591 
8592 /* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused.  */
8593 
8594 tree
build_x_va_arg(location_t loc,tree expr,tree type)8595 build_x_va_arg (location_t loc, tree expr, tree type)
8596 {
8597   if (processing_template_decl)
8598     {
8599       tree r = build_min (VA_ARG_EXPR, type, expr);
8600       SET_EXPR_LOCATION (r, loc);
8601       return r;
8602     }
8603 
8604   type = complete_type_or_else (type, NULL_TREE);
8605 
8606   if (expr == error_mark_node || !type)
8607     return error_mark_node;
8608 
8609   expr = mark_lvalue_use (expr);
8610 
8611   if (TYPE_REF_P (type))
8612     {
8613       error ("cannot receive reference type %qT through %<...%>", type);
8614       return error_mark_node;
8615     }
8616 
8617   if (type_has_nontrivial_copy_init (type)
8618       || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
8619     {
8620       /* conditionally-supported behavior [expr.call] 5.2.2/7.  Let's treat
8621 	 it as pass by invisible reference.  */
8622       warning_at (loc, OPT_Wconditionally_supported,
8623 		 "receiving objects of non-trivially-copyable type %q#T "
8624 		 "through %<...%> is conditionally-supported", type);
8625 
8626       tree ref = cp_build_reference_type (type, false);
8627       expr = build_va_arg (loc, expr, ref);
8628       return convert_from_reference (expr);
8629     }
8630 
8631   tree ret = build_va_arg (loc, expr, type);
8632   if (CLASS_TYPE_P (type))
8633     /* Wrap the VA_ARG_EXPR in a TARGET_EXPR now so other code doesn't need to
8634        know how to handle it.  */
8635     ret = get_target_expr (ret);
8636   return ret;
8637 }
8638 
8639 /* TYPE has been given to va_arg.  Apply the default conversions which
8640    would have happened when passed via ellipsis.  Return the promoted
8641    type, or the passed type if there is no change.  */
8642 
8643 tree
cxx_type_promotes_to(tree type)8644 cxx_type_promotes_to (tree type)
8645 {
8646   tree promote;
8647 
8648   /* Perform the array-to-pointer and function-to-pointer
8649      conversions.  */
8650   type = type_decays_to (type);
8651 
8652   promote = type_promotes_to (type);
8653   if (same_type_p (type, promote))
8654     promote = type;
8655 
8656   return promote;
8657 }
8658 
8659 /* ARG is a default argument expression being passed to a parameter of
8660    the indicated TYPE, which is a parameter to FN.  PARMNUM is the
8661    zero-based argument number.  Do any required conversions.  Return
8662    the converted value.  */
8663 
8664 static GTY(()) vec<tree, va_gc> *default_arg_context;
8665 void
push_defarg_context(tree fn)8666 push_defarg_context (tree fn)
8667 { vec_safe_push (default_arg_context, fn); }
8668 
8669 void
pop_defarg_context(void)8670 pop_defarg_context (void)
8671 { default_arg_context->pop (); }
8672 
8673 tree
convert_default_arg(tree type,tree arg,tree fn,int parmnum,tsubst_flags_t complain)8674 convert_default_arg (tree type, tree arg, tree fn, int parmnum,
8675 		     tsubst_flags_t complain)
8676 {
8677   int i;
8678   tree t;
8679 
8680   /* See through clones.  */
8681   fn = DECL_ORIGIN (fn);
8682   /* And inheriting ctors.  */
8683   if (flag_new_inheriting_ctors)
8684     fn = strip_inheriting_ctors (fn);
8685 
8686   /* Detect recursion.  */
8687   FOR_EACH_VEC_SAFE_ELT (default_arg_context, i, t)
8688     if (t == fn)
8689       {
8690 	if (complain & tf_error)
8691 	  error ("recursive evaluation of default argument for %q#D", fn);
8692 	return error_mark_node;
8693       }
8694 
8695   /* If the ARG is an unparsed default argument expression, the
8696      conversion cannot be performed.  */
8697   if (TREE_CODE (arg) == DEFERRED_PARSE)
8698     {
8699       if (complain & tf_error)
8700 	error ("call to %qD uses the default argument for parameter %P, which "
8701 	       "is not yet defined", fn, parmnum);
8702       return error_mark_node;
8703     }
8704 
8705   push_defarg_context (fn);
8706 
8707   if (fn && DECL_TEMPLATE_INFO (fn))
8708     arg = tsubst_default_argument (fn, parmnum, type, arg, complain);
8709 
8710   /* Due to:
8711 
8712        [dcl.fct.default]
8713 
8714        The names in the expression are bound, and the semantic
8715        constraints are checked, at the point where the default
8716        expressions appears.
8717 
8718      we must not perform access checks here.  */
8719   push_deferring_access_checks (dk_no_check);
8720   /* We must make a copy of ARG, in case subsequent processing
8721      alters any part of it.  */
8722   arg = break_out_target_exprs (arg, /*clear location*/true);
8723 
8724   arg = convert_for_initialization (0, type, arg, LOOKUP_IMPLICIT,
8725 				    ICR_DEFAULT_ARGUMENT, fn, parmnum,
8726 				    complain);
8727   arg = convert_for_arg_passing (type, arg, complain);
8728   pop_deferring_access_checks();
8729 
8730   pop_defarg_context ();
8731 
8732   return arg;
8733 }
8734 
8735 /* Returns the type which will really be used for passing an argument of
8736    type TYPE.  */
8737 
8738 tree
type_passed_as(tree type)8739 type_passed_as (tree type)
8740 {
8741   /* Pass classes with copy ctors by invisible reference.  */
8742   if (TREE_ADDRESSABLE (type))
8743     type = build_reference_type (type);
8744   else if (targetm.calls.promote_prototypes (NULL_TREE)
8745 	   && INTEGRAL_TYPE_P (type)
8746 	   && COMPLETE_TYPE_P (type)
8747 	   && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
8748     type = integer_type_node;
8749 
8750   return type;
8751 }
8752 
8753 /* Actually perform the appropriate conversion.  */
8754 
8755 tree
convert_for_arg_passing(tree type,tree val,tsubst_flags_t complain)8756 convert_for_arg_passing (tree type, tree val, tsubst_flags_t complain)
8757 {
8758   tree bitfield_type;
8759 
8760   /* If VAL is a bitfield, then -- since it has already been converted
8761      to TYPE -- it cannot have a precision greater than TYPE.
8762 
8763      If it has a smaller precision, we must widen it here.  For
8764      example, passing "int f:3;" to a function expecting an "int" will
8765      not result in any conversion before this point.
8766 
8767      If the precision is the same we must not risk widening.  For
8768      example, the COMPONENT_REF for a 32-bit "long long" bitfield will
8769      often have type "int", even though the C++ type for the field is
8770      "long long".  If the value is being passed to a function
8771      expecting an "int", then no conversions will be required.  But,
8772      if we call convert_bitfield_to_declared_type, the bitfield will
8773      be converted to "long long".  */
8774   bitfield_type = is_bitfield_expr_with_lowered_type (val);
8775   if (bitfield_type
8776       && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
8777     val = convert_to_integer_nofold (TYPE_MAIN_VARIANT (bitfield_type), val);
8778 
8779   if (val == error_mark_node)
8780     ;
8781   /* Pass classes with copy ctors by invisible reference.  */
8782   else if (TREE_ADDRESSABLE (type))
8783     val = build1 (ADDR_EXPR, build_reference_type (type), val);
8784   else if (targetm.calls.promote_prototypes (NULL_TREE)
8785 	   && INTEGRAL_TYPE_P (type)
8786 	   && COMPLETE_TYPE_P (type)
8787 	   && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
8788     val = cp_perform_integral_promotions (val, complain);
8789   if (complain & tf_warning)
8790     {
8791       if (warn_suggest_attribute_format)
8792 	{
8793 	  tree rhstype = TREE_TYPE (val);
8794 	  const enum tree_code coder = TREE_CODE (rhstype);
8795 	  const enum tree_code codel = TREE_CODE (type);
8796 	  if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
8797 	      && coder == codel
8798 	      && check_missing_format_attribute (type, rhstype))
8799 	    warning (OPT_Wsuggest_attribute_format,
8800 		     "argument of function call might be a candidate "
8801 		     "for a format attribute");
8802 	}
8803       maybe_warn_parm_abi (type, cp_expr_loc_or_input_loc (val));
8804     }
8805 
8806   if (complain & tf_warning)
8807     warn_for_address_or_pointer_of_packed_member (type, val);
8808 
8809   return val;
8810 }
8811 
8812 /* Returns non-zero iff FN is a function with magic varargs, i.e. ones for
8813    which just decay_conversion or no conversions at all should be done.
8814    This is true for some builtins which don't act like normal functions.
8815    Return 2 if no conversions at all should be done, 1 if just
8816    decay_conversion.  Return 3 for special treatment of the 3rd argument
8817    for __builtin_*_overflow_p.  */
8818 
8819 int
magic_varargs_p(tree fn)8820 magic_varargs_p (tree fn)
8821 {
8822   if (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
8823     switch (DECL_FUNCTION_CODE (fn))
8824       {
8825       case BUILT_IN_CLASSIFY_TYPE:
8826       case BUILT_IN_CONSTANT_P:
8827       case BUILT_IN_NEXT_ARG:
8828       case BUILT_IN_VA_START:
8829 	return 1;
8830 
8831       case BUILT_IN_ADD_OVERFLOW_P:
8832       case BUILT_IN_SUB_OVERFLOW_P:
8833       case BUILT_IN_MUL_OVERFLOW_P:
8834 	return 3;
8835 
8836       default:;
8837 	return lookup_attribute ("type generic",
8838 				 TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
8839       }
8840 
8841   return 0;
8842 }
8843 
8844 /* Returns the decl of the dispatcher function if FN is a function version.  */
8845 
8846 tree
get_function_version_dispatcher(tree fn)8847 get_function_version_dispatcher (tree fn)
8848 {
8849   tree dispatcher_decl = NULL;
8850 
8851   if (DECL_LOCAL_DECL_P (fn))
8852     fn = DECL_LOCAL_DECL_ALIAS (fn);
8853 
8854   gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
8855 	      && DECL_FUNCTION_VERSIONED (fn));
8856 
8857   gcc_assert (targetm.get_function_versions_dispatcher);
8858   dispatcher_decl = targetm.get_function_versions_dispatcher (fn);
8859 
8860   if (dispatcher_decl == NULL)
8861     {
8862       error_at (input_location, "use of multiversioned function "
8863 				"without a default");
8864       return NULL;
8865     }
8866 
8867   retrofit_lang_decl (dispatcher_decl);
8868   gcc_assert (dispatcher_decl != NULL);
8869   return dispatcher_decl;
8870 }
8871 
8872 /* fn is a function version dispatcher that is marked used. Mark all the
8873    semantically identical function versions it will dispatch as used.  */
8874 
8875 void
mark_versions_used(tree fn)8876 mark_versions_used (tree fn)
8877 {
8878   struct cgraph_node *node;
8879   struct cgraph_function_version_info *node_v;
8880   struct cgraph_function_version_info *it_v;
8881 
8882   gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
8883 
8884   node = cgraph_node::get (fn);
8885   if (node == NULL)
8886     return;
8887 
8888   gcc_assert (node->dispatcher_function);
8889 
8890   node_v = node->function_version ();
8891   if (node_v == NULL)
8892     return;
8893 
8894   /* All semantically identical versions are chained.  Traverse and mark each
8895      one of them as used.  */
8896   it_v = node_v->next;
8897   while (it_v != NULL)
8898     {
8899       mark_used (it_v->this_node->decl);
8900       it_v = it_v->next;
8901     }
8902 }
8903 
8904 /* Build a call to "the copy constructor" for the type of A, even if it
8905    wouldn't be selected by normal overload resolution.  Used for
8906    diagnostics.  */
8907 
8908 static tree
call_copy_ctor(tree a,tsubst_flags_t complain)8909 call_copy_ctor (tree a, tsubst_flags_t complain)
8910 {
8911   tree ctype = TYPE_MAIN_VARIANT (TREE_TYPE (a));
8912   tree binfo = TYPE_BINFO (ctype);
8913   tree copy = get_copy_ctor (ctype, complain);
8914   copy = build_baselink (binfo, binfo, copy, NULL_TREE);
8915   tree ob = build_dummy_object (ctype);
8916   releasing_vec args (make_tree_vector_single (a));
8917   tree r = build_new_method_call (ob, copy, &args, NULL_TREE,
8918 				  LOOKUP_NORMAL, NULL, complain);
8919   return r;
8920 }
8921 
8922 /* Return the base constructor corresponding to COMPLETE_CTOR or NULL_TREE.  */
8923 
8924 static tree
base_ctor_for(tree complete_ctor)8925 base_ctor_for (tree complete_ctor)
8926 {
8927   tree clone;
8928   FOR_EACH_CLONE (clone, DECL_CLONED_FUNCTION (complete_ctor))
8929     if (DECL_BASE_CONSTRUCTOR_P (clone))
8930       return clone;
8931   return NULL_TREE;
8932 }
8933 
8934 /* Try to make EXP suitable to be used as the initializer for a base subobject,
8935    and return whether we were successful.  EXP must have already been cleared
8936    by unsafe_copy_elision_p{,_opt}.  */
8937 
8938 static bool
make_base_init_ok(tree exp)8939 make_base_init_ok (tree exp)
8940 {
8941   if (TREE_CODE (exp) == TARGET_EXPR)
8942     exp = TARGET_EXPR_INITIAL (exp);
8943   while (TREE_CODE (exp) == COMPOUND_EXPR)
8944     exp = TREE_OPERAND (exp, 1);
8945   if (TREE_CODE (exp) == COND_EXPR)
8946     {
8947       bool ret = make_base_init_ok (TREE_OPERAND (exp, 2));
8948       if (tree op1 = TREE_OPERAND (exp, 1))
8949 	{
8950 	  bool r1 = make_base_init_ok (op1);
8951 	  /* If unsafe_copy_elision_p was false, the arms should match.  */
8952 	  gcc_assert (r1 == ret);
8953 	}
8954       return ret;
8955     }
8956   if (TREE_CODE (exp) != AGGR_INIT_EXPR)
8957     /* A trivial copy is OK.  */
8958     return true;
8959   if (!AGGR_INIT_VIA_CTOR_P (exp))
8960     /* unsafe_copy_elision_p_opt must have said this is OK.  */
8961     return true;
8962   tree fn = cp_get_callee_fndecl_nofold (exp);
8963   if (DECL_BASE_CONSTRUCTOR_P (fn))
8964     return true;
8965   gcc_assert (DECL_COMPLETE_CONSTRUCTOR_P (fn));
8966   fn = base_ctor_for (fn);
8967   if (!fn || DECL_HAS_VTT_PARM_P (fn))
8968     /* The base constructor has more parameters, so we can't just change the
8969        call target.  It would be possible to splice in the appropriate
8970        arguments, but probably not worth the complexity.  */
8971     return false;
8972   mark_used (fn);
8973   AGGR_INIT_EXPR_FN (exp) = build_address (fn);
8974   return true;
8975 }
8976 
8977 /* Return 2 if T refers to a base, 1 if a potentially-overlapping field,
8978    neither of which can be used for return by invisible reference.  We avoid
8979    doing C++17 mandatory copy elision for either of these cases.
8980 
8981    This returns non-zero even if the type of T has no tail padding that other
8982    data could be allocated into, because that depends on the particular ABI.
8983    unsafe_copy_elision_p_opt does consider whether there is padding.  */
8984 
8985 int
unsafe_return_slot_p(tree t)8986 unsafe_return_slot_p (tree t)
8987 {
8988   /* Check empty bases separately, they don't have fields.  */
8989   if (is_empty_base_ref (t))
8990     return 2;
8991 
8992   STRIP_NOPS (t);
8993   if (TREE_CODE (t) == ADDR_EXPR)
8994     t = TREE_OPERAND (t, 0);
8995   if (TREE_CODE (t) == COMPONENT_REF)
8996     t = TREE_OPERAND (t, 1);
8997   if (TREE_CODE (t) != FIELD_DECL)
8998     return false;
8999   if (!CLASS_TYPE_P (TREE_TYPE (t)))
9000     /* The middle-end will do the right thing for scalar types.  */
9001     return false;
9002   if (DECL_FIELD_IS_BASE (t))
9003     return 2;
9004   if (lookup_attribute ("no_unique_address", DECL_ATTRIBUTES (t)))
9005     return 1;
9006   return 0;
9007 }
9008 
9009 /* True IFF EXP is a prvalue that represents return by invisible reference.  */
9010 
9011 static bool
init_by_return_slot_p(tree exp)9012 init_by_return_slot_p (tree exp)
9013 {
9014   /* Copy elision only happens with a TARGET_EXPR.  */
9015   if (TREE_CODE (exp) != TARGET_EXPR)
9016     return false;
9017   tree init = TARGET_EXPR_INITIAL (exp);
9018   /* build_compound_expr pushes COMPOUND_EXPR inside TARGET_EXPR.  */
9019   while (TREE_CODE (init) == COMPOUND_EXPR)
9020     init = TREE_OPERAND (init, 1);
9021   if (TREE_CODE (init) == COND_EXPR)
9022     {
9023       /* We'll end up copying from each of the arms of the COND_EXPR directly
9024 	 into the target, so look at them.  */
9025       if (tree op = TREE_OPERAND (init, 1))
9026 	if (init_by_return_slot_p (op))
9027 	  return true;
9028       return init_by_return_slot_p (TREE_OPERAND (init, 2));
9029     }
9030   return (TREE_CODE (init) == AGGR_INIT_EXPR
9031 	  && !AGGR_INIT_VIA_CTOR_P (init));
9032 }
9033 
9034 /* We can't elide a copy from a function returning by value to a
9035    potentially-overlapping subobject, as the callee might clobber tail padding.
9036    Return true iff this could be that case.
9037 
9038    Places that use this function (or _opt) to decide to elide a copy should
9039    probably use make_safe_copy_elision instead.  */
9040 
9041 static bool
unsafe_copy_elision_p(tree target,tree exp)9042 unsafe_copy_elision_p (tree target, tree exp)
9043 {
9044   return unsafe_return_slot_p (target) && init_by_return_slot_p (exp);
9045 }
9046 
9047 /* As above, but for optimization allow more cases that are actually safe.  */
9048 
9049 static bool
unsafe_copy_elision_p_opt(tree target,tree exp)9050 unsafe_copy_elision_p_opt (tree target, tree exp)
9051 {
9052   tree type = TYPE_MAIN_VARIANT (TREE_TYPE (exp));
9053   /* It's safe to elide the copy for a class with no tail padding.  */
9054   if (!is_empty_class (type)
9055       && tree_int_cst_equal (TYPE_SIZE (type), CLASSTYPE_SIZE (type)))
9056     return false;
9057   return unsafe_copy_elision_p (target, exp);
9058 }
9059 
9060 /* Try to make EXP suitable to be used as the initializer for TARGET,
9061    and return whether we were successful.  */
9062 
9063 bool
make_safe_copy_elision(tree target,tree exp)9064 make_safe_copy_elision (tree target, tree exp)
9065 {
9066   int uns = unsafe_return_slot_p (target);
9067   if (!uns)
9068     return true;
9069   if (init_by_return_slot_p (exp))
9070     return false;
9071   if (uns == 1)
9072     return true;
9073   return make_base_init_ok (exp);
9074 }
9075 
9076 /* True IFF the result of the conversion C is a prvalue.  */
9077 
9078 static bool
conv_is_prvalue(conversion * c)9079 conv_is_prvalue (conversion *c)
9080 {
9081   if (c->kind == ck_rvalue)
9082     return true;
9083   if (c->kind == ck_base && c->need_temporary_p)
9084     return true;
9085   if (c->kind == ck_user && !TYPE_REF_P (c->type))
9086     return true;
9087   if (c->kind == ck_identity && c->u.expr
9088       && TREE_CODE (c->u.expr) == TARGET_EXPR)
9089     return true;
9090 
9091   return false;
9092 }
9093 
9094 /* True iff C is a conversion that binds a reference to a prvalue.  */
9095 
9096 static bool
conv_binds_ref_to_prvalue(conversion * c)9097 conv_binds_ref_to_prvalue (conversion *c)
9098 {
9099   if (c->kind != ck_ref_bind)
9100     return false;
9101   if (c->need_temporary_p)
9102     return true;
9103 
9104   return conv_is_prvalue (next_conversion (c));
9105 }
9106 
9107 /* True iff converting EXPR to a reference type TYPE does not involve
9108    creating a temporary.  */
9109 
9110 bool
ref_conv_binds_directly_p(tree type,tree expr)9111 ref_conv_binds_directly_p (tree type, tree expr)
9112 {
9113   gcc_assert (TYPE_REF_P (type));
9114 
9115   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
9116   void *p = conversion_obstack_alloc (0);
9117 
9118   conversion *conv = implicit_conversion (type, TREE_TYPE (expr), expr,
9119 					  /*c_cast_p=*/false,
9120 					  LOOKUP_IMPLICIT, tf_none);
9121   bool ret = conv && !conv->bad_p && !conv_binds_ref_to_prvalue (conv);
9122 
9123   /* Free all the conversions we allocated.  */
9124   obstack_free (&conversion_obstack, p);
9125 
9126   return ret;
9127 }
9128 
9129 /* Call the trivial destructor for INSTANCE, which can be either an lvalue of
9130    class type or a pointer to class type.  If NO_PTR_DEREF is true and
9131    INSTANCE has pointer type, clobber the pointer rather than what it points
9132    to.  */
9133 
9134 tree
build_trivial_dtor_call(tree instance,bool no_ptr_deref)9135 build_trivial_dtor_call (tree instance, bool no_ptr_deref)
9136 {
9137   gcc_assert (!is_dummy_object (instance));
9138 
9139   if (!flag_lifetime_dse)
9140     {
9141     no_clobber:
9142       return fold_convert (void_type_node, instance);
9143     }
9144 
9145   if (INDIRECT_TYPE_P (TREE_TYPE (instance))
9146       && (!no_ptr_deref || TYPE_REF_P (TREE_TYPE (instance))))
9147     {
9148       if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (instance))))
9149 	goto no_clobber;
9150       instance = cp_build_fold_indirect_ref (instance);
9151     }
9152 
9153   /* A trivial destructor should still clobber the object.  */
9154   tree clobber = build_clobber (TREE_TYPE (instance));
9155   return build2 (MODIFY_EXPR, void_type_node,
9156 		 instance, clobber);
9157 }
9158 
9159 /* Return true if in an immediate function context, or an unevaluated operand,
9160    or a subexpression of an immediate invocation.  */
9161 
9162 bool
in_immediate_context()9163 in_immediate_context ()
9164 {
9165   return (cp_unevaluated_operand != 0
9166 	  || (current_function_decl != NULL_TREE
9167 	      && DECL_IMMEDIATE_FUNCTION_P (current_function_decl))
9168 	  || (current_binding_level->kind == sk_function_parms
9169 	      && current_binding_level->immediate_fn_ctx_p)
9170 	  || in_consteval_if_p);
9171 }
9172 
9173 /* Return true if a call to FN with number of arguments NARGS
9174    is an immediate invocation.  */
9175 
9176 static bool
immediate_invocation_p(tree fn,int nargs)9177 immediate_invocation_p (tree fn, int nargs)
9178 {
9179   return (TREE_CODE (fn) == FUNCTION_DECL
9180 	  && DECL_IMMEDIATE_FUNCTION_P (fn)
9181 	  && !in_immediate_context ()
9182 	  /* As an exception, we defer std::source_location::current ()
9183 	     invocations until genericization because LWG3396 mandates
9184 	     special behavior for it.  */
9185 	  && (nargs > 1 || !source_location_current_p (fn)));
9186 }
9187 
9188 /* temp_override for in_consteval_if_p, which can't use make_temp_override
9189    because it is a bitfield.  */
9190 
9191 struct in_consteval_if_p_temp_override {
9192   bool save_in_consteval_if_p;
in_consteval_if_p_temp_overridein_consteval_if_p_temp_override9193   in_consteval_if_p_temp_override ()
9194     : save_in_consteval_if_p (in_consteval_if_p) {}
resetin_consteval_if_p_temp_override9195   void reset () { in_consteval_if_p = save_in_consteval_if_p; }
~in_consteval_if_p_temp_overridein_consteval_if_p_temp_override9196   ~in_consteval_if_p_temp_override ()
9197   { reset (); }
9198 };
9199 
9200 /* Subroutine of the various build_*_call functions.  Overload resolution
9201    has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
9202    ARGS is a TREE_LIST of the unconverted arguments to the call.  FLAGS is a
9203    bitmask of various LOOKUP_* flags which apply to the call itself.  */
9204 
9205 static tree
build_over_call(struct z_candidate * cand,int flags,tsubst_flags_t complain)9206 build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
9207 {
9208   tree fn = cand->fn;
9209   const vec<tree, va_gc> *args = cand->args;
9210   tree first_arg = cand->first_arg;
9211   conversion **convs = cand->convs;
9212   conversion *conv;
9213   tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
9214   int parmlen;
9215   tree val;
9216   int i = 0;
9217   int j = 0;
9218   unsigned int arg_index = 0;
9219   int is_method = 0;
9220   int nargs;
9221   tree *argarray;
9222   bool already_used = false;
9223 
9224   /* In a template, there is no need to perform all of the work that
9225      is normally done.  We are only interested in the type of the call
9226      expression, i.e., the return type of the function.  Any semantic
9227      errors will be deferred until the template is instantiated.  */
9228   if (processing_template_decl)
9229     {
9230       if (undeduced_auto_decl (fn))
9231 	mark_used (fn, complain);
9232       else
9233 	/* Otherwise set TREE_USED for the benefit of -Wunused-function.
9234 	   See PR80598.  */
9235 	TREE_USED (fn) = 1;
9236 
9237       tree return_type = TREE_TYPE (TREE_TYPE (fn));
9238       tree callee;
9239       if (first_arg == NULL_TREE)
9240 	{
9241 	  callee = build_addr_func (fn, complain);
9242 	  if (callee == error_mark_node)
9243 	    return error_mark_node;
9244 	}
9245       else
9246 	{
9247 	  callee = build_baselink (cand->conversion_path, cand->access_path,
9248 				   fn, NULL_TREE);
9249 	  callee = build_min (COMPONENT_REF, TREE_TYPE (fn),
9250 			      first_arg, callee, NULL_TREE);
9251 	}
9252 
9253       tree expr = build_call_vec (return_type, callee, args);
9254       SET_EXPR_LOCATION (expr, input_location);
9255       if (TREE_THIS_VOLATILE (fn) && cfun)
9256 	current_function_returns_abnormally = 1;
9257       if (immediate_invocation_p (fn, vec_safe_length (args)))
9258 	{
9259 	  tree obj_arg = NULL_TREE, exprimm = expr;
9260 	  if (DECL_CONSTRUCTOR_P (fn))
9261 	    obj_arg = first_arg;
9262 	  if (obj_arg
9263 	      && is_dummy_object (obj_arg)
9264 	      && !type_dependent_expression_p (obj_arg))
9265 	    {
9266 	      exprimm = build_cplus_new (DECL_CONTEXT (fn), expr, complain);
9267 	      obj_arg = NULL_TREE;
9268 	    }
9269 	  /* Look through *(const T *)&obj.  */
9270 	  else if (obj_arg && TREE_CODE (obj_arg) == INDIRECT_REF)
9271 	    {
9272 	      tree addr = TREE_OPERAND (obj_arg, 0);
9273 	      STRIP_NOPS (addr);
9274 	      if (TREE_CODE (addr) == ADDR_EXPR)
9275 		{
9276 		  tree typeo = TREE_TYPE (obj_arg);
9277 		  tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
9278 		  if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
9279 		    obj_arg = TREE_OPERAND (addr, 0);
9280 		}
9281 	    }
9282 	  fold_non_dependent_expr (exprimm, complain,
9283 				   /*manifestly_const_eval=*/true,
9284 				   obj_arg);
9285 	}
9286       return convert_from_reference (expr);
9287     }
9288 
9289   /* Give any warnings we noticed during overload resolution.  */
9290   if (cand->warnings && (complain & tf_warning))
9291     {
9292       struct candidate_warning *w;
9293       for (w = cand->warnings; w; w = w->next)
9294 	joust (cand, w->loser, 1, complain);
9295     }
9296 
9297   /* Core issue 2327: P0135 doesn't say how to handle the case where the
9298      argument to the copy constructor ends up being a prvalue after
9299      conversion.  Let's do the normal processing, but pretend we aren't
9300      actually using the copy constructor.  */
9301   bool force_elide = false;
9302   if (cxx_dialect >= cxx17
9303       && cand->num_convs == 1
9304       && DECL_COMPLETE_CONSTRUCTOR_P (fn)
9305       && (DECL_COPY_CONSTRUCTOR_P (fn)
9306 	  || DECL_MOVE_CONSTRUCTOR_P (fn))
9307       && !unsafe_return_slot_p (first_arg)
9308       && conv_binds_ref_to_prvalue (convs[0]))
9309     {
9310       force_elide = true;
9311       goto not_really_used;
9312     }
9313 
9314   /* OK, we're actually calling this inherited constructor; set its deletedness
9315      appropriately.  We can get away with doing this here because calling is
9316      the only way to refer to a constructor.  */
9317   if (DECL_INHERITED_CTOR (fn)
9318       && !deduce_inheriting_ctor (fn))
9319     {
9320       if (complain & tf_error)
9321 	mark_used (fn);
9322       return error_mark_node;
9323     }
9324 
9325   /* Make =delete work with SFINAE.  */
9326   if (DECL_DELETED_FN (fn))
9327     {
9328       if (complain & tf_error)
9329 	mark_used (fn);
9330       return error_mark_node;
9331     }
9332 
9333   if (DECL_FUNCTION_MEMBER_P (fn))
9334     {
9335       tree access_fn;
9336       /* If FN is a template function, two cases must be considered.
9337 	 For example:
9338 
9339 	   struct A {
9340 	     protected:
9341 	       template <class T> void f();
9342 	   };
9343 	   template <class T> struct B {
9344 	     protected:
9345 	       void g();
9346 	   };
9347 	   struct C : A, B<int> {
9348 	     using A::f;	// #1
9349 	     using B<int>::g;	// #2
9350 	   };
9351 
9352 	 In case #1 where `A::f' is a member template, DECL_ACCESS is
9353 	 recorded in the primary template but not in its specialization.
9354 	 We check access of FN using its primary template.
9355 
9356 	 In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
9357 	 because it is a member of class template B, DECL_ACCESS is
9358 	 recorded in the specialization `B<int>::g'.  We cannot use its
9359 	 primary template because `B<T>::g' and `B<int>::g' may have
9360 	 different access.  */
9361       if (DECL_TEMPLATE_INFO (fn)
9362 	  && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
9363 	access_fn = DECL_TI_TEMPLATE (fn);
9364       else
9365 	access_fn = fn;
9366       if (!perform_or_defer_access_check (cand->access_path, access_fn,
9367 					  fn, complain))
9368 	return error_mark_node;
9369     }
9370 
9371   /* If we're checking for implicit delete, don't bother with argument
9372      conversions.  */
9373   if (flags & LOOKUP_SPECULATIVE)
9374     {
9375       if (cand->viable == 1)
9376 	return fn;
9377       else if (!(complain & tf_error))
9378 	/* Reject bad conversions now.  */
9379 	return error_mark_node;
9380       /* else continue to get conversion error.  */
9381     }
9382 
9383  not_really_used:
9384 
9385   /* N3276 magic doesn't apply to nested calls.  */
9386   tsubst_flags_t decltype_flag = (complain & tf_decltype);
9387   complain &= ~tf_decltype;
9388   /* No-Cleanup doesn't apply to nested calls either.  */
9389   tsubst_flags_t no_cleanup_complain = complain;
9390   complain &= ~tf_no_cleanup;
9391 
9392   /* Find maximum size of vector to hold converted arguments.  */
9393   parmlen = list_length (parm);
9394   nargs = vec_safe_length (args) + (first_arg != NULL_TREE ? 1 : 0);
9395   if (parmlen > nargs)
9396     nargs = parmlen;
9397   argarray = XALLOCAVEC (tree, nargs);
9398 
9399   in_consteval_if_p_temp_override icip;
9400   /* If the call is immediate function invocation, make sure
9401      taking address of immediate functions is allowed in its arguments.  */
9402   if (immediate_invocation_p (STRIP_TEMPLATE (fn), nargs))
9403     in_consteval_if_p = true;
9404 
9405   /* The implicit parameters to a constructor are not considered by overload
9406      resolution, and must be of the proper type.  */
9407   if (DECL_CONSTRUCTOR_P (fn))
9408     {
9409       tree object_arg;
9410       if (first_arg != NULL_TREE)
9411 	{
9412 	  object_arg = first_arg;
9413 	  first_arg = NULL_TREE;
9414 	}
9415       else
9416 	{
9417 	  object_arg = (*args)[arg_index];
9418 	  ++arg_index;
9419 	}
9420       argarray[j++] = build_this (object_arg);
9421       parm = TREE_CHAIN (parm);
9422       /* We should never try to call the abstract constructor.  */
9423       gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
9424 
9425       if (DECL_HAS_VTT_PARM_P (fn))
9426 	{
9427 	  argarray[j++] = (*args)[arg_index];
9428 	  ++arg_index;
9429 	  parm = TREE_CHAIN (parm);
9430 	}
9431 
9432       if (cxx_dialect < cxx20
9433 	  && (cand->flags & LOOKUP_PREFER_RVALUE))
9434 	{
9435 	  /* The implicit move specified in 15.8.3/3 fails "...if the type of
9436 	     the first parameter of the selected constructor is not an rvalue
9437 	     reference to the object's type (possibly cv-qualified)...." */
9438 	  gcc_assert (!(complain & tf_error));
9439 	  tree ptype = convs[0]->type;
9440 	  /* Allow calling a by-value converting constructor even though it
9441 	     isn't permitted by the above, because we've allowed it since GCC 5
9442 	     (PR58051) and it's allowed in C++20.  But don't call a copy
9443 	     constructor.  */
9444 	  if ((TYPE_REF_P (ptype) && !TYPE_REF_IS_RVALUE (ptype))
9445 	      || CONVERSION_RANK (convs[0]) > cr_exact)
9446 	    return error_mark_node;
9447 	}
9448     }
9449   /* Bypass access control for 'this' parameter.  */
9450   else if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
9451     {
9452       tree arg = build_this (first_arg != NULL_TREE
9453 			     ? first_arg
9454 			     : (*args)[arg_index]);
9455       tree argtype = TREE_TYPE (arg);
9456 
9457       if (arg == error_mark_node)
9458 	return error_mark_node;
9459 
9460       if (convs[i]->bad_p)
9461 	{
9462 	  if (complain & tf_error)
9463 	    {
9464 	      auto_diagnostic_group d;
9465 	      if (permerror (input_location, "passing %qT as %<this%> "
9466 			     "argument discards qualifiers",
9467 			     TREE_TYPE (argtype)))
9468 		inform (DECL_SOURCE_LOCATION (fn), "  in call to %qD", fn);
9469 	    }
9470 	  else
9471 	    return error_mark_node;
9472 	}
9473 
9474       /* The class where FN is defined.  */
9475       tree ctx = DECL_CONTEXT (fn);
9476 
9477       /* See if the function member or the whole class type is declared
9478 	 final and the call can be devirtualized.  */
9479       if (DECL_FINAL_P (fn) || CLASSTYPE_FINAL (ctx))
9480 	flags |= LOOKUP_NONVIRTUAL;
9481 
9482       /* [class.mfct.non-static]: If a non-static member function of a class
9483 	 X is called for an object that is not of type X, or of a type
9484 	 derived from X, the behavior is undefined.
9485 
9486 	 So we can assume that anything passed as 'this' is non-null, and
9487 	 optimize accordingly.  */
9488       /* Check that the base class is accessible.  */
9489       if (!accessible_base_p (TREE_TYPE (argtype),
9490 			      BINFO_TYPE (cand->conversion_path), true))
9491 	{
9492 	  if (complain & tf_error)
9493 	    error ("%qT is not an accessible base of %qT",
9494 		   BINFO_TYPE (cand->conversion_path),
9495 		   TREE_TYPE (argtype));
9496 	  else
9497 	    return error_mark_node;
9498 	}
9499       /* If fn was found by a using declaration, the conversion path
9500 	 will be to the derived class, not the base declaring fn. We
9501 	 must convert to the base.  */
9502       tree base_binfo = cand->conversion_path;
9503       if (BINFO_TYPE (base_binfo) != ctx)
9504 	{
9505 	  base_binfo = lookup_base (base_binfo, ctx, ba_unique, NULL, complain);
9506 	  if (base_binfo == error_mark_node)
9507 	    return error_mark_node;
9508 	}
9509 
9510       /* If we know the dynamic type of the object, look up the final overrider
9511 	 in the BINFO.  */
9512       if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0
9513 	  && resolves_to_fixed_type_p (arg))
9514 	{
9515 	  tree ov = lookup_vfn_in_binfo (DECL_VINDEX (fn), base_binfo);
9516 
9517 	  /* And unwind base_binfo to match.  If we don't find the type we're
9518 	     looking for in BINFO_INHERITANCE_CHAIN, we're looking at diamond
9519 	     inheritance; for now do a normal virtual call in that case.  */
9520 	  tree octx = DECL_CONTEXT (ov);
9521 	  tree obinfo = base_binfo;
9522 	  while (obinfo && !SAME_BINFO_TYPE_P (BINFO_TYPE (obinfo), octx))
9523 	    obinfo = BINFO_INHERITANCE_CHAIN (obinfo);
9524 	  if (obinfo)
9525 	    {
9526 	      fn = ov;
9527 	      base_binfo = obinfo;
9528 	      flags |= LOOKUP_NONVIRTUAL;
9529 	    }
9530 	}
9531 
9532       tree converted_arg = build_base_path (PLUS_EXPR, arg,
9533 					    base_binfo, 1, complain);
9534 
9535       argarray[j++] = converted_arg;
9536       parm = TREE_CHAIN (parm);
9537       if (first_arg != NULL_TREE)
9538 	first_arg = NULL_TREE;
9539       else
9540 	++arg_index;
9541       ++i;
9542       is_method = 1;
9543     }
9544 
9545   gcc_assert (first_arg == NULL_TREE);
9546   for (; arg_index < vec_safe_length (args) && parm;
9547        parm = TREE_CHAIN (parm), ++arg_index, ++i)
9548     {
9549       tree type = TREE_VALUE (parm);
9550       tree arg = (*args)[arg_index];
9551       bool conversion_warning = true;
9552 
9553       conv = convs[i];
9554 
9555       /* If the argument is NULL and used to (implicitly) instantiate a
9556          template function (and bind one of the template arguments to
9557          the type of 'long int'), we don't want to warn about passing NULL
9558          to non-pointer argument.
9559          For example, if we have this template function:
9560 
9561            template<typename T> void func(T x) {}
9562 
9563          we want to warn (when -Wconversion is enabled) in this case:
9564 
9565            void foo() {
9566              func<int>(NULL);
9567            }
9568 
9569          but not in this case:
9570 
9571            void foo() {
9572              func(NULL);
9573            }
9574       */
9575       if (null_node_p (arg)
9576           && DECL_TEMPLATE_INFO (fn)
9577           && cand->template_decl
9578 	  && !cand->explicit_targs)
9579         conversion_warning = false;
9580 
9581       /* Set user_conv_p on the argument conversions, so rvalue/base handling
9582 	 knows not to allow any more UDCs.  This needs to happen after we
9583 	 process cand->warnings.  */
9584       if (flags & LOOKUP_NO_CONVERSION)
9585 	conv->user_conv_p = true;
9586 
9587       tsubst_flags_t arg_complain = complain;
9588       if (!conversion_warning)
9589 	arg_complain &= ~tf_warning;
9590 
9591       val = convert_like_with_context (conv, arg, fn, i - is_method,
9592 				       arg_complain);
9593       val = convert_for_arg_passing (type, val, arg_complain);
9594 
9595       if (val == error_mark_node)
9596         return error_mark_node;
9597       else
9598         argarray[j++] = val;
9599     }
9600 
9601   /* Default arguments */
9602   for (; parm && parm != void_list_node; parm = TREE_CHAIN (parm), i++)
9603     {
9604       if (TREE_VALUE (parm) == error_mark_node)
9605 	return error_mark_node;
9606       val = convert_default_arg (TREE_VALUE (parm),
9607 				 TREE_PURPOSE (parm),
9608 				 fn, i - is_method,
9609 				 complain);
9610       if (val == error_mark_node)
9611         return error_mark_node;
9612       argarray[j++] = val;
9613     }
9614 
9615   /* Ellipsis */
9616   int magic = magic_varargs_p (fn);
9617   for (; arg_index < vec_safe_length (args); ++arg_index)
9618     {
9619       tree a = (*args)[arg_index];
9620       if ((magic == 3 && arg_index == 2) || magic == 2)
9621 	{
9622 	  /* Do no conversions for certain magic varargs.  */
9623 	  a = mark_type_use (a);
9624 	  if (TREE_CODE (a) == FUNCTION_DECL && reject_gcc_builtin (a))
9625 	    return error_mark_node;
9626 	}
9627       else if (magic != 0)
9628 	/* For other magic varargs only do decay_conversion.  */
9629 	a = decay_conversion (a, complain);
9630       else if (DECL_CONSTRUCTOR_P (fn)
9631 	       && same_type_ignoring_top_level_qualifiers_p (DECL_CONTEXT (fn),
9632 							     TREE_TYPE (a)))
9633 	{
9634 	  /* Avoid infinite recursion trying to call A(...).  */
9635 	  if (complain & tf_error)
9636 	    /* Try to call the actual copy constructor for a good error.  */
9637 	    call_copy_ctor (a, complain);
9638 	  return error_mark_node;
9639 	}
9640       else
9641 	a = convert_arg_to_ellipsis (a, complain);
9642       if (a == error_mark_node)
9643 	return error_mark_node;
9644       argarray[j++] = a;
9645     }
9646 
9647   gcc_assert (j <= nargs);
9648   nargs = j;
9649   icip.reset ();
9650 
9651   /* Avoid performing argument transformation if warnings are disabled.
9652      When tf_warning is set and at least one of the warnings is active
9653      the check_function_arguments function might warn about something.  */
9654 
9655   bool warned_p = false;
9656   if ((complain & tf_warning)
9657       && (warn_nonnull
9658 	  || warn_format
9659 	  || warn_suggest_attribute_format
9660 	  || warn_restrict))
9661     {
9662       tree *fargs = (!nargs ? argarray
9663 			    : (tree *) alloca (nargs * sizeof (tree)));
9664       for (j = 0; j < nargs; j++)
9665 	{
9666 	  /* For -Wformat undo the implicit passing by hidden reference
9667 	     done by convert_arg_to_ellipsis.  */
9668 	  if (TREE_CODE (argarray[j]) == ADDR_EXPR
9669 	      && TYPE_REF_P (TREE_TYPE (argarray[j])))
9670 	    fargs[j] = TREE_OPERAND (argarray[j], 0);
9671 	  else
9672 	    fargs[j] = argarray[j];
9673 	}
9674 
9675       warned_p = check_function_arguments (input_location, fn, TREE_TYPE (fn),
9676 					   nargs, fargs, NULL);
9677     }
9678 
9679   if (DECL_INHERITED_CTOR (fn))
9680     {
9681       /* Check for passing ellipsis arguments to an inherited constructor.  We
9682 	 could handle this by open-coding the inherited constructor rather than
9683 	 defining it, but let's not bother now.  */
9684       if (!cp_unevaluated_operand
9685 	  && cand->num_convs
9686 	  && cand->convs[cand->num_convs-1]->ellipsis_p)
9687 	{
9688 	  if (complain & tf_error)
9689 	    {
9690 	      sorry ("passing arguments to ellipsis of inherited constructor "
9691 		     "%qD", cand->fn);
9692 	      inform (DECL_SOURCE_LOCATION (cand->fn), "declared here");
9693 	    }
9694 	  return error_mark_node;
9695 	}
9696 
9697       /* A base constructor inheriting from a virtual base doesn't get the
9698 	 inherited arguments, just this and __vtt.  */
9699       if (ctor_omit_inherited_parms (fn))
9700 	nargs = 2;
9701     }
9702 
9703   /* Avoid actually calling copy constructors and copy assignment operators,
9704      if possible.  */
9705 
9706   if (! flag_elide_constructors && !force_elide)
9707     /* Do things the hard way.  */;
9708   else if (cand->num_convs == 1
9709            && (DECL_COPY_CONSTRUCTOR_P (fn)
9710                || DECL_MOVE_CONSTRUCTOR_P (fn))
9711 	   /* It's unsafe to elide the constructor when handling
9712 	      a noexcept-expression, it may evaluate to the wrong
9713 	      value (c++/53025).  */
9714 	   && (force_elide || cp_noexcept_operand == 0))
9715     {
9716       tree targ;
9717       tree arg = argarray[num_artificial_parms_for (fn)];
9718       tree fa = argarray[0];
9719       bool trivial = trivial_fn_p (fn);
9720 
9721       /* Pull out the real argument, disregarding const-correctness.  */
9722       targ = arg;
9723       /* Strip the reference binding for the constructor parameter.  */
9724       if (CONVERT_EXPR_P (targ)
9725 	  && TYPE_REF_P (TREE_TYPE (targ)))
9726 	targ = TREE_OPERAND (targ, 0);
9727       /* But don't strip any other reference bindings; binding a temporary to a
9728 	 reference prevents copy elision.  */
9729       while ((CONVERT_EXPR_P (targ)
9730 	      && !TYPE_REF_P (TREE_TYPE (targ)))
9731 	     || TREE_CODE (targ) == NON_LVALUE_EXPR)
9732 	targ = TREE_OPERAND (targ, 0);
9733       if (TREE_CODE (targ) == ADDR_EXPR)
9734 	{
9735 	  targ = TREE_OPERAND (targ, 0);
9736 	  if (!same_type_ignoring_top_level_qualifiers_p
9737 	      (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
9738 	    targ = NULL_TREE;
9739 	}
9740       else
9741 	targ = NULL_TREE;
9742 
9743       if (targ)
9744 	arg = targ;
9745       else
9746 	arg = cp_build_fold_indirect_ref (arg);
9747 
9748       /* In C++17 we shouldn't be copying a TARGET_EXPR except into a
9749 	 potentially-overlapping subobject.  */
9750       if (CHECKING_P && cxx_dialect >= cxx17)
9751 	gcc_assert (TREE_CODE (arg) != TARGET_EXPR
9752 		    || force_elide
9753 		    /* It's from binding the ref parm to a packed field. */
9754 		    || convs[0]->need_temporary_p
9755 		    || seen_error ()
9756 		    /* See unsafe_copy_elision_p.  */
9757 		    || unsafe_return_slot_p (fa));
9758 
9759       bool unsafe = unsafe_copy_elision_p_opt (fa, arg);
9760       bool eliding_temp = (TREE_CODE (arg) == TARGET_EXPR && !unsafe);
9761 
9762       /* [class.copy]: the copy constructor is implicitly defined even if the
9763 	 implementation elided its use.  But don't warn about deprecation when
9764 	 eliding a temporary, as then no copy is actually performed.  */
9765       warning_sentinel s (warn_deprecated_copy, eliding_temp);
9766       if (force_elide)
9767 	/* The language says this isn't called.  */;
9768       else if (!trivial)
9769 	{
9770 	  if (!mark_used (fn, complain) && !(complain & tf_error))
9771 	    return error_mark_node;
9772 	  already_used = true;
9773 	}
9774       else
9775 	cp_handle_deprecated_or_unavailable (fn, complain);
9776 
9777       if (eliding_temp && DECL_BASE_CONSTRUCTOR_P (fn)
9778 	  && !make_base_init_ok (arg))
9779 	unsafe = true;
9780 
9781       /* If we're creating a temp and we already have one, don't create a
9782 	 new one.  If we're not creating a temp but we get one, use
9783 	 INIT_EXPR to collapse the temp into our target.  Otherwise, if the
9784 	 ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
9785 	 temp or an INIT_EXPR otherwise.  */
9786       if (is_dummy_object (fa))
9787 	{
9788 	  if (TREE_CODE (arg) == TARGET_EXPR)
9789 	    return arg;
9790 	  else if (trivial)
9791 	    return force_target_expr (DECL_CONTEXT (fn), arg, complain);
9792 	}
9793       else if ((trivial || TREE_CODE (arg) == TARGET_EXPR)
9794 	       && !unsafe)
9795 	{
9796 	  tree to = cp_build_fold_indirect_ref (fa);
9797 	  val = build2 (INIT_EXPR, DECL_CONTEXT (fn), to, arg);
9798 	  return val;
9799 	}
9800     }
9801   else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
9802 	   && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR)
9803 	   && trivial_fn_p (fn))
9804     {
9805       /* Don't use cp_build_fold_indirect_ref, op= returns an lvalue even if
9806 	 the object argument isn't one.  */
9807       tree to = cp_build_indirect_ref (input_location, argarray[0],
9808 				       RO_ARROW, complain);
9809       tree type = TREE_TYPE (to);
9810       tree as_base = CLASSTYPE_AS_BASE (type);
9811       tree arg = argarray[1];
9812       location_t loc = cp_expr_loc_or_input_loc (arg);
9813 
9814       if (is_really_empty_class (type, /*ignore_vptr*/true))
9815 	{
9816 	  /* Avoid copying empty classes.  */
9817 	  val = build2 (COMPOUND_EXPR, type, arg, to);
9818 	  suppress_warning (val, OPT_Wunused);
9819 	}
9820       else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
9821 	{
9822 	  if (is_std_init_list (type)
9823 	      && conv_binds_ref_to_prvalue (convs[1]))
9824 	    warning_at (loc, OPT_Winit_list_lifetime,
9825 			"assignment from temporary %<initializer_list%> does "
9826 			"not extend the lifetime of the underlying array");
9827 	  arg = cp_build_fold_indirect_ref (arg);
9828 	  val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
9829 	}
9830       else
9831 	{
9832 	  /* We must only copy the non-tail padding parts.  */
9833 	  tree arg0, arg2, t;
9834 	  tree array_type, alias_set;
9835 
9836 	  arg2 = TYPE_SIZE_UNIT (as_base);
9837 	  to = cp_stabilize_reference (to);
9838 	  arg0 = cp_build_addr_expr (to, complain);
9839 
9840 	  array_type = build_array_type (unsigned_char_type_node,
9841 					 build_index_type
9842 					   (size_binop (MINUS_EXPR,
9843 							arg2, size_int (1))));
9844 	  alias_set = build_int_cst (build_pointer_type (type), 0);
9845 	  t = build2 (MODIFY_EXPR, void_type_node,
9846 		      build2 (MEM_REF, array_type, arg0, alias_set),
9847 		      build2 (MEM_REF, array_type, arg, alias_set));
9848 	  val = build2 (COMPOUND_EXPR, TREE_TYPE (to), t, to);
9849           suppress_warning (val, OPT_Wunused);
9850 	}
9851 
9852       cp_handle_deprecated_or_unavailable (fn, complain);
9853 
9854       return val;
9855     }
9856   else if (trivial_fn_p (fn))
9857     {
9858       if (DECL_DESTRUCTOR_P (fn))
9859 	return build_trivial_dtor_call (argarray[0]);
9860       else if (default_ctor_p (fn))
9861 	{
9862 	  if (is_dummy_object (argarray[0]))
9863 	    return force_target_expr (DECL_CONTEXT (fn), void_node,
9864 				      no_cleanup_complain);
9865 	  else
9866 	    return cp_build_fold_indirect_ref (argarray[0]);
9867 	}
9868     }
9869 
9870   gcc_assert (!force_elide);
9871 
9872   if (!already_used
9873       && !mark_used (fn, complain))
9874     return error_mark_node;
9875 
9876   /* Warn if the built-in writes to an object of a non-trivial type.  */
9877   if (warn_class_memaccess
9878       && vec_safe_length (args) >= 2
9879       && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
9880     maybe_warn_class_memaccess (input_location, fn, args);
9881 
9882   if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
9883     {
9884       tree t;
9885       tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
9886 				DECL_CONTEXT (fn),
9887 				ba_any, NULL, complain);
9888       gcc_assert (binfo && binfo != error_mark_node);
9889 
9890       argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1,
9891 				     complain);
9892       if (TREE_SIDE_EFFECTS (argarray[0]))
9893 	argarray[0] = save_expr (argarray[0]);
9894       t = build_pointer_type (TREE_TYPE (fn));
9895       fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
9896       TREE_TYPE (fn) = t;
9897     }
9898   else
9899     {
9900       /* If FN is marked deprecated, then we've already issued a deprecated-use
9901 	 warning from mark_used above, so avoid redundantly issuing another one
9902 	 from build_addr_func.  */
9903       warning_sentinel w (warn_deprecated_decl);
9904 
9905       fn = build_addr_func (fn, complain);
9906       if (fn == error_mark_node)
9907 	return error_mark_node;
9908     }
9909 
9910   tree call = build_cxx_call (fn, nargs, argarray, complain|decltype_flag);
9911   if (call == error_mark_node)
9912     return call;
9913   if (cand->flags & LOOKUP_LIST_INIT_CTOR)
9914     {
9915       tree c = extract_call_expr (call);
9916       /* build_new_op will clear this when appropriate.  */
9917       CALL_EXPR_ORDERED_ARGS (c) = true;
9918     }
9919   if (warned_p)
9920     {
9921       tree c = extract_call_expr (call);
9922       if (TREE_CODE (c) == CALL_EXPR)
9923 	suppress_warning (c /* Suppress all warnings.  */);
9924     }
9925   if (TREE_CODE (fn) == ADDR_EXPR)
9926     {
9927       tree fndecl = STRIP_TEMPLATE (TREE_OPERAND (fn, 0));
9928       if (immediate_invocation_p (fndecl, nargs))
9929 	{
9930 	  tree obj_arg = NULL_TREE;
9931 	  /* Undo convert_from_reference called by build_cxx_call.  */
9932 	  if (REFERENCE_REF_P (call))
9933 	    call = TREE_OPERAND (call, 0);
9934 	  if (DECL_CONSTRUCTOR_P (fndecl))
9935 	    obj_arg = cand->first_arg ? cand->first_arg : (*args)[0];
9936 	  if (obj_arg && is_dummy_object (obj_arg))
9937 	    {
9938 	      call = build_cplus_new (DECL_CONTEXT (fndecl), call, complain);
9939 	      obj_arg = NULL_TREE;
9940 	    }
9941 	  /* Look through *(const T *)&obj.  */
9942 	  else if (obj_arg && TREE_CODE (obj_arg) == INDIRECT_REF)
9943 	    {
9944 	      tree addr = TREE_OPERAND (obj_arg, 0);
9945 	      STRIP_NOPS (addr);
9946 	      if (TREE_CODE (addr) == ADDR_EXPR)
9947 		{
9948 		  tree typeo = TREE_TYPE (obj_arg);
9949 		  tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
9950 		  if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
9951 		    obj_arg = TREE_OPERAND (addr, 0);
9952 		}
9953 	    }
9954 	  call = cxx_constant_value_sfinae (call, obj_arg, complain);
9955 	  if (obj_arg && !error_operand_p (call))
9956 	    call = build2 (INIT_EXPR, void_type_node, obj_arg, call);
9957 	  call = convert_from_reference (call);
9958 	}
9959     }
9960   return call;
9961 }
9962 
9963 namespace
9964 {
9965 
9966 /* Return the DECL of the first non-static subobject of class TYPE
9967    that satisfies the predicate PRED or null if none can be found.  */
9968 
9969 template <class Predicate>
9970 tree
first_non_static_field(tree type,Predicate pred)9971 first_non_static_field (tree type, Predicate pred)
9972 {
9973   if (!type || !CLASS_TYPE_P (type))
9974     return NULL_TREE;
9975 
9976   for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
9977     {
9978       if (TREE_CODE (field) != FIELD_DECL)
9979 	continue;
9980       if (TREE_STATIC (field))
9981 	continue;
9982       if (pred (field))
9983 	return field;
9984     }
9985 
9986   int i = 0;
9987 
9988   for (tree base_binfo, binfo = TYPE_BINFO (type);
9989        BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
9990     {
9991       tree base = TREE_TYPE (base_binfo);
9992       if (pred (base))
9993 	return base;
9994       if (tree field = first_non_static_field (base, pred))
9995 	return field;
9996     }
9997 
9998   return NULL_TREE;
9999 }
10000 
10001 struct NonPublicField
10002 {
operator ()__anon4ec8517c0711::NonPublicField10003   bool operator() (const_tree t) const
10004   {
10005     return DECL_P (t) && (TREE_PRIVATE (t) || TREE_PROTECTED (t));
10006   }
10007 };
10008 
10009 /* Return the DECL of the first non-public subobject of class TYPE
10010    or null if none can be found.  */
10011 
10012 static inline tree
first_non_public_field(tree type)10013 first_non_public_field (tree type)
10014 {
10015   return first_non_static_field (type, NonPublicField ());
10016 }
10017 
10018 struct NonTrivialField
10019 {
operator ()__anon4ec8517c0711::NonTrivialField10020   bool operator() (const_tree t) const
10021   {
10022     return !trivial_type_p (DECL_P (t) ? TREE_TYPE (t) : t);
10023   }
10024 };
10025 
10026 /* Return the DECL of the first non-trivial subobject of class TYPE
10027    or null if none can be found.  */
10028 
10029 static inline tree
first_non_trivial_field(tree type)10030 first_non_trivial_field (tree type)
10031 {
10032   return first_non_static_field (type, NonTrivialField ());
10033 }
10034 
10035 }   /* unnamed namespace */
10036 
10037 /* Return true if all copy and move assignment operator overloads for
10038    class TYPE are trivial and at least one of them is not deleted and,
10039    when ACCESS is set, accessible.  Return false otherwise.  Set
10040    HASASSIGN to true when the TYPE has a (not necessarily trivial)
10041    copy or move assignment.  */
10042 
10043 static bool
has_trivial_copy_assign_p(tree type,bool access,bool * hasassign)10044 has_trivial_copy_assign_p (tree type, bool access, bool *hasassign)
10045 {
10046   tree fns = get_class_binding (type, assign_op_identifier);
10047   bool all_trivial = true;
10048 
10049   /* Iterate over overloads of the assignment operator, checking
10050      accessible copy assignments for triviality.  */
10051 
10052   for (tree f : ovl_range (fns))
10053     {
10054       /* Skip operators that aren't copy assignments.  */
10055       if (!copy_fn_p (f))
10056 	continue;
10057 
10058       bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10059 			 || accessible_p (TYPE_BINFO (type), f, true));
10060 
10061       /* Skip template assignment operators and deleted functions.  */
10062       if (TREE_CODE (f) != FUNCTION_DECL || DECL_DELETED_FN (f))
10063 	continue;
10064 
10065       if (accessible)
10066 	*hasassign = true;
10067 
10068       if (!accessible || !trivial_fn_p (f))
10069 	all_trivial = false;
10070 
10071       /* Break early when both properties have been determined.  */
10072       if (*hasassign && !all_trivial)
10073 	break;
10074     }
10075 
10076   /* Return true if they're all trivial and one of the expressions
10077      TYPE() = TYPE() or TYPE() = (TYPE&)() is valid.  */
10078   tree ref = cp_build_reference_type (type, false);
10079   return (all_trivial
10080 	  && (is_trivially_xible (MODIFY_EXPR, type, type)
10081 	      || is_trivially_xible (MODIFY_EXPR, type, ref)));
10082 }
10083 
10084 /* Return true if all copy and move ctor overloads for class TYPE are
10085    trivial and at least one of them is not deleted and, when ACCESS is
10086    set, accessible.  Return false otherwise.  Set each element of HASCTOR[]
10087    to true when the TYPE has a (not necessarily trivial) default and copy
10088    (or move) ctor, respectively.  */
10089 
10090 static bool
has_trivial_copy_p(tree type,bool access,bool hasctor[2])10091 has_trivial_copy_p (tree type, bool access, bool hasctor[2])
10092 {
10093   tree fns = get_class_binding (type, complete_ctor_identifier);
10094   bool all_trivial = true;
10095 
10096   for (tree f : ovl_range (fns))
10097     {
10098       /* Skip template constructors.  */
10099       if (TREE_CODE (f) != FUNCTION_DECL)
10100 	continue;
10101 
10102       bool cpy_or_move_ctor_p = copy_fn_p (f);
10103 
10104       /* Skip ctors other than default, copy, and move.  */
10105       if (!cpy_or_move_ctor_p && !default_ctor_p (f))
10106 	continue;
10107 
10108       if (DECL_DELETED_FN (f))
10109 	continue;
10110 
10111       bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10112 			 || accessible_p (TYPE_BINFO (type), f, true));
10113 
10114       if (accessible)
10115 	hasctor[cpy_or_move_ctor_p] = true;
10116 
10117       if (cpy_or_move_ctor_p && (!accessible || !trivial_fn_p (f)))
10118 	all_trivial = false;
10119 
10120       /* Break early when both properties have been determined.  */
10121       if (hasctor[0] && hasctor[1] && !all_trivial)
10122 	break;
10123     }
10124 
10125   return all_trivial;
10126 }
10127 
10128 /* Issue a warning on a call to the built-in function FNDECL if it is
10129    a raw memory write whose destination is not an object of (something
10130    like) trivial or standard layout type with a non-deleted assignment
10131    and copy ctor.  Detects const correctness violations, corrupting
10132    references, virtual table pointers, and bypassing non-trivial
10133    assignments.  */
10134 
10135 static void
maybe_warn_class_memaccess(location_t loc,tree fndecl,const vec<tree,va_gc> * args)10136 maybe_warn_class_memaccess (location_t loc, tree fndecl,
10137 			    const vec<tree, va_gc> *args)
10138 {
10139   /* Except for bcopy where it's second, the destination pointer is
10140      the first argument for all functions handled here.  Compute
10141      the index of the destination and source arguments.  */
10142   unsigned dstidx = DECL_FUNCTION_CODE (fndecl) == BUILT_IN_BCOPY;
10143   unsigned srcidx = !dstidx;
10144 
10145   tree dest = (*args)[dstidx];
10146   if (!TREE_TYPE (dest)
10147       || (TREE_CODE (TREE_TYPE (dest)) != ARRAY_TYPE
10148 	  && !INDIRECT_TYPE_P (TREE_TYPE (dest))))
10149     return;
10150 
10151   tree srctype = NULL_TREE;
10152 
10153   /* Determine the type of the pointed-to object and whether it's
10154      a complete class type.  */
10155   tree desttype = TREE_TYPE (TREE_TYPE (dest));
10156 
10157   if (!desttype || !COMPLETE_TYPE_P (desttype) || !CLASS_TYPE_P (desttype))
10158     return;
10159 
10160   /* Check to see if the raw memory call is made by a non-static member
10161      function with THIS as the destination argument for the destination
10162      type.  If so, and if the class has no non-trivial bases or members,
10163      be more permissive.  */
10164   if (current_function_decl
10165       && DECL_NONSTATIC_MEMBER_FUNCTION_P (current_function_decl)
10166       && is_this_parameter (tree_strip_nop_conversions (dest)))
10167     {
10168       tree ctx = DECL_CONTEXT (current_function_decl);
10169       bool special = same_type_ignoring_top_level_qualifiers_p (ctx, desttype);
10170       tree binfo = TYPE_BINFO (ctx);
10171 
10172       if (special
10173 	  && !BINFO_VTABLE (binfo)
10174 	  && !first_non_trivial_field (desttype))
10175 	return;
10176     }
10177 
10178   /* True if the class is trivial.  */
10179   bool trivial = trivial_type_p (desttype);
10180 
10181   /* Set to true if DESTYPE has an accessible copy assignment.  */
10182   bool hasassign = false;
10183   /* True if all of the class' overloaded copy assignment operators
10184      are all trivial (and not deleted) and at least one of them is
10185      accessible.  */
10186   bool trivassign = has_trivial_copy_assign_p (desttype, true, &hasassign);
10187 
10188   /* Set to true if DESTTYPE has an accessible default and copy ctor,
10189      respectively.  */
10190   bool hasctors[2] = { false, false };
10191 
10192   /* True if all of the class' overloaded copy constructors are all
10193      trivial (and not deleted) and at least one of them is accessible.  */
10194   bool trivcopy = has_trivial_copy_p (desttype, true, hasctors);
10195 
10196   /* Set FLD to the first private/protected member of the class.  */
10197   tree fld = trivial ? first_non_public_field (desttype) : NULL_TREE;
10198 
10199   /* The warning format string.  */
10200   const char *warnfmt = NULL;
10201   /* A suggested alternative to offer instead of the raw memory call.
10202      Empty string when none can be come up with.  */
10203   const char *suggest = "";
10204   bool warned = false;
10205 
10206   switch (DECL_FUNCTION_CODE (fndecl))
10207     {
10208     case BUILT_IN_MEMSET:
10209       if (!integer_zerop (maybe_constant_value ((*args)[1])))
10210 	{
10211 	  /* Diagnose setting non-copy-assignable or non-trivial types,
10212 	     or types with a private member, to (potentially) non-zero
10213 	     bytes.  Since the value of the bytes being written is unknown,
10214 	     suggest using assignment instead (if one exists).  Also warn
10215 	     for writes into objects for which zero-initialization doesn't
10216 	     mean all bits clear (pointer-to-member data, where null is all
10217 	     bits set).  Since the value being written is (most likely)
10218 	     non-zero, simply suggest assignment (but not copy assignment).  */
10219 	  suggest = "; use assignment instead";
10220 	  if (!trivassign)
10221 	    warnfmt = G_("%qD writing to an object of type %#qT with "
10222 			 "no trivial copy-assignment");
10223 	  else if (!trivial)
10224 	    warnfmt = G_("%qD writing to an object of non-trivial type %#qT%s");
10225 	  else if (fld)
10226 	    {
10227 	      const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10228 	      warned = warning_at (loc, OPT_Wclass_memaccess,
10229 				   "%qD writing to an object of type %#qT with "
10230 				   "%qs member %qD",
10231 				   fndecl, desttype, access, fld);
10232 	    }
10233 	  else if (!zero_init_p (desttype))
10234 	    warnfmt = G_("%qD writing to an object of type %#qT containing "
10235 			 "a pointer to data member%s");
10236 
10237 	  break;
10238 	}
10239       /* Fall through.  */
10240 
10241     case BUILT_IN_BZERO:
10242       /* Similarly to the above, diagnose clearing non-trivial or non-
10243 	 standard layout objects, or objects of types with no assignmenmt.
10244 	 Since the value being written is known to be zero, suggest either
10245 	 copy assignment, copy ctor, or default ctor as an alternative,
10246 	 depending on what's available.  */
10247 
10248       if (hasassign && hasctors[0])
10249 	suggest = G_("; use assignment or value-initialization instead");
10250       else if (hasassign)
10251 	suggest = G_("; use assignment instead");
10252       else if (hasctors[0])
10253 	suggest = G_("; use value-initialization instead");
10254 
10255       if (!trivassign)
10256 	warnfmt = G_("%qD clearing an object of type %#qT with "
10257 		     "no trivial copy-assignment%s");
10258       else if (!trivial)
10259 	warnfmt =  G_("%qD clearing an object of non-trivial type %#qT%s");
10260       else if (!zero_init_p (desttype))
10261 	warnfmt = G_("%qD clearing an object of type %#qT containing "
10262 		     "a pointer-to-member%s");
10263       break;
10264 
10265     case BUILT_IN_BCOPY:
10266     case BUILT_IN_MEMCPY:
10267     case BUILT_IN_MEMMOVE:
10268     case BUILT_IN_MEMPCPY:
10269       /* Determine the type of the source object.  */
10270       srctype = TREE_TYPE ((*args)[srcidx]);
10271       if (!srctype || !INDIRECT_TYPE_P (srctype))
10272 	srctype = void_type_node;
10273       else
10274 	srctype = TREE_TYPE (srctype);
10275 
10276       /* Since it's impossible to determine wheter the byte copy is
10277 	 being used in place of assignment to an existing object or
10278 	 as a substitute for initialization, assume it's the former.
10279 	 Determine the best alternative to use instead depending on
10280 	 what's not deleted.  */
10281       if (hasassign && hasctors[1])
10282 	suggest = G_("; use copy-assignment or copy-initialization instead");
10283       else if (hasassign)
10284 	suggest = G_("; use copy-assignment instead");
10285       else if (hasctors[1])
10286 	suggest = G_("; use copy-initialization instead");
10287 
10288       if (!trivassign)
10289 	warnfmt = G_("%qD writing to an object of type %#qT with no trivial "
10290 		     "copy-assignment%s");
10291       else if (!trivially_copyable_p (desttype))
10292 	warnfmt = G_("%qD writing to an object of non-trivially copyable "
10293 		     "type %#qT%s");
10294       else if (!trivcopy)
10295 	warnfmt = G_("%qD writing to an object with a deleted copy constructor");
10296 
10297       else if (!trivial
10298 	       && !VOID_TYPE_P (srctype)
10299 	       && !is_byte_access_type (srctype)
10300 	       && !same_type_ignoring_top_level_qualifiers_p (desttype,
10301 							      srctype))
10302 	{
10303 	  /* Warn when copying into a non-trivial object from an object
10304 	     of a different type other than void or char.  */
10305 	  warned = warning_at (loc, OPT_Wclass_memaccess,
10306 			       "%qD copying an object of non-trivial type "
10307 			       "%#qT from an array of %#qT",
10308 			       fndecl, desttype, srctype);
10309 	}
10310       else if (fld
10311 	       && !VOID_TYPE_P (srctype)
10312 	       && !is_byte_access_type (srctype)
10313 	       && !same_type_ignoring_top_level_qualifiers_p (desttype,
10314 							      srctype))
10315 	{
10316 	  const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10317 	  warned = warning_at (loc, OPT_Wclass_memaccess,
10318 			       "%qD copying an object of type %#qT with "
10319 			       "%qs member %qD from an array of %#qT; use "
10320 			       "assignment or copy-initialization instead",
10321 			       fndecl, desttype, access, fld, srctype);
10322 	}
10323       else if (!trivial && vec_safe_length (args) > 2)
10324 	{
10325 	  tree sz = maybe_constant_value ((*args)[2]);
10326 	  if (!tree_fits_uhwi_p (sz))
10327 	    break;
10328 
10329 	  /* Finally, warn on partial copies.  */
10330 	  unsigned HOST_WIDE_INT typesize
10331 	    = tree_to_uhwi (TYPE_SIZE_UNIT (desttype));
10332 	  if (typesize == 0)
10333 	    break;
10334 	  if (unsigned HOST_WIDE_INT partial = tree_to_uhwi (sz) % typesize)
10335 	    warned = warning_at (loc, OPT_Wclass_memaccess,
10336 				 (typesize - partial > 1
10337 				  ? G_("%qD writing to an object of "
10338 				       "a non-trivial type %#qT leaves %wu "
10339 				       "bytes unchanged")
10340 				  : G_("%qD writing to an object of "
10341 				       "a non-trivial type %#qT leaves %wu "
10342 				       "byte unchanged")),
10343 				 fndecl, desttype, typesize - partial);
10344 	}
10345       break;
10346 
10347     case BUILT_IN_REALLOC:
10348 
10349       if (!trivially_copyable_p (desttype))
10350 	warnfmt = G_("%qD moving an object of non-trivially copyable type "
10351 		     "%#qT; use %<new%> and %<delete%> instead");
10352       else if (!trivcopy)
10353 	warnfmt = G_("%qD moving an object of type %#qT with deleted copy "
10354 		     "constructor; use %<new%> and %<delete%> instead");
10355       else if (!get_dtor (desttype, tf_none))
10356 	warnfmt = G_("%qD moving an object of type %#qT with deleted "
10357 		     "destructor");
10358       else if (!trivial)
10359 	{
10360 	  tree sz = maybe_constant_value ((*args)[1]);
10361 	  if (TREE_CODE (sz) == INTEGER_CST
10362 	      && tree_int_cst_lt (sz, TYPE_SIZE_UNIT (desttype)))
10363 	    /* Finally, warn on reallocation into insufficient space.  */
10364 	    warned = warning_at (loc, OPT_Wclass_memaccess,
10365 				 "%qD moving an object of non-trivial type "
10366 				 "%#qT and size %E into a region of size %E",
10367 				 fndecl, desttype, TYPE_SIZE_UNIT (desttype),
10368 				 sz);
10369 	}
10370       break;
10371 
10372     default:
10373       return;
10374     }
10375 
10376   if (warnfmt)
10377     {
10378       if (suggest)
10379 	warned = warning_at (loc, OPT_Wclass_memaccess,
10380 			     warnfmt, fndecl, desttype, suggest);
10381       else
10382 	warned = warning_at (loc, OPT_Wclass_memaccess,
10383 			     warnfmt, fndecl, desttype);
10384     }
10385 
10386   if (warned)
10387     inform (location_of (desttype), "%#qT declared here", desttype);
10388 }
10389 
10390 /* Build and return a call to FN, using NARGS arguments in ARGARRAY.
10391    If FN is the result of resolving an overloaded target built-in,
10392    ORIG_FNDECL is the original function decl, otherwise it is null.
10393    This function performs no overload resolution, conversion, or other
10394    high-level operations.  */
10395 
10396 tree
build_cxx_call(tree fn,int nargs,tree * argarray,tsubst_flags_t complain,tree orig_fndecl)10397 build_cxx_call (tree fn, int nargs, tree *argarray,
10398 		tsubst_flags_t complain, tree orig_fndecl)
10399 {
10400   tree fndecl;
10401 
10402   /* Remember roughly where this call is.  */
10403   location_t loc = cp_expr_loc_or_input_loc (fn);
10404   fn = build_call_a (fn, nargs, argarray);
10405   SET_EXPR_LOCATION (fn, loc);
10406 
10407   fndecl = get_callee_fndecl (fn);
10408   if (!orig_fndecl)
10409     orig_fndecl = fndecl;
10410 
10411   /* Check that arguments to builtin functions match the expectations.  */
10412   if (fndecl
10413       && !processing_template_decl
10414       && fndecl_built_in_p (fndecl))
10415     {
10416       int i;
10417 
10418       /* We need to take care that values to BUILT_IN_NORMAL
10419          are reduced.  */
10420       for (i = 0; i < nargs; i++)
10421 	argarray[i] = maybe_constant_value (argarray[i]);
10422 
10423       if (!check_builtin_function_arguments (EXPR_LOCATION (fn), vNULL, fndecl,
10424 					     orig_fndecl, nargs, argarray))
10425 	return error_mark_node;
10426       else if (fndecl_built_in_p (fndecl, BUILT_IN_CLEAR_PADDING))
10427 	{
10428 	  tree arg0 = argarray[0];
10429 	  STRIP_NOPS (arg0);
10430 	  if (TREE_CODE (arg0) == ADDR_EXPR
10431 	      && DECL_P (TREE_OPERAND (arg0, 0))
10432 	      && same_type_ignoring_top_level_qualifiers_p
10433 			(TREE_TYPE (TREE_TYPE (argarray[0])),
10434 			 TREE_TYPE (TREE_TYPE (arg0))))
10435 	    /* For __builtin_clear_padding (&var) we know the type
10436 	       is for a complete object, so there is no risk in clearing
10437 	       padding that is reused in some derived class member.  */;
10438 	  else if (!trivially_copyable_p (TREE_TYPE (TREE_TYPE (argarray[0]))))
10439 	    {
10440 	      error_at (EXPR_LOC_OR_LOC (argarray[0], input_location),
10441 			"argument %u in call to function %qE "
10442 			"has pointer to a non-trivially-copyable type (%qT)",
10443 			1, fndecl, TREE_TYPE (argarray[0]));
10444 	      return error_mark_node;
10445 	    }
10446 	}
10447     }
10448 
10449   if (VOID_TYPE_P (TREE_TYPE (fn)))
10450     return fn;
10451 
10452   /* 5.2.2/11: If a function call is a prvalue of object type: if the
10453      function call is either the operand of a decltype-specifier or the
10454      right operand of a comma operator that is the operand of a
10455      decltype-specifier, a temporary object is not introduced for the
10456      prvalue. The type of the prvalue may be incomplete.  */
10457   if (!(complain & tf_decltype))
10458     {
10459       fn = require_complete_type_sfinae (fn, complain);
10460       if (fn == error_mark_node)
10461 	return error_mark_node;
10462 
10463       if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
10464 	{
10465 	  fn = build_cplus_new (TREE_TYPE (fn), fn, complain);
10466 	  maybe_warn_parm_abi (TREE_TYPE (fn), loc);
10467 	}
10468     }
10469   return convert_from_reference (fn);
10470 }
10471 
10472 /* Returns the value to use for the in-charge parameter when making a
10473    call to a function with the indicated NAME.
10474 
10475    FIXME:Can't we find a neater way to do this mapping?  */
10476 
10477 tree
in_charge_arg_for_name(tree name)10478 in_charge_arg_for_name (tree name)
10479 {
10480   if (IDENTIFIER_CTOR_P (name))
10481     {
10482       if (name == complete_ctor_identifier)
10483 	return integer_one_node;
10484       gcc_checking_assert (name == base_ctor_identifier);
10485     }
10486   else
10487     {
10488       if (name == complete_dtor_identifier)
10489 	return integer_two_node;
10490       else if (name == deleting_dtor_identifier)
10491 	return integer_three_node;
10492       gcc_checking_assert (name == base_dtor_identifier);
10493     }
10494 
10495   return integer_zero_node;
10496 }
10497 
10498 /* We've built up a constructor call RET.  Complain if it delegates to the
10499    constructor we're currently compiling.  */
10500 
10501 static void
check_self_delegation(tree ret)10502 check_self_delegation (tree ret)
10503 {
10504   if (TREE_CODE (ret) == TARGET_EXPR)
10505     ret = TARGET_EXPR_INITIAL (ret);
10506   tree fn = cp_get_callee_fndecl_nofold (ret);
10507   if (fn && DECL_ABSTRACT_ORIGIN (fn) == current_function_decl)
10508     error ("constructor delegates to itself");
10509 }
10510 
10511 /* Build a call to a constructor, destructor, or an assignment
10512    operator for INSTANCE, an expression with class type.  NAME
10513    indicates the special member function to call; *ARGS are the
10514    arguments.  ARGS may be NULL.  This may change ARGS.  BINFO
10515    indicates the base of INSTANCE that is to be passed as the `this'
10516    parameter to the member function called.
10517 
10518    FLAGS are the LOOKUP_* flags to use when processing the call.
10519 
10520    If NAME indicates a complete object constructor, INSTANCE may be
10521    NULL_TREE.  In this case, the caller will call build_cplus_new to
10522    store the newly constructed object into a VAR_DECL.  */
10523 
10524 tree
build_special_member_call(tree instance,tree name,vec<tree,va_gc> ** args,tree binfo,int flags,tsubst_flags_t complain)10525 build_special_member_call (tree instance, tree name, vec<tree, va_gc> **args,
10526 			   tree binfo, int flags, tsubst_flags_t complain)
10527 {
10528   tree fns;
10529   /* The type of the subobject to be constructed or destroyed.  */
10530   tree class_type;
10531   vec<tree, va_gc> *allocated = NULL;
10532   tree ret;
10533 
10534   gcc_assert (IDENTIFIER_CDTOR_P (name) || name == assign_op_identifier);
10535 
10536   if (error_operand_p (instance))
10537     return error_mark_node;
10538 
10539   if (IDENTIFIER_DTOR_P (name))
10540     {
10541       gcc_assert (args == NULL || vec_safe_is_empty (*args));
10542       if (!type_build_dtor_call (TREE_TYPE (instance)))
10543 	/* Shortcut to avoid lazy destructor declaration.  */
10544 	return build_trivial_dtor_call (instance);
10545     }
10546 
10547   if (TYPE_P (binfo))
10548     {
10549       /* Resolve the name.  */
10550       if (!complete_type_or_maybe_complain (binfo, NULL_TREE, complain))
10551 	return error_mark_node;
10552 
10553       binfo = TYPE_BINFO (binfo);
10554     }
10555 
10556   gcc_assert (binfo != NULL_TREE);
10557 
10558   class_type = BINFO_TYPE (binfo);
10559 
10560   /* Handle the special case where INSTANCE is NULL_TREE.  */
10561   if (name == complete_ctor_identifier && !instance)
10562     instance = build_dummy_object (class_type);
10563   else
10564     {
10565       /* Convert to the base class, if necessary.  */
10566       if (!same_type_ignoring_top_level_qualifiers_p
10567 	  (TREE_TYPE (instance), BINFO_TYPE (binfo)))
10568 	{
10569 	  if (IDENTIFIER_CDTOR_P (name))
10570 	    /* For constructors and destructors, either the base is
10571 	       non-virtual, or it is virtual but we are doing the
10572 	       conversion from a constructor or destructor for the
10573 	       complete object.  In either case, we can convert
10574 	       statically.  */
10575 	    instance = convert_to_base_statically (instance, binfo);
10576 	  else
10577 	    {
10578 	      /* However, for assignment operators, we must convert
10579 		 dynamically if the base is virtual.  */
10580 	      gcc_checking_assert (name == assign_op_identifier);
10581 	      instance = build_base_path (PLUS_EXPR, instance,
10582 					  binfo, /*nonnull=*/1, complain);
10583 	    }
10584 	}
10585     }
10586 
10587   gcc_assert (instance != NULL_TREE);
10588 
10589   /* In C++17, "If the initializer expression is a prvalue and the
10590      cv-unqualified version of the source type is the same class as the class
10591      of the destination, the initializer expression is used to initialize the
10592      destination object."  Handle that here to avoid doing overload
10593      resolution.  */
10594   if (cxx_dialect >= cxx17
10595       && args && vec_safe_length (*args) == 1
10596       && !unsafe_return_slot_p (instance))
10597     {
10598       tree arg = (**args)[0];
10599 
10600       if (BRACE_ENCLOSED_INITIALIZER_P (arg)
10601 	  && !TYPE_HAS_LIST_CTOR (class_type)
10602 	  && !CONSTRUCTOR_IS_DESIGNATED_INIT (arg)
10603 	  && CONSTRUCTOR_NELTS (arg) == 1)
10604 	arg = CONSTRUCTOR_ELT (arg, 0)->value;
10605 
10606       if ((TREE_CODE (arg) == TARGET_EXPR
10607 	   || TREE_CODE (arg) == CONSTRUCTOR)
10608 	  && (same_type_ignoring_top_level_qualifiers_p
10609 	      (class_type, TREE_TYPE (arg))))
10610 	{
10611 	  if (is_dummy_object (instance))
10612 	    return arg;
10613 	  else if (TREE_CODE (arg) == TARGET_EXPR)
10614 	    TARGET_EXPR_DIRECT_INIT_P (arg) = true;
10615 
10616 	  if ((complain & tf_error)
10617 	      && (flags & LOOKUP_DELEGATING_CONS))
10618 	    check_self_delegation (arg);
10619 	  /* Avoid change of behavior on Wunused-var-2.C.  */
10620 	  instance = mark_lvalue_use (instance);
10621 	  return build2 (INIT_EXPR, class_type, instance, arg);
10622 	}
10623     }
10624 
10625   fns = lookup_fnfields (binfo, name, 1, complain);
10626 
10627   /* When making a call to a constructor or destructor for a subobject
10628      that uses virtual base classes, pass down a pointer to a VTT for
10629      the subobject.  */
10630   if ((name == base_ctor_identifier
10631        || name == base_dtor_identifier)
10632       && CLASSTYPE_VBASECLASSES (class_type))
10633     {
10634       tree vtt;
10635       tree sub_vtt;
10636 
10637       /* If the current function is a complete object constructor
10638 	 or destructor, then we fetch the VTT directly.
10639 	 Otherwise, we look it up using the VTT we were given.  */
10640       vtt = DECL_CHAIN (CLASSTYPE_VTABLES (current_class_type));
10641       vtt = decay_conversion (vtt, complain);
10642       if (vtt == error_mark_node)
10643 	return error_mark_node;
10644       vtt = build_if_in_charge (vtt, current_vtt_parm);
10645       if (BINFO_SUBVTT_INDEX (binfo))
10646 	sub_vtt = fold_build_pointer_plus (vtt, BINFO_SUBVTT_INDEX (binfo));
10647       else
10648 	sub_vtt = vtt;
10649 
10650       if (args == NULL)
10651 	{
10652 	  allocated = make_tree_vector ();
10653 	  args = &allocated;
10654 	}
10655 
10656       vec_safe_insert (*args, 0, sub_vtt);
10657     }
10658 
10659   ret = build_new_method_call (instance, fns, args,
10660 			       TYPE_BINFO (BINFO_TYPE (binfo)),
10661 			       flags, /*fn=*/NULL,
10662 			       complain);
10663 
10664   if (allocated != NULL)
10665     release_tree_vector (allocated);
10666 
10667   if ((complain & tf_error)
10668       && (flags & LOOKUP_DELEGATING_CONS)
10669       && name == complete_ctor_identifier)
10670     check_self_delegation (ret);
10671 
10672   return ret;
10673 }
10674 
10675 /* Return the NAME, as a C string.  The NAME indicates a function that
10676    is a member of TYPE.  *FREE_P is set to true if the caller must
10677    free the memory returned.
10678 
10679    Rather than go through all of this, we should simply set the names
10680    of constructors and destructors appropriately, and dispense with
10681    ctor_identifier, dtor_identifier, etc.  */
10682 
10683 static char *
name_as_c_string(tree name,tree type,bool * free_p)10684 name_as_c_string (tree name, tree type, bool *free_p)
10685 {
10686   const char *pretty_name;
10687 
10688   /* Assume that we will not allocate memory.  */
10689   *free_p = false;
10690   /* Constructors and destructors are special.  */
10691   if (IDENTIFIER_CDTOR_P (name))
10692     {
10693       pretty_name
10694 	= identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type)));
10695       /* For a destructor, add the '~'.  */
10696       if (IDENTIFIER_DTOR_P (name))
10697 	{
10698 	  pretty_name = concat ("~", pretty_name, NULL);
10699 	  /* Remember that we need to free the memory allocated.  */
10700 	  *free_p = true;
10701 	}
10702     }
10703   else if (IDENTIFIER_CONV_OP_P (name))
10704     {
10705       pretty_name = concat ("operator ",
10706 			    type_as_string_translate (TREE_TYPE (name),
10707 						      TFF_PLAIN_IDENTIFIER),
10708 			    NULL);
10709       /* Remember that we need to free the memory allocated.  */
10710       *free_p = true;
10711     }
10712   else
10713     pretty_name = identifier_to_locale (IDENTIFIER_POINTER (name));
10714 
10715   return CONST_CAST (char *, pretty_name);
10716 }
10717 
10718 /* If CANDIDATES contains exactly one candidate, return it, otherwise
10719    return NULL.  */
10720 
10721 static z_candidate *
single_z_candidate(z_candidate * candidates)10722 single_z_candidate (z_candidate *candidates)
10723 {
10724   if (candidates == NULL)
10725     return NULL;
10726 
10727   if (candidates->next)
10728     return NULL;
10729 
10730   return candidates;
10731 }
10732 
10733 /* If CANDIDATE is invalid due to a bad argument type, return the
10734    pertinent conversion_info.
10735 
10736    Otherwise, return NULL.  */
10737 
10738 static const conversion_info *
maybe_get_bad_conversion_for_unmatched_call(const z_candidate * candidate)10739 maybe_get_bad_conversion_for_unmatched_call (const z_candidate *candidate)
10740 {
10741   /* Must be an rr_arg_conversion or rr_bad_arg_conversion.  */
10742   rejection_reason *r = candidate->reason;
10743 
10744   if (r == NULL)
10745     return NULL;
10746 
10747   switch (r->code)
10748     {
10749     default:
10750       return NULL;
10751 
10752     case rr_arg_conversion:
10753       return &r->u.conversion;
10754 
10755     case rr_bad_arg_conversion:
10756       return &r->u.bad_conversion;
10757     }
10758 }
10759 
10760 /* Issue an error and note complaining about a bad argument type at a
10761    callsite with a single candidate FNDECL.
10762 
10763    ARG_LOC is the location of the argument (or UNKNOWN_LOCATION, in which
10764    case input_location is used).
10765    FROM_TYPE is the type of the actual argument; TO_TYPE is the type of
10766    the formal parameter.  */
10767 
10768 void
complain_about_bad_argument(location_t arg_loc,tree from_type,tree to_type,tree fndecl,int parmnum)10769 complain_about_bad_argument (location_t arg_loc,
10770 			     tree from_type, tree to_type,
10771 			     tree fndecl, int parmnum)
10772 {
10773   auto_diagnostic_group d;
10774   range_label_for_type_mismatch rhs_label (from_type, to_type);
10775   range_label *label = &rhs_label;
10776   if (arg_loc == UNKNOWN_LOCATION)
10777     {
10778       arg_loc = input_location;
10779       label = NULL;
10780     }
10781   gcc_rich_location richloc (arg_loc, label);
10782   error_at (&richloc,
10783 	    "cannot convert %qH to %qI",
10784 	    from_type, to_type);
10785   maybe_inform_about_fndecl_for_bogus_argument_init (fndecl,
10786 						     parmnum);
10787 }
10788 
10789 /* Subroutine of build_new_method_call_1, for where there are no viable
10790    candidates for the call.  */
10791 
10792 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)10793 complain_about_no_candidates_for_method_call (tree instance,
10794 					      z_candidate *candidates,
10795 					      tree explicit_targs,
10796 					      tree basetype,
10797 					      tree optype, tree name,
10798 					      bool skip_first_for_error,
10799 					      vec<tree, va_gc> *user_args)
10800 {
10801   auto_diagnostic_group d;
10802   if (!COMPLETE_OR_OPEN_TYPE_P (basetype))
10803     cxx_incomplete_type_error (instance, basetype);
10804   else if (optype)
10805     error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
10806 	   basetype, optype, build_tree_list_vec (user_args),
10807 	   TREE_TYPE (instance));
10808   else
10809     {
10810       /* Special-case for when there's a single candidate that's failing
10811 	 due to a bad argument type.  */
10812       if (z_candidate *candidate = single_z_candidate (candidates))
10813 	  if (const conversion_info *conv
10814 		= maybe_get_bad_conversion_for_unmatched_call (candidate))
10815 	    {
10816 	      tree from_type = conv->from;
10817 	      if (!TYPE_P (conv->from))
10818 		from_type = lvalue_type (conv->from);
10819 	      complain_about_bad_argument (conv->loc,
10820 					   from_type, conv->to_type,
10821 					   candidate->fn, conv->n_arg);
10822 	      return;
10823 	    }
10824 
10825       tree arglist = build_tree_list_vec (user_args);
10826       tree errname = name;
10827       bool twiddle = false;
10828       if (IDENTIFIER_CDTOR_P (errname))
10829 	{
10830 	  twiddle = IDENTIFIER_DTOR_P (errname);
10831 	  errname = constructor_name (basetype);
10832 	}
10833       if (explicit_targs)
10834 	errname = lookup_template_function (errname, explicit_targs);
10835       if (skip_first_for_error)
10836 	arglist = TREE_CHAIN (arglist);
10837       error ("no matching function for call to %<%T::%s%E(%A)%#V%>",
10838 	     basetype, &"~"[!twiddle], errname, arglist,
10839 	     TREE_TYPE (instance));
10840     }
10841   print_z_candidates (location_of (name), candidates);
10842 }
10843 
10844 /* Build a call to "INSTANCE.FN (ARGS)".  If FN_P is non-NULL, it will
10845    be set, upon return, to the function called.  ARGS may be NULL.
10846    This may change ARGS.  */
10847 
10848 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)10849 build_new_method_call (tree instance, tree fns, vec<tree, va_gc> **args,
10850 		       tree conversion_path, int flags,
10851 		       tree *fn_p, tsubst_flags_t complain)
10852 {
10853   struct z_candidate *candidates = 0, *cand;
10854   tree explicit_targs = NULL_TREE;
10855   tree basetype = NULL_TREE;
10856   tree access_binfo;
10857   tree optype;
10858   tree first_mem_arg = NULL_TREE;
10859   tree name;
10860   bool skip_first_for_error;
10861   vec<tree, va_gc> *user_args;
10862   tree call;
10863   tree fn;
10864   int template_only = 0;
10865   bool any_viable_p;
10866   tree orig_instance;
10867   tree orig_fns;
10868   vec<tree, va_gc> *orig_args = NULL;
10869   void *p;
10870 
10871   auto_cond_timevar tv (TV_OVERLOAD);
10872 
10873   gcc_assert (instance != NULL_TREE);
10874 
10875   /* We don't know what function we're going to call, yet.  */
10876   if (fn_p)
10877     *fn_p = NULL_TREE;
10878 
10879   if (error_operand_p (instance)
10880       || !fns || error_operand_p (fns))
10881     return error_mark_node;
10882 
10883   if (!BASELINK_P (fns))
10884     {
10885       if (complain & tf_error)
10886 	error ("call to non-function %qD", fns);
10887       return error_mark_node;
10888     }
10889 
10890   orig_instance = instance;
10891   orig_fns = fns;
10892 
10893   /* Dismantle the baselink to collect all the information we need.  */
10894   if (!conversion_path)
10895     conversion_path = BASELINK_BINFO (fns);
10896   access_binfo = BASELINK_ACCESS_BINFO (fns);
10897   optype = BASELINK_OPTYPE (fns);
10898   fns = BASELINK_FUNCTIONS (fns);
10899   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10900     {
10901       explicit_targs = TREE_OPERAND (fns, 1);
10902       fns = TREE_OPERAND (fns, 0);
10903       template_only = 1;
10904     }
10905   gcc_assert (OVL_P (fns));
10906   fn = OVL_FIRST (fns);
10907   name = DECL_NAME (fn);
10908 
10909   basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
10910   gcc_assert (CLASS_TYPE_P (basetype));
10911 
10912   user_args = args == NULL ? NULL : *args;
10913   /* Under DR 147 A::A() is an invalid constructor call,
10914      not a functional cast.  */
10915   if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
10916     {
10917       if (! (complain & tf_error))
10918 	return error_mark_node;
10919 
10920       basetype = DECL_CONTEXT (fn);
10921       name = constructor_name (basetype);
10922       auto_diagnostic_group d;
10923       if (permerror (input_location,
10924 		     "cannot call constructor %<%T::%D%> directly",
10925 		     basetype, name))
10926 	inform (input_location, "for a function-style cast, remove the "
10927 		"redundant %<::%D%>", name);
10928       call = build_functional_cast (input_location, basetype,
10929 				    build_tree_list_vec (user_args),
10930 				    complain);
10931       return call;
10932     }
10933 
10934   if (processing_template_decl)
10935     {
10936       orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
10937       instance = build_non_dependent_expr (instance);
10938       if (args != NULL)
10939 	make_args_non_dependent (*args);
10940     }
10941 
10942   /* Process the argument list.  */
10943   if (args != NULL && *args != NULL)
10944     {
10945       *args = resolve_args (*args, complain);
10946       if (*args == NULL)
10947 	return error_mark_node;
10948       user_args = *args;
10949     }
10950 
10951   /* Consider the object argument to be used even if we end up selecting a
10952      static member function.  */
10953   instance = mark_type_use (instance);
10954 
10955   /* Figure out whether to skip the first argument for the error
10956      message we will display to users if an error occurs.  We don't
10957      want to display any compiler-generated arguments.  The "this"
10958      pointer hasn't been added yet.  However, we must remove the VTT
10959      pointer if this is a call to a base-class constructor or
10960      destructor.  */
10961   skip_first_for_error = false;
10962   if (IDENTIFIER_CDTOR_P (name))
10963     {
10964       /* Callers should explicitly indicate whether they want to ctor
10965 	 the complete object or just the part without virtual bases.  */
10966       gcc_assert (name != ctor_identifier);
10967 
10968       /* Remove the VTT pointer, if present.  */
10969       if ((name == base_ctor_identifier || name == base_dtor_identifier)
10970 	  && CLASSTYPE_VBASECLASSES (basetype))
10971 	skip_first_for_error = true;
10972 
10973       /* It's OK to call destructors and constructors on cv-qualified
10974 	 objects.  Therefore, convert the INSTANCE to the unqualified
10975 	 type, if necessary.  */
10976       if (!same_type_p (basetype, TREE_TYPE (instance)))
10977 	{
10978 	  instance = build_this (instance);
10979 	  instance = build_nop (build_pointer_type (basetype), instance);
10980 	  instance = build_fold_indirect_ref (instance);
10981 	}
10982     }
10983   else
10984     gcc_assert (!DECL_DESTRUCTOR_P (fn) && !DECL_CONSTRUCTOR_P (fn));
10985 
10986   /* For the overload resolution we need to find the actual `this`
10987      that would be captured if the call turns out to be to a
10988      non-static member function.  Do not actually capture it at this
10989      point.  */
10990   if (DECL_CONSTRUCTOR_P (fn))
10991     /* Constructors don't use the enclosing 'this'.  */
10992     first_mem_arg = instance;
10993   else
10994     first_mem_arg = maybe_resolve_dummy (instance, false);
10995 
10996   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
10997   p = conversion_obstack_alloc (0);
10998 
10999   /* The number of arguments artificial parms in ARGS; we subtract one because
11000      there's no 'this' in ARGS.  */
11001   unsigned skip = num_artificial_parms_for (fn) - 1;
11002 
11003   /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
11004      initializer, not T({ }).  */
11005   if (DECL_CONSTRUCTOR_P (fn)
11006       && vec_safe_length (user_args) > skip
11007       && DIRECT_LIST_INIT_P ((*user_args)[skip]))
11008     {
11009       tree init_list = (*user_args)[skip];
11010       tree init = NULL_TREE;
11011 
11012       gcc_assert (user_args->length () == skip + 1
11013 		  && !(flags & LOOKUP_ONLYCONVERTING));
11014 
11015       /* If the initializer list has no elements and T is a class type with
11016 	 a default constructor, the object is value-initialized.  Handle
11017 	 this here so we don't need to handle it wherever we use
11018 	 build_special_member_call.  */
11019       if (CONSTRUCTOR_NELTS (init_list) == 0
11020 	  && TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
11021 	  /* For a user-provided default constructor, use the normal
11022 	     mechanisms so that protected access works.  */
11023 	  && type_has_non_user_provided_default_constructor (basetype)
11024 	  && !processing_template_decl)
11025 	init = build_value_init (basetype, complain);
11026 
11027       /* If BASETYPE is an aggregate, we need to do aggregate
11028 	 initialization.  */
11029       else if (CP_AGGREGATE_TYPE_P (basetype))
11030 	{
11031 	  init = reshape_init (basetype, init_list, complain);
11032 	  init = digest_init (basetype, init, complain);
11033 	}
11034 
11035       if (init)
11036 	{
11037 	  if (is_dummy_object (instance))
11038 	    return get_target_expr_sfinae (init, complain);
11039 	  init = build2 (INIT_EXPR, TREE_TYPE (instance), instance, init);
11040 	  TREE_SIDE_EFFECTS (init) = true;
11041 	  return init;
11042 	}
11043 
11044       /* Otherwise go ahead with overload resolution.  */
11045       add_list_candidates (fns, first_mem_arg, user_args,
11046 			   basetype, explicit_targs, template_only,
11047 			   conversion_path, access_binfo, flags,
11048 			   &candidates, complain);
11049     }
11050   else
11051     add_candidates (fns, first_mem_arg, user_args, optype,
11052 		    explicit_targs, template_only, conversion_path,
11053 		    access_binfo, flags, &candidates, complain);
11054 
11055   any_viable_p = false;
11056   candidates = splice_viable (candidates, false, &any_viable_p);
11057 
11058   if (!any_viable_p)
11059     {
11060       /* [dcl.init], 17.6.2.2:
11061 
11062 	 Otherwise, if no constructor is viable, the destination type is
11063 	 a (possibly cv-qualified) aggregate class A, and the initializer
11064 	 is a parenthesized expression-list, the object is initialized as
11065 	 follows...
11066 
11067 	 We achieve this by building up a CONSTRUCTOR, as for list-init,
11068 	 and setting CONSTRUCTOR_IS_PAREN_INIT to distinguish between
11069 	 the two.  */
11070       if (DECL_CONSTRUCTOR_P (fn)
11071 	  && !(flags & LOOKUP_ONLYCONVERTING)
11072 	  && cxx_dialect >= cxx20
11073 	  && CP_AGGREGATE_TYPE_P (basetype)
11074 	  && !vec_safe_is_empty (user_args))
11075 	{
11076 	  /* Create a CONSTRUCTOR from ARGS, e.g. {1, 2} from <1, 2>.  */
11077 	  tree ctor = build_constructor_from_vec (init_list_type_node,
11078 						  user_args);
11079 	  CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
11080 	  CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
11081 	  if (is_dummy_object (instance))
11082 	    return ctor;
11083 	  else
11084 	    {
11085 	      ctor = digest_init (basetype, ctor, complain);
11086 	      if (ctor == error_mark_node)
11087 		return error_mark_node;
11088 	      ctor = build2 (INIT_EXPR, TREE_TYPE (instance), instance, ctor);
11089 	      TREE_SIDE_EFFECTS (ctor) = true;
11090 	      return ctor;
11091 	    }
11092 	}
11093       if (complain & tf_error)
11094 	complain_about_no_candidates_for_method_call (instance, candidates,
11095 						      explicit_targs, basetype,
11096 						      optype, name,
11097 						      skip_first_for_error,
11098 						      user_args);
11099       call = error_mark_node;
11100     }
11101   else
11102     {
11103       cand = tourney (candidates, complain);
11104       if (cand == 0)
11105 	{
11106 	  char *pretty_name;
11107 	  bool free_p;
11108 	  tree arglist;
11109 
11110 	  if (complain & tf_error)
11111 	    {
11112 	      pretty_name = name_as_c_string (name, basetype, &free_p);
11113 	      arglist = build_tree_list_vec (user_args);
11114 	      if (skip_first_for_error)
11115 		arglist = TREE_CHAIN (arglist);
11116 	      auto_diagnostic_group d;
11117 	      if (!any_strictly_viable (candidates))
11118 		error ("no matching function for call to %<%s(%A)%>",
11119 		       pretty_name, arglist);
11120 	      else
11121 		error ("call of overloaded %<%s(%A)%> is ambiguous",
11122 		       pretty_name, arglist);
11123 	      print_z_candidates (location_of (name), candidates);
11124 	      if (free_p)
11125 		free (pretty_name);
11126 	    }
11127 	  call = error_mark_node;
11128 	  if (fn_p)
11129 	    *fn_p = error_mark_node;
11130 	}
11131       else
11132 	{
11133 	  fn = cand->fn;
11134 	  call = NULL_TREE;
11135 
11136 	  if (!(flags & LOOKUP_NONVIRTUAL)
11137 	      && DECL_PURE_VIRTUAL_P (fn)
11138 	      && instance == current_class_ref
11139 	      && (complain & tf_warning))
11140 	    {
11141 	      /* This is not an error, it is runtime undefined
11142 		 behavior.  */
11143 	      if (!current_function_decl)
11144 		warning (0, "pure virtual %q#D called from "
11145 			 "non-static data member initializer", fn);
11146 	      else if (DECL_CONSTRUCTOR_P (current_function_decl)
11147 		       || DECL_DESTRUCTOR_P (current_function_decl))
11148 		warning (0, (DECL_CONSTRUCTOR_P (current_function_decl)
11149 			     ? G_("pure virtual %q#D called from constructor")
11150 			     : G_("pure virtual %q#D called from destructor")),
11151 			 fn);
11152 	    }
11153 
11154 	  if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
11155 	      && !DECL_CONSTRUCTOR_P (fn)
11156 	      && is_dummy_object (instance))
11157 	    {
11158 	      instance = maybe_resolve_dummy (instance, true);
11159 	      if (instance == error_mark_node)
11160 		call = error_mark_node;
11161 	      else if (!is_dummy_object (instance))
11162 		{
11163 		  /* We captured 'this' in the current lambda now that
11164 		     we know we really need it.  */
11165 		  cand->first_arg = instance;
11166 		}
11167 	      else if (current_class_ptr && any_dependent_bases_p ())
11168 		/* We can't tell until instantiation time whether we can use
11169 		   *this as the implicit object argument.  */;
11170 	      else
11171 		{
11172 		  if (complain & tf_error)
11173 		    error ("cannot call member function %qD without object",
11174 			   fn);
11175 		  call = error_mark_node;
11176 		}
11177 	    }
11178 
11179 	  if (call != error_mark_node)
11180 	    {
11181 	      /* Now we know what function is being called.  */
11182 	      if (fn_p)
11183 		*fn_p = fn;
11184 	      /* Build the actual CALL_EXPR.  */
11185 	      call = build_over_call (cand, flags, complain);
11186 	      /* In an expression of the form `a->f()' where `f' turns
11187 		 out to be a static member function, `a' is
11188 		 none-the-less evaluated.  */
11189 	      if (TREE_CODE (TREE_TYPE (fn)) != METHOD_TYPE
11190 		  && !is_dummy_object (instance)
11191 		  && TREE_SIDE_EFFECTS (instance))
11192 		{
11193 		  /* But avoid the implicit lvalue-rvalue conversion when 'a'
11194 		     is volatile.  */
11195 		  tree a = instance;
11196 		  if (TREE_THIS_VOLATILE (a))
11197 		    a = build_this (a);
11198 		  if (TREE_SIDE_EFFECTS (a))
11199 		    call = build2 (COMPOUND_EXPR, TREE_TYPE (call), a, call);
11200 		}
11201 	      else if (call != error_mark_node
11202 		       && DECL_DESTRUCTOR_P (cand->fn)
11203 		       && !VOID_TYPE_P (TREE_TYPE (call)))
11204 		/* An explicit call of the form "x->~X()" has type
11205 		   "void".  However, on platforms where destructors
11206 		   return "this" (i.e., those where
11207 		   targetm.cxx.cdtor_returns_this is true), such calls
11208 		   will appear to have a return value of pointer type
11209 		   to the low-level call machinery.  We do not want to
11210 		   change the low-level machinery, since we want to be
11211 		   able to optimize "delete f()" on such platforms as
11212 		   "operator delete(~X(f()))" (rather than generating
11213 		   "t = f(), ~X(t), operator delete (t)").  */
11214 		call = build_nop (void_type_node, call);
11215 	    }
11216 	}
11217     }
11218 
11219   if (processing_template_decl && call != error_mark_node)
11220     {
11221       bool cast_to_void = false;
11222 
11223       if (TREE_CODE (call) == COMPOUND_EXPR)
11224 	call = TREE_OPERAND (call, 1);
11225       else if (TREE_CODE (call) == NOP_EXPR)
11226 	{
11227 	  cast_to_void = true;
11228 	  call = TREE_OPERAND (call, 0);
11229 	}
11230       if (INDIRECT_REF_P (call))
11231 	call = TREE_OPERAND (call, 0);
11232 
11233       /* Prune all but the selected function from the original overload
11234 	 set so that we can avoid some duplicate work at instantiation time.  */
11235       if (really_overloaded_fn (fns))
11236 	{
11237 	  if (DECL_TEMPLATE_INFO (fn)
11238 	      && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
11239 	    {
11240 	      /* Use the selected template, not the specialization, so that
11241 		 this looks like an actual lookup result for sake of
11242 		 filter_memfn_lookup.  */
11243 
11244 	      if (OVL_SINGLE_P (fns))
11245 		/* If the original overload set consists of a single function
11246 		   template, this isn't beneficial.  */
11247 		goto skip_prune;
11248 
11249 	      fn = ovl_make (DECL_TI_TEMPLATE (fn));
11250 	      if (template_only)
11251 		fn = lookup_template_function (fn, explicit_targs);
11252 	    }
11253 	  orig_fns = copy_node (orig_fns);
11254 	  BASELINK_FUNCTIONS (orig_fns) = fn;
11255 	  BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (orig_fns) = true;
11256 	}
11257 
11258 skip_prune:
11259       call = (build_min_non_dep_call_vec
11260 	      (call,
11261 	       build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
11262 			  orig_instance, orig_fns, NULL_TREE),
11263 	       orig_args));
11264       SET_EXPR_LOCATION (call, input_location);
11265       call = convert_from_reference (call);
11266       if (cast_to_void)
11267 	call = build_nop (void_type_node, call);
11268     }
11269 
11270  /* Free all the conversions we allocated.  */
11271   obstack_free (&conversion_obstack, p);
11272 
11273   if (orig_args != NULL)
11274     release_tree_vector (orig_args);
11275 
11276   return call;
11277 }
11278 
11279 /* Returns true iff standard conversion sequence ICS1 is a proper
11280    subsequence of ICS2.  */
11281 
11282 static bool
is_subseq(conversion * ics1,conversion * ics2)11283 is_subseq (conversion *ics1, conversion *ics2)
11284 {
11285   /* We can assume that a conversion of the same code
11286      between the same types indicates a subsequence since we only get
11287      here if the types we are converting from are the same.  */
11288 
11289   while (ics1->kind == ck_rvalue
11290 	 || ics1->kind == ck_lvalue)
11291     ics1 = next_conversion (ics1);
11292 
11293   while (1)
11294     {
11295       while (ics2->kind == ck_rvalue
11296 	     || ics2->kind == ck_lvalue)
11297 	ics2 = next_conversion (ics2);
11298 
11299       if (ics2->kind == ck_user
11300 	  || !has_next (ics2->kind))
11301 	/* At this point, ICS1 cannot be a proper subsequence of
11302 	   ICS2.  We can get a USER_CONV when we are comparing the
11303 	   second standard conversion sequence of two user conversion
11304 	   sequences.  */
11305 	return false;
11306 
11307       ics2 = next_conversion (ics2);
11308 
11309       while (ics2->kind == ck_rvalue
11310 	     || ics2->kind == ck_lvalue)
11311 	ics2 = next_conversion (ics2);
11312 
11313       if (ics2->kind == ics1->kind
11314 	  && same_type_p (ics2->type, ics1->type)
11315 	  && (ics1->kind == ck_identity
11316 	      || same_type_p (next_conversion (ics2)->type,
11317 			      next_conversion (ics1)->type)))
11318 	return true;
11319     }
11320 }
11321 
11322 /* Returns nonzero iff DERIVED is derived from BASE.  The inputs may
11323    be any _TYPE nodes.  */
11324 
11325 bool
is_properly_derived_from(tree derived,tree base)11326 is_properly_derived_from (tree derived, tree base)
11327 {
11328   if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
11329     return false;
11330 
11331   /* We only allow proper derivation here.  The DERIVED_FROM_P macro
11332      considers every class derived from itself.  */
11333   return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
11334 	  && DERIVED_FROM_P (base, derived));
11335 }
11336 
11337 /* We build the ICS for an implicit object parameter as a pointer
11338    conversion sequence.  However, such a sequence should be compared
11339    as if it were a reference conversion sequence.  If ICS is the
11340    implicit conversion sequence for an implicit object parameter,
11341    modify it accordingly.  */
11342 
11343 static void
maybe_handle_implicit_object(conversion ** ics)11344 maybe_handle_implicit_object (conversion **ics)
11345 {
11346   if ((*ics)->this_p)
11347     {
11348       /* [over.match.funcs]
11349 
11350 	 For non-static member functions, the type of the
11351 	 implicit object parameter is "reference to cv X"
11352 	 where X is the class of which the function is a
11353 	 member and cv is the cv-qualification on the member
11354 	 function declaration.  */
11355       conversion *t = *ics;
11356       tree reference_type;
11357 
11358       /* The `this' parameter is a pointer to a class type.  Make the
11359 	 implicit conversion talk about a reference to that same class
11360 	 type.  */
11361       reference_type = TREE_TYPE (t->type);
11362       reference_type = build_reference_type (reference_type);
11363 
11364       if (t->kind == ck_qual)
11365 	t = next_conversion (t);
11366       if (t->kind == ck_ptr)
11367 	t = next_conversion (t);
11368       t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
11369       t = direct_reference_binding (reference_type, t);
11370       t->this_p = 1;
11371       t->rvaluedness_matches_p = 0;
11372       *ics = t;
11373     }
11374 }
11375 
11376 /* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
11377    and return the initial reference binding conversion. Otherwise,
11378    leave *ICS unchanged and return NULL.  */
11379 
11380 static conversion *
maybe_handle_ref_bind(conversion ** ics)11381 maybe_handle_ref_bind (conversion **ics)
11382 {
11383   if ((*ics)->kind == ck_ref_bind)
11384     {
11385       conversion *old_ics = *ics;
11386       *ics = next_conversion (old_ics);
11387       (*ics)->user_conv_p = old_ics->user_conv_p;
11388       return old_ics;
11389     }
11390 
11391   return NULL;
11392 }
11393 
11394 /* Get the expression at the beginning of the conversion chain C.  */
11395 
11396 static tree
conv_get_original_expr(conversion * c)11397 conv_get_original_expr (conversion *c)
11398 {
11399   for (; c; c = next_conversion (c))
11400     if (c->kind == ck_identity || c->kind == ck_ambig || c->kind == ck_aggr)
11401       return c->u.expr;
11402   return NULL_TREE;
11403 }
11404 
11405 /* Return a tree representing the number of elements initialized by the
11406    list-initialization C.  The caller must check that C converts to an
11407    array type.  */
11408 
11409 static tree
nelts_initialized_by_list_init(conversion * c)11410 nelts_initialized_by_list_init (conversion *c)
11411 {
11412   /* If the array we're converting to has a dimension, we'll use that.  */
11413   if (TYPE_DOMAIN (c->type))
11414     return array_type_nelts_top (c->type);
11415   else
11416     {
11417       /* Otherwise, we look at how many elements the constructor we're
11418 	 initializing from has.  */
11419       tree ctor = conv_get_original_expr (c);
11420       return size_int (CONSTRUCTOR_NELTS (ctor));
11421     }
11422 }
11423 
11424 /* True iff C is a conversion that binds a reference or a pointer to
11425    an array of unknown bound.  */
11426 
11427 static inline bool
conv_binds_to_array_of_unknown_bound(conversion * c)11428 conv_binds_to_array_of_unknown_bound (conversion *c)
11429 {
11430   /* ck_ref_bind won't have the reference stripped.  */
11431   tree type = non_reference (c->type);
11432   /* ck_qual won't have the pointer stripped.  */
11433   type = strip_pointer_operator (type);
11434   return (TREE_CODE (type) == ARRAY_TYPE
11435 	  && TYPE_DOMAIN (type) == NULL_TREE);
11436 }
11437 
11438 /* Compare two implicit conversion sequences according to the rules set out in
11439    [over.ics.rank].  Return values:
11440 
11441       1: ics1 is better than ics2
11442      -1: ics2 is better than ics1
11443       0: ics1 and ics2 are indistinguishable */
11444 
11445 static int
compare_ics(conversion * ics1,conversion * ics2)11446 compare_ics (conversion *ics1, conversion *ics2)
11447 {
11448   tree from_type1;
11449   tree from_type2;
11450   tree to_type1;
11451   tree to_type2;
11452   tree deref_from_type1 = NULL_TREE;
11453   tree deref_from_type2 = NULL_TREE;
11454   tree deref_to_type1 = NULL_TREE;
11455   tree deref_to_type2 = NULL_TREE;
11456   conversion_rank rank1, rank2;
11457 
11458   /* REF_BINDING is nonzero if the result of the conversion sequence
11459      is a reference type.   In that case REF_CONV is the reference
11460      binding conversion. */
11461   conversion *ref_conv1;
11462   conversion *ref_conv2;
11463 
11464   /* Compare badness before stripping the reference conversion.  */
11465   if (ics1->bad_p > ics2->bad_p)
11466     return -1;
11467   else if (ics1->bad_p < ics2->bad_p)
11468     return 1;
11469 
11470   /* Handle implicit object parameters.  */
11471   maybe_handle_implicit_object (&ics1);
11472   maybe_handle_implicit_object (&ics2);
11473 
11474   /* Handle reference parameters.  */
11475   ref_conv1 = maybe_handle_ref_bind (&ics1);
11476   ref_conv2 = maybe_handle_ref_bind (&ics2);
11477 
11478   /* List-initialization sequence L1 is a better conversion sequence than
11479      list-initialization sequence L2 if L1 converts to
11480      std::initializer_list<X> for some X and L2 does not.  */
11481   if (ics1->kind == ck_list && ics2->kind != ck_list)
11482     return 1;
11483   if (ics2->kind == ck_list && ics1->kind != ck_list)
11484     return -1;
11485 
11486   /* [over.ics.rank]
11487 
11488      When  comparing  the  basic forms of implicit conversion sequences (as
11489      defined in _over.best.ics_)
11490 
11491      --a standard conversion sequence (_over.ics.scs_) is a better
11492        conversion sequence than a user-defined conversion sequence
11493        or an ellipsis conversion sequence, and
11494 
11495      --a user-defined conversion sequence (_over.ics.user_) is a
11496        better conversion sequence than an ellipsis conversion sequence
11497        (_over.ics.ellipsis_).  */
11498   /* Use BAD_CONVERSION_RANK because we already checked for a badness
11499      mismatch.  If both ICS are bad, we try to make a decision based on
11500      what would have happened if they'd been good.  This is not an
11501      extension, we'll still give an error when we build up the call; this
11502      just helps us give a more helpful error message.  */
11503   rank1 = BAD_CONVERSION_RANK (ics1);
11504   rank2 = BAD_CONVERSION_RANK (ics2);
11505 
11506   if (rank1 > rank2)
11507     return -1;
11508   else if (rank1 < rank2)
11509     return 1;
11510 
11511   if (ics1->ellipsis_p)
11512     /* Both conversions are ellipsis conversions.  */
11513     return 0;
11514 
11515   /* User-defined  conversion sequence U1 is a better conversion sequence
11516      than another user-defined conversion sequence U2 if they contain the
11517      same user-defined conversion operator or constructor and if the sec-
11518      ond standard conversion sequence of U1 is  better  than  the  second
11519      standard conversion sequence of U2.  */
11520 
11521   /* Handle list-conversion with the same code even though it isn't always
11522      ranked as a user-defined conversion and it doesn't have a second
11523      standard conversion sequence; it will still have the desired effect.
11524      Specifically, we need to do the reference binding comparison at the
11525      end of this function.  */
11526 
11527   if (ics1->user_conv_p || ics1->kind == ck_list
11528       || ics1->kind == ck_aggr || ics2->kind == ck_aggr)
11529     {
11530       conversion *t1 = strip_standard_conversion (ics1);
11531       conversion *t2 = strip_standard_conversion (ics2);
11532 
11533       if (!t1 || !t2 || t1->kind != t2->kind)
11534 	return 0;
11535       else if (t1->kind == ck_user)
11536 	{
11537 	  tree f1 = t1->cand ? t1->cand->fn : t1->type;
11538 	  tree f2 = t2->cand ? t2->cand->fn : t2->type;
11539 	  if (f1 != f2)
11540 	    return 0;
11541 	}
11542       /* List-initialization sequence L1 is a better conversion sequence than
11543 	 list-initialization sequence L2 if
11544 
11545 	 -- L1 and L2 convert to arrays of the same element type, and either
11546 	 the number of elements n1 initialized by L1 is less than the number
11547 	 of elements n2 initialized by L2, or n1=n2 and L2 converts to an array
11548 	 of unknown bound and L1 does not.  (Added in CWG 1307 and extended by
11549 	 P0388R4.)  */
11550       else if (t1->kind == ck_aggr
11551 	       && TREE_CODE (t1->type) == ARRAY_TYPE
11552 	       && TREE_CODE (t2->type) == ARRAY_TYPE
11553 	       && same_type_p (TREE_TYPE (t1->type), TREE_TYPE (t2->type)))
11554 	{
11555 	  tree n1 = nelts_initialized_by_list_init (t1);
11556 	  tree n2 = nelts_initialized_by_list_init (t2);
11557 	  if (tree_int_cst_lt (n1, n2))
11558 	    return 1;
11559 	  else if (tree_int_cst_lt (n2, n1))
11560 	    return -1;
11561 	  /* The n1 == n2 case.  */
11562 	  bool c1 = conv_binds_to_array_of_unknown_bound (t1);
11563 	  bool c2 = conv_binds_to_array_of_unknown_bound (t2);
11564 	  if (c1 && !c2)
11565 	    return -1;
11566 	  else if (!c1 && c2)
11567 	    return 1;
11568 	  else
11569 	    return 0;
11570 	}
11571       else
11572 	{
11573 	  /* For ambiguous or aggregate conversions, use the target type as
11574 	     a proxy for the conversion function.  */
11575 	  if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
11576 	    return 0;
11577 	}
11578 
11579       /* We can just fall through here, after setting up
11580 	 FROM_TYPE1 and FROM_TYPE2.  */
11581       from_type1 = t1->type;
11582       from_type2 = t2->type;
11583     }
11584   else
11585     {
11586       conversion *t1;
11587       conversion *t2;
11588 
11589       /* We're dealing with two standard conversion sequences.
11590 
11591 	 [over.ics.rank]
11592 
11593 	 Standard conversion sequence S1 is a better conversion
11594 	 sequence than standard conversion sequence S2 if
11595 
11596 	 --S1 is a proper subsequence of S2 (comparing the conversion
11597 	   sequences in the canonical form defined by _over.ics.scs_,
11598 	   excluding any Lvalue Transformation; the identity
11599 	   conversion sequence is considered to be a subsequence of
11600 	   any non-identity conversion sequence */
11601 
11602       t1 = ics1;
11603       while (t1->kind != ck_identity)
11604 	t1 = next_conversion (t1);
11605       from_type1 = t1->type;
11606 
11607       t2 = ics2;
11608       while (t2->kind != ck_identity)
11609 	t2 = next_conversion (t2);
11610       from_type2 = t2->type;
11611     }
11612 
11613   /* One sequence can only be a subsequence of the other if they start with
11614      the same type.  They can start with different types when comparing the
11615      second standard conversion sequence in two user-defined conversion
11616      sequences.  */
11617   if (same_type_p (from_type1, from_type2))
11618     {
11619       if (is_subseq (ics1, ics2))
11620 	return 1;
11621       if (is_subseq (ics2, ics1))
11622 	return -1;
11623     }
11624 
11625   /* [over.ics.rank]
11626 
11627      Or, if not that,
11628 
11629      --the rank of S1 is better than the rank of S2 (by the rules
11630        defined below):
11631 
11632     Standard conversion sequences are ordered by their ranks: an Exact
11633     Match is a better conversion than a Promotion, which is a better
11634     conversion than a Conversion.
11635 
11636     Two conversion sequences with the same rank are indistinguishable
11637     unless one of the following rules applies:
11638 
11639     --A conversion that does not a convert a pointer, pointer to member,
11640       or std::nullptr_t to bool is better than one that does.
11641 
11642     The ICS_STD_RANK automatically handles the pointer-to-bool rule,
11643     so that we do not have to check it explicitly.  */
11644   if (ics1->rank < ics2->rank)
11645     return 1;
11646   else if (ics2->rank < ics1->rank)
11647     return -1;
11648 
11649   to_type1 = ics1->type;
11650   to_type2 = ics2->type;
11651 
11652   /* A conversion from scalar arithmetic type to complex is worse than a
11653      conversion between scalar arithmetic types.  */
11654   if (same_type_p (from_type1, from_type2)
11655       && ARITHMETIC_TYPE_P (from_type1)
11656       && ARITHMETIC_TYPE_P (to_type1)
11657       && ARITHMETIC_TYPE_P (to_type2)
11658       && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
11659 	  != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
11660     {
11661       if (TREE_CODE (to_type1) == COMPLEX_TYPE)
11662 	return -1;
11663       else
11664 	return 1;
11665     }
11666 
11667   if (TYPE_PTR_P (from_type1)
11668       && TYPE_PTR_P (from_type2)
11669       && TYPE_PTR_P (to_type1)
11670       && TYPE_PTR_P (to_type2))
11671     {
11672       deref_from_type1 = TREE_TYPE (from_type1);
11673       deref_from_type2 = TREE_TYPE (from_type2);
11674       deref_to_type1 = TREE_TYPE (to_type1);
11675       deref_to_type2 = TREE_TYPE (to_type2);
11676     }
11677   /* The rules for pointers to members A::* are just like the rules
11678      for pointers A*, except opposite: if B is derived from A then
11679      A::* converts to B::*, not vice versa.  For that reason, we
11680      switch the from_ and to_ variables here.  */
11681   else if ((TYPE_PTRDATAMEM_P (from_type1) && TYPE_PTRDATAMEM_P (from_type2)
11682 	    && TYPE_PTRDATAMEM_P (to_type1) && TYPE_PTRDATAMEM_P (to_type2))
11683 	   || (TYPE_PTRMEMFUNC_P (from_type1)
11684 	       && TYPE_PTRMEMFUNC_P (from_type2)
11685 	       && TYPE_PTRMEMFUNC_P (to_type1)
11686 	       && TYPE_PTRMEMFUNC_P (to_type2)))
11687     {
11688       deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
11689       deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
11690       deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
11691       deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
11692     }
11693 
11694   if (deref_from_type1 != NULL_TREE
11695       && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
11696       && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
11697     {
11698       /* This was one of the pointer or pointer-like conversions.
11699 
11700 	 [over.ics.rank]
11701 
11702 	 --If class B is derived directly or indirectly from class A,
11703 	   conversion of B* to A* is better than conversion of B* to
11704 	   void*, and conversion of A* to void* is better than
11705 	   conversion of B* to void*.  */
11706       if (VOID_TYPE_P (deref_to_type1)
11707 	  && VOID_TYPE_P (deref_to_type2))
11708 	{
11709 	  if (is_properly_derived_from (deref_from_type1,
11710 					deref_from_type2))
11711 	    return -1;
11712 	  else if (is_properly_derived_from (deref_from_type2,
11713 					     deref_from_type1))
11714 	    return 1;
11715 	}
11716       else if (VOID_TYPE_P (deref_to_type1)
11717 	       || VOID_TYPE_P (deref_to_type2))
11718 	{
11719 	  if (same_type_p (deref_from_type1, deref_from_type2))
11720 	    {
11721 	      if (VOID_TYPE_P (deref_to_type2))
11722 		{
11723 		  if (is_properly_derived_from (deref_from_type1,
11724 						deref_to_type1))
11725 		    return 1;
11726 		}
11727 	      /* We know that DEREF_TO_TYPE1 is `void' here.  */
11728 	      else if (is_properly_derived_from (deref_from_type1,
11729 						 deref_to_type2))
11730 		return -1;
11731 	    }
11732 	}
11733       else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
11734 	       && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
11735 	{
11736 	  /* [over.ics.rank]
11737 
11738 	     --If class B is derived directly or indirectly from class A
11739 	       and class C is derived directly or indirectly from B,
11740 
11741 	     --conversion of C* to B* is better than conversion of C* to
11742 	       A*,
11743 
11744 	     --conversion of B* to A* is better than conversion of C* to
11745 	       A*  */
11746 	  if (same_type_p (deref_from_type1, deref_from_type2))
11747 	    {
11748 	      if (is_properly_derived_from (deref_to_type1,
11749 					    deref_to_type2))
11750 		return 1;
11751 	      else if (is_properly_derived_from (deref_to_type2,
11752 						 deref_to_type1))
11753 		return -1;
11754 	    }
11755 	  else if (same_type_p (deref_to_type1, deref_to_type2))
11756 	    {
11757 	      if (is_properly_derived_from (deref_from_type2,
11758 					    deref_from_type1))
11759 		return 1;
11760 	      else if (is_properly_derived_from (deref_from_type1,
11761 						 deref_from_type2))
11762 		return -1;
11763 	    }
11764 	}
11765     }
11766   else if (CLASS_TYPE_P (non_reference (from_type1))
11767 	   && same_type_p (from_type1, from_type2))
11768     {
11769       tree from = non_reference (from_type1);
11770 
11771       /* [over.ics.rank]
11772 
11773 	 --binding of an expression of type C to a reference of type
11774 	   B& is better than binding an expression of type C to a
11775 	   reference of type A&
11776 
11777 	 --conversion of C to B is better than conversion of C to A,  */
11778       if (is_properly_derived_from (from, to_type1)
11779 	  && is_properly_derived_from (from, to_type2))
11780 	{
11781 	  if (is_properly_derived_from (to_type1, to_type2))
11782 	    return 1;
11783 	  else if (is_properly_derived_from (to_type2, to_type1))
11784 	    return -1;
11785 	}
11786     }
11787   else if (CLASS_TYPE_P (non_reference (to_type1))
11788 	   && same_type_p (to_type1, to_type2))
11789     {
11790       tree to = non_reference (to_type1);
11791 
11792       /* [over.ics.rank]
11793 
11794 	 --binding of an expression of type B to a reference of type
11795 	   A& is better than binding an expression of type C to a
11796 	   reference of type A&,
11797 
11798 	 --conversion of B to A is better than conversion of C to A  */
11799       if (is_properly_derived_from (from_type1, to)
11800 	  && is_properly_derived_from (from_type2, to))
11801 	{
11802 	  if (is_properly_derived_from (from_type2, from_type1))
11803 	    return 1;
11804 	  else if (is_properly_derived_from (from_type1, from_type2))
11805 	    return -1;
11806 	}
11807     }
11808 
11809   /* [over.ics.rank]
11810 
11811      --S1 and S2 differ only in their qualification conversion and  yield
11812        similar  types  T1 and T2 (_conv.qual_), respectively, and the cv-
11813        qualification signature of type T1 is a proper subset of  the  cv-
11814        qualification signature of type T2  */
11815   if (ics1->kind == ck_qual
11816       && ics2->kind == ck_qual
11817       && same_type_p (from_type1, from_type2))
11818     {
11819       int result = comp_cv_qual_signature (to_type1, to_type2);
11820       if (result != 0)
11821 	return result;
11822     }
11823 
11824   /* [over.ics.rank]
11825 
11826      --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
11827      to an implicit object parameter of a non-static member function
11828      declared without a ref-qualifier, and either S1 binds an lvalue
11829      reference to an lvalue and S2 binds an rvalue reference or S1 binds an
11830      rvalue reference to an rvalue and S2 binds an lvalue reference (C++0x
11831      draft standard, 13.3.3.2)
11832 
11833      --S1 and S2 are reference bindings (_dcl.init.ref_), and the
11834      types to which the references refer are the same type except for
11835      top-level cv-qualifiers, and the type to which the reference
11836      initialized by S2 refers is more cv-qualified than the type to
11837      which the reference initialized by S1 refers.
11838 
11839      DR 1328 [over.match.best]: the context is an initialization by
11840      conversion function for direct reference binding (13.3.1.6) of a
11841      reference to function type, the return type of F1 is the same kind of
11842      reference (i.e. lvalue or rvalue) as the reference being initialized,
11843      and the return type of F2 is not.  */
11844 
11845   if (ref_conv1 && ref_conv2)
11846     {
11847       if (!ref_conv1->this_p && !ref_conv2->this_p
11848 	  && (ref_conv1->rvaluedness_matches_p
11849 	      != ref_conv2->rvaluedness_matches_p)
11850 	  && (same_type_p (ref_conv1->type, ref_conv2->type)
11851 	      || (TYPE_REF_IS_RVALUE (ref_conv1->type)
11852 		  != TYPE_REF_IS_RVALUE (ref_conv2->type))))
11853 	{
11854 	  if (ref_conv1->bad_p
11855 	      && !same_type_p (TREE_TYPE (ref_conv1->type),
11856 			       TREE_TYPE (ref_conv2->type)))
11857 	    /* Don't prefer a bad conversion that drops cv-quals to a bad
11858 	       conversion with the wrong rvalueness.  */
11859 	    return 0;
11860 	  return (ref_conv1->rvaluedness_matches_p
11861 		  - ref_conv2->rvaluedness_matches_p);
11862 	}
11863 
11864       if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
11865 	{
11866 	  /* Per P0388R4:
11867 
11868 	    void f (int(&)[]),     // (1)
11869 		 f (int(&)[1]),    // (2)
11870 		 f (int*);	   // (3)
11871 
11872 	    (2) is better than (1), but (3) should be equal to (1) and to
11873 	    (2).  For that reason we don't use ck_qual for (1) which would
11874 	    give it the cr_exact rank while (3) remains ck_identity.
11875 	    Therefore we compare (1) and (2) here.  For (1) we'll have
11876 
11877 	      ck_ref_bind <- ck_identity
11878 		int[] &	       int[1]
11879 
11880 	    so to handle this we must look at ref_conv.  */
11881 	  bool c1 = conv_binds_to_array_of_unknown_bound (ref_conv1);
11882 	  bool c2 = conv_binds_to_array_of_unknown_bound (ref_conv2);
11883 	  if (c1 && !c2)
11884 	    return -1;
11885 	  else if (!c1 && c2)
11886 	    return 1;
11887 
11888 	  int q1 = cp_type_quals (TREE_TYPE (ref_conv1->type));
11889 	  int q2 = cp_type_quals (TREE_TYPE (ref_conv2->type));
11890 	  if (ref_conv1->bad_p)
11891 	    {
11892 	      /* Prefer the one that drops fewer cv-quals.  */
11893 	      tree ftype = next_conversion (ref_conv1)->type;
11894 	      int fquals = cp_type_quals (ftype);
11895 	      q1 ^= fquals;
11896 	      q2 ^= fquals;
11897 	    }
11898 	  return comp_cv_qualification (q2, q1);
11899 	}
11900     }
11901 
11902   /* [over.ics.rank]
11903 
11904      Per CWG 1601:
11905      -- A conversion that promotes an enumeration whose underlying type
11906      is fixed to its underlying type is better than one that promotes to
11907      the promoted underlying type, if the two are different.  */
11908   if (ics1->rank == cr_promotion
11909       && ics2->rank == cr_promotion
11910       && UNSCOPED_ENUM_P (from_type1)
11911       && ENUM_FIXED_UNDERLYING_TYPE_P (from_type1)
11912       && same_type_p (from_type1, from_type2))
11913     {
11914       tree utype = ENUM_UNDERLYING_TYPE (from_type1);
11915       tree prom = type_promotes_to (from_type1);
11916       if (!same_type_p (utype, prom))
11917 	{
11918 	  if (same_type_p (to_type1, utype)
11919 	      && same_type_p (to_type2, prom))
11920 	    return 1;
11921 	  else if (same_type_p (to_type2, utype)
11922 		   && same_type_p (to_type1, prom))
11923 	    return -1;
11924 	}
11925     }
11926 
11927   /* Neither conversion sequence is better than the other.  */
11928   return 0;
11929 }
11930 
11931 /* The source type for this standard conversion sequence.  */
11932 
11933 static tree
source_type(conversion * t)11934 source_type (conversion *t)
11935 {
11936   return strip_standard_conversion (t)->type;
11937 }
11938 
11939 /* Note a warning about preferring WINNER to LOSER.  We do this by storing
11940    a pointer to LOSER and re-running joust to produce the warning if WINNER
11941    is actually used.  */
11942 
11943 static void
add_warning(struct z_candidate * winner,struct z_candidate * loser)11944 add_warning (struct z_candidate *winner, struct z_candidate *loser)
11945 {
11946   candidate_warning *cw = (candidate_warning *)
11947     conversion_obstack_alloc (sizeof (candidate_warning));
11948   cw->loser = loser;
11949   cw->next = winner->warnings;
11950   winner->warnings = cw;
11951 }
11952 
11953 /* CAND is a constructor candidate in joust in C++17 and up.  If it copies a
11954    prvalue returned from a conversion function, replace CAND with the candidate
11955    for the conversion and return true.  Otherwise, return false.  */
11956 
11957 static bool
joust_maybe_elide_copy(z_candidate * & cand)11958 joust_maybe_elide_copy (z_candidate *&cand)
11959 {
11960   tree fn = cand->fn;
11961   if (!DECL_COPY_CONSTRUCTOR_P (fn) && !DECL_MOVE_CONSTRUCTOR_P (fn))
11962     return false;
11963   conversion *conv = cand->convs[0];
11964   if (conv->kind == ck_ambig)
11965     return false;
11966   gcc_checking_assert (conv->kind == ck_ref_bind);
11967   conv = next_conversion (conv);
11968   if (conv->kind == ck_user && !TYPE_REF_P (conv->type))
11969     {
11970       gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
11971 			   (conv->type, DECL_CONTEXT (fn)));
11972       z_candidate *uc = conv->cand;
11973       if (DECL_CONV_FN_P (uc->fn))
11974 	{
11975 	  cand = uc;
11976 	  return true;
11977 	}
11978     }
11979   return false;
11980 }
11981 
11982 /* True if the defining declarations of the two candidates have equivalent
11983    parameters.  */
11984 
11985 static bool
cand_parms_match(z_candidate * c1,z_candidate * c2)11986 cand_parms_match (z_candidate *c1, z_candidate *c2)
11987 {
11988   tree fn1 = c1->fn;
11989   tree fn2 = c2->fn;
11990   if (fn1 == fn2)
11991     return true;
11992   if (identifier_p (fn1) || identifier_p (fn2))
11993     return false;
11994   /* We don't look at c1->template_decl because that's only set for primary
11995      templates, not e.g. non-template member functions of class templates.  */
11996   tree t1 = most_general_template (fn1);
11997   tree t2 = most_general_template (fn2);
11998   if (t1 || t2)
11999     {
12000       if (!t1 || !t2)
12001 	return false;
12002       if (t1 == t2)
12003 	return true;
12004       fn1 = DECL_TEMPLATE_RESULT (t1);
12005       fn2 = DECL_TEMPLATE_RESULT (t2);
12006     }
12007   tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
12008   tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (fn2));
12009   if (DECL_FUNCTION_MEMBER_P (fn1)
12010       && DECL_FUNCTION_MEMBER_P (fn2)
12011       && (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn1)
12012 	  != DECL_NONSTATIC_MEMBER_FUNCTION_P (fn2)))
12013     {
12014       /* Ignore 'this' when comparing the parameters of a static member
12015 	 function with those of a non-static one.  */
12016       parms1 = skip_artificial_parms_for (fn1, parms1);
12017       parms2 = skip_artificial_parms_for (fn2, parms2);
12018     }
12019   return compparms (parms1, parms2);
12020 }
12021 
12022 /* Compare two candidates for overloading as described in
12023    [over.match.best].  Return values:
12024 
12025       1: cand1 is better than cand2
12026      -1: cand2 is better than cand1
12027       0: cand1 and cand2 are indistinguishable */
12028 
12029 static int
joust(struct z_candidate * cand1,struct z_candidate * cand2,bool warn,tsubst_flags_t complain)12030 joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn,
12031        tsubst_flags_t complain)
12032 {
12033   int winner = 0;
12034   int off1 = 0, off2 = 0;
12035   size_t i;
12036   size_t len;
12037 
12038   /* Candidates that involve bad conversions are always worse than those
12039      that don't.  */
12040   if (cand1->viable > cand2->viable)
12041     return 1;
12042   if (cand1->viable < cand2->viable)
12043     return -1;
12044 
12045   /* If we have two pseudo-candidates for conversions to the same type,
12046      or two candidates for the same function, arbitrarily pick one.  */
12047   if (cand1->fn == cand2->fn
12048       && cand1->reversed () == cand2->reversed ()
12049       && (IS_TYPE_OR_DECL_P (cand1->fn)))
12050     return 1;
12051 
12052   /* Prefer a non-deleted function over an implicitly deleted move
12053      constructor or assignment operator.  This differs slightly from the
12054      wording for issue 1402 (which says the move op is ignored by overload
12055      resolution), but this way produces better error messages.  */
12056   if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12057       && TREE_CODE (cand2->fn) == FUNCTION_DECL
12058       && DECL_DELETED_FN (cand1->fn) != DECL_DELETED_FN (cand2->fn))
12059     {
12060       if (DECL_DELETED_FN (cand1->fn) && DECL_DEFAULTED_FN (cand1->fn)
12061 	  && move_fn_p (cand1->fn))
12062 	return -1;
12063       if (DECL_DELETED_FN (cand2->fn) && DECL_DEFAULTED_FN (cand2->fn)
12064 	  && move_fn_p (cand2->fn))
12065 	return 1;
12066     }
12067 
12068   /* a viable function F1
12069      is defined to be a better function than another viable function F2  if
12070      for  all arguments i, ICSi(F1) is not a worse conversion sequence than
12071      ICSi(F2), and then */
12072 
12073   /* for some argument j, ICSj(F1) is a better conversion  sequence  than
12074      ICSj(F2) */
12075 
12076   /* For comparing static and non-static member functions, we ignore
12077      the implicit object parameter of the non-static function.  The
12078      standard says to pretend that the static function has an object
12079      parm, but that won't work with operator overloading.  */
12080   len = cand1->num_convs;
12081   if (len != cand2->num_convs)
12082     {
12083       int static_1 = DECL_STATIC_FUNCTION_P (cand1->fn);
12084       int static_2 = DECL_STATIC_FUNCTION_P (cand2->fn);
12085 
12086       if (DECL_CONSTRUCTOR_P (cand1->fn)
12087 	  && is_list_ctor (cand1->fn) != is_list_ctor (cand2->fn))
12088 	/* We're comparing a near-match list constructor and a near-match
12089 	   non-list constructor.  Just treat them as unordered.  */
12090 	return 0;
12091 
12092       gcc_assert (static_1 != static_2);
12093 
12094       if (static_1)
12095 	off2 = 1;
12096       else
12097 	{
12098 	  off1 = 1;
12099 	  --len;
12100 	}
12101     }
12102 
12103   /* Handle C++17 copy elision in [over.match.ctor] (direct-init) context.  The
12104      standard currently says that only constructors are candidates, but if one
12105      copies a prvalue returned by a conversion function we want to treat the
12106      conversion as the candidate instead.
12107 
12108      Clang does something similar, as discussed at
12109      http://lists.isocpp.org/core/2017/10/3166.php
12110      http://lists.isocpp.org/core/2019/03/5721.php  */
12111   int elided_tiebreaker = 0;
12112   if (len == 1 && cxx_dialect >= cxx17
12113       && DECL_P (cand1->fn)
12114       && DECL_COMPLETE_CONSTRUCTOR_P (cand1->fn)
12115       && !(cand1->flags & LOOKUP_ONLYCONVERTING))
12116     {
12117       bool elided1 = joust_maybe_elide_copy (cand1);
12118       bool elided2 = joust_maybe_elide_copy (cand2);
12119       /* As a tiebreaker below we will prefer a constructor to a conversion
12120 	 operator exposed this way.  */
12121       elided_tiebreaker = elided2 - elided1;
12122     }
12123 
12124   for (i = 0; i < len; ++i)
12125     {
12126       conversion *t1 = cand1->convs[i + off1];
12127       conversion *t2 = cand2->convs[i + off2];
12128       int comp = compare_ics (t1, t2);
12129 
12130       if (comp != 0)
12131 	{
12132 	  if ((complain & tf_warning)
12133 	      && warn_sign_promo
12134 	      && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
12135 		  == cr_std + cr_promotion)
12136 	      && t1->kind == ck_std
12137 	      && t2->kind == ck_std
12138 	      && TREE_CODE (t1->type) == INTEGER_TYPE
12139 	      && TREE_CODE (t2->type) == INTEGER_TYPE
12140 	      && (TYPE_PRECISION (t1->type)
12141 		  == TYPE_PRECISION (t2->type))
12142 	      && (TYPE_UNSIGNED (next_conversion (t1)->type)
12143 		  || (TREE_CODE (next_conversion (t1)->type)
12144 		      == ENUMERAL_TYPE)))
12145 	    {
12146 	      tree type = next_conversion (t1)->type;
12147 	      tree type1, type2;
12148 	      struct z_candidate *w, *l;
12149 	      if (comp > 0)
12150 		type1 = t1->type, type2 = t2->type,
12151 		  w = cand1, l = cand2;
12152 	      else
12153 		type1 = t2->type, type2 = t1->type,
12154 		  w = cand2, l = cand1;
12155 
12156 	      if (warn)
12157 		{
12158 		  warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
12159 			   type, type1, type2);
12160 		  warning (OPT_Wsign_promo, "  in call to %qD", w->fn);
12161 		}
12162 	      else
12163 		add_warning (w, l);
12164 	    }
12165 
12166 	  if (winner && comp != winner)
12167 	    {
12168 	      /* Ambiguity between normal and reversed comparison operators
12169 		 with the same parameter types; prefer the normal one.  */
12170 	      if ((cand1->reversed () != cand2->reversed ())
12171 		  && cand_parms_match (cand1, cand2))
12172 		return cand1->reversed () ? -1 : 1;
12173 
12174 	      winner = 0;
12175 	      goto tweak;
12176 	    }
12177 	  winner = comp;
12178 	}
12179     }
12180 
12181   /* warn about confusing overload resolution for user-defined conversions,
12182      either between a constructor and a conversion op, or between two
12183      conversion ops.  */
12184   if ((complain & tf_warning)
12185       /* In C++17, the constructor might have been elided, which means that
12186 	 an originally null ->second_conv could become non-null.  */
12187       && winner && warn_conversion && cand1->second_conv && cand2->second_conv
12188       && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
12189       && winner != compare_ics (cand1->second_conv, cand2->second_conv))
12190     {
12191       struct z_candidate *w, *l;
12192       bool give_warning = false;
12193 
12194       if (winner == 1)
12195 	w = cand1, l = cand2;
12196       else
12197 	w = cand2, l = cand1;
12198 
12199       /* We don't want to complain about `X::operator T1 ()'
12200 	 beating `X::operator T2 () const', when T2 is a no less
12201 	 cv-qualified version of T1.  */
12202       if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
12203 	  && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
12204 	{
12205 	  tree t = TREE_TYPE (TREE_TYPE (l->fn));
12206 	  tree f = TREE_TYPE (TREE_TYPE (w->fn));
12207 
12208 	  if (TREE_CODE (t) == TREE_CODE (f) && INDIRECT_TYPE_P (t))
12209 	    {
12210 	      t = TREE_TYPE (t);
12211 	      f = TREE_TYPE (f);
12212 	    }
12213 	  if (!comp_ptr_ttypes (t, f))
12214 	    give_warning = true;
12215 	}
12216       else
12217 	give_warning = true;
12218 
12219       if (!give_warning)
12220 	/*NOP*/;
12221       else if (warn)
12222 	{
12223 	  tree source = source_type (w->convs[0]);
12224 	  if (INDIRECT_TYPE_P (source))
12225 	    source = TREE_TYPE (source);
12226 	  auto_diagnostic_group d;
12227 	  if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
12228 	      && warning (OPT_Wconversion, "  for conversion from %qH to %qI",
12229 			  source, w->second_conv->type))
12230 	    {
12231 	      inform (input_location, "  because conversion sequence "
12232 		      "for the argument is better");
12233 	    }
12234 	}
12235       else
12236 	add_warning (w, l);
12237     }
12238 
12239   if (winner)
12240     return winner;
12241 
12242   /* Put this tiebreaker first, so that we don't try to look at second_conv of
12243      a constructor candidate that doesn't have one.  */
12244   if (elided_tiebreaker)
12245     return elided_tiebreaker;
12246 
12247   /* DR 495 moved this tiebreaker above the template ones.  */
12248   /* or, if not that,
12249      the  context  is  an  initialization by user-defined conversion (see
12250      _dcl.init_  and  _over.match.user_)  and  the  standard   conversion
12251      sequence  from  the return type of F1 to the destination type (i.e.,
12252      the type of the entity being initialized)  is  a  better  conversion
12253      sequence  than the standard conversion sequence from the return type
12254      of F2 to the destination type.  */
12255 
12256   if (cand1->second_conv)
12257     {
12258       winner = compare_ics (cand1->second_conv, cand2->second_conv);
12259       if (winner)
12260 	return winner;
12261     }
12262 
12263   /* or, if not that,
12264      F1 is a non-template function and F2 is a template function
12265      specialization.  */
12266 
12267   if (!cand1->template_decl && cand2->template_decl)
12268     return 1;
12269   else if (cand1->template_decl && !cand2->template_decl)
12270     return -1;
12271 
12272   /* or, if not that,
12273      F1 and F2 are template functions and the function template for F1 is
12274      more specialized than the template for F2 according to the partial
12275      ordering rules.  */
12276 
12277   if (cand1->template_decl && cand2->template_decl)
12278     {
12279       winner = more_specialized_fn
12280 	(TI_TEMPLATE (cand1->template_decl),
12281 	 TI_TEMPLATE (cand2->template_decl),
12282 	 /* [temp.func.order]: The presence of unused ellipsis and default
12283 	    arguments has no effect on the partial ordering of function
12284 	    templates.   add_function_candidate() will not have
12285 	    counted the "this" argument for constructors.  */
12286 	 cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
12287       if (winner)
12288 	return winner;
12289     }
12290 
12291   /* Concepts: F1 and F2 are non-template functions with the same
12292      parameter-type-lists, and F1 is more constrained than F2 according to the
12293      partial ordering of constraints described in 13.5.4.  */
12294 
12295   if (flag_concepts && DECL_P (cand1->fn) && DECL_P (cand2->fn)
12296       && !cand1->template_decl && !cand2->template_decl
12297       && cand_parms_match (cand1, cand2))
12298     {
12299       winner = more_constrained (cand1->fn, cand2->fn);
12300       if (winner)
12301 	return winner;
12302     }
12303 
12304   /* F2 is a rewritten candidate (12.4.1.2) and F1 is not, or F1 and F2 are
12305      rewritten candidates, and F2 is a synthesized candidate with reversed
12306      order of parameters and F1 is not.  */
12307   if (cand1->rewritten ())
12308     {
12309       if (!cand2->rewritten ())
12310 	return -1;
12311       if (!cand1->reversed () && cand2->reversed ())
12312 	return 1;
12313       if (cand1->reversed () && !cand2->reversed ())
12314 	return -1;
12315     }
12316   else if (cand2->rewritten ())
12317     return 1;
12318 
12319   /* F1 is generated from a deduction-guide (13.3.1.8) and F2 is not */
12320   if (deduction_guide_p (cand1->fn))
12321     {
12322       gcc_assert (deduction_guide_p (cand2->fn));
12323       /* We distinguish between candidates from an explicit deduction guide and
12324 	 candidates built from a constructor based on DECL_ARTIFICIAL.  */
12325       int art1 = DECL_ARTIFICIAL (cand1->fn);
12326       int art2 = DECL_ARTIFICIAL (cand2->fn);
12327       if (art1 != art2)
12328 	return art2 - art1;
12329 
12330       if (art1)
12331 	{
12332 	  /* Prefer the special copy guide over a declared copy/move
12333 	     constructor.  */
12334 	  if (copy_guide_p (cand1->fn))
12335 	    return 1;
12336 	  if (copy_guide_p (cand2->fn))
12337 	    return -1;
12338 
12339 	  /* Prefer a candidate generated from a non-template constructor.  */
12340 	  int tg1 = template_guide_p (cand1->fn);
12341 	  int tg2 = template_guide_p (cand2->fn);
12342 	  if (tg1 != tg2)
12343 	    return tg2 - tg1;
12344 	}
12345     }
12346 
12347   /* F1 is a member of a class D, F2 is a member of a base class B of D, and
12348      for all arguments the corresponding parameters of F1 and F2 have the same
12349      type (CWG 2273/2277). */
12350   if (DECL_P (cand1->fn) && DECL_CLASS_SCOPE_P (cand1->fn)
12351       && !DECL_CONV_FN_P (cand1->fn)
12352       && DECL_P (cand2->fn) && DECL_CLASS_SCOPE_P (cand2->fn)
12353       && !DECL_CONV_FN_P (cand2->fn))
12354     {
12355       tree base1 = DECL_CONTEXT (strip_inheriting_ctors (cand1->fn));
12356       tree base2 = DECL_CONTEXT (strip_inheriting_ctors (cand2->fn));
12357 
12358       bool used1 = false;
12359       bool used2 = false;
12360       if (base1 == base2)
12361 	/* No difference.  */;
12362       else if (DERIVED_FROM_P (base1, base2))
12363 	used1 = true;
12364       else if (DERIVED_FROM_P (base2, base1))
12365 	used2 = true;
12366 
12367       if (int diff = used2 - used1)
12368 	{
12369 	  for (i = 0; i < len; ++i)
12370 	    {
12371 	      conversion *t1 = cand1->convs[i + off1];
12372 	      conversion *t2 = cand2->convs[i + off2];
12373 	      if (!same_type_p (t1->type, t2->type))
12374 		break;
12375 	    }
12376 	  if (i == len)
12377 	    return diff;
12378 	}
12379     }
12380 
12381   /* Check whether we can discard a builtin candidate, either because we
12382      have two identical ones or matching builtin and non-builtin candidates.
12383 
12384      (Pedantically in the latter case the builtin which matched the user
12385      function should not be added to the overload set, but we spot it here.
12386 
12387      [over.match.oper]
12388      ... the builtin candidates include ...
12389      - do not have the same parameter type list as any non-template
12390        non-member candidate.  */
12391 
12392   if (identifier_p (cand1->fn) || identifier_p (cand2->fn))
12393     {
12394       for (i = 0; i < len; ++i)
12395 	if (!same_type_p (cand1->convs[i]->type,
12396 			  cand2->convs[i]->type))
12397 	  break;
12398       if (i == cand1->num_convs)
12399 	{
12400 	  if (cand1->fn == cand2->fn)
12401 	    /* Two built-in candidates; arbitrarily pick one.  */
12402 	    return 1;
12403 	  else if (identifier_p (cand1->fn))
12404 	    /* cand1 is built-in; prefer cand2.  */
12405 	    return -1;
12406 	  else
12407 	    /* cand2 is built-in; prefer cand1.  */
12408 	    return 1;
12409 	}
12410     }
12411 
12412   /* For candidates of a multi-versioned function,  make the version with
12413      the highest priority win.  This version will be checked for dispatching
12414      first.  If this version can be inlined into the caller, the front-end
12415      will simply make a direct call to this function.  */
12416 
12417   if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12418       && DECL_FUNCTION_VERSIONED (cand1->fn)
12419       && TREE_CODE (cand2->fn) == FUNCTION_DECL
12420       && DECL_FUNCTION_VERSIONED (cand2->fn))
12421     {
12422       tree f1 = TREE_TYPE (cand1->fn);
12423       tree f2 = TREE_TYPE (cand2->fn);
12424       tree p1 = TYPE_ARG_TYPES (f1);
12425       tree p2 = TYPE_ARG_TYPES (f2);
12426 
12427       /* Check if cand1->fn and cand2->fn are versions of the same function.  It
12428          is possible that cand1->fn and cand2->fn are function versions but of
12429          different functions.  Check types to see if they are versions of the same
12430          function.  */
12431       if (compparms (p1, p2)
12432 	  && same_type_p (TREE_TYPE (f1), TREE_TYPE (f2)))
12433 	{
12434 	  /* Always make the version with the higher priority, more
12435 	     specialized, win.  */
12436 	  gcc_assert (targetm.compare_version_priority);
12437 	  if (targetm.compare_version_priority (cand1->fn, cand2->fn) >= 0)
12438 	    return 1;
12439 	  else
12440 	    return -1;
12441 	}
12442     }
12443 
12444   /* If the two function declarations represent the same function (this can
12445      happen with declarations in multiple scopes and arg-dependent lookup),
12446      arbitrarily choose one.  But first make sure the default args we're
12447      using match.  */
12448   if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
12449       && equal_functions (cand1->fn, cand2->fn))
12450     {
12451       tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
12452       tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
12453 
12454       gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
12455 
12456       for (i = 0; i < len; ++i)
12457 	{
12458 	  /* Don't crash if the fn is variadic.  */
12459 	  if (!parms1)
12460 	    break;
12461 	  parms1 = TREE_CHAIN (parms1);
12462 	  parms2 = TREE_CHAIN (parms2);
12463 	}
12464 
12465       if (off1)
12466 	parms1 = TREE_CHAIN (parms1);
12467       else if (off2)
12468 	parms2 = TREE_CHAIN (parms2);
12469 
12470       for (; parms1; ++i)
12471 	{
12472 	  if (!cp_tree_equal (TREE_PURPOSE (parms1),
12473 			      TREE_PURPOSE (parms2)))
12474 	    {
12475 	      if (warn)
12476 		{
12477 		  if (complain & tf_error)
12478 		    {
12479 		      auto_diagnostic_group d;
12480 		      if (permerror (input_location,
12481 				     "default argument mismatch in "
12482 				     "overload resolution"))
12483 			{
12484 			  inform (DECL_SOURCE_LOCATION (cand1->fn),
12485 				  " candidate 1: %q#F", cand1->fn);
12486 			  inform (DECL_SOURCE_LOCATION (cand2->fn),
12487 				  " candidate 2: %q#F", cand2->fn);
12488 			}
12489 		    }
12490 		  else
12491 		    return 0;
12492 		}
12493 	      else
12494 		add_warning (cand1, cand2);
12495 	      break;
12496 	    }
12497 	  parms1 = TREE_CHAIN (parms1);
12498 	  parms2 = TREE_CHAIN (parms2);
12499 	}
12500 
12501       return 1;
12502     }
12503 
12504 tweak:
12505 
12506   /* Extension: If the worst conversion for one candidate is better than the
12507      worst conversion for the other, take the first.  */
12508   if (!pedantic && (complain & tf_warning_or_error))
12509     {
12510       conversion_rank rank1 = cr_identity, rank2 = cr_identity;
12511       struct z_candidate *w = 0, *l = 0;
12512 
12513       for (i = 0; i < len; ++i)
12514 	{
12515 	  if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
12516 	    rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
12517 	  if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
12518 	    rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
12519 	}
12520       if (rank1 < rank2)
12521 	winner = 1, w = cand1, l = cand2;
12522       if (rank1 > rank2)
12523 	winner = -1, w = cand2, l = cand1;
12524       if (winner)
12525 	{
12526 	  /* Don't choose a deleted function over ambiguity.  */
12527 	  if (DECL_P (w->fn) && DECL_DELETED_FN (w->fn))
12528 	    return 0;
12529 	  if (warn)
12530 	    {
12531 	      auto_diagnostic_group d;
12532 	      if (pedwarn (input_location, 0,
12533 			   "ISO C++ says that these are ambiguous, even "
12534 			   "though the worst conversion for the first is "
12535 			   "better than the worst conversion for the second:"))
12536 		{
12537 		  print_z_candidate (input_location, N_("candidate 1:"), w);
12538 		  print_z_candidate (input_location, N_("candidate 2:"), l);
12539 		}
12540 	    }
12541 	  else
12542 	    add_warning (w, l);
12543 	  return winner;
12544 	}
12545     }
12546 
12547   gcc_assert (!winner);
12548   return 0;
12549 }
12550 
12551 /* Given a list of candidates for overloading, find the best one, if any.
12552    This algorithm has a worst case of O(2n) (winner is last), and a best
12553    case of O(n/2) (totally ambiguous); much better than a sorting
12554    algorithm.  */
12555 
12556 static struct z_candidate *
tourney(struct z_candidate * candidates,tsubst_flags_t complain)12557 tourney (struct z_candidate *candidates, tsubst_flags_t complain)
12558 {
12559   struct z_candidate *champ = candidates, *challenger;
12560   int fate;
12561   int champ_compared_to_predecessor = 0;
12562 
12563   /* Walk through the list once, comparing each current champ to the next
12564      candidate, knocking out a candidate or two with each comparison.  */
12565 
12566   for (challenger = champ->next; challenger; )
12567     {
12568       fate = joust (champ, challenger, 0, complain);
12569       if (fate == 1)
12570 	challenger = challenger->next;
12571       else
12572 	{
12573 	  if (fate == 0)
12574 	    {
12575 	      champ = challenger->next;
12576 	      if (champ == 0)
12577 		return NULL;
12578 	      champ_compared_to_predecessor = 0;
12579 	    }
12580 	  else
12581 	    {
12582 	      champ = challenger;
12583 	      champ_compared_to_predecessor = 1;
12584 	    }
12585 
12586 	  challenger = champ->next;
12587 	}
12588     }
12589 
12590   /* Make sure the champ is better than all the candidates it hasn't yet
12591      been compared to.  */
12592 
12593   for (challenger = candidates;
12594        challenger != champ
12595 	 && !(champ_compared_to_predecessor && challenger->next == champ);
12596        challenger = challenger->next)
12597     {
12598       fate = joust (champ, challenger, 0, complain);
12599       if (fate != 1)
12600 	return NULL;
12601     }
12602 
12603   return champ;
12604 }
12605 
12606 /* Returns nonzero if things of type FROM can be converted to TO.  */
12607 
12608 bool
can_convert(tree to,tree from,tsubst_flags_t complain)12609 can_convert (tree to, tree from, tsubst_flags_t complain)
12610 {
12611   tree arg = NULL_TREE;
12612   /* implicit_conversion only considers user-defined conversions
12613      if it has an expression for the call argument list.  */
12614   if (CLASS_TYPE_P (from) || CLASS_TYPE_P (to))
12615     arg = build_stub_object (from);
12616   return can_convert_arg (to, from, arg, LOOKUP_IMPLICIT, complain);
12617 }
12618 
12619 /* Returns nonzero if things of type FROM can be converted to TO with a
12620    standard conversion.  */
12621 
12622 bool
can_convert_standard(tree to,tree from,tsubst_flags_t complain)12623 can_convert_standard (tree to, tree from, tsubst_flags_t complain)
12624 {
12625   return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT, complain);
12626 }
12627 
12628 /* Returns nonzero if ARG (of type FROM) can be converted to TO.  */
12629 
12630 bool
can_convert_arg(tree to,tree from,tree arg,int flags,tsubst_flags_t complain)12631 can_convert_arg (tree to, tree from, tree arg, int flags,
12632 		 tsubst_flags_t complain)
12633 {
12634   conversion *t;
12635   void *p;
12636   bool ok_p;
12637 
12638   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
12639   p = conversion_obstack_alloc (0);
12640   /* We want to discard any access checks done for this test,
12641      as we might not be in the appropriate access context and
12642      we'll do the check again when we actually perform the
12643      conversion.  */
12644   push_deferring_access_checks (dk_deferred);
12645 
12646   t  = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
12647 			    flags, complain);
12648   ok_p = (t && !t->bad_p);
12649 
12650   /* Discard the access checks now.  */
12651   pop_deferring_access_checks ();
12652   /* Free all the conversions we allocated.  */
12653   obstack_free (&conversion_obstack, p);
12654 
12655   return ok_p;
12656 }
12657 
12658 /* Like can_convert_arg, but allows dubious conversions as well.  */
12659 
12660 bool
can_convert_arg_bad(tree to,tree from,tree arg,int flags,tsubst_flags_t complain)12661 can_convert_arg_bad (tree to, tree from, tree arg, int flags,
12662 		     tsubst_flags_t complain)
12663 {
12664   conversion *t;
12665   void *p;
12666 
12667   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
12668   p = conversion_obstack_alloc (0);
12669   /* Try to perform the conversion.  */
12670   t  = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
12671 			    flags, complain);
12672   /* Free all the conversions we allocated.  */
12673   obstack_free (&conversion_obstack, p);
12674 
12675   return t != NULL;
12676 }
12677 
12678 /* Return an IMPLICIT_CONV_EXPR from EXPR to TYPE with bits set from overload
12679    resolution FLAGS.  */
12680 
12681 tree
build_implicit_conv_flags(tree type,tree expr,int flags)12682 build_implicit_conv_flags (tree type, tree expr, int flags)
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   if (!(flags & LOOKUP_ONLYCONVERTING))
12691     IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
12692   if (flags & LOOKUP_NO_NARROWING)
12693     IMPLICIT_CONV_EXPR_BRACED_INIT (expr) = true;
12694   return expr;
12695 }
12696 
12697 /* Convert EXPR to TYPE.  Return the converted expression.
12698 
12699    Note that we allow bad conversions here because by the time we get to
12700    this point we are committed to doing the conversion.  If we end up
12701    doing a bad conversion, convert_like will complain.  */
12702 
12703 tree
perform_implicit_conversion_flags(tree type,tree expr,tsubst_flags_t complain,int flags)12704 perform_implicit_conversion_flags (tree type, tree expr,
12705 				   tsubst_flags_t complain, int flags)
12706 {
12707   conversion *conv;
12708   void *p;
12709   location_t loc = cp_expr_loc_or_input_loc (expr);
12710 
12711   if (TYPE_REF_P (type))
12712     expr = mark_lvalue_use (expr);
12713   else
12714     expr = mark_rvalue_use (expr);
12715 
12716   if (error_operand_p (expr))
12717     return error_mark_node;
12718 
12719   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
12720   p = conversion_obstack_alloc (0);
12721 
12722   conv = implicit_conversion (type, TREE_TYPE (expr), expr,
12723 			      /*c_cast_p=*/false,
12724 			      flags, complain);
12725 
12726   if (!conv)
12727     {
12728       if (complain & tf_error)
12729 	implicit_conversion_error (loc, type, expr);
12730       expr = error_mark_node;
12731     }
12732   else if (processing_template_decl && conv->kind != ck_identity)
12733     expr = build_implicit_conv_flags (type, expr, flags);
12734   else
12735     {
12736       /* Give a conversion call the same location as expr.  */
12737       iloc_sentinel il (loc);
12738       expr = convert_like (conv, expr, complain);
12739     }
12740 
12741   /* Free all the conversions we allocated.  */
12742   obstack_free (&conversion_obstack, p);
12743 
12744   return expr;
12745 }
12746 
12747 tree
perform_implicit_conversion(tree type,tree expr,tsubst_flags_t complain)12748 perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
12749 {
12750   return perform_implicit_conversion_flags (type, expr, complain,
12751 					    LOOKUP_IMPLICIT);
12752 }
12753 
12754 /* Convert EXPR to TYPE (as a direct-initialization) if that is
12755    permitted.  If the conversion is valid, the converted expression is
12756    returned.  Otherwise, NULL_TREE is returned, except in the case
12757    that TYPE is a class type; in that case, an error is issued.  If
12758    C_CAST_P is true, then this direct-initialization is taking
12759    place as part of a static_cast being attempted as part of a C-style
12760    cast.  */
12761 
12762 tree
perform_direct_initialization_if_possible(tree type,tree expr,bool c_cast_p,tsubst_flags_t complain)12763 perform_direct_initialization_if_possible (tree type,
12764 					   tree expr,
12765 					   bool c_cast_p,
12766                                            tsubst_flags_t complain)
12767 {
12768   conversion *conv;
12769   void *p;
12770 
12771   if (type == error_mark_node || error_operand_p (expr))
12772     return error_mark_node;
12773   /* [dcl.init]
12774 
12775      If the destination type is a (possibly cv-qualified) class type:
12776 
12777      -- If the initialization is direct-initialization ...,
12778      constructors are considered.
12779 
12780        -- If overload resolution is successful, the selected constructor
12781        is called to initialize the object, with the initializer expression
12782        or expression-list as its argument(s).
12783 
12784        -- Otherwise, if no constructor is viable, the destination type is
12785        a (possibly cv-qualified) aggregate class A, and the initializer is
12786        a parenthesized expression-list, the object is initialized as
12787        follows...  */
12788   if (CLASS_TYPE_P (type))
12789     {
12790       releasing_vec args (make_tree_vector_single (expr));
12791       expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
12792 					&args, type, LOOKUP_NORMAL, complain);
12793       return build_cplus_new (type, expr, complain);
12794     }
12795 
12796   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
12797   p = conversion_obstack_alloc (0);
12798 
12799   conv = implicit_conversion (type, TREE_TYPE (expr), expr,
12800 			      c_cast_p,
12801 			      LOOKUP_NORMAL, complain);
12802   if (!conv || conv->bad_p)
12803     expr = NULL_TREE;
12804   else if (processing_template_decl && conv->kind != ck_identity)
12805     {
12806       /* In a template, we are only concerned about determining the
12807 	 type of non-dependent expressions, so we do not have to
12808 	 perform the actual conversion.  But for initializers, we
12809 	 need to be able to perform it at instantiation
12810 	 (or instantiate_non_dependent_expr) time.  */
12811       expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
12812       IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
12813     }
12814   else
12815     expr = convert_like (conv, expr, NULL_TREE, 0,
12816 			 /*issue_conversion_warnings=*/false,
12817 			 c_cast_p, complain);
12818 
12819   /* Free all the conversions we allocated.  */
12820   obstack_free (&conversion_obstack, p);
12821 
12822   return expr;
12823 }
12824 
12825 /* When initializing a reference that lasts longer than a full-expression,
12826    this special rule applies:
12827 
12828      [class.temporary]
12829 
12830      The temporary to which the reference is bound or the temporary
12831      that is the complete object to which the reference is bound
12832      persists for the lifetime of the reference.
12833 
12834      The temporaries created during the evaluation of the expression
12835      initializing the reference, except the temporary to which the
12836      reference is bound, are destroyed at the end of the
12837      full-expression in which they are created.
12838 
12839    In that case, we store the converted expression into a new
12840    VAR_DECL in a new scope.
12841 
12842    However, we want to be careful not to create temporaries when
12843    they are not required.  For example, given:
12844 
12845      struct B {};
12846      struct D : public B {};
12847      D f();
12848      const B& b = f();
12849 
12850    there is no need to copy the return value from "f"; we can just
12851    extend its lifetime.  Similarly, given:
12852 
12853      struct S {};
12854      struct T { operator S(); };
12855      T t;
12856      const S& s = t;
12857 
12858   we can extend the lifetime of the return value of the conversion
12859   operator.
12860 
12861   The next several functions are involved in this lifetime extension.  */
12862 
12863 /* DECL is a VAR_DECL or FIELD_DECL whose type is a REFERENCE_TYPE.  The
12864    reference is being bound to a temporary.  Create and return a new
12865    VAR_DECL with the indicated TYPE; this variable will store the value to
12866    which the reference is bound.  */
12867 
12868 tree
make_temporary_var_for_ref_to_temp(tree decl,tree type)12869 make_temporary_var_for_ref_to_temp (tree decl, tree type)
12870 {
12871   tree var = create_temporary_var (type);
12872 
12873   /* Register the variable.  */
12874   if (VAR_P (decl)
12875       && (TREE_STATIC (decl) || CP_DECL_THREAD_LOCAL_P (decl)))
12876     {
12877       /* Namespace-scope or local static; give it a mangled name.  */
12878 
12879       /* If an initializer is visible to multiple translation units, those
12880 	 translation units must agree on the addresses of the
12881 	 temporaries. Therefore the temporaries must be given a consistent name
12882 	 and vague linkage. The mangled name of a temporary is the name of the
12883 	 non-temporary object in whose initializer they appear, prefixed with
12884 	 GR and suffixed with a sequence number mangled using the usual rules
12885 	 for a seq-id. Temporaries are numbered with a pre-order, depth-first,
12886 	 left-to-right walk of the complete initializer.  */
12887       copy_linkage (var, decl);
12888 
12889       tree name = mangle_ref_init_variable (decl);
12890       DECL_NAME (var) = name;
12891       SET_DECL_ASSEMBLER_NAME (var, name);
12892     }
12893   else
12894     /* Create a new cleanup level if necessary.  */
12895     maybe_push_cleanup_level (type);
12896 
12897   return pushdecl (var);
12898 }
12899 
12900 /* EXPR is the initializer for a variable DECL of reference or
12901    std::initializer_list type.  Create, push and return a new VAR_DECL
12902    for the initializer so that it will live as long as DECL.  Any
12903    cleanup for the new variable is returned through CLEANUP, and the
12904    code to initialize the new variable is returned through INITP.  */
12905 
12906 static tree
set_up_extended_ref_temp(tree decl,tree expr,vec<tree,va_gc> ** cleanups,tree * initp,tree * cond_guard)12907 set_up_extended_ref_temp (tree decl, tree expr, vec<tree, va_gc> **cleanups,
12908 			  tree *initp, tree *cond_guard)
12909 {
12910   tree init;
12911   tree type;
12912   tree var;
12913 
12914   /* Create the temporary variable.  */
12915   type = TREE_TYPE (expr);
12916   var = make_temporary_var_for_ref_to_temp (decl, type);
12917   layout_decl (var, 0);
12918   /* If the rvalue is the result of a function call it will be
12919      a TARGET_EXPR.  If it is some other construct (such as a
12920      member access expression where the underlying object is
12921      itself the result of a function call), turn it into a
12922      TARGET_EXPR here.  It is important that EXPR be a
12923      TARGET_EXPR below since otherwise the INIT_EXPR will
12924      attempt to make a bitwise copy of EXPR to initialize
12925      VAR.  */
12926   if (TREE_CODE (expr) != TARGET_EXPR)
12927     expr = get_target_expr (expr);
12928   else if (TREE_ADDRESSABLE (expr))
12929     TREE_ADDRESSABLE (var) = 1;
12930 
12931   if (TREE_CODE (decl) == FIELD_DECL
12932       && extra_warnings && !warning_suppressed_p (decl))
12933     {
12934       warning (OPT_Wextra, "a temporary bound to %qD only persists "
12935 	       "until the constructor exits", decl);
12936       suppress_warning (decl);
12937     }
12938 
12939   /* Recursively extend temps in this initializer.  */
12940   TARGET_EXPR_INITIAL (expr)
12941     = extend_ref_init_temps (decl, TARGET_EXPR_INITIAL (expr), cleanups,
12942 			     cond_guard);
12943 
12944   /* Any reference temp has a non-trivial initializer.  */
12945   DECL_NONTRIVIALLY_INITIALIZED_P (var) = true;
12946 
12947   /* If the initializer is constant, put it in DECL_INITIAL so we get
12948      static initialization and use in constant expressions.  */
12949   init = maybe_constant_init (expr, var, /*manifestly_const_eval=*/true);
12950   /* As in store_init_value.  */
12951   init = cp_fully_fold (init);
12952   if (TREE_CONSTANT (init))
12953     {
12954       if (literal_type_p (type) && CP_TYPE_CONST_NON_VOLATILE_P (type))
12955 	{
12956 	  /* 5.19 says that a constant expression can include an
12957 	     lvalue-rvalue conversion applied to "a glvalue of literal type
12958 	     that refers to a non-volatile temporary object initialized
12959 	     with a constant expression".  Rather than try to communicate
12960 	     that this VAR_DECL is a temporary, just mark it constexpr.  */
12961 	  DECL_DECLARED_CONSTEXPR_P (var) = true;
12962 	  DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var) = true;
12963 	  TREE_CONSTANT (var) = true;
12964 	  TREE_READONLY (var) = true;
12965 	}
12966       DECL_INITIAL (var) = init;
12967       init = NULL_TREE;
12968     }
12969   else
12970     /* Create the INIT_EXPR that will initialize the temporary
12971        variable.  */
12972     init = split_nonconstant_init (var, expr);
12973   if (at_function_scope_p ())
12974     {
12975       add_decl_expr (var);
12976 
12977       if (TREE_STATIC (var))
12978 	init = add_stmt_to_compound (init, register_dtor_fn (var));
12979       else
12980 	{
12981 	  tree cleanup = cxx_maybe_build_cleanup (var, tf_warning_or_error);
12982 	  if (cleanup)
12983 	    {
12984 	      if (cond_guard && cleanup != error_mark_node)
12985 		{
12986 		  if (*cond_guard == NULL_TREE)
12987 		    {
12988 		      *cond_guard = build_local_temp (boolean_type_node);
12989 		      add_decl_expr (*cond_guard);
12990 		      tree set = cp_build_modify_expr (UNKNOWN_LOCATION,
12991 						       *cond_guard, NOP_EXPR,
12992 						       boolean_false_node,
12993 						       tf_warning_or_error);
12994 		      finish_expr_stmt (set);
12995 		    }
12996 		  cleanup = build3 (COND_EXPR, void_type_node,
12997 				    *cond_guard, cleanup, NULL_TREE);
12998 		}
12999 	      vec_safe_push (*cleanups, cleanup);
13000 	    }
13001 	}
13002 
13003       /* We must be careful to destroy the temporary only
13004 	 after its initialization has taken place.  If the
13005 	 initialization throws an exception, then the
13006 	 destructor should not be run.  We cannot simply
13007 	 transform INIT into something like:
13008 
13009 	 (INIT, ({ CLEANUP_STMT; }))
13010 
13011 	 because emit_local_var always treats the
13012 	 initializer as a full-expression.  Thus, the
13013 	 destructor would run too early; it would run at the
13014 	 end of initializing the reference variable, rather
13015 	 than at the end of the block enclosing the
13016 	 reference variable.
13017 
13018 	 The solution is to pass back a cleanup expression
13019 	 which the caller is responsible for attaching to
13020 	 the statement tree.  */
13021     }
13022   else
13023     {
13024       rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
13025       if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
13026 	{
13027 	  if (CP_DECL_THREAD_LOCAL_P (var))
13028 	    tls_aggregates = tree_cons (NULL_TREE, var,
13029 					tls_aggregates);
13030 	  else
13031 	    static_aggregates = tree_cons (NULL_TREE, var,
13032 					   static_aggregates);
13033 	}
13034       else
13035 	/* Check whether the dtor is callable.  */
13036 	cxx_maybe_build_cleanup (var, tf_warning_or_error);
13037     }
13038   /* Avoid -Wunused-variable warning (c++/38958).  */
13039   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
13040       && VAR_P (decl))
13041     TREE_USED (decl) = DECL_READ_P (decl) = true;
13042 
13043   *initp = init;
13044   return var;
13045 }
13046 
13047 /* Convert EXPR to the indicated reference TYPE, in a way suitable for
13048    initializing a variable of that TYPE.  */
13049 
13050 tree
initialize_reference(tree type,tree expr,int flags,tsubst_flags_t complain)13051 initialize_reference (tree type, tree expr,
13052 		      int flags, tsubst_flags_t complain)
13053 {
13054   conversion *conv;
13055   void *p;
13056   location_t loc = cp_expr_loc_or_input_loc (expr);
13057 
13058   if (type == error_mark_node || error_operand_p (expr))
13059     return error_mark_node;
13060 
13061   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
13062   p = conversion_obstack_alloc (0);
13063 
13064   conv = reference_binding (type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
13065 			    flags, complain);
13066   /* If this conversion failed, we're in C++20, and we have something like
13067      A& a(b) where A is an aggregate, try again, this time as A& a{b}.  */
13068   if ((!conv || conv->bad_p)
13069       && (flags & LOOKUP_AGGREGATE_PAREN_INIT))
13070     {
13071       tree e = build_constructor_single (init_list_type_node, NULL_TREE, expr);
13072       CONSTRUCTOR_IS_DIRECT_INIT (e) = true;
13073       CONSTRUCTOR_IS_PAREN_INIT (e) = true;
13074       conversion *c = reference_binding (type, TREE_TYPE (e), e,
13075 					 /*c_cast_p=*/false, flags, complain);
13076       /* If this worked, use it.  */
13077       if (c && !c->bad_p)
13078 	expr = e, conv = c;
13079     }
13080   if (!conv || conv->bad_p)
13081     {
13082       if (complain & tf_error)
13083 	{
13084 	  if (conv)
13085 	    convert_like (conv, expr, complain);
13086 	  else if (!CP_TYPE_CONST_P (TREE_TYPE (type))
13087 		   && !TYPE_REF_IS_RVALUE (type)
13088 		   && !lvalue_p (expr))
13089 	    error_at (loc, "invalid initialization of non-const reference of "
13090 		      "type %qH from an rvalue of type %qI",
13091 		      type, TREE_TYPE (expr));
13092 	  else
13093 	    error_at (loc, "invalid initialization of reference of type "
13094 		      "%qH from expression of type %qI", type,
13095 		      TREE_TYPE (expr));
13096 	}
13097       return error_mark_node;
13098     }
13099 
13100   if (conv->kind == ck_ref_bind)
13101     /* Perform the conversion.  */
13102     expr = convert_like (conv, expr, complain);
13103   else if (conv->kind == ck_ambig)
13104     /* We gave an error in build_user_type_conversion_1.  */
13105     expr = error_mark_node;
13106   else
13107     gcc_unreachable ();
13108 
13109   /* Free all the conversions we allocated.  */
13110   obstack_free (&conversion_obstack, p);
13111 
13112   return expr;
13113 }
13114 
13115 /* If *P is an xvalue expression, prevent temporary lifetime extension if it
13116    gets used to initialize a reference.  */
13117 
13118 static tree
prevent_lifetime_extension(tree t)13119 prevent_lifetime_extension (tree t)
13120 {
13121   tree *p = &t;
13122   while (TREE_CODE (*p) == COMPOUND_EXPR)
13123     p = &TREE_OPERAND (*p, 1);
13124   while (handled_component_p (*p))
13125     p = &TREE_OPERAND (*p, 0);
13126   /* Change a TARGET_EXPR from prvalue to xvalue.  */
13127   if (TREE_CODE (*p) == TARGET_EXPR)
13128     *p = build2 (COMPOUND_EXPR, TREE_TYPE (*p), *p,
13129 		 move (TARGET_EXPR_SLOT (*p)));
13130   return t;
13131 }
13132 
13133 /* Subroutine of extend_ref_init_temps.  Possibly extend one initializer,
13134    which is bound either to a reference or a std::initializer_list.  */
13135 
13136 static tree
extend_ref_init_temps_1(tree decl,tree init,vec<tree,va_gc> ** cleanups,tree * cond_guard)13137 extend_ref_init_temps_1 (tree decl, tree init, vec<tree, va_gc> **cleanups,
13138 			 tree *cond_guard)
13139 {
13140   tree sub = init;
13141   tree *p;
13142   STRIP_NOPS (sub);
13143   if (TREE_CODE (sub) == COMPOUND_EXPR)
13144     {
13145       TREE_OPERAND (sub, 1)
13146 	= extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
13147 				   cond_guard);
13148       return init;
13149     }
13150   if (TREE_CODE (sub) == COND_EXPR)
13151     {
13152       tree cur_cond_guard = NULL_TREE;
13153       if (TREE_OPERAND (sub, 1))
13154 	TREE_OPERAND (sub, 1)
13155 	  = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
13156 				     &cur_cond_guard);
13157       if (cur_cond_guard)
13158 	{
13159 	  tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
13160 					   NOP_EXPR, boolean_true_node,
13161 					   tf_warning_or_error);
13162 	  TREE_OPERAND (sub, 1)
13163 	    = cp_build_compound_expr (set, TREE_OPERAND (sub, 1),
13164 				      tf_warning_or_error);
13165 	}
13166       cur_cond_guard = NULL_TREE;
13167       if (TREE_OPERAND (sub, 2))
13168 	TREE_OPERAND (sub, 2)
13169 	  = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 2), cleanups,
13170 				     &cur_cond_guard);
13171       if (cur_cond_guard)
13172 	{
13173 	  tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
13174 					   NOP_EXPR, boolean_true_node,
13175 					   tf_warning_or_error);
13176 	  TREE_OPERAND (sub, 2)
13177 	    = cp_build_compound_expr (set, TREE_OPERAND (sub, 2),
13178 				      tf_warning_or_error);
13179 	}
13180       return init;
13181     }
13182   if (TREE_CODE (sub) != ADDR_EXPR)
13183     return init;
13184   /* Deal with binding to a subobject.  */
13185   for (p = &TREE_OPERAND (sub, 0);
13186        TREE_CODE (*p) == COMPONENT_REF || TREE_CODE (*p) == ARRAY_REF; )
13187     p = &TREE_OPERAND (*p, 0);
13188   if (TREE_CODE (*p) == TARGET_EXPR)
13189     {
13190       tree subinit = NULL_TREE;
13191       *p = set_up_extended_ref_temp (decl, *p, cleanups, &subinit, cond_guard);
13192       recompute_tree_invariant_for_addr_expr (sub);
13193       if (init != sub)
13194 	init = fold_convert (TREE_TYPE (init), sub);
13195       if (subinit)
13196 	init = build2 (COMPOUND_EXPR, TREE_TYPE (init), subinit, init);
13197     }
13198   return init;
13199 }
13200 
13201 /* INIT is part of the initializer for DECL.  If there are any
13202    reference or initializer lists being initialized, extend their
13203    lifetime to match that of DECL.  */
13204 
13205 tree
extend_ref_init_temps(tree decl,tree init,vec<tree,va_gc> ** cleanups,tree * cond_guard)13206 extend_ref_init_temps (tree decl, tree init, vec<tree, va_gc> **cleanups,
13207 		       tree *cond_guard)
13208 {
13209   tree type = TREE_TYPE (init);
13210   if (processing_template_decl)
13211     return init;
13212   if (TYPE_REF_P (type))
13213     init = extend_ref_init_temps_1 (decl, init, cleanups, cond_guard);
13214   else
13215     {
13216       tree ctor = init;
13217       if (TREE_CODE (ctor) == TARGET_EXPR)
13218 	ctor = TARGET_EXPR_INITIAL (ctor);
13219       if (TREE_CODE (ctor) == CONSTRUCTOR)
13220 	{
13221 	  /* [dcl.init] When initializing an aggregate from a parenthesized list
13222 	     of values... a temporary object bound to a reference does not have
13223 	     its lifetime extended.  */
13224 	  if (CONSTRUCTOR_IS_PAREN_INIT (ctor))
13225 	    return init;
13226 
13227 	  if (is_std_init_list (type))
13228 	    {
13229 	      /* The temporary array underlying a std::initializer_list
13230 		 is handled like a reference temporary.  */
13231 	      tree array = CONSTRUCTOR_ELT (ctor, 0)->value;
13232 	      array = extend_ref_init_temps_1 (decl, array, cleanups,
13233 					       cond_guard);
13234 	      CONSTRUCTOR_ELT (ctor, 0)->value = array;
13235 	    }
13236 	  else
13237 	    {
13238 	      unsigned i;
13239 	      constructor_elt *p;
13240 	      vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
13241 	      FOR_EACH_VEC_SAFE_ELT (elts, i, p)
13242 		p->value = extend_ref_init_temps (decl, p->value, cleanups,
13243 						  cond_guard);
13244 	    }
13245 	  recompute_constructor_flags (ctor);
13246 	  if (decl_maybe_constant_var_p (decl) && TREE_CONSTANT (ctor))
13247 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
13248 	}
13249     }
13250 
13251   return init;
13252 }
13253 
13254 /* Returns true iff an initializer for TYPE could contain temporaries that
13255    need to be extended because they are bound to references or
13256    std::initializer_list.  */
13257 
13258 bool
type_has_extended_temps(tree type)13259 type_has_extended_temps (tree type)
13260 {
13261   type = strip_array_types (type);
13262   if (TYPE_REF_P (type))
13263     return true;
13264   if (CLASS_TYPE_P (type))
13265     {
13266       if (is_std_init_list (type))
13267 	return true;
13268       for (tree f = next_initializable_field (TYPE_FIELDS (type));
13269 	   f; f = next_initializable_field (DECL_CHAIN (f)))
13270 	if (type_has_extended_temps (TREE_TYPE (f)))
13271 	  return true;
13272     }
13273   return false;
13274 }
13275 
13276 /* Returns true iff TYPE is some variant of std::initializer_list.  */
13277 
13278 bool
is_std_init_list(tree type)13279 is_std_init_list (tree type)
13280 {
13281   if (!TYPE_P (type))
13282     return false;
13283   if (cxx_dialect == cxx98)
13284     return false;
13285   /* Look through typedefs.  */
13286   type = TYPE_MAIN_VARIANT (type);
13287   return (CLASS_TYPE_P (type)
13288 	  && CP_TYPE_CONTEXT (type) == std_node
13289 	  && init_list_identifier == DECL_NAME (TYPE_NAME (type)));
13290 }
13291 
13292 /* Returns true iff DECL is a list constructor: i.e. a constructor which
13293    will accept an argument list of a single std::initializer_list<T>.  */
13294 
13295 bool
is_list_ctor(tree decl)13296 is_list_ctor (tree decl)
13297 {
13298   tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
13299   tree arg;
13300 
13301   if (!args || args == void_list_node)
13302     return false;
13303 
13304   arg = non_reference (TREE_VALUE (args));
13305   if (!is_std_init_list (arg))
13306     return false;
13307 
13308   args = TREE_CHAIN (args);
13309 
13310   if (args && args != void_list_node && !TREE_PURPOSE (args))
13311     /* There are more non-defaulted parms.  */
13312     return false;
13313 
13314   return true;
13315 }
13316 
13317 #include "gt-cp-call.h"
13318