c++: track whether we expect a TARGET_EXPR to be elided
[official-gcc.git] / gcc / cp / call.cc
blob70ec964a21914b2252b8bd865d7565a80aaa5c95
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).
6 This file is part of GCC.
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.
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.
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/>. */
23 /* High-level class interface. */
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"
46 /* The various kinds of conversion. */
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 /* When LOOKUP_SHORTCUT_BAD_CONVS is set, we may return a conversion of
64 this kind whenever we know the true conversion is either bad or outright
65 invalid, but we don't want to attempt to compute the bad conversion (for
66 sake of avoiding unnecessary instantiation). bad_p should always be set
67 for these. */
68 ck_deferred_bad,
71 /* The rank of the conversion. Order of the enumerals matters; better
72 conversions should come earlier in the list. */
74 enum conversion_rank {
75 cr_identity,
76 cr_exact,
77 cr_promotion,
78 cr_std,
79 cr_pbool,
80 cr_user,
81 cr_ellipsis,
82 cr_bad
85 /* An implicit conversion sequence, in the sense of [over.best.ics].
86 The first conversion to be performed is at the end of the chain.
87 That conversion is always a cr_identity conversion. */
89 struct conversion {
90 /* The kind of conversion represented by this step. */
91 conversion_kind kind;
92 /* The rank of this conversion. */
93 conversion_rank rank;
94 BOOL_BITFIELD user_conv_p : 1;
95 BOOL_BITFIELD ellipsis_p : 1;
96 BOOL_BITFIELD this_p : 1;
97 /* True if this conversion would be permitted with a bending of
98 language standards, e.g. disregarding pointer qualifiers or
99 converting integers to pointers. */
100 BOOL_BITFIELD bad_p : 1;
101 /* If KIND is ck_ref_bind or ck_base, true to indicate that a
102 temporary should be created to hold the result of the
103 conversion. If KIND is ck_ambig or ck_user, true means force
104 copy-initialization. */
105 BOOL_BITFIELD need_temporary_p : 1;
106 /* If KIND is ck_ptr or ck_pmem, true to indicate that a conversion
107 from a pointer-to-derived to pointer-to-base is being performed. */
108 BOOL_BITFIELD base_p : 1;
109 /* If KIND is ck_ref_bind, true when either an lvalue reference is
110 being bound to an lvalue expression or an rvalue reference is
111 being bound to an rvalue expression. If KIND is ck_rvalue or ck_base,
112 true when we are treating an lvalue as an rvalue (12.8p33). If
113 ck_identity, we will be binding a reference directly or decaying to
114 a pointer. */
115 BOOL_BITFIELD rvaluedness_matches_p: 1;
116 BOOL_BITFIELD check_narrowing: 1;
117 /* Whether check_narrowing should only check TREE_CONSTANTs; used
118 in build_converted_constant_expr. */
119 BOOL_BITFIELD check_narrowing_const_only: 1;
120 /* True if this conversion is taking place in a copy-initialization context
121 and we should only consider converting constructors. Only set in
122 ck_base and ck_rvalue. */
123 BOOL_BITFIELD copy_init_p : 1;
124 /* The type of the expression resulting from the conversion. */
125 tree type;
126 union {
127 /* The next conversion in the chain. Since the conversions are
128 arranged from outermost to innermost, the NEXT conversion will
129 actually be performed before this conversion. This variant is
130 used only when KIND is neither ck_identity, ck_aggr, ck_ambig nor
131 ck_list. Please use the next_conversion function instead
132 of using this field directly. */
133 conversion *next;
134 /* The expression at the beginning of the conversion chain. This
135 variant is used only if KIND is ck_identity, ck_aggr, or ck_ambig.
136 You can use conv_get_original_expr to get this expression. */
137 tree expr;
138 /* The array of conversions for an initializer_list, so this
139 variant is used only when KIN D is ck_list. */
140 conversion **list;
141 } u;
142 /* The function candidate corresponding to this conversion
143 sequence. This field is only used if KIND is ck_user. */
144 struct z_candidate *cand;
147 #define CONVERSION_RANK(NODE) \
148 ((NODE)->bad_p ? cr_bad \
149 : (NODE)->ellipsis_p ? cr_ellipsis \
150 : (NODE)->user_conv_p ? cr_user \
151 : (NODE)->rank)
153 #define BAD_CONVERSION_RANK(NODE) \
154 ((NODE)->ellipsis_p ? cr_ellipsis \
155 : (NODE)->user_conv_p ? cr_user \
156 : (NODE)->rank)
158 static struct obstack conversion_obstack;
159 static bool conversion_obstack_initialized;
160 struct rejection_reason;
162 static struct z_candidate * tourney (struct z_candidate *, tsubst_flags_t);
163 static int equal_functions (tree, tree);
164 static int joust (struct z_candidate *, struct z_candidate *, bool,
165 tsubst_flags_t);
166 static int compare_ics (conversion *, conversion *);
167 static void maybe_warn_class_memaccess (location_t, tree,
168 const vec<tree, va_gc> *);
169 static tree build_over_call (struct z_candidate *, int, tsubst_flags_t);
170 static tree convert_like (conversion *, tree, tsubst_flags_t);
171 static tree convert_like_with_context (conversion *, tree, tree, int,
172 tsubst_flags_t);
173 static void op_error (const op_location_t &, enum tree_code, enum tree_code,
174 tree, tree, tree, bool);
175 static struct z_candidate *build_user_type_conversion_1 (tree, tree, int,
176 tsubst_flags_t);
177 static void print_z_candidate (location_t, const char *, struct z_candidate *);
178 static void print_z_candidates (location_t, struct z_candidate *);
179 static tree build_this (tree);
180 static struct z_candidate *splice_viable (struct z_candidate *, bool, bool *);
181 static bool any_strictly_viable (struct z_candidate *);
182 static struct z_candidate *add_template_candidate
183 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
184 tree, tree, tree, int, unification_kind_t, bool, tsubst_flags_t);
185 static struct z_candidate *add_template_candidate_real
186 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
187 tree, tree, tree, int, tree, unification_kind_t, bool, tsubst_flags_t);
188 static bool is_complete (tree);
189 static struct z_candidate *add_conv_candidate
190 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, tree,
191 tree, tsubst_flags_t);
192 static struct z_candidate *add_function_candidate
193 (struct z_candidate **, tree, tree, tree, const vec<tree, va_gc> *, tree,
194 tree, int, conversion**, bool, tsubst_flags_t);
195 static conversion *implicit_conversion (tree, tree, tree, bool, int,
196 tsubst_flags_t);
197 static conversion *reference_binding (tree, tree, tree, bool, int,
198 tsubst_flags_t);
199 static conversion *build_conv (conversion_kind, tree, conversion *);
200 static conversion *build_list_conv (tree, tree, int, tsubst_flags_t);
201 static conversion *next_conversion (conversion *);
202 static bool is_subseq (conversion *, conversion *);
203 static conversion *maybe_handle_ref_bind (conversion **);
204 static void maybe_handle_implicit_object (conversion **);
205 static struct z_candidate *add_candidate
206 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, size_t,
207 conversion **, tree, tree, int, struct rejection_reason *, int);
208 static tree source_type (conversion *);
209 static void add_warning (struct z_candidate *, struct z_candidate *);
210 static conversion *direct_reference_binding (tree, conversion *);
211 static bool promoted_arithmetic_type_p (tree);
212 static conversion *conditional_conversion (tree, tree, tsubst_flags_t);
213 static char *name_as_c_string (tree, tree, bool *);
214 static tree prep_operand (tree);
215 static void add_candidates (tree, tree, const vec<tree, va_gc> *, tree, tree,
216 bool, tree, tree, int, struct z_candidate **,
217 tsubst_flags_t);
218 static conversion *merge_conversion_sequences (conversion *, conversion *);
219 static tree build_temp (tree, tree, int, diagnostic_t *, tsubst_flags_t);
220 static conversion *build_identity_conv (tree, tree);
221 static inline bool conv_binds_to_array_of_unknown_bound (conversion *);
222 static bool conv_is_prvalue (conversion *);
223 static tree prevent_lifetime_extension (tree);
225 /* Returns nonzero iff the destructor name specified in NAME matches BASETYPE.
226 NAME can take many forms... */
228 bool
229 check_dtor_name (tree basetype, tree name)
231 /* Just accept something we've already complained about. */
232 if (name == error_mark_node)
233 return true;
235 if (TREE_CODE (name) == TYPE_DECL)
236 name = TREE_TYPE (name);
237 else if (TYPE_P (name))
238 /* OK */;
239 else if (identifier_p (name))
241 if ((MAYBE_CLASS_TYPE_P (basetype)
242 || TREE_CODE (basetype) == ENUMERAL_TYPE)
243 && name == constructor_name (basetype))
244 return true;
246 /* Otherwise lookup the name, it could be an unrelated typedef
247 of the correct type. */
248 name = lookup_name (name, LOOK_want::TYPE);
249 if (!name)
250 return false;
251 name = TREE_TYPE (name);
252 if (name == error_mark_node)
253 return false;
255 else
257 /* In the case of:
259 template <class T> struct S { ~S(); };
260 int i;
261 i.~S();
263 NAME will be a class template. */
264 gcc_assert (DECL_CLASS_TEMPLATE_P (name));
265 return false;
268 return same_type_p (TYPE_MAIN_VARIANT (basetype), TYPE_MAIN_VARIANT (name));
271 /* We want the address of a function or method. We avoid creating a
272 pointer-to-member function. */
274 tree
275 build_addr_func (tree function, tsubst_flags_t complain)
277 tree type = TREE_TYPE (function);
279 /* We have to do these by hand to avoid real pointer to member
280 functions. */
281 if (TREE_CODE (type) == METHOD_TYPE)
283 if (TREE_CODE (function) == OFFSET_REF)
285 tree object = build_address (TREE_OPERAND (function, 0));
286 return get_member_function_from_ptrfunc (&object,
287 TREE_OPERAND (function, 1),
288 complain);
290 function = build_address (function);
292 else if (TREE_CODE (function) == FUNCTION_DECL
293 && DECL_IMMEDIATE_FUNCTION_P (function))
294 function = build_address (function);
295 else
296 function = decay_conversion (function, complain, /*reject_builtin=*/false);
298 return function;
301 /* Build a CALL_EXPR, we can handle FUNCTION_TYPEs, METHOD_TYPEs, or
302 POINTER_TYPE to those. Note, pointer to member function types
303 (TYPE_PTRMEMFUNC_P) must be handled by our callers. There are
304 two variants. build_call_a is the primitive taking an array of
305 arguments, while build_call_n is a wrapper that handles varargs. */
307 tree
308 build_call_n (tree function, int n, ...)
310 if (n == 0)
311 return build_call_a (function, 0, NULL);
312 else
314 tree *argarray = XALLOCAVEC (tree, n);
315 va_list ap;
316 int i;
318 va_start (ap, n);
319 for (i = 0; i < n; i++)
320 argarray[i] = va_arg (ap, tree);
321 va_end (ap);
322 return build_call_a (function, n, argarray);
326 /* Update various flags in cfun and the call itself based on what is being
327 called. Split out of build_call_a so that bot_manip can use it too. */
329 void
330 set_flags_from_callee (tree call)
332 /* Handle both CALL_EXPRs and AGGR_INIT_EXPRs. */
333 tree decl = cp_get_callee_fndecl_nofold (call);
335 /* We check both the decl and the type; a function may be known not to
336 throw without being declared throw(). */
337 bool nothrow = decl && TREE_NOTHROW (decl);
338 tree callee = cp_get_callee (call);
339 if (callee)
340 nothrow |= TYPE_NOTHROW_P (TREE_TYPE (TREE_TYPE (callee)));
341 else if (TREE_CODE (call) == CALL_EXPR
342 && internal_fn_flags (CALL_EXPR_IFN (call)) & ECF_NOTHROW)
343 nothrow = true;
345 if (cfun && cp_function_chain && !cp_unevaluated_operand)
347 if (!nothrow && at_function_scope_p ())
348 cp_function_chain->can_throw = 1;
350 if (decl && TREE_THIS_VOLATILE (decl))
351 current_function_returns_abnormally = 1;
354 TREE_NOTHROW (call) = nothrow;
357 tree
358 build_call_a (tree function, int n, tree *argarray)
360 tree decl;
361 tree result_type;
362 tree fntype;
363 int i;
365 function = build_addr_func (function, tf_warning_or_error);
367 gcc_assert (TYPE_PTR_P (TREE_TYPE (function)));
368 fntype = TREE_TYPE (TREE_TYPE (function));
369 gcc_assert (FUNC_OR_METHOD_TYPE_P (fntype));
370 result_type = TREE_TYPE (fntype);
371 /* An rvalue has no cv-qualifiers. */
372 if (SCALAR_TYPE_P (result_type) || VOID_TYPE_P (result_type))
373 result_type = cv_unqualified (result_type);
375 function = build_call_array_loc (input_location,
376 result_type, function, n, argarray);
377 set_flags_from_callee (function);
379 decl = get_callee_fndecl (function);
381 if (decl && !TREE_USED (decl))
383 /* We invoke build_call directly for several library
384 functions. These may have been declared normally if
385 we're building libgcc, so we can't just check
386 DECL_ARTIFICIAL. */
387 gcc_assert (DECL_ARTIFICIAL (decl)
388 || !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)),
389 "__", 2));
390 mark_used (decl);
393 require_complete_eh_spec_types (fntype, decl);
395 TREE_HAS_CONSTRUCTOR (function) = (decl && DECL_CONSTRUCTOR_P (decl));
397 /* Don't pass empty class objects by value. This is useful
398 for tags in STL, which are used to control overload resolution.
399 We don't need to handle other cases of copying empty classes. */
400 if (!decl || !fndecl_built_in_p (decl))
401 for (i = 0; i < n; i++)
403 tree arg = CALL_EXPR_ARG (function, i);
404 if (is_empty_class (TREE_TYPE (arg))
405 && simple_empty_class_p (TREE_TYPE (arg), arg, INIT_EXPR))
407 while (TREE_CODE (arg) == TARGET_EXPR)
408 /* We're disconnecting the initializer from its target,
409 don't create a temporary. */
410 arg = TARGET_EXPR_INITIAL (arg);
411 tree t = build0 (EMPTY_CLASS_EXPR, TREE_TYPE (arg));
412 arg = build2 (COMPOUND_EXPR, TREE_TYPE (t), arg, t);
413 CALL_EXPR_ARG (function, i) = arg;
417 return function;
420 /* New overloading code. */
422 struct z_candidate;
424 struct candidate_warning {
425 z_candidate *loser;
426 candidate_warning *next;
429 /* Information for providing diagnostics about why overloading failed. */
431 enum rejection_reason_code {
432 rr_none,
433 rr_arity,
434 rr_explicit_conversion,
435 rr_template_conversion,
436 rr_arg_conversion,
437 rr_bad_arg_conversion,
438 rr_template_unification,
439 rr_invalid_copy,
440 rr_inherited_ctor,
441 rr_constraint_failure
444 struct conversion_info {
445 /* The index of the argument, 0-based. */
446 int n_arg;
447 /* The actual argument or its type. */
448 tree from;
449 /* The type of the parameter. */
450 tree to_type;
451 /* The location of the argument. */
452 location_t loc;
455 struct rejection_reason {
456 enum rejection_reason_code code;
457 union {
458 /* Information about an arity mismatch. */
459 struct {
460 /* The expected number of arguments. */
461 int expected;
462 /* The actual number of arguments in the call. */
463 int actual;
464 /* Whether EXPECTED should be treated as a lower bound. */
465 bool least_p;
466 } arity;
467 /* Information about an argument conversion mismatch. */
468 struct conversion_info conversion;
469 /* Same, but for bad argument conversions. */
470 struct conversion_info bad_conversion;
471 /* Information about template unification failures. These are the
472 parameters passed to fn_type_unification. */
473 struct {
474 tree tmpl;
475 tree explicit_targs;
476 int num_targs;
477 const tree *args;
478 unsigned int nargs;
479 tree return_type;
480 unification_kind_t strict;
481 int flags;
482 } template_unification;
483 /* Information about template instantiation failures. These are the
484 parameters passed to instantiate_template. */
485 struct {
486 tree tmpl;
487 tree targs;
488 } template_instantiation;
489 } u;
492 struct z_candidate {
493 /* The FUNCTION_DECL that will be called if this candidate is
494 selected by overload resolution. */
495 tree fn;
496 /* If not NULL_TREE, the first argument to use when calling this
497 function. */
498 tree first_arg;
499 /* The rest of the arguments to use when calling this function. If
500 there are no further arguments this may be NULL or it may be an
501 empty vector. */
502 const vec<tree, va_gc> *args;
503 /* The implicit conversion sequences for each of the arguments to
504 FN. */
505 conversion **convs;
506 /* The number of implicit conversion sequences. */
507 size_t num_convs;
508 /* If FN is a user-defined conversion, the standard conversion
509 sequence from the type returned by FN to the desired destination
510 type. */
511 conversion *second_conv;
512 struct rejection_reason *reason;
513 /* If FN is a member function, the binfo indicating the path used to
514 qualify the name of FN at the call site. This path is used to
515 determine whether or not FN is accessible if it is selected by
516 overload resolution. The DECL_CONTEXT of FN will always be a
517 (possibly improper) base of this binfo. */
518 tree access_path;
519 /* If FN is a non-static member function, the binfo indicating the
520 subobject to which the `this' pointer should be converted if FN
521 is selected by overload resolution. The type pointed to by
522 the `this' pointer must correspond to the most derived class
523 indicated by the CONVERSION_PATH. */
524 tree conversion_path;
525 tree template_decl;
526 tree explicit_targs;
527 candidate_warning *warnings;
528 z_candidate *next;
529 int viable;
531 /* The flags active in add_candidate. */
532 int flags;
534 bool rewritten () const { return (flags & LOOKUP_REWRITTEN); }
535 bool reversed () const { return (flags & LOOKUP_REVERSED); }
538 /* Returns true iff T is a null pointer constant in the sense of
539 [conv.ptr]. */
541 bool
542 null_ptr_cst_p (tree t)
544 tree type = TREE_TYPE (t);
546 /* [conv.ptr]
548 A null pointer constant is an integer literal ([lex.icon]) with value
549 zero or a prvalue of type std::nullptr_t. */
550 if (NULLPTR_TYPE_P (type))
551 return true;
553 if (cxx_dialect >= cxx11)
555 STRIP_ANY_LOCATION_WRAPPER (t);
557 /* Core issue 903 says only literal 0 is a null pointer constant. */
558 if (TREE_CODE (t) == INTEGER_CST
559 && !TREE_OVERFLOW (t)
560 && TREE_CODE (type) == INTEGER_TYPE
561 && integer_zerop (t)
562 && !char_type_p (type))
563 return true;
565 else if (CP_INTEGRAL_TYPE_P (type))
567 t = fold_non_dependent_expr (t, tf_none);
568 STRIP_NOPS (t);
569 if (integer_zerop (t) && !TREE_OVERFLOW (t))
570 return true;
573 return false;
576 /* Returns true iff T is a null member pointer value (4.11). */
578 bool
579 null_member_pointer_value_p (tree t)
581 tree type = TREE_TYPE (t);
582 if (!type)
583 return false;
584 else if (TYPE_PTRMEMFUNC_P (type))
585 return (TREE_CODE (t) == CONSTRUCTOR
586 && CONSTRUCTOR_NELTS (t)
587 && integer_zerop (CONSTRUCTOR_ELT (t, 0)->value));
588 else if (TYPE_PTRDATAMEM_P (type))
589 return integer_all_onesp (t);
590 else
591 return false;
594 /* Returns nonzero if PARMLIST consists of only default parms,
595 ellipsis, and/or undeduced parameter packs. */
597 bool
598 sufficient_parms_p (const_tree parmlist)
600 for (; parmlist && parmlist != void_list_node;
601 parmlist = TREE_CHAIN (parmlist))
602 if (!TREE_PURPOSE (parmlist)
603 && !PACK_EXPANSION_P (TREE_VALUE (parmlist)))
604 return false;
605 return true;
608 /* Allocate N bytes of memory from the conversion obstack. The memory
609 is zeroed before being returned. */
611 static void *
612 conversion_obstack_alloc (size_t n)
614 void *p;
615 if (!conversion_obstack_initialized)
617 gcc_obstack_init (&conversion_obstack);
618 conversion_obstack_initialized = true;
620 p = obstack_alloc (&conversion_obstack, n);
621 memset (p, 0, n);
622 return p;
625 /* Allocate rejection reasons. */
627 static struct rejection_reason *
628 alloc_rejection (enum rejection_reason_code code)
630 struct rejection_reason *p;
631 p = (struct rejection_reason *) conversion_obstack_alloc (sizeof *p);
632 p->code = code;
633 return p;
636 static struct rejection_reason *
637 arity_rejection (tree first_arg, int expected, int actual, bool least_p = false)
639 struct rejection_reason *r = alloc_rejection (rr_arity);
640 int adjust = first_arg != NULL_TREE;
641 r->u.arity.expected = expected - adjust;
642 r->u.arity.actual = actual - adjust;
643 r->u.arity.least_p = least_p;
644 return r;
647 static struct rejection_reason *
648 arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
649 location_t loc)
651 struct rejection_reason *r = alloc_rejection (rr_arg_conversion);
652 int adjust = first_arg != NULL_TREE;
653 r->u.conversion.n_arg = n_arg - adjust;
654 r->u.conversion.from = from;
655 r->u.conversion.to_type = to;
656 r->u.conversion.loc = loc;
657 return r;
660 static struct rejection_reason *
661 bad_arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
662 location_t loc)
664 struct rejection_reason *r = alloc_rejection (rr_bad_arg_conversion);
665 int adjust = first_arg != NULL_TREE;
666 r->u.bad_conversion.n_arg = n_arg - adjust;
667 r->u.bad_conversion.from = from;
668 r->u.bad_conversion.to_type = to;
669 r->u.bad_conversion.loc = loc;
670 return r;
673 static struct rejection_reason *
674 explicit_conversion_rejection (tree from, tree to)
676 struct rejection_reason *r = alloc_rejection (rr_explicit_conversion);
677 r->u.conversion.n_arg = 0;
678 r->u.conversion.from = from;
679 r->u.conversion.to_type = to;
680 r->u.conversion.loc = UNKNOWN_LOCATION;
681 return r;
684 static struct rejection_reason *
685 template_conversion_rejection (tree from, tree to)
687 struct rejection_reason *r = alloc_rejection (rr_template_conversion);
688 r->u.conversion.n_arg = 0;
689 r->u.conversion.from = from;
690 r->u.conversion.to_type = to;
691 r->u.conversion.loc = UNKNOWN_LOCATION;
692 return r;
695 static struct rejection_reason *
696 template_unification_rejection (tree tmpl, tree explicit_targs, tree targs,
697 const tree *args, unsigned int nargs,
698 tree return_type, unification_kind_t strict,
699 int flags)
701 size_t args_n_bytes = sizeof (*args) * nargs;
702 tree *args1 = (tree *) conversion_obstack_alloc (args_n_bytes);
703 struct rejection_reason *r = alloc_rejection (rr_template_unification);
704 r->u.template_unification.tmpl = tmpl;
705 r->u.template_unification.explicit_targs = explicit_targs;
706 r->u.template_unification.num_targs = TREE_VEC_LENGTH (targs);
707 /* Copy args to our own storage. */
708 memcpy (args1, args, args_n_bytes);
709 r->u.template_unification.args = args1;
710 r->u.template_unification.nargs = nargs;
711 r->u.template_unification.return_type = return_type;
712 r->u.template_unification.strict = strict;
713 r->u.template_unification.flags = flags;
714 return r;
717 static struct rejection_reason *
718 template_unification_error_rejection (void)
720 return alloc_rejection (rr_template_unification);
723 static struct rejection_reason *
724 invalid_copy_with_fn_template_rejection (void)
726 struct rejection_reason *r = alloc_rejection (rr_invalid_copy);
727 return r;
730 static struct rejection_reason *
731 inherited_ctor_rejection (void)
733 struct rejection_reason *r = alloc_rejection (rr_inherited_ctor);
734 return r;
737 /* Build a constraint failure record. */
739 static struct rejection_reason *
740 constraint_failure (void)
742 struct rejection_reason *r = alloc_rejection (rr_constraint_failure);
743 return r;
746 /* Dynamically allocate a conversion. */
748 static conversion *
749 alloc_conversion (conversion_kind kind)
751 conversion *c;
752 c = (conversion *) conversion_obstack_alloc (sizeof (conversion));
753 c->kind = kind;
754 return c;
757 /* Make sure that all memory on the conversion obstack has been
758 freed. */
760 void
761 validate_conversion_obstack (void)
763 if (conversion_obstack_initialized)
764 gcc_assert ((obstack_next_free (&conversion_obstack)
765 == obstack_base (&conversion_obstack)));
768 /* Dynamically allocate an array of N conversions. */
770 static conversion **
771 alloc_conversions (size_t n)
773 return (conversion **) conversion_obstack_alloc (n * sizeof (conversion *));
776 /* True iff the active member of conversion::u for code CODE is NEXT. */
778 static inline bool
779 has_next (conversion_kind code)
781 return !(code == ck_identity
782 || code == ck_ambig
783 || code == ck_list
784 || code == ck_aggr
785 || code == ck_deferred_bad);
788 static conversion *
789 build_conv (conversion_kind code, tree type, conversion *from)
791 conversion *t;
792 conversion_rank rank = CONVERSION_RANK (from);
794 /* Only call this function for conversions that use u.next. */
795 gcc_assert (from == NULL || has_next (code));
797 /* Note that the caller is responsible for filling in t->cand for
798 user-defined conversions. */
799 t = alloc_conversion (code);
800 t->type = type;
801 t->u.next = from;
803 switch (code)
805 case ck_ptr:
806 case ck_pmem:
807 case ck_base:
808 case ck_std:
809 if (rank < cr_std)
810 rank = cr_std;
811 break;
813 case ck_qual:
814 case ck_fnptr:
815 if (rank < cr_exact)
816 rank = cr_exact;
817 break;
819 default:
820 break;
822 t->rank = rank;
823 t->user_conv_p = (code == ck_user || from->user_conv_p);
824 t->bad_p = from->bad_p;
825 t->base_p = false;
826 return t;
829 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
830 specialization of std::initializer_list<T>, if such a conversion is
831 possible. */
833 static conversion *
834 build_list_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
836 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (type), 0);
837 unsigned len = CONSTRUCTOR_NELTS (ctor);
838 conversion **subconvs = alloc_conversions (len);
839 conversion *t;
840 unsigned i;
841 tree val;
843 /* Within a list-initialization we can have more user-defined
844 conversions. */
845 flags &= ~LOOKUP_NO_CONVERSION;
846 /* But no narrowing conversions. */
847 flags |= LOOKUP_NO_NARROWING;
849 /* Can't make an array of these types. */
850 if (TYPE_REF_P (elttype)
851 || TREE_CODE (elttype) == FUNCTION_TYPE
852 || VOID_TYPE_P (elttype))
853 return NULL;
855 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
857 conversion *sub
858 = implicit_conversion (elttype, TREE_TYPE (val), val,
859 false, flags, complain);
860 if (sub == NULL)
861 return NULL;
863 subconvs[i] = sub;
866 t = alloc_conversion (ck_list);
867 t->type = type;
868 t->u.list = subconvs;
869 t->rank = cr_exact;
871 for (i = 0; i < len; ++i)
873 conversion *sub = subconvs[i];
874 if (sub->rank > t->rank)
875 t->rank = sub->rank;
876 if (sub->user_conv_p)
877 t->user_conv_p = true;
878 if (sub->bad_p)
879 t->bad_p = true;
882 return t;
885 /* Return the next conversion of the conversion chain (if applicable),
886 or NULL otherwise. Please use this function instead of directly
887 accessing fields of struct conversion. */
889 static conversion *
890 next_conversion (conversion *conv)
892 if (conv == NULL
893 || !has_next (conv->kind))
894 return NULL;
895 return conv->u.next;
898 /* Strip to the first ck_user, ck_ambig, ck_list, ck_aggr or ck_identity
899 encountered. */
901 static conversion *
902 strip_standard_conversion (conversion *conv)
904 while (conv
905 && conv->kind != ck_user
906 && has_next (conv->kind))
907 conv = next_conversion (conv);
908 return conv;
911 /* Subroutine of build_aggr_conv: check whether FROM is a valid aggregate
912 initializer for array type ATYPE. */
914 static bool
915 can_convert_array (tree atype, tree from, int flags, tsubst_flags_t complain)
917 tree elttype = TREE_TYPE (atype);
918 unsigned i;
920 if (TREE_CODE (from) == CONSTRUCTOR)
922 for (i = 0; i < CONSTRUCTOR_NELTS (from); ++i)
924 tree val = CONSTRUCTOR_ELT (from, i)->value;
925 bool ok;
926 if (TREE_CODE (elttype) == ARRAY_TYPE)
927 ok = can_convert_array (elttype, val, flags, complain);
928 else
929 ok = can_convert_arg (elttype, TREE_TYPE (val), val, flags,
930 complain);
931 if (!ok)
932 return false;
934 return true;
937 if (char_type_p (TYPE_MAIN_VARIANT (elttype))
938 && TREE_CODE (tree_strip_any_location_wrapper (from)) == STRING_CST)
939 return array_string_literal_compatible_p (atype, from);
941 /* No other valid way to aggregate initialize an array. */
942 return false;
945 /* Helper for build_aggr_conv. Return true if FIELD is in PSET, or if
946 FIELD has ANON_AGGR_TYPE_P and any initializable field in there recursively
947 is in PSET. */
949 static bool
950 field_in_pset (hash_set<tree, true> &pset, tree field)
952 if (pset.contains (field))
953 return true;
954 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
955 for (field = TYPE_FIELDS (TREE_TYPE (field));
956 field; field = DECL_CHAIN (field))
958 field = next_aggregate_field (field);
959 if (field == NULL_TREE)
960 break;
961 if (field_in_pset (pset, field))
962 return true;
964 return false;
967 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
968 aggregate class, if such a conversion is possible. */
970 static conversion *
971 build_aggr_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
973 unsigned HOST_WIDE_INT i = 0;
974 conversion *c;
975 tree field = next_aggregate_field (TYPE_FIELDS (type));
976 tree empty_ctor = NULL_TREE;
977 hash_set<tree, true> pset;
979 /* We already called reshape_init in implicit_conversion, but it might not
980 have done anything in the case of parenthesized aggr init. */
982 /* The conversions within the init-list aren't affected by the enclosing
983 context; they're always simple copy-initialization. */
984 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
986 /* For designated initializers, verify that each initializer is convertible
987 to corresponding TREE_TYPE (ce->index) and mark those FIELD_DECLs as
988 visited. In the following loop then ignore already visited
989 FIELD_DECLs. */
990 tree idx, val;
991 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, idx, val)
993 if (!idx)
994 break;
996 gcc_checking_assert (TREE_CODE (idx) == FIELD_DECL);
998 tree ftype = TREE_TYPE (idx);
999 bool ok;
1001 if (TREE_CODE (ftype) == ARRAY_TYPE)
1002 ok = can_convert_array (ftype, val, flags, complain);
1003 else
1004 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1005 complain);
1007 if (!ok)
1008 return NULL;
1010 /* For unions, there should be just one initializer. */
1011 if (TREE_CODE (type) == UNION_TYPE)
1013 field = NULL_TREE;
1014 i = 1;
1015 break;
1017 pset.add (idx);
1020 for (; field; field = next_aggregate_field (DECL_CHAIN (field)))
1022 tree ftype = TREE_TYPE (field);
1023 bool ok;
1025 if (!pset.is_empty () && field_in_pset (pset, field))
1026 continue;
1027 if (i < CONSTRUCTOR_NELTS (ctor))
1029 constructor_elt *ce = CONSTRUCTOR_ELT (ctor, i);
1030 gcc_checking_assert (!ce->index);
1031 val = ce->value;
1032 ++i;
1034 else if (DECL_INITIAL (field))
1035 val = get_nsdmi (field, /*ctor*/false, complain);
1036 else if (TYPE_REF_P (ftype))
1037 /* Value-initialization of reference is ill-formed. */
1038 return NULL;
1039 else
1041 if (empty_ctor == NULL_TREE)
1042 empty_ctor = build_constructor (init_list_type_node, NULL);
1043 val = empty_ctor;
1046 if (TREE_CODE (ftype) == ARRAY_TYPE)
1047 ok = can_convert_array (ftype, val, flags, complain);
1048 else
1049 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1050 complain);
1052 if (!ok)
1053 return NULL;
1055 if (TREE_CODE (type) == UNION_TYPE)
1056 break;
1059 if (i < CONSTRUCTOR_NELTS (ctor))
1060 return NULL;
1062 c = alloc_conversion (ck_aggr);
1063 c->type = type;
1064 c->rank = cr_exact;
1065 c->user_conv_p = true;
1066 c->check_narrowing = true;
1067 c->u.expr = ctor;
1068 return c;
1071 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
1072 array type, if such a conversion is possible. */
1074 static conversion *
1075 build_array_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
1077 conversion *c;
1078 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1079 tree elttype = TREE_TYPE (type);
1080 bool bad = false;
1081 bool user = false;
1082 enum conversion_rank rank = cr_exact;
1084 /* We might need to propagate the size from the element to the array. */
1085 complete_type (type);
1087 if (TYPE_DOMAIN (type)
1088 && !variably_modified_type_p (TYPE_DOMAIN (type), NULL_TREE))
1090 unsigned HOST_WIDE_INT alen = tree_to_uhwi (array_type_nelts_top (type));
1091 if (alen < len)
1092 return NULL;
1095 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1097 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1099 conversion *sub
1100 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1101 false, flags, complain);
1102 if (sub == NULL)
1103 return NULL;
1105 if (sub->rank > rank)
1106 rank = sub->rank;
1107 if (sub->user_conv_p)
1108 user = true;
1109 if (sub->bad_p)
1110 bad = true;
1113 c = alloc_conversion (ck_aggr);
1114 c->type = type;
1115 c->rank = rank;
1116 c->user_conv_p = user;
1117 c->bad_p = bad;
1118 c->u.expr = ctor;
1119 return c;
1122 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
1123 complex type, if such a conversion is possible. */
1125 static conversion *
1126 build_complex_conv (tree type, tree ctor, int flags,
1127 tsubst_flags_t complain)
1129 conversion *c;
1130 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1131 tree elttype = TREE_TYPE (type);
1132 bool bad = false;
1133 bool user = false;
1134 enum conversion_rank rank = cr_exact;
1136 if (len != 2)
1137 return NULL;
1139 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1141 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1143 conversion *sub
1144 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1145 false, flags, complain);
1146 if (sub == NULL)
1147 return NULL;
1149 if (sub->rank > rank)
1150 rank = sub->rank;
1151 if (sub->user_conv_p)
1152 user = true;
1153 if (sub->bad_p)
1154 bad = true;
1157 c = alloc_conversion (ck_aggr);
1158 c->type = type;
1159 c->rank = rank;
1160 c->user_conv_p = user;
1161 c->bad_p = bad;
1162 c->u.expr = ctor;
1163 return c;
1166 /* Build a representation of the identity conversion from EXPR to
1167 itself. The TYPE should match the type of EXPR, if EXPR is non-NULL. */
1169 static conversion *
1170 build_identity_conv (tree type, tree expr)
1172 conversion *c;
1174 c = alloc_conversion (ck_identity);
1175 c->type = type;
1176 c->u.expr = expr;
1178 return c;
1181 /* Converting from EXPR to TYPE was ambiguous in the sense that there
1182 were multiple user-defined conversions to accomplish the job.
1183 Build a conversion that indicates that ambiguity. */
1185 static conversion *
1186 build_ambiguous_conv (tree type, tree expr)
1188 conversion *c;
1190 c = alloc_conversion (ck_ambig);
1191 c->type = type;
1192 c->u.expr = expr;
1194 return c;
1197 tree
1198 strip_top_quals (tree t)
1200 if (TREE_CODE (t) == ARRAY_TYPE)
1201 return t;
1202 return cp_build_qualified_type (t, 0);
1205 /* Returns the standard conversion path (see [conv]) from type FROM to type
1206 TO, if any. For proper handling of null pointer constants, you must
1207 also pass the expression EXPR to convert from. If C_CAST_P is true,
1208 this conversion is coming from a C-style cast. */
1210 static conversion *
1211 standard_conversion (tree to, tree from, tree expr, bool c_cast_p,
1212 int flags, tsubst_flags_t complain)
1214 enum tree_code fcode, tcode;
1215 conversion *conv;
1216 bool fromref = false;
1217 tree qualified_to;
1219 to = non_reference (to);
1220 if (TYPE_REF_P (from))
1222 fromref = true;
1223 from = TREE_TYPE (from);
1225 qualified_to = to;
1226 to = strip_top_quals (to);
1227 from = strip_top_quals (from);
1229 if (expr && type_unknown_p (expr))
1231 if (TYPE_PTRFN_P (to) || TYPE_PTRMEMFUNC_P (to))
1233 tsubst_flags_t tflags = tf_conv;
1234 expr = instantiate_type (to, expr, tflags);
1235 if (expr == error_mark_node)
1236 return NULL;
1237 from = TREE_TYPE (expr);
1239 else if (TREE_CODE (to) == BOOLEAN_TYPE)
1241 /* Necessary for eg, TEMPLATE_ID_EXPRs (c++/50961). */
1242 expr = resolve_nondeduced_context (expr, complain);
1243 from = TREE_TYPE (expr);
1247 fcode = TREE_CODE (from);
1248 tcode = TREE_CODE (to);
1250 conv = build_identity_conv (from, expr);
1251 if (fcode == FUNCTION_TYPE || fcode == ARRAY_TYPE)
1253 from = type_decays_to (from);
1254 fcode = TREE_CODE (from);
1255 /* Tell convert_like that we're using the address. */
1256 conv->rvaluedness_matches_p = true;
1257 conv = build_conv (ck_lvalue, from, conv);
1259 /* Wrapping a ck_rvalue around a class prvalue (as a result of using
1260 obvalue_p) seems odd, since it's already a prvalue, but that's how we
1261 express the copy constructor call required by copy-initialization. */
1262 else if (fromref || (expr && obvalue_p (expr)))
1264 if (expr)
1266 tree bitfield_type;
1267 bitfield_type = is_bitfield_expr_with_lowered_type (expr);
1268 if (bitfield_type)
1270 from = strip_top_quals (bitfield_type);
1271 fcode = TREE_CODE (from);
1274 conv = build_conv (ck_rvalue, from, conv);
1275 if (flags & LOOKUP_PREFER_RVALUE)
1276 /* Tell convert_like to set LOOKUP_PREFER_RVALUE. */
1277 conv->rvaluedness_matches_p = true;
1278 /* If we're performing copy-initialization, remember to skip
1279 explicit constructors. */
1280 if (flags & LOOKUP_ONLYCONVERTING)
1281 conv->copy_init_p = true;
1284 /* Allow conversion between `__complex__' data types. */
1285 if (tcode == COMPLEX_TYPE && fcode == COMPLEX_TYPE)
1287 /* The standard conversion sequence to convert FROM to TO is
1288 the standard conversion sequence to perform componentwise
1289 conversion. */
1290 conversion *part_conv = standard_conversion
1291 (TREE_TYPE (to), TREE_TYPE (from), NULL_TREE, c_cast_p, flags,
1292 complain);
1294 if (!part_conv)
1295 conv = NULL;
1296 else if (part_conv->kind == ck_identity)
1297 /* Leave conv alone. */;
1298 else
1300 conv = build_conv (part_conv->kind, to, conv);
1301 conv->rank = part_conv->rank;
1304 return conv;
1307 if (same_type_p (from, to))
1309 if (CLASS_TYPE_P (to) && conv->kind == ck_rvalue)
1310 conv->type = qualified_to;
1311 return conv;
1314 /* [conv.ptr]
1315 A null pointer constant can be converted to a pointer type; ... A
1316 null pointer constant of integral type can be converted to an
1317 rvalue of type std::nullptr_t. */
1318 if ((tcode == POINTER_TYPE || TYPE_PTRMEM_P (to)
1319 || NULLPTR_TYPE_P (to))
1320 && ((expr && null_ptr_cst_p (expr))
1321 || NULLPTR_TYPE_P (from)))
1322 conv = build_conv (ck_std, to, conv);
1323 else if ((tcode == INTEGER_TYPE && fcode == POINTER_TYPE)
1324 || (tcode == POINTER_TYPE && fcode == INTEGER_TYPE))
1326 /* For backwards brain damage compatibility, allow interconversion of
1327 pointers and integers with a pedwarn. */
1328 conv = build_conv (ck_std, to, conv);
1329 conv->bad_p = true;
1331 else if (UNSCOPED_ENUM_P (to) && fcode == INTEGER_TYPE)
1333 /* For backwards brain damage compatibility, allow interconversion of
1334 enums and integers with a pedwarn. */
1335 conv = build_conv (ck_std, to, conv);
1336 conv->bad_p = true;
1338 else if ((tcode == POINTER_TYPE && fcode == POINTER_TYPE)
1339 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from)))
1341 tree to_pointee;
1342 tree from_pointee;
1344 if (tcode == POINTER_TYPE)
1346 to_pointee = TREE_TYPE (to);
1347 from_pointee = TREE_TYPE (from);
1349 /* Since this is the target of a pointer, it can't have function
1350 qualifiers, so any TYPE_QUALS must be for attributes const or
1351 noreturn. Strip them. */
1352 if (TREE_CODE (to_pointee) == FUNCTION_TYPE
1353 && TYPE_QUALS (to_pointee))
1354 to_pointee = build_qualified_type (to_pointee, TYPE_UNQUALIFIED);
1355 if (TREE_CODE (from_pointee) == FUNCTION_TYPE
1356 && TYPE_QUALS (from_pointee))
1357 from_pointee = build_qualified_type (from_pointee, TYPE_UNQUALIFIED);
1359 else
1361 to_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (to);
1362 from_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (from);
1365 if (tcode == POINTER_TYPE
1366 && same_type_ignoring_top_level_qualifiers_p (from_pointee,
1367 to_pointee))
1369 else if (VOID_TYPE_P (to_pointee)
1370 && !TYPE_PTRDATAMEM_P (from)
1371 && TREE_CODE (from_pointee) != FUNCTION_TYPE)
1373 tree nfrom = TREE_TYPE (from);
1374 /* Don't try to apply restrict to void. */
1375 int quals = cp_type_quals (nfrom) & ~TYPE_QUAL_RESTRICT;
1376 from_pointee = cp_build_qualified_type (void_type_node, quals);
1377 from = build_pointer_type (from_pointee);
1378 conv = build_conv (ck_ptr, from, conv);
1380 else if (TYPE_PTRDATAMEM_P (from))
1382 tree fbase = TYPE_PTRMEM_CLASS_TYPE (from);
1383 tree tbase = TYPE_PTRMEM_CLASS_TYPE (to);
1385 if (same_type_p (fbase, tbase))
1386 /* No base conversion needed. */;
1387 else if (DERIVED_FROM_P (fbase, tbase)
1388 && (same_type_ignoring_top_level_qualifiers_p
1389 (from_pointee, to_pointee)))
1391 from = build_ptrmem_type (tbase, from_pointee);
1392 conv = build_conv (ck_pmem, from, conv);
1394 else
1395 return NULL;
1397 else if (CLASS_TYPE_P (from_pointee)
1398 && CLASS_TYPE_P (to_pointee)
1399 /* [conv.ptr]
1401 An rvalue of type "pointer to cv D," where D is a
1402 class type, can be converted to an rvalue of type
1403 "pointer to cv B," where B is a base class (clause
1404 _class.derived_) of D. If B is an inaccessible
1405 (clause _class.access_) or ambiguous
1406 (_class.member.lookup_) base class of D, a program
1407 that necessitates this conversion is ill-formed.
1408 Therefore, we use DERIVED_FROM_P, and do not check
1409 access or uniqueness. */
1410 && DERIVED_FROM_P (to_pointee, from_pointee))
1412 from_pointee
1413 = cp_build_qualified_type (to_pointee,
1414 cp_type_quals (from_pointee));
1415 from = build_pointer_type (from_pointee);
1416 conv = build_conv (ck_ptr, from, conv);
1417 conv->base_p = true;
1420 if (same_type_p (from, to))
1421 /* OK */;
1422 else if (c_cast_p && comp_ptr_ttypes_const (to, from, bounds_either))
1423 /* In a C-style cast, we ignore CV-qualification because we
1424 are allowed to perform a static_cast followed by a
1425 const_cast. */
1426 conv = build_conv (ck_qual, to, conv);
1427 else if (!c_cast_p && comp_ptr_ttypes (to_pointee, from_pointee))
1428 conv = build_conv (ck_qual, to, conv);
1429 else if (expr && string_conv_p (to, expr, 0))
1430 /* converting from string constant to char *. */
1431 conv = build_conv (ck_qual, to, conv);
1432 else if (fnptr_conv_p (to, from))
1433 conv = build_conv (ck_fnptr, to, conv);
1434 /* Allow conversions among compatible ObjC pointer types (base
1435 conversions have been already handled above). */
1436 else if (c_dialect_objc ()
1437 && objc_compare_types (to, from, -4, NULL_TREE))
1438 conv = build_conv (ck_ptr, to, conv);
1439 else if (ptr_reasonably_similar (to_pointee, from_pointee))
1441 conv = build_conv (ck_ptr, to, conv);
1442 conv->bad_p = true;
1444 else
1445 return NULL;
1447 from = to;
1449 else if (TYPE_PTRMEMFUNC_P (to) && TYPE_PTRMEMFUNC_P (from))
1451 tree fromfn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (from));
1452 tree tofn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (to));
1453 tree fbase = class_of_this_parm (fromfn);
1454 tree tbase = class_of_this_parm (tofn);
1456 /* If FBASE and TBASE are equivalent but incomplete, DERIVED_FROM_P
1457 yields false. But a pointer to member of incomplete class is OK. */
1458 if (!same_type_p (fbase, tbase) && !DERIVED_FROM_P (fbase, tbase))
1459 return NULL;
1461 tree fstat = static_fn_type (fromfn);
1462 tree tstat = static_fn_type (tofn);
1463 if (same_type_p (tstat, fstat)
1464 || fnptr_conv_p (tstat, fstat))
1465 /* OK */;
1466 else
1467 return NULL;
1469 if (!same_type_p (fbase, tbase))
1471 from = build_memfn_type (fstat,
1472 tbase,
1473 cp_type_quals (tbase),
1474 type_memfn_rqual (tofn));
1475 from = build_ptrmemfunc_type (build_pointer_type (from));
1476 conv = build_conv (ck_pmem, from, conv);
1477 conv->base_p = true;
1479 if (fnptr_conv_p (tstat, fstat))
1480 conv = build_conv (ck_fnptr, to, conv);
1482 else if (tcode == BOOLEAN_TYPE)
1484 /* [conv.bool]
1486 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer
1487 to member type can be converted to a prvalue of type bool. ...
1488 For direct-initialization (8.5 [dcl.init]), a prvalue of type
1489 std::nullptr_t can be converted to a prvalue of type bool; */
1490 if (ARITHMETIC_TYPE_P (from)
1491 || UNSCOPED_ENUM_P (from)
1492 || fcode == POINTER_TYPE
1493 || TYPE_PTRMEM_P (from)
1494 || NULLPTR_TYPE_P (from))
1496 conv = build_conv (ck_std, to, conv);
1497 if (fcode == POINTER_TYPE
1498 || TYPE_PTRDATAMEM_P (from)
1499 || (TYPE_PTRMEMFUNC_P (from)
1500 && conv->rank < cr_pbool)
1501 || NULLPTR_TYPE_P (from))
1502 conv->rank = cr_pbool;
1503 if (NULLPTR_TYPE_P (from) && (flags & LOOKUP_ONLYCONVERTING))
1504 conv->bad_p = true;
1505 if (flags & LOOKUP_NO_NARROWING)
1506 conv->check_narrowing = true;
1507 return conv;
1510 return NULL;
1512 /* We don't check for ENUMERAL_TYPE here because there are no standard
1513 conversions to enum type. */
1514 /* As an extension, allow conversion to complex type. */
1515 else if (ARITHMETIC_TYPE_P (to))
1517 if (! (INTEGRAL_CODE_P (fcode)
1518 || (fcode == REAL_TYPE && !(flags & LOOKUP_NO_NON_INTEGRAL)))
1519 || SCOPED_ENUM_P (from))
1520 return NULL;
1522 /* If we're parsing an enum with no fixed underlying type, we're
1523 dealing with an incomplete type, which renders the conversion
1524 ill-formed. */
1525 if (!COMPLETE_TYPE_P (from))
1526 return NULL;
1528 conv = build_conv (ck_std, to, conv);
1530 tree underlying_type = NULL_TREE;
1531 if (TREE_CODE (from) == ENUMERAL_TYPE
1532 && ENUM_FIXED_UNDERLYING_TYPE_P (from))
1533 underlying_type = ENUM_UNDERLYING_TYPE (from);
1535 /* Give this a better rank if it's a promotion.
1537 To handle CWG 1601, also bump the rank if we are converting
1538 an enumeration with a fixed underlying type to the underlying
1539 type. */
1540 if ((same_type_p (to, type_promotes_to (from))
1541 || (underlying_type && same_type_p (to, underlying_type)))
1542 && next_conversion (conv)->rank <= cr_promotion)
1543 conv->rank = cr_promotion;
1545 /* A prvalue of floating-point type can be converted to a prvalue of
1546 another floating-point type with a greater or equal conversion
1547 rank ([conv.rank]). A prvalue of standard floating-point type can
1548 be converted to a prvalue of another standard floating-point type.
1549 For backwards compatibility with handling __float128 and other
1550 non-standard floating point types, allow all implicit floating
1551 point conversions if neither type is extended floating-point
1552 type and if at least one of them is, fail if they have unordered
1553 conversion rank or from has higher conversion rank. */
1554 if (fcode == REAL_TYPE
1555 && tcode == REAL_TYPE
1556 && (extended_float_type_p (from)
1557 || extended_float_type_p (to))
1558 && cp_compare_floating_point_conversion_ranks (from, to) >= 2)
1559 conv->bad_p = true;
1561 else if (fcode == VECTOR_TYPE && tcode == VECTOR_TYPE
1562 && vector_types_convertible_p (from, to, false))
1563 return build_conv (ck_std, to, conv);
1564 else if (MAYBE_CLASS_TYPE_P (to) && MAYBE_CLASS_TYPE_P (from)
1565 && is_properly_derived_from (from, to))
1567 if (conv->kind == ck_rvalue)
1568 conv = next_conversion (conv);
1569 conv = build_conv (ck_base, to, conv);
1570 /* The derived-to-base conversion indicates the initialization
1571 of a parameter with base type from an object of a derived
1572 type. A temporary object is created to hold the result of
1573 the conversion unless we're binding directly to a reference. */
1574 conv->need_temporary_p = !(flags & LOOKUP_NO_TEMP_BIND);
1575 if (flags & LOOKUP_PREFER_RVALUE)
1576 /* Tell convert_like to set LOOKUP_PREFER_RVALUE. */
1577 conv->rvaluedness_matches_p = true;
1578 /* If we're performing copy-initialization, remember to skip
1579 explicit constructors. */
1580 if (flags & LOOKUP_ONLYCONVERTING)
1581 conv->copy_init_p = true;
1583 else
1584 return NULL;
1586 if (flags & LOOKUP_NO_NARROWING)
1587 conv->check_narrowing = true;
1589 return conv;
1592 /* Returns nonzero if T1 is reference-related to T2. */
1594 bool
1595 reference_related_p (tree t1, tree t2)
1597 if (t1 == error_mark_node || t2 == error_mark_node)
1598 return false;
1600 t1 = TYPE_MAIN_VARIANT (t1);
1601 t2 = TYPE_MAIN_VARIANT (t2);
1603 /* [dcl.init.ref]
1605 Given types "cv1 T1" and "cv2 T2," "cv1 T1" is reference-related
1606 to "cv2 T2" if T1 is similar to T2, or T1 is a base class of T2. */
1607 return (similar_type_p (t1, t2)
1608 || (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
1609 && DERIVED_FROM_P (t1, t2)));
1612 /* Returns nonzero if T1 is reference-compatible with T2. */
1614 bool
1615 reference_compatible_p (tree t1, tree t2)
1617 /* [dcl.init.ref]
1619 "cv1 T1" is reference compatible with "cv2 T2" if
1620 a prvalue of type "pointer to cv2 T2" can be converted to the type
1621 "pointer to cv1 T1" via a standard conversion sequence. */
1622 tree ptype1 = build_pointer_type (t1);
1623 tree ptype2 = build_pointer_type (t2);
1624 conversion *conv = standard_conversion (ptype1, ptype2, NULL_TREE,
1625 /*c_cast_p=*/false, 0, tf_none);
1626 if (!conv || conv->bad_p)
1627 return false;
1628 return true;
1631 /* Return true if converting FROM to TO would involve a qualification
1632 conversion. */
1634 static bool
1635 involves_qualification_conversion_p (tree to, tree from)
1637 /* If we're not convering a pointer to another one, we won't get
1638 a qualification conversion. */
1639 if (!((TYPE_PTR_P (to) && TYPE_PTR_P (from))
1640 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from))))
1641 return false;
1643 conversion *conv = standard_conversion (to, from, NULL_TREE,
1644 /*c_cast_p=*/false, 0, tf_none);
1645 for (conversion *t = conv; t; t = next_conversion (t))
1646 if (t->kind == ck_qual)
1647 return true;
1649 return false;
1652 /* A reference of the indicated TYPE is being bound directly to the
1653 expression represented by the implicit conversion sequence CONV.
1654 Return a conversion sequence for this binding. */
1656 static conversion *
1657 direct_reference_binding (tree type, conversion *conv)
1659 tree t;
1661 gcc_assert (TYPE_REF_P (type));
1662 gcc_assert (!TYPE_REF_P (conv->type));
1664 t = TREE_TYPE (type);
1666 if (conv->kind == ck_identity)
1667 /* Mark the identity conv as to not decay to rvalue. */
1668 conv->rvaluedness_matches_p = true;
1670 /* [over.ics.rank]
1672 When a parameter of reference type binds directly
1673 (_dcl.init.ref_) to an argument expression, the implicit
1674 conversion sequence is the identity conversion, unless the
1675 argument expression has a type that is a derived class of the
1676 parameter type, in which case the implicit conversion sequence is
1677 a derived-to-base Conversion.
1679 If the parameter binds directly to the result of applying a
1680 conversion function to the argument expression, the implicit
1681 conversion sequence is a user-defined conversion sequence
1682 (_over.ics.user_), with the second standard conversion sequence
1683 either an identity conversion or, if the conversion function
1684 returns an entity of a type that is a derived class of the
1685 parameter type, a derived-to-base conversion. */
1686 if (is_properly_derived_from (conv->type, t))
1688 /* Represent the derived-to-base conversion. */
1689 conv = build_conv (ck_base, t, conv);
1690 /* We will actually be binding to the base-class subobject in
1691 the derived class, so we mark this conversion appropriately.
1692 That way, convert_like knows not to generate a temporary. */
1693 conv->need_temporary_p = false;
1695 else if (involves_qualification_conversion_p (t, conv->type))
1696 /* Represent the qualification conversion. After DR 2352
1697 #1 and #2 were indistinguishable conversion sequences:
1699 void f(int*); // #1
1700 void f(const int* const &); // #2
1701 void g(int* p) { f(p); }
1703 because the types "int *" and "const int *const" are
1704 reference-related and we were binding both directly and they
1705 had the same rank. To break it up, we add a ck_qual under the
1706 ck_ref_bind so that conversion sequence ranking chooses #1.
1708 We strip_top_quals here which is also what standard_conversion
1709 does. Failure to do so would confuse comp_cv_qual_signature
1710 into thinking that in
1712 void f(const int * const &); // #1
1713 void f(const int *); // #2
1714 int *x;
1715 f(x);
1717 #2 is a better match than #1 even though they're ambiguous (97296). */
1718 conv = build_conv (ck_qual, strip_top_quals (t), conv);
1720 return build_conv (ck_ref_bind, type, conv);
1723 /* Returns the conversion path from type FROM to reference type TO for
1724 purposes of reference binding. For lvalue binding, either pass a
1725 reference type to FROM or an lvalue expression to EXPR. If the
1726 reference will be bound to a temporary, NEED_TEMPORARY_P is set for
1727 the conversion returned. If C_CAST_P is true, this
1728 conversion is coming from a C-style cast. */
1730 static conversion *
1731 reference_binding (tree rto, tree rfrom, tree expr, bool c_cast_p, int flags,
1732 tsubst_flags_t complain)
1734 conversion *conv = NULL;
1735 tree to = TREE_TYPE (rto);
1736 tree from = rfrom;
1737 tree tfrom;
1738 bool related_p;
1739 bool compatible_p;
1740 cp_lvalue_kind gl_kind;
1741 bool is_lvalue;
1743 if (TREE_CODE (to) == FUNCTION_TYPE && expr && type_unknown_p (expr))
1745 expr = instantiate_type (to, expr, tf_none);
1746 if (expr == error_mark_node)
1747 return NULL;
1748 from = TREE_TYPE (expr);
1751 bool copy_list_init = false;
1752 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1754 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
1755 /* DR 1288: Otherwise, if the initializer list has a single element
1756 of type E and ... [T's] referenced type is reference-related to E,
1757 the object or reference is initialized from that element...
1759 ??? With P0388R4, we should bind 't' directly to U{}:
1760 using U = A[2];
1761 A (&&t)[] = {U{}};
1762 because A[] and A[2] are reference-related. But we don't do it
1763 because grok_reference_init has deduced the array size (to 1), and
1764 A[1] and A[2] aren't reference-related. */
1765 if (CONSTRUCTOR_NELTS (expr) == 1
1766 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
1768 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
1769 if (error_operand_p (elt))
1770 return NULL;
1771 tree etype = TREE_TYPE (elt);
1772 if (reference_related_p (to, etype))
1774 expr = elt;
1775 from = etype;
1776 goto skip;
1779 /* Otherwise, if T is a reference type, a prvalue temporary of the type
1780 referenced by T is copy-list-initialized, and the reference is bound
1781 to that temporary. */
1782 copy_list_init = true;
1783 skip:;
1786 if (TYPE_REF_P (from))
1788 from = TREE_TYPE (from);
1789 if (!TYPE_REF_IS_RVALUE (rfrom)
1790 || TREE_CODE (from) == FUNCTION_TYPE)
1791 gl_kind = clk_ordinary;
1792 else
1793 gl_kind = clk_rvalueref;
1795 else if (expr)
1796 gl_kind = lvalue_kind (expr);
1797 else if (CLASS_TYPE_P (from)
1798 || TREE_CODE (from) == ARRAY_TYPE)
1799 gl_kind = clk_class;
1800 else
1801 gl_kind = clk_none;
1803 /* Don't allow a class prvalue when LOOKUP_NO_TEMP_BIND. */
1804 if ((flags & LOOKUP_NO_TEMP_BIND)
1805 && (gl_kind & clk_class))
1806 gl_kind = clk_none;
1808 /* Same mask as real_lvalue_p. */
1809 is_lvalue = gl_kind && !(gl_kind & (clk_rvalueref|clk_class));
1811 tfrom = from;
1812 if ((gl_kind & clk_bitfield) != 0)
1813 tfrom = unlowered_expr_type (expr);
1815 /* Figure out whether or not the types are reference-related and
1816 reference compatible. We have to do this after stripping
1817 references from FROM. */
1818 related_p = reference_related_p (to, tfrom);
1819 /* If this is a C cast, first convert to an appropriately qualified
1820 type, so that we can later do a const_cast to the desired type. */
1821 if (related_p && c_cast_p
1822 && !at_least_as_qualified_p (to, tfrom))
1823 to = cp_build_qualified_type (to, cp_type_quals (tfrom));
1824 compatible_p = reference_compatible_p (to, tfrom);
1826 /* Directly bind reference when target expression's type is compatible with
1827 the reference and expression is an lvalue. In DR391, the wording in
1828 [8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
1829 const and rvalue references to rvalues of compatible class type.
1830 We should also do direct bindings for non-class xvalues. */
1831 if ((related_p || compatible_p) && gl_kind)
1833 /* [dcl.init.ref]
1835 If the initializer expression
1837 -- is an lvalue (but not an lvalue for a bit-field), and "cv1 T1"
1838 is reference-compatible with "cv2 T2,"
1840 the reference is bound directly to the initializer expression
1841 lvalue.
1843 [...]
1844 If the initializer expression is an rvalue, with T2 a class type,
1845 and "cv1 T1" is reference-compatible with "cv2 T2", the reference
1846 is bound to the object represented by the rvalue or to a sub-object
1847 within that object. */
1849 conv = build_identity_conv (tfrom, expr);
1850 conv = direct_reference_binding (rto, conv);
1852 if (TYPE_REF_P (rfrom))
1853 /* Handle rvalue reference to function properly. */
1854 conv->rvaluedness_matches_p
1855 = (TYPE_REF_IS_RVALUE (rto) == TYPE_REF_IS_RVALUE (rfrom));
1856 else
1857 conv->rvaluedness_matches_p
1858 = (TYPE_REF_IS_RVALUE (rto) == !is_lvalue);
1860 if ((gl_kind & clk_bitfield) != 0
1861 || ((gl_kind & clk_packed) != 0 && !TYPE_PACKED (to)))
1862 /* For the purposes of overload resolution, we ignore the fact
1863 this expression is a bitfield or packed field. (In particular,
1864 [over.ics.ref] says specifically that a function with a
1865 non-const reference parameter is viable even if the
1866 argument is a bitfield.)
1868 However, when we actually call the function we must create
1869 a temporary to which to bind the reference. If the
1870 reference is volatile, or isn't const, then we cannot make
1871 a temporary, so we just issue an error when the conversion
1872 actually occurs. */
1873 conv->need_temporary_p = true;
1875 /* Don't allow binding of lvalues (other than function lvalues) to
1876 rvalue references. */
1877 if (is_lvalue && TYPE_REF_IS_RVALUE (rto)
1878 && TREE_CODE (to) != FUNCTION_TYPE)
1879 conv->bad_p = true;
1881 /* Nor the reverse. */
1882 if (!is_lvalue && !TYPE_REF_IS_RVALUE (rto)
1883 /* Unless it's really a C++20 lvalue being treated as an xvalue.
1884 But in C++23, such an expression is just an xvalue, not a special
1885 lvalue, so the binding is once again ill-formed. */
1886 && !(cxx_dialect == cxx20
1887 && (gl_kind & clk_implicit_rval))
1888 && (!CP_TYPE_CONST_NON_VOLATILE_P (to)
1889 || (flags & LOOKUP_NO_RVAL_BIND))
1890 && TREE_CODE (to) != FUNCTION_TYPE)
1891 conv->bad_p = true;
1893 if (!compatible_p)
1894 conv->bad_p = true;
1896 return conv;
1898 /* [class.conv.fct] A conversion function is never used to convert a
1899 (possibly cv-qualified) object to the (possibly cv-qualified) same
1900 object type (or a reference to it), to a (possibly cv-qualified) base
1901 class of that type (or a reference to it).... */
1902 else if (CLASS_TYPE_P (from) && !related_p
1903 && !(flags & LOOKUP_NO_CONVERSION))
1905 /* [dcl.init.ref]
1907 If the initializer expression
1909 -- has a class type (i.e., T2 is a class type) can be
1910 implicitly converted to an lvalue of type "cv3 T3," where
1911 "cv1 T1" is reference-compatible with "cv3 T3". (this
1912 conversion is selected by enumerating the applicable
1913 conversion functions (_over.match.ref_) and choosing the
1914 best one through overload resolution. (_over.match_).
1916 the reference is bound to the lvalue result of the conversion
1917 in the second case. */
1918 z_candidate *cand = build_user_type_conversion_1 (rto, expr, flags,
1919 complain);
1920 if (cand)
1921 return cand->second_conv;
1924 /* From this point on, we conceptually need temporaries, even if we
1925 elide them. Only the cases above are "direct bindings". */
1926 if (flags & LOOKUP_NO_TEMP_BIND)
1927 return NULL;
1929 /* [over.ics.rank]
1931 When a parameter of reference type is not bound directly to an
1932 argument expression, the conversion sequence is the one required
1933 to convert the argument expression to the underlying type of the
1934 reference according to _over.best.ics_. Conceptually, this
1935 conversion sequence corresponds to copy-initializing a temporary
1936 of the underlying type with the argument expression. Any
1937 difference in top-level cv-qualification is subsumed by the
1938 initialization itself and does not constitute a conversion. */
1940 bool maybe_valid_p = true;
1942 /* [dcl.init.ref]
1944 Otherwise, the reference shall be an lvalue reference to a
1945 non-volatile const type, or the reference shall be an rvalue
1946 reference. */
1947 if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto))
1948 maybe_valid_p = false;
1950 /* [dcl.init.ref]
1952 Otherwise, a temporary of type "cv1 T1" is created and
1953 initialized from the initializer expression using the rules for a
1954 non-reference copy initialization. If T1 is reference-related to
1955 T2, cv1 must be the same cv-qualification as, or greater
1956 cv-qualification than, cv2; otherwise, the program is ill-formed. */
1957 if (related_p && !at_least_as_qualified_p (to, from))
1958 maybe_valid_p = false;
1960 /* We try below to treat an invalid reference binding as a bad conversion
1961 to improve diagnostics, but doing so may cause otherwise unnecessary
1962 instantiations that can lead to a hard error. So during the first pass
1963 of overload resolution wherein we shortcut bad conversions, instead just
1964 produce a special conversion indicating a second pass is necessary if
1965 there's no strictly viable candidate. */
1966 if (!maybe_valid_p && (flags & LOOKUP_SHORTCUT_BAD_CONVS))
1968 conv = alloc_conversion (ck_deferred_bad);
1969 conv->bad_p = true;
1970 return conv;
1973 /* We're generating a temporary now, but don't bind any more in the
1974 conversion (specifically, don't slice the temporary returned by a
1975 conversion operator). */
1976 flags |= LOOKUP_NO_TEMP_BIND;
1978 /* Core issue 899: When [copy-]initializing a temporary to be bound
1979 to the first parameter of a copy constructor (12.8) called with
1980 a single argument in the context of direct-initialization,
1981 explicit conversion functions are also considered.
1983 So don't set LOOKUP_ONLYCONVERTING in that case. */
1984 if (!(flags & LOOKUP_COPY_PARM))
1985 flags |= LOOKUP_ONLYCONVERTING;
1987 if (!conv)
1988 conv = implicit_conversion (to, from, expr, c_cast_p,
1989 flags, complain);
1990 if (!conv)
1991 return NULL;
1993 if (conv->user_conv_p)
1995 if (copy_list_init)
1996 /* Remember this was copy-list-initialization. */
1997 conv->need_temporary_p = true;
1999 /* If initializing the temporary used a conversion function,
2000 recalculate the second conversion sequence. */
2001 for (conversion *t = conv; t; t = next_conversion (t))
2002 if (t->kind == ck_user
2003 && DECL_CONV_FN_P (t->cand->fn))
2005 tree ftype = TREE_TYPE (TREE_TYPE (t->cand->fn));
2006 /* A prvalue of non-class type is cv-unqualified. */
2007 if (!TYPE_REF_P (ftype) && !CLASS_TYPE_P (ftype))
2008 ftype = cv_unqualified (ftype);
2009 int sflags = (flags|LOOKUP_NO_CONVERSION)&~LOOKUP_NO_TEMP_BIND;
2010 conversion *new_second
2011 = reference_binding (rto, ftype, NULL_TREE, c_cast_p,
2012 sflags, complain);
2013 if (!new_second)
2014 return NULL;
2015 conv = merge_conversion_sequences (t, new_second);
2016 gcc_assert (maybe_valid_p || conv->bad_p);
2017 return conv;
2021 conv = build_conv (ck_ref_bind, rto, conv);
2022 /* This reference binding, unlike those above, requires the
2023 creation of a temporary. */
2024 conv->need_temporary_p = true;
2025 conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
2026 conv->bad_p |= !maybe_valid_p;
2028 return conv;
2031 /* Most of the implementation of implicit_conversion, with the same
2032 parameters. */
2034 static conversion *
2035 implicit_conversion_1 (tree to, tree from, tree expr, bool c_cast_p,
2036 int flags, tsubst_flags_t complain)
2038 conversion *conv;
2040 if (from == error_mark_node || to == error_mark_node
2041 || expr == error_mark_node)
2042 return NULL;
2044 /* Other flags only apply to the primary function in overload
2045 resolution, or after we've chosen one. */
2046 flags &= (LOOKUP_ONLYCONVERTING|LOOKUP_NO_CONVERSION|LOOKUP_COPY_PARM
2047 |LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND|LOOKUP_PREFER_RVALUE
2048 |LOOKUP_NO_NARROWING|LOOKUP_PROTECT|LOOKUP_NO_NON_INTEGRAL
2049 |LOOKUP_SHORTCUT_BAD_CONVS);
2051 /* FIXME: actually we don't want warnings either, but we can't just
2052 have 'complain &= ~(tf_warning|tf_error)' because it would cause
2053 the regression of, eg, g++.old-deja/g++.benjamin/16077.C.
2054 We really ought not to issue that warning until we've committed
2055 to that conversion. */
2056 complain &= ~tf_error;
2058 /* Call reshape_init early to remove redundant braces. */
2059 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr)
2060 && CLASS_TYPE_P (to)
2061 && COMPLETE_TYPE_P (complete_type (to))
2062 && !CLASSTYPE_NON_AGGREGATE (to))
2064 expr = reshape_init (to, expr, complain);
2065 if (expr == error_mark_node)
2066 return NULL;
2067 from = TREE_TYPE (expr);
2070 if (TYPE_REF_P (to))
2071 conv = reference_binding (to, from, expr, c_cast_p, flags, complain);
2072 else
2073 conv = standard_conversion (to, from, expr, c_cast_p, flags, complain);
2075 if (conv)
2076 return conv;
2078 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
2080 if (is_std_init_list (to) && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2081 return build_list_conv (to, expr, flags, complain);
2083 /* As an extension, allow list-initialization of _Complex. */
2084 if (TREE_CODE (to) == COMPLEX_TYPE
2085 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2087 conv = build_complex_conv (to, expr, flags, complain);
2088 if (conv)
2089 return conv;
2092 /* Allow conversion from an initializer-list with one element to a
2093 scalar type. */
2094 if (SCALAR_TYPE_P (to))
2096 int nelts = CONSTRUCTOR_NELTS (expr);
2097 tree elt;
2099 if (nelts == 0)
2100 elt = build_value_init (to, tf_none);
2101 else if (nelts == 1 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2102 elt = CONSTRUCTOR_ELT (expr, 0)->value;
2103 else
2104 elt = error_mark_node;
2106 conv = implicit_conversion (to, TREE_TYPE (elt), elt,
2107 c_cast_p, flags, complain);
2108 if (conv)
2110 conv->check_narrowing = true;
2111 if (BRACE_ENCLOSED_INITIALIZER_P (elt))
2112 /* Too many levels of braces, i.e. '{{1}}'. */
2113 conv->bad_p = true;
2114 return conv;
2117 else if (TREE_CODE (to) == ARRAY_TYPE)
2118 return build_array_conv (to, expr, flags, complain);
2121 if (expr != NULL_TREE
2122 && (MAYBE_CLASS_TYPE_P (from)
2123 || MAYBE_CLASS_TYPE_P (to))
2124 && (flags & LOOKUP_NO_CONVERSION) == 0)
2126 struct z_candidate *cand;
2128 if (CLASS_TYPE_P (to)
2129 && BRACE_ENCLOSED_INITIALIZER_P (expr)
2130 && !CLASSTYPE_NON_AGGREGATE (complete_type (to)))
2131 return build_aggr_conv (to, expr, flags, complain);
2133 cand = build_user_type_conversion_1 (to, expr, flags, complain);
2134 if (cand)
2136 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
2137 && CONSTRUCTOR_NELTS (expr) == 1
2138 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
2139 && !is_list_ctor (cand->fn))
2141 /* "If C is not an initializer-list constructor and the
2142 initializer list has a single element of type cv U, where U is
2143 X or a class derived from X, the implicit conversion sequence
2144 has Exact Match rank if U is X, or Conversion rank if U is
2145 derived from X." */
2146 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
2147 tree elttype = TREE_TYPE (elt);
2148 if (reference_related_p (to, elttype))
2149 return implicit_conversion (to, elttype, elt,
2150 c_cast_p, flags, complain);
2152 conv = cand->second_conv;
2155 /* We used to try to bind a reference to a temporary here, but that
2156 is now handled after the recursive call to this function at the end
2157 of reference_binding. */
2158 return conv;
2161 return NULL;
2164 /* Returns the implicit conversion sequence (see [over.ics]) from type
2165 FROM to type TO. The optional expression EXPR may affect the
2166 conversion. FLAGS are the usual overloading flags. If C_CAST_P is
2167 true, this conversion is coming from a C-style cast. */
2169 static conversion *
2170 implicit_conversion (tree to, tree from, tree expr, bool c_cast_p,
2171 int flags, tsubst_flags_t complain)
2173 conversion *conv = implicit_conversion_1 (to, from, expr, c_cast_p,
2174 flags, complain);
2175 if (!conv || conv->bad_p)
2176 return conv;
2177 if (conv_is_prvalue (conv)
2178 && CLASS_TYPE_P (conv->type)
2179 && CLASSTYPE_PURE_VIRTUALS (conv->type))
2180 conv->bad_p = true;
2181 return conv;
2184 /* Like implicit_conversion, but return NULL if the conversion is bad.
2186 This is not static so that check_non_deducible_conversion can call it within
2187 add_template_candidate_real as part of overload resolution; it should not be
2188 called outside of overload resolution. */
2190 conversion *
2191 good_conversion (tree to, tree from, tree expr,
2192 int flags, tsubst_flags_t complain)
2194 conversion *c = implicit_conversion (to, from, expr, /*cast*/false,
2195 flags, complain);
2196 if (c && c->bad_p)
2197 c = NULL;
2198 return c;
2201 /* Add a new entry to the list of candidates. Used by the add_*_candidate
2202 functions. ARGS will not be changed until a single candidate is
2203 selected. */
2205 static struct z_candidate *
2206 add_candidate (struct z_candidate **candidates,
2207 tree fn, tree first_arg, const vec<tree, va_gc> *args,
2208 size_t num_convs, conversion **convs,
2209 tree access_path, tree conversion_path,
2210 int viable, struct rejection_reason *reason,
2211 int flags)
2213 struct z_candidate *cand = (struct z_candidate *)
2214 conversion_obstack_alloc (sizeof (struct z_candidate));
2216 cand->fn = fn;
2217 cand->first_arg = first_arg;
2218 cand->args = args;
2219 cand->convs = convs;
2220 cand->num_convs = num_convs;
2221 cand->access_path = access_path;
2222 cand->conversion_path = conversion_path;
2223 cand->viable = viable;
2224 cand->reason = reason;
2225 cand->next = *candidates;
2226 cand->flags = flags;
2227 *candidates = cand;
2229 if (convs && cand->reversed ())
2230 /* Swap the conversions for comparison in joust; we'll swap them back
2231 before build_over_call. */
2232 std::swap (convs[0], convs[1]);
2234 return cand;
2237 /* Return the number of remaining arguments in the parameter list
2238 beginning with ARG. */
2241 remaining_arguments (tree arg)
2243 int n;
2245 for (n = 0; arg != NULL_TREE && arg != void_list_node;
2246 arg = TREE_CHAIN (arg))
2247 n++;
2249 return n;
2252 /* [over.match.copy]: When initializing a temporary object (12.2) to be bound
2253 to the first parameter of a constructor where the parameter is of type
2254 "reference to possibly cv-qualified T" and the constructor is called with a
2255 single argument in the context of direct-initialization of an object of type
2256 "cv2 T", explicit conversion functions are also considered.
2258 So set LOOKUP_COPY_PARM to let reference_binding know that
2259 it's being called in that context. */
2262 conv_flags (int i, int nargs, tree fn, tree arg, int flags)
2264 int lflags = flags;
2265 tree t;
2266 if (i == 0 && nargs == 1 && DECL_CONSTRUCTOR_P (fn)
2267 && (t = FUNCTION_FIRST_USER_PARMTYPE (fn))
2268 && (same_type_ignoring_top_level_qualifiers_p
2269 (non_reference (TREE_VALUE (t)), DECL_CONTEXT (fn))))
2271 if (!(flags & LOOKUP_ONLYCONVERTING))
2272 lflags |= LOOKUP_COPY_PARM;
2273 if ((flags & LOOKUP_LIST_INIT_CTOR)
2274 && BRACE_ENCLOSED_INITIALIZER_P (arg))
2275 lflags |= LOOKUP_NO_CONVERSION;
2277 else
2278 lflags |= LOOKUP_ONLYCONVERTING;
2280 return lflags;
2283 /* Build an appropriate 'this' conversion for the method FN and class
2284 type CTYPE from the value ARG (having type ARGTYPE) to the type PARMTYPE.
2285 This function modifies PARMTYPE, ARGTYPE and ARG. */
2287 static conversion *
2288 build_this_conversion (tree fn, tree ctype,
2289 tree& parmtype, tree& argtype, tree& arg,
2290 int flags, tsubst_flags_t complain)
2292 gcc_assert (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2293 && !DECL_CONSTRUCTOR_P (fn));
2295 /* The type of the implicit object parameter ('this') for
2296 overload resolution is not always the same as for the
2297 function itself; conversion functions are considered to
2298 be members of the class being converted, and functions
2299 introduced by a using-declaration are considered to be
2300 members of the class that uses them.
2302 Since build_over_call ignores the ICS for the `this'
2303 parameter, we can just change the parm type. */
2304 parmtype = cp_build_qualified_type (ctype,
2305 cp_type_quals (TREE_TYPE (parmtype)));
2306 bool this_p = true;
2307 if (FUNCTION_REF_QUALIFIED (TREE_TYPE (fn)))
2309 /* If the function has a ref-qualifier, the implicit
2310 object parameter has reference type. */
2311 bool rv = FUNCTION_RVALUE_QUALIFIED (TREE_TYPE (fn));
2312 parmtype = cp_build_reference_type (parmtype, rv);
2313 /* The special handling of 'this' conversions in compare_ics
2314 does not apply if there is a ref-qualifier. */
2315 this_p = false;
2317 else
2319 parmtype = build_pointer_type (parmtype);
2320 /* We don't use build_this here because we don't want to
2321 capture the object argument until we've chosen a
2322 non-static member function. */
2323 arg = build_address (arg);
2324 argtype = lvalue_type (arg);
2326 flags |= LOOKUP_ONLYCONVERTING;
2327 conversion *t = implicit_conversion (parmtype, argtype, arg,
2328 /*c_cast_p=*/false, flags, complain);
2329 t->this_p = this_p;
2330 return t;
2333 /* Create an overload candidate for the function or method FN called
2334 with the argument list FIRST_ARG/ARGS and add it to CANDIDATES.
2335 FLAGS is passed on to implicit_conversion.
2337 This does not change ARGS.
2339 CTYPE, if non-NULL, is the type we want to pretend this function
2340 comes from for purposes of overload resolution.
2342 SHORTCUT_BAD_CONVS controls how we handle "bad" argument conversions.
2343 If true, we stop computing conversions upon seeing the first bad
2344 conversion. This is used by add_candidates to avoid computing
2345 more conversions than necessary in the presence of a strictly viable
2346 candidate, while preserving the defacto behavior of overload resolution
2347 when it turns out there are only non-strictly viable candidates. */
2349 static struct z_candidate *
2350 add_function_candidate (struct z_candidate **candidates,
2351 tree fn, tree ctype, tree first_arg,
2352 const vec<tree, va_gc> *args, tree access_path,
2353 tree conversion_path, int flags,
2354 conversion **convs,
2355 bool shortcut_bad_convs,
2356 tsubst_flags_t complain)
2358 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
2359 int i, len;
2360 tree parmnode;
2361 tree orig_first_arg = first_arg;
2362 int skip;
2363 int viable = 1;
2364 struct rejection_reason *reason = NULL;
2366 /* The `this', `in_chrg' and VTT arguments to constructors are not
2367 considered in overload resolution. */
2368 if (DECL_CONSTRUCTOR_P (fn))
2370 if (ctor_omit_inherited_parms (fn))
2371 /* Bring back parameters omitted from an inherited ctor. */
2372 parmlist = FUNCTION_FIRST_USER_PARMTYPE (DECL_ORIGIN (fn));
2373 else
2374 parmlist = skip_artificial_parms_for (fn, parmlist);
2375 skip = num_artificial_parms_for (fn);
2376 if (skip > 0 && first_arg != NULL_TREE)
2378 --skip;
2379 first_arg = NULL_TREE;
2382 else
2383 skip = 0;
2385 len = vec_safe_length (args) - skip + (first_arg != NULL_TREE ? 1 : 0);
2386 if (!convs)
2387 convs = alloc_conversions (len);
2389 /* 13.3.2 - Viable functions [over.match.viable]
2390 First, to be a viable function, a candidate function shall have enough
2391 parameters to agree in number with the arguments in the list.
2393 We need to check this first; otherwise, checking the ICSes might cause
2394 us to produce an ill-formed template instantiation. */
2396 parmnode = parmlist;
2397 for (i = 0; i < len; ++i)
2399 if (parmnode == NULL_TREE || parmnode == void_list_node)
2400 break;
2401 parmnode = TREE_CHAIN (parmnode);
2404 if ((i < len && parmnode)
2405 || !sufficient_parms_p (parmnode))
2407 int remaining = remaining_arguments (parmnode);
2408 viable = 0;
2409 reason = arity_rejection (first_arg, i + remaining, len);
2412 /* An inherited constructor (12.6.3 [class.inhctor.init]) that has a first
2413 parameter of type "reference to cv C" (including such a constructor
2414 instantiated from a template) is excluded from the set of candidate
2415 functions when used to construct an object of type D with an argument list
2416 containing a single argument if C is reference-related to D. */
2417 if (viable && len == 1 && parmlist && DECL_CONSTRUCTOR_P (fn)
2418 && flag_new_inheriting_ctors
2419 && DECL_INHERITED_CTOR (fn))
2421 tree ptype = non_reference (TREE_VALUE (parmlist));
2422 tree dtype = DECL_CONTEXT (fn);
2423 tree btype = DECL_INHERITED_CTOR_BASE (fn);
2424 if (reference_related_p (ptype, dtype)
2425 && reference_related_p (btype, ptype))
2427 viable = false;
2428 reason = inherited_ctor_rejection ();
2432 /* Second, for a function to be viable, its constraints must be
2433 satisfied. */
2434 if (flag_concepts && viable && !constraints_satisfied_p (fn))
2436 reason = constraint_failure ();
2437 viable = false;
2440 /* When looking for a function from a subobject from an implicit
2441 copy/move constructor/operator=, don't consider anything that takes (a
2442 reference to) an unrelated type. See c++/44909 and core 1092. */
2443 if (viable && parmlist && (flags & LOOKUP_DEFAULTED))
2445 if (DECL_CONSTRUCTOR_P (fn))
2446 i = 1;
2447 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
2448 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR))
2449 i = 2;
2450 else
2451 i = 0;
2452 if (i && len == i)
2454 parmnode = chain_index (i-1, parmlist);
2455 if (!reference_related_p (non_reference (TREE_VALUE (parmnode)),
2456 ctype))
2457 viable = 0;
2460 /* This only applies at the top level. */
2461 flags &= ~LOOKUP_DEFAULTED;
2464 if (! viable)
2465 goto out;
2467 if (shortcut_bad_convs)
2468 flags |= LOOKUP_SHORTCUT_BAD_CONVS;
2469 else
2470 flags &= ~LOOKUP_SHORTCUT_BAD_CONVS;
2472 /* Third, for F to be a viable function, there shall exist for each
2473 argument an implicit conversion sequence that converts that argument
2474 to the corresponding parameter of F. */
2476 parmnode = parmlist;
2478 for (i = 0; i < len; ++i)
2480 tree argtype, to_type;
2481 tree arg;
2483 if (parmnode == void_list_node)
2484 break;
2486 if (convs[i])
2488 /* Already set during deduction. */
2489 parmnode = TREE_CHAIN (parmnode);
2490 continue;
2493 if (i == 0 && first_arg != NULL_TREE)
2494 arg = first_arg;
2495 else
2496 arg = CONST_CAST_TREE (
2497 (*args)[i + skip - (first_arg != NULL_TREE ? 1 : 0)]);
2498 argtype = lvalue_type (arg);
2500 conversion *t;
2501 if (parmnode)
2503 tree parmtype = TREE_VALUE (parmnode);
2504 if (i == 0
2505 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2506 && !DECL_CONSTRUCTOR_P (fn))
2507 t = build_this_conversion (fn, ctype, parmtype, argtype, arg,
2508 flags, complain);
2509 else
2511 int lflags = conv_flags (i, len-skip, fn, arg, flags);
2512 t = implicit_conversion (parmtype, argtype, arg,
2513 /*c_cast_p=*/false, lflags, complain);
2515 to_type = parmtype;
2516 parmnode = TREE_CHAIN (parmnode);
2518 else
2520 t = build_identity_conv (argtype, arg);
2521 t->ellipsis_p = true;
2522 to_type = argtype;
2525 convs[i] = t;
2526 if (! t)
2528 viable = 0;
2529 reason = arg_conversion_rejection (first_arg, i, argtype, to_type,
2530 EXPR_LOCATION (arg));
2531 break;
2534 if (t->bad_p)
2536 viable = -1;
2537 reason = bad_arg_conversion_rejection (first_arg, i, arg, to_type,
2538 EXPR_LOCATION (arg));
2539 if (shortcut_bad_convs)
2540 break;
2544 out:
2545 return add_candidate (candidates, fn, orig_first_arg, args, len, convs,
2546 access_path, conversion_path, viable, reason, flags);
2549 /* Create an overload candidate for the conversion function FN which will
2550 be invoked for expression OBJ, producing a pointer-to-function which
2551 will in turn be called with the argument list FIRST_ARG/ARGLIST,
2552 and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
2553 passed on to implicit_conversion.
2555 Actually, we don't really care about FN; we care about the type it
2556 converts to. There may be multiple conversion functions that will
2557 convert to that type, and we rely on build_user_type_conversion_1 to
2558 choose the best one; so when we create our candidate, we record the type
2559 instead of the function. */
2561 static struct z_candidate *
2562 add_conv_candidate (struct z_candidate **candidates, tree fn, tree obj,
2563 const vec<tree, va_gc> *arglist,
2564 tree access_path, tree conversion_path,
2565 tsubst_flags_t complain)
2567 tree totype = TREE_TYPE (TREE_TYPE (fn));
2568 int i, len, viable, flags;
2569 tree parmlist, parmnode;
2570 conversion **convs;
2571 struct rejection_reason *reason;
2573 for (parmlist = totype; TREE_CODE (parmlist) != FUNCTION_TYPE; )
2574 parmlist = TREE_TYPE (parmlist);
2575 parmlist = TYPE_ARG_TYPES (parmlist);
2577 len = vec_safe_length (arglist) + 1;
2578 convs = alloc_conversions (len);
2579 parmnode = parmlist;
2580 viable = 1;
2581 flags = LOOKUP_IMPLICIT;
2582 reason = NULL;
2584 /* Don't bother looking up the same type twice. */
2585 if (*candidates && (*candidates)->fn == totype)
2586 return NULL;
2588 for (i = 0; i < len; ++i)
2590 tree arg, argtype, convert_type = NULL_TREE;
2591 conversion *t;
2593 if (i == 0)
2594 arg = obj;
2595 else
2596 arg = (*arglist)[i - 1];
2597 argtype = lvalue_type (arg);
2599 if (i == 0)
2601 t = build_identity_conv (argtype, NULL_TREE);
2602 t = build_conv (ck_user, totype, t);
2603 /* Leave the 'cand' field null; we'll figure out the conversion in
2604 convert_like if this candidate is chosen. */
2605 convert_type = totype;
2607 else if (parmnode == void_list_node)
2608 break;
2609 else if (parmnode)
2611 t = implicit_conversion (TREE_VALUE (parmnode), argtype, arg,
2612 /*c_cast_p=*/false, flags, complain);
2613 convert_type = TREE_VALUE (parmnode);
2615 else
2617 t = build_identity_conv (argtype, arg);
2618 t->ellipsis_p = true;
2619 convert_type = argtype;
2622 convs[i] = t;
2623 if (! t)
2624 break;
2626 if (t->bad_p)
2628 viable = -1;
2629 reason = bad_arg_conversion_rejection (NULL_TREE, i, arg, convert_type,
2630 EXPR_LOCATION (arg));
2633 if (i == 0)
2634 continue;
2636 if (parmnode)
2637 parmnode = TREE_CHAIN (parmnode);
2640 if (i < len
2641 || ! sufficient_parms_p (parmnode))
2643 int remaining = remaining_arguments (parmnode);
2644 viable = 0;
2645 reason = arity_rejection (NULL_TREE, i + remaining, len);
2648 return add_candidate (candidates, totype, obj, arglist, len, convs,
2649 access_path, conversion_path, viable, reason, flags);
2652 static void
2653 build_builtin_candidate (struct z_candidate **candidates, tree fnname,
2654 tree type1, tree type2, const vec<tree,va_gc> &args,
2655 tree *argtypes, int flags, tsubst_flags_t complain)
2657 conversion *t;
2658 conversion **convs;
2659 size_t num_convs;
2660 int viable = 1;
2661 tree types[2];
2662 struct rejection_reason *reason = NULL;
2664 types[0] = type1;
2665 types[1] = type2;
2667 num_convs = args.length ();
2668 convs = alloc_conversions (num_convs);
2670 /* TRUTH_*_EXPR do "contextual conversion to bool", which means explicit
2671 conversion ops are allowed. We handle that here by just checking for
2672 boolean_type_node because other operators don't ask for it. COND_EXPR
2673 also does contextual conversion to bool for the first operand, but we
2674 handle that in build_conditional_expr, and type1 here is operand 2. */
2675 if (type1 != boolean_type_node)
2676 flags |= LOOKUP_ONLYCONVERTING;
2678 for (unsigned i = 0; i < 2 && i < num_convs; ++i)
2680 t = implicit_conversion (types[i], argtypes[i], args[i],
2681 /*c_cast_p=*/false, flags, complain);
2682 if (! t)
2684 viable = 0;
2685 /* We need something for printing the candidate. */
2686 t = build_identity_conv (types[i], NULL_TREE);
2687 reason = arg_conversion_rejection (NULL_TREE, i, argtypes[i],
2688 types[i], EXPR_LOCATION (args[i]));
2690 else if (t->bad_p)
2692 viable = 0;
2693 reason = bad_arg_conversion_rejection (NULL_TREE, i, args[i],
2694 types[i],
2695 EXPR_LOCATION (args[i]));
2697 convs[i] = t;
2700 /* For COND_EXPR we rearranged the arguments; undo that now. */
2701 if (num_convs == 3)
2703 convs[2] = convs[1];
2704 convs[1] = convs[0];
2705 t = implicit_conversion (boolean_type_node, argtypes[2], args[2],
2706 /*c_cast_p=*/false, flags,
2707 complain);
2708 if (t)
2709 convs[0] = t;
2710 else
2712 viable = 0;
2713 reason = arg_conversion_rejection (NULL_TREE, 0, argtypes[2],
2714 boolean_type_node,
2715 EXPR_LOCATION (args[2]));
2719 add_candidate (candidates, fnname, /*first_arg=*/NULL_TREE, /*args=*/NULL,
2720 num_convs, convs,
2721 /*access_path=*/NULL_TREE,
2722 /*conversion_path=*/NULL_TREE,
2723 viable, reason, flags);
2726 static bool
2727 is_complete (tree t)
2729 return COMPLETE_TYPE_P (complete_type (t));
2732 /* Returns nonzero if TYPE is a promoted arithmetic type. */
2734 static bool
2735 promoted_arithmetic_type_p (tree type)
2737 /* [over.built]
2739 In this section, the term promoted integral type is used to refer
2740 to those integral types which are preserved by integral promotion
2741 (including e.g. int and long but excluding e.g. char).
2742 Similarly, the term promoted arithmetic type refers to promoted
2743 integral types plus floating types. */
2744 return ((CP_INTEGRAL_TYPE_P (type)
2745 && same_type_p (type_promotes_to (type), type))
2746 || TREE_CODE (type) == REAL_TYPE);
2749 /* Create any builtin operator overload candidates for the operator in
2750 question given the converted operand types TYPE1 and TYPE2. The other
2751 args are passed through from add_builtin_candidates to
2752 build_builtin_candidate.
2754 TYPE1 and TYPE2 may not be permissible, and we must filter them.
2755 If CODE is requires candidates operands of the same type of the kind
2756 of which TYPE1 and TYPE2 are, we add both candidates
2757 CODE (TYPE1, TYPE1) and CODE (TYPE2, TYPE2). */
2759 static void
2760 add_builtin_candidate (struct z_candidate **candidates, enum tree_code code,
2761 enum tree_code code2, tree fnname, tree type1,
2762 tree type2, vec<tree,va_gc> &args, tree *argtypes,
2763 int flags, tsubst_flags_t complain)
2765 switch (code)
2767 case POSTINCREMENT_EXPR:
2768 case POSTDECREMENT_EXPR:
2769 args[1] = integer_zero_node;
2770 type2 = integer_type_node;
2771 break;
2772 default:
2773 break;
2776 switch (code)
2779 /* 4 For every pair (T, VQ), where T is an arithmetic type other than bool,
2780 and VQ is either volatile or empty, there exist candidate operator
2781 functions of the form
2782 VQ T& operator++(VQ T&);
2783 T operator++(VQ T&, int);
2784 5 For every pair (T, VQ), where T is an arithmetic type other than bool,
2785 and VQ is either volatile or empty, there exist candidate operator
2786 functions of the form
2787 VQ T& operator--(VQ T&);
2788 T operator--(VQ T&, int);
2789 6 For every pair (T, VQ), where T is a cv-qualified or cv-unqualified object
2790 type, and VQ is either volatile or empty, there exist candidate operator
2791 functions of the form
2792 T*VQ& operator++(T*VQ&);
2793 T*VQ& operator--(T*VQ&);
2794 T* operator++(T*VQ&, int);
2795 T* operator--(T*VQ&, int); */
2797 case POSTDECREMENT_EXPR:
2798 case PREDECREMENT_EXPR:
2799 if (TREE_CODE (type1) == BOOLEAN_TYPE)
2800 return;
2801 /* FALLTHRU */
2802 case POSTINCREMENT_EXPR:
2803 case PREINCREMENT_EXPR:
2804 /* P0002R1, Remove deprecated operator++(bool) added "other than bool"
2805 to p4. */
2806 if (TREE_CODE (type1) == BOOLEAN_TYPE && cxx_dialect >= cxx17)
2807 return;
2808 if (ARITHMETIC_TYPE_P (type1) || TYPE_PTROB_P (type1))
2810 type1 = build_reference_type (type1);
2811 break;
2813 return;
2815 /* 7 For every cv-qualified or cv-unqualified object type T, there
2816 exist candidate operator functions of the form
2818 T& operator*(T*);
2821 8 For every function type T that does not have cv-qualifiers or
2822 a ref-qualifier, there exist candidate operator functions of the form
2823 T& operator*(T*); */
2825 case INDIRECT_REF:
2826 if (TYPE_PTR_P (type1)
2827 && (TYPE_PTROB_P (type1)
2828 || TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE))
2829 break;
2830 return;
2832 /* 9 For every type T, there exist candidate operator functions of the form
2833 T* operator+(T*);
2835 10 For every floating-point or promoted integral type T, there exist
2836 candidate operator functions of the form
2837 T operator+(T);
2838 T operator-(T); */
2840 case UNARY_PLUS_EXPR: /* unary + */
2841 if (TYPE_PTR_P (type1))
2842 break;
2843 /* FALLTHRU */
2844 case NEGATE_EXPR:
2845 if (ARITHMETIC_TYPE_P (type1))
2846 break;
2847 return;
2849 /* 11 For every promoted integral type T, there exist candidate operator
2850 functions of the form
2851 T operator~(T); */
2853 case BIT_NOT_EXPR:
2854 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1))
2855 break;
2856 return;
2858 /* 12 For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, C1
2859 is the same type as C2 or is a derived class of C2, and T is an object
2860 type or a function type there exist candidate operator functions of the
2861 form
2862 CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
2863 where CV12 is the union of CV1 and CV2. */
2865 case MEMBER_REF:
2866 if (TYPE_PTR_P (type1) && TYPE_PTRMEM_P (type2))
2868 tree c1 = TREE_TYPE (type1);
2869 tree c2 = TYPE_PTRMEM_CLASS_TYPE (type2);
2871 if (CLASS_TYPE_P (c1) && DERIVED_FROM_P (c2, c1)
2872 && (TYPE_PTRMEMFUNC_P (type2)
2873 || is_complete (TYPE_PTRMEM_POINTED_TO_TYPE (type2))))
2874 break;
2876 return;
2878 /* 13 For every pair of types L and R, where each of L and R is a floating-point
2879 or promoted integral type, there exist candidate operator functions of the
2880 form
2881 LR operator*(L, R);
2882 LR operator/(L, R);
2883 LR operator+(L, R);
2884 LR operator-(L, R);
2885 bool operator<(L, R);
2886 bool operator>(L, R);
2887 bool operator<=(L, R);
2888 bool operator>=(L, R);
2889 bool operator==(L, R);
2890 bool operator!=(L, R);
2891 where LR is the result of the usual arithmetic conversions between
2892 types L and R.
2894 14 For every integral type T there exists a candidate operator function of
2895 the form
2897 std::strong_ordering operator<=>(T, T);
2899 15 For every pair of floating-point types L and R, there exists a candidate
2900 operator function of the form
2902 std::partial_ordering operator<=>(L, R);
2904 16 For every cv-qualified or cv-unqualified object type T there exist
2905 candidate operator functions of the form
2906 T* operator+(T*, std::ptrdiff_t);
2907 T& operator[](T*, std::ptrdiff_t);
2908 T* operator-(T*, std::ptrdiff_t);
2909 T* operator+(std::ptrdiff_t, T*);
2910 T& operator[](std::ptrdiff_t, T*);
2912 17 For every T, where T is a pointer to object type, there exist candidate
2913 operator functions of the form
2914 std::ptrdiff_t operator-(T, T);
2916 18 For every T, where T is an enumeration type or a pointer type, there
2917 exist candidate operator functions of the form
2918 bool operator<(T, T);
2919 bool operator>(T, T);
2920 bool operator<=(T, T);
2921 bool operator>=(T, T);
2922 bool operator==(T, T);
2923 bool operator!=(T, T);
2924 R operator<=>(T, T);
2926 where R is the result type specified in [expr.spaceship].
2928 19 For every T, where T is a pointer-to-member type or std::nullptr_t,
2929 there exist candidate operator functions of the form
2930 bool operator==(T, T);
2931 bool operator!=(T, T); */
2933 case MINUS_EXPR:
2934 if (TYPE_PTROB_P (type1) && TYPE_PTROB_P (type2))
2935 break;
2936 if (TYPE_PTROB_P (type1)
2937 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2939 type2 = ptrdiff_type_node;
2940 break;
2942 /* FALLTHRU */
2943 case MULT_EXPR:
2944 case TRUNC_DIV_EXPR:
2945 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2946 break;
2947 return;
2949 /* This isn't exactly what's specified above for operator<=>, but it's
2950 close enough. In particular, we don't care about the return type
2951 specified above; it doesn't participate in overload resolution and it
2952 doesn't affect the semantics of the built-in operator. */
2953 case SPACESHIP_EXPR:
2954 case EQ_EXPR:
2955 case NE_EXPR:
2956 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
2957 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2)))
2958 break;
2959 if (NULLPTR_TYPE_P (type1) && NULLPTR_TYPE_P (type2))
2960 break;
2961 if (TYPE_PTRMEM_P (type1) && null_ptr_cst_p (args[1]))
2963 type2 = type1;
2964 break;
2966 if (TYPE_PTRMEM_P (type2) && null_ptr_cst_p (args[0]))
2968 type1 = type2;
2969 break;
2971 /* Fall through. */
2972 case LT_EXPR:
2973 case GT_EXPR:
2974 case LE_EXPR:
2975 case GE_EXPR:
2976 case MAX_EXPR:
2977 case MIN_EXPR:
2978 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2979 break;
2980 if (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
2981 break;
2982 if (TREE_CODE (type1) == ENUMERAL_TYPE
2983 && TREE_CODE (type2) == ENUMERAL_TYPE)
2984 break;
2985 if (TYPE_PTR_P (type1)
2986 && null_ptr_cst_p (args[1]))
2988 type2 = type1;
2989 break;
2991 if (null_ptr_cst_p (args[0])
2992 && TYPE_PTR_P (type2))
2994 type1 = type2;
2995 break;
2997 return;
2999 case PLUS_EXPR:
3000 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3001 break;
3002 /* FALLTHRU */
3003 case ARRAY_REF:
3004 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && TYPE_PTROB_P (type2))
3006 type1 = ptrdiff_type_node;
3007 break;
3009 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3011 type2 = ptrdiff_type_node;
3012 break;
3014 return;
3016 /* 18For every pair of promoted integral types L and R, there exist candi-
3017 date operator functions of the form
3018 LR operator%(L, R);
3019 LR operator&(L, R);
3020 LR operator^(L, R);
3021 LR operator|(L, R);
3022 L operator<<(L, R);
3023 L operator>>(L, R);
3024 where LR is the result of the usual arithmetic conversions between
3025 types L and R. */
3027 case TRUNC_MOD_EXPR:
3028 case BIT_AND_EXPR:
3029 case BIT_IOR_EXPR:
3030 case BIT_XOR_EXPR:
3031 case LSHIFT_EXPR:
3032 case RSHIFT_EXPR:
3033 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3034 break;
3035 return;
3037 /* 19For every triple L, VQ, R), where L is an arithmetic or enumeration
3038 type, VQ is either volatile or empty, and R is a promoted arithmetic
3039 type, there exist candidate operator functions of the form
3040 VQ L& operator=(VQ L&, R);
3041 VQ L& operator*=(VQ L&, R);
3042 VQ L& operator/=(VQ L&, R);
3043 VQ L& operator+=(VQ L&, R);
3044 VQ L& operator-=(VQ L&, R);
3046 20For every pair T, VQ), where T is any type and VQ is either volatile
3047 or empty, there exist candidate operator functions of the form
3048 T*VQ& operator=(T*VQ&, T*);
3050 21For every pair T, VQ), where T is a pointer to member type and VQ is
3051 either volatile or empty, there exist candidate operator functions of
3052 the form
3053 VQ T& operator=(VQ T&, T);
3055 22For every triple T, VQ, I), where T is a cv-qualified or cv-
3056 unqualified complete object type, VQ is either volatile or empty, and
3057 I is a promoted integral type, there exist candidate operator func-
3058 tions of the form
3059 T*VQ& operator+=(T*VQ&, I);
3060 T*VQ& operator-=(T*VQ&, I);
3062 23For every triple L, VQ, R), where L is an integral or enumeration
3063 type, VQ is either volatile or empty, and R is a promoted integral
3064 type, there exist candidate operator functions of the form
3066 VQ L& operator%=(VQ L&, R);
3067 VQ L& operator<<=(VQ L&, R);
3068 VQ L& operator>>=(VQ L&, R);
3069 VQ L& operator&=(VQ L&, R);
3070 VQ L& operator^=(VQ L&, R);
3071 VQ L& operator|=(VQ L&, R); */
3073 case MODIFY_EXPR:
3074 switch (code2)
3076 case PLUS_EXPR:
3077 case MINUS_EXPR:
3078 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3080 type2 = ptrdiff_type_node;
3081 break;
3083 /* FALLTHRU */
3084 case MULT_EXPR:
3085 case TRUNC_DIV_EXPR:
3086 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3087 break;
3088 return;
3090 case TRUNC_MOD_EXPR:
3091 case BIT_AND_EXPR:
3092 case BIT_IOR_EXPR:
3093 case BIT_XOR_EXPR:
3094 case LSHIFT_EXPR:
3095 case RSHIFT_EXPR:
3096 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3097 break;
3098 return;
3100 case NOP_EXPR:
3101 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3102 break;
3103 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3104 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3105 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3106 || ((TYPE_PTRMEMFUNC_P (type1)
3107 || TYPE_PTR_P (type1))
3108 && null_ptr_cst_p (args[1])))
3110 type2 = type1;
3111 break;
3113 return;
3115 default:
3116 gcc_unreachable ();
3118 type1 = build_reference_type (type1);
3119 break;
3121 case COND_EXPR:
3122 /* [over.built]
3124 For every pair of promoted arithmetic types L and R, there
3125 exist candidate operator functions of the form
3127 LR operator?(bool, L, R);
3129 where LR is the result of the usual arithmetic conversions
3130 between types L and R.
3132 For every type T, where T is a pointer or pointer-to-member
3133 type, there exist candidate operator functions of the form T
3134 operator?(bool, T, T); */
3136 if (promoted_arithmetic_type_p (type1)
3137 && promoted_arithmetic_type_p (type2))
3138 /* That's OK. */
3139 break;
3141 /* Otherwise, the types should be pointers. */
3142 if (!TYPE_PTR_OR_PTRMEM_P (type1) || !TYPE_PTR_OR_PTRMEM_P (type2))
3143 return;
3145 /* We don't check that the two types are the same; the logic
3146 below will actually create two candidates; one in which both
3147 parameter types are TYPE1, and one in which both parameter
3148 types are TYPE2. */
3149 break;
3151 case REALPART_EXPR:
3152 case IMAGPART_EXPR:
3153 if (ARITHMETIC_TYPE_P (type1))
3154 break;
3155 return;
3157 default:
3158 gcc_unreachable ();
3161 /* Make sure we don't create builtin candidates with dependent types. */
3162 bool u1 = uses_template_parms (type1);
3163 bool u2 = type2 ? uses_template_parms (type2) : false;
3164 if (u1 || u2)
3166 /* Try to recover if one of the types is non-dependent. But if
3167 there's only one type, there's nothing we can do. */
3168 if (!type2)
3169 return;
3170 /* And we lose if both are dependent. */
3171 if (u1 && u2)
3172 return;
3173 /* Or if they have different forms. */
3174 if (TREE_CODE (type1) != TREE_CODE (type2))
3175 return;
3177 if (u1 && !u2)
3178 type1 = type2;
3179 else if (u2 && !u1)
3180 type2 = type1;
3183 /* If we're dealing with two pointer types or two enumeral types,
3184 we need candidates for both of them. */
3185 if (type2 && !same_type_p (type1, type2)
3186 && TREE_CODE (type1) == TREE_CODE (type2)
3187 && (TYPE_REF_P (type1)
3188 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3189 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3190 || TYPE_PTRMEMFUNC_P (type1)
3191 || MAYBE_CLASS_TYPE_P (type1)
3192 || TREE_CODE (type1) == ENUMERAL_TYPE))
3194 if (TYPE_PTR_OR_PTRMEM_P (type1))
3196 tree cptype = composite_pointer_type (input_location,
3197 type1, type2,
3198 error_mark_node,
3199 error_mark_node,
3200 CPO_CONVERSION,
3201 tf_none);
3202 if (cptype != error_mark_node)
3204 build_builtin_candidate
3205 (candidates, fnname, cptype, cptype, args, argtypes,
3206 flags, complain);
3207 return;
3211 build_builtin_candidate
3212 (candidates, fnname, type1, type1, args, argtypes, flags, complain);
3213 build_builtin_candidate
3214 (candidates, fnname, type2, type2, args, argtypes, flags, complain);
3215 return;
3218 build_builtin_candidate
3219 (candidates, fnname, type1, type2, args, argtypes, flags, complain);
3222 tree
3223 type_decays_to (tree type)
3225 if (TREE_CODE (type) == ARRAY_TYPE)
3226 return build_pointer_type (TREE_TYPE (type));
3227 if (TREE_CODE (type) == FUNCTION_TYPE)
3228 return build_pointer_type (type);
3229 return type;
3232 /* There are three conditions of builtin candidates:
3234 1) bool-taking candidates. These are the same regardless of the input.
3235 2) pointer-pair taking candidates. These are generated for each type
3236 one of the input types converts to.
3237 3) arithmetic candidates. According to the standard, we should generate
3238 all of these, but I'm trying not to...
3240 Here we generate a superset of the possible candidates for this particular
3241 case. That is a subset of the full set the standard defines, plus some
3242 other cases which the standard disallows. add_builtin_candidate will
3243 filter out the invalid set. */
3245 static void
3246 add_builtin_candidates (struct z_candidate **candidates, enum tree_code code,
3247 enum tree_code code2, tree fnname,
3248 vec<tree, va_gc> *argv,
3249 int flags, tsubst_flags_t complain)
3251 int ref1;
3252 int enum_p = 0;
3253 tree type, argtypes[3], t;
3254 /* TYPES[i] is the set of possible builtin-operator parameter types
3255 we will consider for the Ith argument. */
3256 vec<tree, va_gc> *types[2];
3257 unsigned ix;
3258 vec<tree, va_gc> &args = *argv;
3259 unsigned len = args.length ();
3261 for (unsigned i = 0; i < len; ++i)
3263 if (args[i])
3264 argtypes[i] = unlowered_expr_type (args[i]);
3265 else
3266 argtypes[i] = NULL_TREE;
3269 switch (code)
3271 /* 4 For every pair T, VQ), where T is an arithmetic or enumeration type,
3272 and VQ is either volatile or empty, there exist candidate operator
3273 functions of the form
3274 VQ T& operator++(VQ T&); */
3276 case POSTINCREMENT_EXPR:
3277 case PREINCREMENT_EXPR:
3278 case POSTDECREMENT_EXPR:
3279 case PREDECREMENT_EXPR:
3280 case MODIFY_EXPR:
3281 ref1 = 1;
3282 break;
3284 /* 24There also exist candidate operator functions of the form
3285 bool operator!(bool);
3286 bool operator&&(bool, bool);
3287 bool operator||(bool, bool); */
3289 case TRUTH_NOT_EXPR:
3290 build_builtin_candidate
3291 (candidates, fnname, boolean_type_node,
3292 NULL_TREE, args, argtypes, flags, complain);
3293 return;
3295 case TRUTH_ORIF_EXPR:
3296 case TRUTH_ANDIF_EXPR:
3297 build_builtin_candidate
3298 (candidates, fnname, boolean_type_node,
3299 boolean_type_node, args, argtypes, flags, complain);
3300 return;
3302 case ADDR_EXPR:
3303 case COMPOUND_EXPR:
3304 case COMPONENT_REF:
3305 case CO_AWAIT_EXPR:
3306 return;
3308 case COND_EXPR:
3309 case EQ_EXPR:
3310 case NE_EXPR:
3311 case LT_EXPR:
3312 case LE_EXPR:
3313 case GT_EXPR:
3314 case GE_EXPR:
3315 case SPACESHIP_EXPR:
3316 enum_p = 1;
3317 /* Fall through. */
3319 default:
3320 ref1 = 0;
3323 types[0] = make_tree_vector ();
3324 types[1] = make_tree_vector ();
3326 if (len == 3)
3327 len = 2;
3328 for (unsigned i = 0; i < len; ++i)
3330 if (MAYBE_CLASS_TYPE_P (argtypes[i]))
3332 tree convs;
3334 if (i == 0 && code == MODIFY_EXPR && code2 == NOP_EXPR)
3335 return;
3337 convs = lookup_conversions (argtypes[i]);
3339 if (code == COND_EXPR)
3341 if (lvalue_p (args[i]))
3342 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3344 vec_safe_push (types[i], TYPE_MAIN_VARIANT (argtypes[i]));
3347 else if (! convs)
3348 return;
3350 for (; convs; convs = TREE_CHAIN (convs))
3352 type = TREE_TYPE (convs);
3354 if (i == 0 && ref1
3355 && (!TYPE_REF_P (type)
3356 || CP_TYPE_CONST_P (TREE_TYPE (type))))
3357 continue;
3359 if (code == COND_EXPR && TYPE_REF_P (type))
3360 vec_safe_push (types[i], type);
3362 type = non_reference (type);
3363 if (i != 0 || ! ref1)
3365 type = cv_unqualified (type_decays_to (type));
3366 if (enum_p && TREE_CODE (type) == ENUMERAL_TYPE)
3367 vec_safe_push (types[i], type);
3368 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3369 type = type_promotes_to (type);
3372 if (! vec_member (type, types[i]))
3373 vec_safe_push (types[i], type);
3376 else
3378 if (code == COND_EXPR && lvalue_p (args[i]))
3379 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3380 type = non_reference (argtypes[i]);
3381 if (i != 0 || ! ref1)
3383 type = cv_unqualified (type_decays_to (type));
3384 if (enum_p && UNSCOPED_ENUM_P (type))
3385 vec_safe_push (types[i], type);
3386 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3387 type = type_promotes_to (type);
3389 vec_safe_push (types[i], type);
3393 /* Run through the possible parameter types of both arguments,
3394 creating candidates with those parameter types. */
3395 FOR_EACH_VEC_ELT_REVERSE (*(types[0]), ix, t)
3397 unsigned jx;
3398 tree u;
3400 if (!types[1]->is_empty ())
3401 FOR_EACH_VEC_ELT_REVERSE (*(types[1]), jx, u)
3402 add_builtin_candidate
3403 (candidates, code, code2, fnname, t,
3404 u, args, argtypes, flags, complain);
3405 else
3406 add_builtin_candidate
3407 (candidates, code, code2, fnname, t,
3408 NULL_TREE, args, argtypes, flags, complain);
3411 release_tree_vector (types[0]);
3412 release_tree_vector (types[1]);
3416 /* If TMPL can be successfully instantiated as indicated by
3417 EXPLICIT_TARGS and ARGLIST, adds the instantiation to CANDIDATES.
3419 TMPL is the template. EXPLICIT_TARGS are any explicit template
3420 arguments. ARGLIST is the arguments provided at the call-site.
3421 This does not change ARGLIST. The RETURN_TYPE is the desired type
3422 for conversion operators. If OBJ is NULL_TREE, FLAGS and CTYPE are
3423 as for add_function_candidate. If an OBJ is supplied, FLAGS and
3424 CTYPE are ignored, and OBJ is as for add_conv_candidate.
3426 SHORTCUT_BAD_CONVS is as in add_function_candidate. */
3428 static struct z_candidate*
3429 add_template_candidate_real (struct z_candidate **candidates, tree tmpl,
3430 tree ctype, tree explicit_targs, tree first_arg,
3431 const vec<tree, va_gc> *arglist, tree return_type,
3432 tree access_path, tree conversion_path,
3433 int flags, tree obj, unification_kind_t strict,
3434 bool shortcut_bad_convs, tsubst_flags_t complain)
3436 int ntparms = DECL_NTPARMS (tmpl);
3437 tree targs = make_tree_vec (ntparms);
3438 unsigned int len = vec_safe_length (arglist);
3439 unsigned int nargs = (first_arg == NULL_TREE ? 0 : 1) + len;
3440 unsigned int skip_without_in_chrg = 0;
3441 tree first_arg_without_in_chrg = first_arg;
3442 tree *args_without_in_chrg;
3443 unsigned int nargs_without_in_chrg;
3444 unsigned int ia, ix;
3445 tree arg;
3446 struct z_candidate *cand;
3447 tree fn;
3448 struct rejection_reason *reason = NULL;
3449 int errs;
3450 conversion **convs = NULL;
3452 /* We don't do deduction on the in-charge parameter, the VTT
3453 parameter or 'this'. */
3454 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl))
3456 if (first_arg_without_in_chrg != NULL_TREE)
3457 first_arg_without_in_chrg = NULL_TREE;
3458 else if (return_type && strict == DEDUCE_CALL)
3459 /* We're deducing for a call to the result of a template conversion
3460 function, so the args don't contain 'this'; leave them alone. */;
3461 else
3462 ++skip_without_in_chrg;
3465 if ((DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (tmpl)
3466 || DECL_BASE_CONSTRUCTOR_P (tmpl))
3467 && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (tmpl)))
3469 if (first_arg_without_in_chrg != NULL_TREE)
3470 first_arg_without_in_chrg = NULL_TREE;
3471 else
3472 ++skip_without_in_chrg;
3475 if (len < skip_without_in_chrg)
3476 return NULL;
3478 if (DECL_CONSTRUCTOR_P (tmpl) && nargs == 2
3479 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (first_arg),
3480 TREE_TYPE ((*arglist)[0])))
3482 /* 12.8/6 says, "A declaration of a constructor for a class X is
3483 ill-formed if its first parameter is of type (optionally cv-qualified)
3484 X and either there are no other parameters or else all other
3485 parameters have default arguments. A member function template is never
3486 instantiated to produce such a constructor signature."
3488 So if we're trying to copy an object of the containing class, don't
3489 consider a template constructor that has a first parameter type that
3490 is just a template parameter, as we would deduce a signature that we
3491 would then reject in the code below. */
3492 if (tree firstparm = FUNCTION_FIRST_USER_PARMTYPE (tmpl))
3494 firstparm = TREE_VALUE (firstparm);
3495 if (PACK_EXPANSION_P (firstparm))
3496 firstparm = PACK_EXPANSION_PATTERN (firstparm);
3497 if (TREE_CODE (firstparm) == TEMPLATE_TYPE_PARM)
3499 gcc_assert (!explicit_targs);
3500 reason = invalid_copy_with_fn_template_rejection ();
3501 goto fail;
3506 nargs_without_in_chrg = ((first_arg_without_in_chrg != NULL_TREE ? 1 : 0)
3507 + (len - skip_without_in_chrg));
3508 args_without_in_chrg = XALLOCAVEC (tree, nargs_without_in_chrg);
3509 ia = 0;
3510 if (first_arg_without_in_chrg != NULL_TREE)
3512 args_without_in_chrg[ia] = first_arg_without_in_chrg;
3513 ++ia;
3515 for (ix = skip_without_in_chrg;
3516 vec_safe_iterate (arglist, ix, &arg);
3517 ++ix)
3519 args_without_in_chrg[ia] = arg;
3520 ++ia;
3522 gcc_assert (ia == nargs_without_in_chrg);
3524 if (!obj && explicit_targs)
3526 /* Check that there's no obvious arity mismatch before proceeding with
3527 deduction. This avoids substituting explicit template arguments
3528 into the template (which could result in an error outside the
3529 immediate context) when the resulting candidate would be unviable
3530 anyway. */
3531 int min_arity = 0, max_arity = 0;
3532 tree parms = TYPE_ARG_TYPES (TREE_TYPE (tmpl));
3533 parms = skip_artificial_parms_for (tmpl, parms);
3534 for (; parms != void_list_node; parms = TREE_CHAIN (parms))
3536 if (!parms || PACK_EXPANSION_P (TREE_VALUE (parms)))
3538 max_arity = -1;
3539 break;
3541 if (TREE_PURPOSE (parms))
3542 /* A parameter with a default argument. */
3543 ++max_arity;
3544 else
3545 ++min_arity, ++max_arity;
3547 if (ia < (unsigned)min_arity)
3549 /* Too few arguments. */
3550 reason = arity_rejection (NULL_TREE, min_arity, ia,
3551 /*least_p=*/(max_arity == -1));
3552 goto fail;
3554 else if (max_arity != -1 && ia > (unsigned)max_arity)
3556 /* Too many arguments. */
3557 reason = arity_rejection (NULL_TREE, max_arity, ia);
3558 goto fail;
3562 errs = errorcount+sorrycount;
3563 if (!obj)
3565 convs = alloc_conversions (nargs);
3567 if (shortcut_bad_convs
3568 && DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl)
3569 && !DECL_CONSTRUCTOR_P (tmpl))
3571 /* Check the 'this' conversion before proceeding with deduction.
3572 This is effectively an extension of the DR 1391 resolution
3573 that we perform in check_non_deducible_conversions, though it's
3574 convenient to do this extra check here instead of there. */
3575 tree parmtype = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (tmpl)));
3576 tree argtype = lvalue_type (first_arg);
3577 tree arg = first_arg;
3578 conversion *t = build_this_conversion (tmpl, ctype,
3579 parmtype, argtype, arg,
3580 flags, complain);
3581 convs[0] = t;
3582 if (t->bad_p)
3584 reason = bad_arg_conversion_rejection (first_arg, 0,
3585 arg, parmtype,
3586 EXPR_LOCATION (arg));
3587 goto fail;
3591 fn = fn_type_unification (tmpl, explicit_targs, targs,
3592 args_without_in_chrg,
3593 nargs_without_in_chrg,
3594 return_type, strict, flags, convs,
3595 false, complain & tf_decltype);
3597 if (fn == error_mark_node)
3599 /* Don't repeat unification later if it already resulted in errors. */
3600 if (errorcount+sorrycount == errs)
3601 reason = template_unification_rejection (tmpl, explicit_targs,
3602 targs, args_without_in_chrg,
3603 nargs_without_in_chrg,
3604 return_type, strict, flags);
3605 else
3606 reason = template_unification_error_rejection ();
3607 goto fail;
3610 /* Now the explicit specifier might have been deduced; check if this
3611 declaration is explicit. If it is and we're ignoring non-converting
3612 constructors, don't add this function to the set of candidates. */
3613 if ((flags & LOOKUP_ONLYCONVERTING) && DECL_NONCONVERTING_P (fn))
3614 return NULL;
3616 if (DECL_CONSTRUCTOR_P (fn) && nargs == 2)
3618 tree arg_types = FUNCTION_FIRST_USER_PARMTYPE (fn);
3619 if (arg_types && same_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (arg_types)),
3620 ctype))
3622 /* We're trying to produce a constructor with a prohibited signature,
3623 as discussed above; handle here any cases we didn't catch then,
3624 such as X(X<T>). */
3625 reason = invalid_copy_with_fn_template_rejection ();
3626 goto fail;
3630 if (obj != NULL_TREE)
3631 /* Aha, this is a conversion function. */
3632 cand = add_conv_candidate (candidates, fn, obj, arglist,
3633 access_path, conversion_path, complain);
3634 else
3635 cand = add_function_candidate (candidates, fn, ctype,
3636 first_arg, arglist, access_path,
3637 conversion_path, flags, convs,
3638 shortcut_bad_convs, complain);
3639 if (DECL_TI_TEMPLATE (fn) != tmpl)
3640 /* This situation can occur if a member template of a template
3641 class is specialized. Then, instantiate_template might return
3642 an instantiation of the specialization, in which case the
3643 DECL_TI_TEMPLATE field will point at the original
3644 specialization. For example:
3646 template <class T> struct S { template <class U> void f(U);
3647 template <> void f(int) {}; };
3648 S<double> sd;
3649 sd.f(3);
3651 Here, TMPL will be template <class U> S<double>::f(U).
3652 And, instantiate template will give us the specialization
3653 template <> S<double>::f(int). But, the DECL_TI_TEMPLATE field
3654 for this will point at template <class T> template <> S<T>::f(int),
3655 so that we can find the definition. For the purposes of
3656 overload resolution, however, we want the original TMPL. */
3657 cand->template_decl = build_template_info (tmpl, targs);
3658 else
3659 cand->template_decl = DECL_TEMPLATE_INFO (fn);
3660 cand->explicit_targs = explicit_targs;
3662 return cand;
3663 fail:
3664 int viable = (reason->code == rr_bad_arg_conversion ? -1 : 0);
3665 return add_candidate (candidates, tmpl, first_arg, arglist, nargs, convs,
3666 access_path, conversion_path, viable, reason, flags);
3670 static struct z_candidate *
3671 add_template_candidate (struct z_candidate **candidates, tree tmpl, tree ctype,
3672 tree explicit_targs, tree first_arg,
3673 const vec<tree, va_gc> *arglist, tree return_type,
3674 tree access_path, tree conversion_path, int flags,
3675 unification_kind_t strict, bool shortcut_bad_convs,
3676 tsubst_flags_t complain)
3678 return
3679 add_template_candidate_real (candidates, tmpl, ctype,
3680 explicit_targs, first_arg, arglist,
3681 return_type, access_path, conversion_path,
3682 flags, NULL_TREE, strict, shortcut_bad_convs,
3683 complain);
3686 /* Create an overload candidate for the conversion function template TMPL,
3687 returning RETURN_TYPE, which will be invoked for expression OBJ to produce a
3688 pointer-to-function which will in turn be called with the argument list
3689 ARGLIST, and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
3690 passed on to implicit_conversion. */
3692 static struct z_candidate *
3693 add_template_conv_candidate (struct z_candidate **candidates, tree tmpl,
3694 tree obj,
3695 const vec<tree, va_gc> *arglist,
3696 tree return_type, tree access_path,
3697 tree conversion_path, tsubst_flags_t complain)
3699 /* Making this work broke PR 71117 and 85118, so until the committee resolves
3700 core issue 2189, let's disable this candidate if there are any call
3701 operators. */
3702 if (*candidates)
3703 return NULL;
3705 return
3706 add_template_candidate_real (candidates, tmpl, NULL_TREE, NULL_TREE,
3707 NULL_TREE, arglist, return_type, access_path,
3708 conversion_path, 0, obj, DEDUCE_CALL,
3709 /*shortcut_bad_convs=*/false, complain);
3712 /* The CANDS are the set of candidates that were considered for
3713 overload resolution. Return the set of viable candidates, or CANDS
3714 if none are viable. If any of the candidates were viable, set
3715 *ANY_VIABLE_P to true. STRICT_P is true if a candidate should be
3716 considered viable only if it is strictly viable. */
3718 static struct z_candidate*
3719 splice_viable (struct z_candidate *cands,
3720 bool strict_p,
3721 bool *any_viable_p)
3723 struct z_candidate *viable;
3724 struct z_candidate **last_viable;
3725 struct z_candidate **cand;
3726 bool found_strictly_viable = false;
3728 /* Be strict inside templates, since build_over_call won't actually
3729 do the conversions to get pedwarns. */
3730 if (processing_template_decl)
3731 strict_p = true;
3733 viable = NULL;
3734 last_viable = &viable;
3735 *any_viable_p = false;
3737 cand = &cands;
3738 while (*cand)
3740 struct z_candidate *c = *cand;
3741 if (!strict_p
3742 && (c->viable == 1 || TREE_CODE (c->fn) == TEMPLATE_DECL))
3744 /* Be strict in the presence of a viable candidate. Also if
3745 there are template candidates, so that we get deduction errors
3746 for them instead of silently preferring a bad conversion. */
3747 strict_p = true;
3748 if (viable && !found_strictly_viable)
3750 /* Put any spliced near matches back onto the main list so
3751 that we see them if there is no strict match. */
3752 *any_viable_p = false;
3753 *last_viable = cands;
3754 cands = viable;
3755 viable = NULL;
3756 last_viable = &viable;
3760 if (strict_p ? c->viable == 1 : c->viable)
3762 *last_viable = c;
3763 *cand = c->next;
3764 c->next = NULL;
3765 last_viable = &c->next;
3766 *any_viable_p = true;
3767 if (c->viable == 1)
3768 found_strictly_viable = true;
3770 else
3771 cand = &c->next;
3774 return viable ? viable : cands;
3777 static bool
3778 any_strictly_viable (struct z_candidate *cands)
3780 for (; cands; cands = cands->next)
3781 if (cands->viable == 1)
3782 return true;
3783 return false;
3786 /* OBJ is being used in an expression like "OBJ.f (...)". In other
3787 words, it is about to become the "this" pointer for a member
3788 function call. Take the address of the object. */
3790 static tree
3791 build_this (tree obj)
3793 /* In a template, we are only concerned about the type of the
3794 expression, so we can take a shortcut. */
3795 if (processing_template_decl)
3796 return build_address (obj);
3798 return cp_build_addr_expr (obj, tf_warning_or_error);
3801 /* Returns true iff functions are equivalent. Equivalent functions are
3802 not '==' only if one is a function-local extern function or if
3803 both are extern "C". */
3805 static inline int
3806 equal_functions (tree fn1, tree fn2)
3808 if (TREE_CODE (fn1) != TREE_CODE (fn2))
3809 return 0;
3810 if (TREE_CODE (fn1) == TEMPLATE_DECL)
3811 return fn1 == fn2;
3812 if (DECL_LOCAL_DECL_P (fn1) || DECL_LOCAL_DECL_P (fn2)
3813 || DECL_EXTERN_C_FUNCTION_P (fn1))
3814 return decls_match (fn1, fn2);
3815 return fn1 == fn2;
3818 /* Print information about a candidate FN being rejected due to INFO. */
3820 static void
3821 print_conversion_rejection (location_t loc, struct conversion_info *info,
3822 tree fn)
3824 tree from = info->from;
3825 if (!TYPE_P (from))
3826 from = lvalue_type (from);
3827 if (info->n_arg == -1)
3829 /* Conversion of implicit `this' argument failed. */
3830 if (!TYPE_P (info->from))
3831 /* A bad conversion for 'this' must be discarding cv-quals. */
3832 inform (loc, " passing %qT as %<this%> "
3833 "argument discards qualifiers",
3834 from);
3835 else
3836 inform (loc, " no known conversion for implicit "
3837 "%<this%> parameter from %qH to %qI",
3838 from, info->to_type);
3840 else if (!TYPE_P (info->from))
3842 if (info->n_arg >= 0)
3843 inform (loc, " conversion of argument %d would be ill-formed:",
3844 info->n_arg + 1);
3845 perform_implicit_conversion (info->to_type, info->from,
3846 tf_warning_or_error);
3848 else if (info->n_arg == -2)
3849 /* Conversion of conversion function return value failed. */
3850 inform (loc, " no known conversion from %qH to %qI",
3851 from, info->to_type);
3852 else
3854 if (TREE_CODE (fn) == FUNCTION_DECL)
3855 loc = get_fndecl_argument_location (fn, info->n_arg);
3856 inform (loc, " no known conversion for argument %d from %qH to %qI",
3857 info->n_arg + 1, from, info->to_type);
3861 /* Print information about a candidate with WANT parameters and we found
3862 HAVE. */
3864 static void
3865 print_arity_information (location_t loc, unsigned int have, unsigned int want,
3866 bool least_p)
3868 if (least_p)
3869 inform_n (loc, want,
3870 " candidate expects at least %d argument, %d provided",
3871 " candidate expects at least %d arguments, %d provided",
3872 want, have);
3873 else
3874 inform_n (loc, want,
3875 " candidate expects %d argument, %d provided",
3876 " candidate expects %d arguments, %d provided",
3877 want, have);
3880 /* Print information about one overload candidate CANDIDATE. MSGSTR
3881 is the text to print before the candidate itself.
3883 NOTE: Unlike most diagnostic functions in GCC, MSGSTR is expected
3884 to have been run through gettext by the caller. This wart makes
3885 life simpler in print_z_candidates and for the translators. */
3887 static void
3888 print_z_candidate (location_t loc, const char *msgstr,
3889 struct z_candidate *candidate)
3891 const char *msg = (msgstr == NULL
3892 ? ""
3893 : ACONCAT ((_(msgstr), " ", NULL)));
3894 tree fn = candidate->fn;
3895 if (flag_new_inheriting_ctors)
3896 fn = strip_inheriting_ctors (fn);
3897 location_t cloc = location_of (fn);
3899 if (identifier_p (fn))
3901 cloc = loc;
3902 if (candidate->num_convs == 3)
3903 inform (cloc, "%s%<%D(%T, %T, %T)%> (built-in)", msg, fn,
3904 candidate->convs[0]->type,
3905 candidate->convs[1]->type,
3906 candidate->convs[2]->type);
3907 else if (candidate->num_convs == 2)
3908 inform (cloc, "%s%<%D(%T, %T)%> (built-in)", msg, fn,
3909 candidate->convs[0]->type,
3910 candidate->convs[1]->type);
3911 else
3912 inform (cloc, "%s%<%D(%T)%> (built-in)", msg, fn,
3913 candidate->convs[0]->type);
3915 else if (TYPE_P (fn))
3916 inform (cloc, "%s%qT (conversion)", msg, fn);
3917 else if (candidate->viable == -1)
3918 inform (cloc, "%s%#qD (near match)", msg, fn);
3919 else if (DECL_DELETED_FN (fn))
3920 inform (cloc, "%s%#qD (deleted)", msg, fn);
3921 else if (candidate->reversed ())
3922 inform (cloc, "%s%#qD (reversed)", msg, fn);
3923 else if (candidate->rewritten ())
3924 inform (cloc, "%s%#qD (rewritten)", msg, fn);
3925 else
3926 inform (cloc, "%s%#qD", msg, fn);
3927 if (fn != candidate->fn)
3929 cloc = location_of (candidate->fn);
3930 inform (cloc, " inherited here");
3932 /* Give the user some information about why this candidate failed. */
3933 if (candidate->reason != NULL)
3935 struct rejection_reason *r = candidate->reason;
3937 switch (r->code)
3939 case rr_arity:
3940 print_arity_information (cloc, r->u.arity.actual,
3941 r->u.arity.expected,
3942 r->u.arity.least_p);
3943 break;
3944 case rr_arg_conversion:
3945 print_conversion_rejection (cloc, &r->u.conversion, fn);
3946 break;
3947 case rr_bad_arg_conversion:
3948 print_conversion_rejection (cloc, &r->u.bad_conversion, fn);
3949 break;
3950 case rr_explicit_conversion:
3951 inform (cloc, " return type %qT of explicit conversion function "
3952 "cannot be converted to %qT with a qualification "
3953 "conversion", r->u.conversion.from,
3954 r->u.conversion.to_type);
3955 break;
3956 case rr_template_conversion:
3957 inform (cloc, " conversion from return type %qT of template "
3958 "conversion function specialization to %qT is not an "
3959 "exact match", r->u.conversion.from,
3960 r->u.conversion.to_type);
3961 break;
3962 case rr_template_unification:
3963 /* We use template_unification_error_rejection if unification caused
3964 actual non-SFINAE errors, in which case we don't need to repeat
3965 them here. */
3966 if (r->u.template_unification.tmpl == NULL_TREE)
3968 inform (cloc, " substitution of deduced template arguments "
3969 "resulted in errors seen above");
3970 break;
3972 /* Re-run template unification with diagnostics. */
3973 inform (cloc, " template argument deduction/substitution failed:");
3974 fn_type_unification (r->u.template_unification.tmpl,
3975 r->u.template_unification.explicit_targs,
3976 (make_tree_vec
3977 (r->u.template_unification.num_targs)),
3978 r->u.template_unification.args,
3979 r->u.template_unification.nargs,
3980 r->u.template_unification.return_type,
3981 r->u.template_unification.strict,
3982 r->u.template_unification.flags,
3983 NULL, true, false);
3984 break;
3985 case rr_invalid_copy:
3986 inform (cloc,
3987 " a constructor taking a single argument of its own "
3988 "class type is invalid");
3989 break;
3990 case rr_constraint_failure:
3991 diagnose_constraints (cloc, fn, NULL_TREE);
3992 break;
3993 case rr_inherited_ctor:
3994 inform (cloc, " an inherited constructor is not a candidate for "
3995 "initialization from an expression of the same or derived "
3996 "type");
3997 break;
3998 case rr_none:
3999 default:
4000 /* This candidate didn't have any issues or we failed to
4001 handle a particular code. Either way... */
4002 gcc_unreachable ();
4007 static void
4008 print_z_candidates (location_t loc, struct z_candidate *candidates)
4010 struct z_candidate *cand1;
4011 struct z_candidate **cand2;
4013 if (!candidates)
4014 return;
4016 /* Remove non-viable deleted candidates. */
4017 cand1 = candidates;
4018 for (cand2 = &cand1; *cand2; )
4020 if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
4021 && !(*cand2)->viable
4022 && DECL_DELETED_FN ((*cand2)->fn))
4023 *cand2 = (*cand2)->next;
4024 else
4025 cand2 = &(*cand2)->next;
4027 /* ...if there are any non-deleted ones. */
4028 if (cand1)
4029 candidates = cand1;
4031 /* There may be duplicates in the set of candidates. We put off
4032 checking this condition as long as possible, since we have no way
4033 to eliminate duplicates from a set of functions in less than n^2
4034 time. Now we are about to emit an error message, so it is more
4035 permissible to go slowly. */
4036 for (cand1 = candidates; cand1; cand1 = cand1->next)
4038 tree fn = cand1->fn;
4039 /* Skip builtin candidates and conversion functions. */
4040 if (!DECL_P (fn))
4041 continue;
4042 cand2 = &cand1->next;
4043 while (*cand2)
4045 if (DECL_P ((*cand2)->fn)
4046 && equal_functions (fn, (*cand2)->fn))
4047 *cand2 = (*cand2)->next;
4048 else
4049 cand2 = &(*cand2)->next;
4053 for (; candidates; candidates = candidates->next)
4054 print_z_candidate (loc, N_("candidate:"), candidates);
4057 /* USER_SEQ is a user-defined conversion sequence, beginning with a
4058 USER_CONV. STD_SEQ is the standard conversion sequence applied to
4059 the result of the conversion function to convert it to the final
4060 desired type. Merge the two sequences into a single sequence,
4061 and return the merged sequence. */
4063 static conversion *
4064 merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
4066 conversion **t;
4067 bool bad = user_seq->bad_p;
4069 gcc_assert (user_seq->kind == ck_user);
4071 /* Find the end of the second conversion sequence. */
4072 for (t = &std_seq; (*t)->kind != ck_identity; t = &((*t)->u.next))
4074 /* The entire sequence is a user-conversion sequence. */
4075 (*t)->user_conv_p = true;
4076 if (bad)
4077 (*t)->bad_p = true;
4080 if ((*t)->rvaluedness_matches_p)
4081 /* We're binding a reference directly to the result of the conversion.
4082 build_user_type_conversion_1 stripped the REFERENCE_TYPE from the return
4083 type, but we want it back. */
4084 user_seq->type = TREE_TYPE (TREE_TYPE (user_seq->cand->fn));
4086 /* Replace the identity conversion with the user conversion
4087 sequence. */
4088 *t = user_seq;
4090 return std_seq;
4093 /* Handle overload resolution for initializing an object of class type from
4094 an initializer list. First we look for a suitable constructor that
4095 takes a std::initializer_list; if we don't find one, we then look for a
4096 non-list constructor.
4098 Parameters are as for add_candidates, except that the arguments are in
4099 the form of a CONSTRUCTOR (the initializer list) rather than a vector, and
4100 the RETURN_TYPE parameter is replaced by TOTYPE, the desired type. */
4102 static void
4103 add_list_candidates (tree fns, tree first_arg,
4104 const vec<tree, va_gc> *args, tree totype,
4105 tree explicit_targs, bool template_only,
4106 tree conversion_path, tree access_path,
4107 int flags,
4108 struct z_candidate **candidates,
4109 tsubst_flags_t complain)
4111 gcc_assert (*candidates == NULL);
4113 /* We're looking for a ctor for list-initialization. */
4114 flags |= LOOKUP_LIST_INIT_CTOR;
4115 /* And we don't allow narrowing conversions. We also use this flag to
4116 avoid the copy constructor call for copy-list-initialization. */
4117 flags |= LOOKUP_NO_NARROWING;
4119 unsigned nart = num_artificial_parms_for (OVL_FIRST (fns)) - 1;
4120 tree init_list = (*args)[nart];
4122 /* Always use the default constructor if the list is empty (DR 990). */
4123 if (CONSTRUCTOR_NELTS (init_list) == 0
4124 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
4126 /* If the class has a list ctor, try passing the list as a single
4127 argument first, but only consider list ctors. */
4128 else if (TYPE_HAS_LIST_CTOR (totype))
4130 flags |= LOOKUP_LIST_ONLY;
4131 add_candidates (fns, first_arg, args, NULL_TREE,
4132 explicit_targs, template_only, conversion_path,
4133 access_path, flags, candidates, complain);
4134 if (any_strictly_viable (*candidates))
4135 return;
4137 else if (CONSTRUCTOR_IS_DESIGNATED_INIT (init_list)
4138 && !CP_AGGREGATE_TYPE_P (totype))
4140 if (complain & tf_error)
4141 error ("designated initializers cannot be used with a "
4142 "non-aggregate type %qT", totype);
4143 return;
4146 /* Expand the CONSTRUCTOR into a new argument vec. */
4147 vec<tree, va_gc> *new_args;
4148 vec_alloc (new_args, nart + CONSTRUCTOR_NELTS (init_list));
4149 for (unsigned i = 0; i < nart; ++i)
4150 new_args->quick_push ((*args)[i]);
4151 for (unsigned i = 0; i < CONSTRUCTOR_NELTS (init_list); ++i)
4152 new_args->quick_push (CONSTRUCTOR_ELT (init_list, i)->value);
4154 /* We aren't looking for list-ctors anymore. */
4155 flags &= ~LOOKUP_LIST_ONLY;
4156 /* We allow more user-defined conversions within an init-list. */
4157 flags &= ~LOOKUP_NO_CONVERSION;
4159 add_candidates (fns, first_arg, new_args, NULL_TREE,
4160 explicit_targs, template_only, conversion_path,
4161 access_path, flags, candidates, complain);
4164 /* Returns the best overload candidate to perform the requested
4165 conversion. This function is used for three the overloading situations
4166 described in [over.match.copy], [over.match.conv], and [over.match.ref].
4167 If TOTYPE is a REFERENCE_TYPE, we're trying to find a direct binding as
4168 per [dcl.init.ref], so we ignore temporary bindings. */
4170 static struct z_candidate *
4171 build_user_type_conversion_1 (tree totype, tree expr, int flags,
4172 tsubst_flags_t complain)
4174 struct z_candidate *candidates, *cand;
4175 tree fromtype;
4176 tree ctors = NULL_TREE;
4177 tree conv_fns = NULL_TREE;
4178 conversion *conv = NULL;
4179 tree first_arg = NULL_TREE;
4180 vec<tree, va_gc> *args = NULL;
4181 bool any_viable_p;
4182 int convflags;
4184 if (!expr)
4185 return NULL;
4187 fromtype = TREE_TYPE (expr);
4189 /* We represent conversion within a hierarchy using RVALUE_CONV and
4190 BASE_CONV, as specified by [over.best.ics]; these become plain
4191 constructor calls, as specified in [dcl.init]. */
4192 gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
4193 || !DERIVED_FROM_P (totype, fromtype));
4195 if (CLASS_TYPE_P (totype))
4196 /* Use lookup_fnfields_slot instead of lookup_fnfields to avoid
4197 creating a garbage BASELINK; constructors can't be inherited. */
4198 ctors = get_class_binding (totype, complete_ctor_identifier);
4200 tree to_nonref = non_reference (totype);
4201 if (MAYBE_CLASS_TYPE_P (fromtype))
4203 if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
4204 (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
4205 && DERIVED_FROM_P (to_nonref, fromtype)))
4207 /* [class.conv.fct] A conversion function is never used to
4208 convert a (possibly cv-qualified) object to the (possibly
4209 cv-qualified) same object type (or a reference to it), to a
4210 (possibly cv-qualified) base class of that type (or a
4211 reference to it)... */
4213 else
4214 conv_fns = lookup_conversions (fromtype);
4217 candidates = 0;
4218 flags |= LOOKUP_NO_CONVERSION;
4219 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4220 flags |= LOOKUP_NO_NARROWING;
4221 /* Prevent add_candidates from treating a non-strictly viable candidate
4222 as unviable. */
4223 complain |= tf_conv;
4225 /* It's OK to bind a temporary for converting constructor arguments, but
4226 not in converting the return value of a conversion operator. */
4227 convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION
4228 | (flags & LOOKUP_NO_NARROWING));
4229 flags &= ~LOOKUP_NO_TEMP_BIND;
4231 if (ctors)
4233 int ctorflags = flags;
4235 first_arg = build_dummy_object (totype);
4237 /* We should never try to call the abstract or base constructor
4238 from here. */
4239 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_FIRST (ctors))
4240 && !DECL_HAS_VTT_PARM_P (OVL_FIRST (ctors)));
4242 args = make_tree_vector_single (expr);
4243 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4245 /* List-initialization. */
4246 add_list_candidates (ctors, first_arg, args, totype, NULL_TREE,
4247 false, TYPE_BINFO (totype), TYPE_BINFO (totype),
4248 ctorflags, &candidates, complain);
4250 else
4252 add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
4253 TYPE_BINFO (totype), TYPE_BINFO (totype),
4254 ctorflags, &candidates, complain);
4257 for (cand = candidates; cand; cand = cand->next)
4259 cand->second_conv = build_identity_conv (totype, NULL_TREE);
4261 /* If totype isn't a reference, and LOOKUP_ONLYCONVERTING is
4262 set, then this is copy-initialization. In that case, "The
4263 result of the call is then used to direct-initialize the
4264 object that is the destination of the copy-initialization."
4265 [dcl.init]
4267 We represent this in the conversion sequence with an
4268 rvalue conversion, which means a constructor call. */
4269 if (!TYPE_REF_P (totype)
4270 && cxx_dialect < cxx17
4271 && (flags & LOOKUP_ONLYCONVERTING)
4272 && !(convflags & LOOKUP_NO_TEMP_BIND))
4273 cand->second_conv
4274 = build_conv (ck_rvalue, totype, cand->second_conv);
4278 if (conv_fns)
4280 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4281 first_arg = CONSTRUCTOR_ELT (expr, 0)->value;
4282 else
4283 first_arg = expr;
4286 for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
4288 tree conversion_path = TREE_PURPOSE (conv_fns);
4289 struct z_candidate *old_candidates;
4291 /* If LOOKUP_NO_CONVERSION, don't consider a conversion function that
4292 would need an addional user-defined conversion, i.e. if the return
4293 type differs in class-ness from the desired type. So we avoid
4294 considering operator bool when calling a copy constructor.
4296 This optimization avoids the failure in PR97600, and is allowed by
4297 [temp.inst]/9: "If the function selected by overload resolution can be
4298 determined without instantiating a class template definition, it is
4299 unspecified whether that instantiation actually takes place." */
4300 tree convtype = non_reference (TREE_TYPE (conv_fns));
4301 if ((flags & LOOKUP_NO_CONVERSION)
4302 && !WILDCARD_TYPE_P (convtype)
4303 && (CLASS_TYPE_P (to_nonref)
4304 != CLASS_TYPE_P (convtype)))
4305 continue;
4307 /* If we are called to convert to a reference type, we are trying to
4308 find a direct binding, so don't even consider temporaries. If
4309 we don't find a direct binding, the caller will try again to
4310 look for a temporary binding. */
4311 if (TYPE_REF_P (totype))
4312 convflags |= LOOKUP_NO_TEMP_BIND;
4314 old_candidates = candidates;
4315 add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
4316 NULL_TREE, false,
4317 conversion_path, TYPE_BINFO (fromtype),
4318 flags, &candidates, complain);
4320 for (cand = candidates; cand != old_candidates; cand = cand->next)
4322 if (cand->viable == 0)
4323 /* Already rejected, don't change to -1. */
4324 continue;
4326 tree rettype = TREE_TYPE (TREE_TYPE (cand->fn));
4327 conversion *ics
4328 = implicit_conversion (totype,
4329 rettype,
4331 /*c_cast_p=*/false, convflags,
4332 complain);
4334 /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
4335 copy-initialization. In that case, "The result of the
4336 call is then used to direct-initialize the object that is
4337 the destination of the copy-initialization." [dcl.init]
4339 We represent this in the conversion sequence with an
4340 rvalue conversion, which means a constructor call. But
4341 don't add a second rvalue conversion if there's already
4342 one there. Which there really shouldn't be, but it's
4343 harmless since we'd add it here anyway. */
4344 if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
4345 && !(convflags & LOOKUP_NO_TEMP_BIND))
4346 ics = build_conv (ck_rvalue, totype, ics);
4348 cand->second_conv = ics;
4350 if (!ics)
4352 cand->viable = 0;
4353 cand->reason = arg_conversion_rejection (NULL_TREE, -2,
4354 rettype, totype,
4355 EXPR_LOCATION (expr));
4357 else if (TYPE_REF_P (totype) && !ics->rvaluedness_matches_p
4358 /* Limit this to non-templates for now (PR90546). */
4359 && !cand->template_decl
4360 && TREE_CODE (TREE_TYPE (totype)) != FUNCTION_TYPE)
4362 /* If we are called to convert to a reference type, we are trying
4363 to find a direct binding per [over.match.ref], so rvaluedness
4364 must match for non-functions. */
4365 cand->viable = 0;
4367 else if (DECL_NONCONVERTING_P (cand->fn)
4368 && ics->rank > cr_exact)
4370 /* 13.3.1.5: For direct-initialization, those explicit
4371 conversion functions that are not hidden within S and
4372 yield type T or a type that can be converted to type T
4373 with a qualification conversion (4.4) are also candidate
4374 functions. */
4375 /* 13.3.1.6 doesn't have a parallel restriction, but it should;
4376 I've raised this issue with the committee. --jason 9/2011 */
4377 cand->viable = -1;
4378 cand->reason = explicit_conversion_rejection (rettype, totype);
4380 else if (cand->viable == 1 && ics->bad_p)
4382 cand->viable = -1;
4383 cand->reason
4384 = bad_arg_conversion_rejection (NULL_TREE, -2,
4385 rettype, totype,
4386 EXPR_LOCATION (expr));
4388 else if (primary_template_specialization_p (cand->fn)
4389 && ics->rank > cr_exact)
4391 /* 13.3.3.1.2: If the user-defined conversion is specified by
4392 a specialization of a conversion function template, the
4393 second standard conversion sequence shall have exact match
4394 rank. */
4395 cand->viable = -1;
4396 cand->reason = template_conversion_rejection (rettype, totype);
4401 candidates = splice_viable (candidates, false, &any_viable_p);
4402 if (!any_viable_p)
4404 if (args)
4405 release_tree_vector (args);
4406 return NULL;
4409 cand = tourney (candidates, complain);
4410 if (cand == NULL)
4412 if (complain & tf_error)
4414 auto_diagnostic_group d;
4415 error_at (cp_expr_loc_or_input_loc (expr),
4416 "conversion from %qH to %qI is ambiguous",
4417 fromtype, totype);
4418 print_z_candidates (location_of (expr), candidates);
4421 cand = candidates; /* any one will do */
4422 cand->second_conv = build_ambiguous_conv (totype, expr);
4423 cand->second_conv->user_conv_p = true;
4424 if (!any_strictly_viable (candidates))
4425 cand->second_conv->bad_p = true;
4426 if (flags & LOOKUP_ONLYCONVERTING)
4427 cand->second_conv->need_temporary_p = true;
4428 /* If there are viable candidates, don't set ICS_BAD_FLAG; an
4429 ambiguous conversion is no worse than another user-defined
4430 conversion. */
4432 return cand;
4435 tree convtype;
4436 if (!DECL_CONSTRUCTOR_P (cand->fn))
4437 convtype = non_reference (TREE_TYPE (TREE_TYPE (cand->fn)));
4438 else if (cand->second_conv->kind == ck_rvalue)
4439 /* DR 5: [in the first step of copy-initialization]...if the function
4440 is a constructor, the call initializes a temporary of the
4441 cv-unqualified version of the destination type. */
4442 convtype = cv_unqualified (totype);
4443 else
4444 convtype = totype;
4445 /* Build the user conversion sequence. */
4446 conv = build_conv
4447 (ck_user,
4448 convtype,
4449 build_identity_conv (TREE_TYPE (expr), expr));
4450 conv->cand = cand;
4451 if (cand->viable == -1)
4452 conv->bad_p = true;
4454 /* We're performing the maybe-rvalue overload resolution and
4455 a conversion function is in play. Reject converting the return
4456 value of the conversion function to a base class. */
4457 if ((flags & LOOKUP_PREFER_RVALUE) && !DECL_CONSTRUCTOR_P (cand->fn))
4458 for (conversion *t = cand->second_conv; t; t = next_conversion (t))
4459 if (t->kind == ck_base)
4460 return NULL;
4462 /* Remember that this was a list-initialization. */
4463 if (flags & LOOKUP_NO_NARROWING)
4464 conv->check_narrowing = true;
4466 /* Combine it with the second conversion sequence. */
4467 cand->second_conv = merge_conversion_sequences (conv,
4468 cand->second_conv);
4470 return cand;
4473 /* Wrapper for above. */
4475 tree
4476 build_user_type_conversion (tree totype, tree expr, int flags,
4477 tsubst_flags_t complain)
4479 struct z_candidate *cand;
4480 tree ret;
4482 auto_cond_timevar tv (TV_OVERLOAD);
4483 cand = build_user_type_conversion_1 (totype, expr, flags, complain);
4485 if (cand)
4487 if (cand->second_conv->kind == ck_ambig)
4488 ret = error_mark_node;
4489 else
4491 expr = convert_like (cand->second_conv, expr, complain);
4492 ret = convert_from_reference (expr);
4495 else
4496 ret = NULL_TREE;
4498 return ret;
4501 /* Give a helpful diagnostic when implicit_conversion fails. */
4503 static void
4504 implicit_conversion_error (location_t loc, tree type, tree expr)
4506 tsubst_flags_t complain = tf_warning_or_error;
4508 /* If expr has unknown type, then it is an overloaded function.
4509 Call instantiate_type to get good error messages. */
4510 if (TREE_TYPE (expr) == unknown_type_node)
4511 instantiate_type (type, expr, complain);
4512 else if (invalid_nonstatic_memfn_p (loc, expr, complain))
4513 /* We gave an error. */;
4514 else if (BRACE_ENCLOSED_INITIALIZER_P (expr)
4515 && CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
4516 && !CP_AGGREGATE_TYPE_P (type))
4517 error_at (loc, "designated initializers cannot be used with a "
4518 "non-aggregate type %qT", type);
4519 else
4521 range_label_for_type_mismatch label (TREE_TYPE (expr), type);
4522 gcc_rich_location rich_loc (loc, &label);
4523 error_at (&rich_loc, "could not convert %qE from %qH to %qI",
4524 expr, TREE_TYPE (expr), type);
4528 /* Worker for build_converted_constant_expr. */
4530 static tree
4531 build_converted_constant_expr_internal (tree type, tree expr,
4532 int flags, tsubst_flags_t complain)
4534 conversion *conv;
4535 void *p;
4536 tree t;
4537 location_t loc = cp_expr_loc_or_input_loc (expr);
4539 if (error_operand_p (expr))
4540 return error_mark_node;
4542 /* Get the high-water mark for the CONVERSION_OBSTACK. */
4543 p = conversion_obstack_alloc (0);
4545 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
4546 /*c_cast_p=*/false, flags, complain);
4548 /* A converted constant expression of type T is an expression, implicitly
4549 converted to type T, where the converted expression is a constant
4550 expression and the implicit conversion sequence contains only
4552 * user-defined conversions,
4553 * lvalue-to-rvalue conversions (7.1),
4554 * array-to-pointer conversions (7.2),
4555 * function-to-pointer conversions (7.3),
4556 * qualification conversions (7.5),
4557 * integral promotions (7.6),
4558 * integral conversions (7.8) other than narrowing conversions (11.6.4),
4559 * null pointer conversions (7.11) from std::nullptr_t,
4560 * null member pointer conversions (7.12) from std::nullptr_t, and
4561 * function pointer conversions (7.13),
4563 and where the reference binding (if any) binds directly. */
4565 for (conversion *c = conv;
4566 c && c->kind != ck_identity;
4567 c = next_conversion (c))
4569 switch (c->kind)
4571 /* A conversion function is OK. If it isn't constexpr, we'll
4572 complain later that the argument isn't constant. */
4573 case ck_user:
4574 /* List-initialization is OK. */
4575 case ck_aggr:
4576 /* The lvalue-to-rvalue conversion is OK. */
4577 case ck_rvalue:
4578 /* Array-to-pointer and function-to-pointer. */
4579 case ck_lvalue:
4580 /* Function pointer conversions. */
4581 case ck_fnptr:
4582 /* Qualification conversions. */
4583 case ck_qual:
4584 break;
4586 case ck_ref_bind:
4587 if (c->need_temporary_p)
4589 if (complain & tf_error)
4590 error_at (loc, "initializing %qH with %qI in converted "
4591 "constant expression does not bind directly",
4592 type, next_conversion (c)->type);
4593 conv = NULL;
4595 break;
4597 case ck_base:
4598 case ck_pmem:
4599 case ck_ptr:
4600 case ck_std:
4601 t = next_conversion (c)->type;
4602 if (INTEGRAL_OR_ENUMERATION_TYPE_P (t)
4603 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4604 /* Integral promotion or conversion. */
4605 break;
4606 if (NULLPTR_TYPE_P (t))
4607 /* Conversion from nullptr to pointer or pointer-to-member. */
4608 break;
4610 if (complain & tf_error)
4611 error_at (loc, "conversion from %qH to %qI in a "
4612 "converted constant expression", t, type);
4613 /* fall through. */
4615 default:
4616 conv = NULL;
4617 break;
4621 /* Avoid confusing convert_nontype_argument by introducing
4622 a redundant conversion to the same reference type. */
4623 if (conv && conv->kind == ck_ref_bind
4624 && REFERENCE_REF_P (expr))
4626 tree ref = TREE_OPERAND (expr, 0);
4627 if (same_type_p (type, TREE_TYPE (ref)))
4628 return ref;
4631 if (conv)
4633 /* Don't copy a class in a template. */
4634 if (CLASS_TYPE_P (type) && conv->kind == ck_rvalue
4635 && processing_template_decl)
4636 conv = next_conversion (conv);
4638 /* Issuing conversion warnings for value-dependent expressions is
4639 likely too noisy. */
4640 warning_sentinel w (warn_conversion);
4641 conv->check_narrowing = true;
4642 conv->check_narrowing_const_only = true;
4643 expr = convert_like (conv, expr, complain);
4645 else
4647 if (complain & tf_error)
4648 implicit_conversion_error (loc, type, expr);
4649 expr = error_mark_node;
4652 /* Free all the conversions we allocated. */
4653 obstack_free (&conversion_obstack, p);
4655 return expr;
4658 /* Subroutine of convert_nontype_argument.
4660 EXPR is an expression used in a context that requires a converted
4661 constant-expression, such as a template non-type parameter. Do any
4662 necessary conversions (that are permitted for converted
4663 constant-expressions) to convert it to the desired type.
4665 This function doesn't consider explicit conversion functions. If
4666 you mean to use "a contextually converted constant expression of type
4667 bool", use build_converted_constant_bool_expr.
4669 If conversion is successful, returns the converted expression;
4670 otherwise, returns error_mark_node. */
4672 tree
4673 build_converted_constant_expr (tree type, tree expr, tsubst_flags_t complain)
4675 return build_converted_constant_expr_internal (type, expr, LOOKUP_IMPLICIT,
4676 complain);
4679 /* Used to create "a contextually converted constant expression of type
4680 bool". This differs from build_converted_constant_expr in that it
4681 also considers explicit conversion functions. */
4683 tree
4684 build_converted_constant_bool_expr (tree expr, tsubst_flags_t complain)
4686 return build_converted_constant_expr_internal (boolean_type_node, expr,
4687 LOOKUP_NORMAL, complain);
4690 /* Do any initial processing on the arguments to a function call. */
4692 vec<tree, va_gc> *
4693 resolve_args (vec<tree, va_gc> *args, tsubst_flags_t complain)
4695 unsigned int ix;
4696 tree arg;
4698 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
4700 if (error_operand_p (arg))
4701 return NULL;
4702 else if (VOID_TYPE_P (TREE_TYPE (arg)))
4704 if (complain & tf_error)
4705 error_at (cp_expr_loc_or_input_loc (arg),
4706 "invalid use of void expression");
4707 return NULL;
4709 else if (invalid_nonstatic_memfn_p (EXPR_LOCATION (arg), arg, complain))
4710 return NULL;
4712 /* Force auto deduction now. Omit tf_warning to avoid redundant
4713 deprecated warning on deprecated-14.C. */
4714 if (!mark_single_function (arg, complain & ~tf_warning))
4715 return NULL;
4717 return args;
4720 /* Perform overload resolution on FN, which is called with the ARGS.
4722 Return the candidate function selected by overload resolution, or
4723 NULL if the event that overload resolution failed. In the case
4724 that overload resolution fails, *CANDIDATES will be the set of
4725 candidates considered, and ANY_VIABLE_P will be set to true or
4726 false to indicate whether or not any of the candidates were
4727 viable.
4729 The ARGS should already have gone through RESOLVE_ARGS before this
4730 function is called. */
4732 static struct z_candidate *
4733 perform_overload_resolution (tree fn,
4734 const vec<tree, va_gc> *args,
4735 struct z_candidate **candidates,
4736 bool *any_viable_p, tsubst_flags_t complain)
4738 struct z_candidate *cand;
4739 tree explicit_targs;
4740 int template_only;
4742 auto_cond_timevar tv (TV_OVERLOAD);
4744 explicit_targs = NULL_TREE;
4745 template_only = 0;
4747 *candidates = NULL;
4748 *any_viable_p = true;
4750 /* Check FN. */
4751 gcc_assert (OVL_P (fn) || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
4753 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4755 explicit_targs = TREE_OPERAND (fn, 1);
4756 fn = TREE_OPERAND (fn, 0);
4757 template_only = 1;
4760 /* Add the various candidate functions. */
4761 add_candidates (fn, NULL_TREE, args, NULL_TREE,
4762 explicit_targs, template_only,
4763 /*conversion_path=*/NULL_TREE,
4764 /*access_path=*/NULL_TREE,
4765 LOOKUP_NORMAL,
4766 candidates, complain);
4768 *candidates = splice_viable (*candidates, false, any_viable_p);
4769 if (*any_viable_p)
4770 cand = tourney (*candidates, complain);
4771 else
4772 cand = NULL;
4774 return cand;
4777 /* Print an error message about being unable to build a call to FN with
4778 ARGS. ANY_VIABLE_P indicates whether any candidate functions could
4779 be located; CANDIDATES is a possibly empty list of such
4780 functions. */
4782 static void
4783 print_error_for_call_failure (tree fn, const vec<tree, va_gc> *args,
4784 struct z_candidate *candidates)
4786 tree targs = NULL_TREE;
4787 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4789 targs = TREE_OPERAND (fn, 1);
4790 fn = TREE_OPERAND (fn, 0);
4792 tree name = OVL_NAME (fn);
4793 location_t loc = location_of (name);
4794 if (targs)
4795 name = lookup_template_function (name, targs);
4797 auto_diagnostic_group d;
4798 if (!any_strictly_viable (candidates))
4799 error_at (loc, "no matching function for call to %<%D(%A)%>",
4800 name, build_tree_list_vec (args));
4801 else
4802 error_at (loc, "call of overloaded %<%D(%A)%> is ambiguous",
4803 name, build_tree_list_vec (args));
4804 if (candidates)
4805 print_z_candidates (loc, candidates);
4808 /* Perform overload resolution on the set of deduction guides DGUIDES
4809 using ARGS. Returns the selected deduction guide, or error_mark_node
4810 if overload resolution fails. */
4812 tree
4813 perform_dguide_overload_resolution (tree dguides, const vec<tree, va_gc> *args,
4814 tsubst_flags_t complain)
4816 z_candidate *candidates;
4817 bool any_viable_p;
4818 tree result;
4820 gcc_assert (deduction_guide_p (OVL_FIRST (dguides)));
4822 /* Get the high-water mark for the CONVERSION_OBSTACK. */
4823 void *p = conversion_obstack_alloc (0);
4825 z_candidate *cand = perform_overload_resolution (dguides, args, &candidates,
4826 &any_viable_p, complain);
4827 if (!cand)
4829 if (complain & tf_error)
4830 print_error_for_call_failure (dguides, args, candidates);
4831 result = error_mark_node;
4833 else
4834 result = cand->fn;
4836 /* Free all the conversions we allocated. */
4837 obstack_free (&conversion_obstack, p);
4839 return result;
4842 /* Return an expression for a call to FN (a namespace-scope function,
4843 or a static member function) with the ARGS. This may change
4844 ARGS. */
4846 tree
4847 build_new_function_call (tree fn, vec<tree, va_gc> **args,
4848 tsubst_flags_t complain)
4850 struct z_candidate *candidates, *cand;
4851 bool any_viable_p;
4852 void *p;
4853 tree result;
4855 if (args != NULL && *args != NULL)
4857 *args = resolve_args (*args, complain);
4858 if (*args == NULL)
4859 return error_mark_node;
4862 if (flag_tm)
4863 tm_malloc_replacement (fn);
4865 /* Get the high-water mark for the CONVERSION_OBSTACK. */
4866 p = conversion_obstack_alloc (0);
4868 cand = perform_overload_resolution (fn, *args, &candidates, &any_viable_p,
4869 complain);
4871 if (!cand)
4873 if (complain & tf_error)
4875 // If there is a single (non-viable) function candidate,
4876 // let the error be diagnosed by cp_build_function_call_vec.
4877 if (!any_viable_p && candidates && ! candidates->next
4878 && (TREE_CODE (candidates->fn) == FUNCTION_DECL))
4879 return cp_build_function_call_vec (candidates->fn, args, complain);
4881 // Otherwise, emit notes for non-viable candidates.
4882 print_error_for_call_failure (fn, *args, candidates);
4884 result = error_mark_node;
4886 else
4888 result = build_over_call (cand, LOOKUP_NORMAL, complain);
4891 if (flag_coroutines
4892 && result
4893 && TREE_CODE (result) == CALL_EXPR
4894 && DECL_BUILT_IN_CLASS (TREE_OPERAND (CALL_EXPR_FN (result), 0))
4895 == BUILT_IN_NORMAL)
4896 result = coro_validate_builtin_call (result);
4898 /* Free all the conversions we allocated. */
4899 obstack_free (&conversion_obstack, p);
4901 return result;
4904 /* Build a call to a global operator new. FNNAME is the name of the
4905 operator (either "operator new" or "operator new[]") and ARGS are
4906 the arguments provided. This may change ARGS. *SIZE points to the
4907 total number of bytes required by the allocation, and is updated if
4908 that is changed here. *COOKIE_SIZE is non-NULL if a cookie should
4909 be used. If this function determines that no cookie should be
4910 used, after all, *COOKIE_SIZE is set to NULL_TREE. If SIZE_CHECK
4911 is not NULL_TREE, it is evaluated before calculating the final
4912 array size, and if it fails, the array size is replaced with
4913 (size_t)-1 (usually triggering a std::bad_alloc exception). If FN
4914 is non-NULL, it will be set, upon return, to the allocation
4915 function called. */
4917 tree
4918 build_operator_new_call (tree fnname, vec<tree, va_gc> **args,
4919 tree *size, tree *cookie_size,
4920 tree align_arg, tree size_check,
4921 tree *fn, tsubst_flags_t complain)
4923 tree original_size = *size;
4924 tree fns;
4925 struct z_candidate *candidates;
4926 struct z_candidate *cand = NULL;
4927 bool any_viable_p;
4929 if (fn)
4930 *fn = NULL_TREE;
4931 /* Set to (size_t)-1 if the size check fails. */
4932 if (size_check != NULL_TREE)
4934 tree errval = TYPE_MAX_VALUE (sizetype);
4935 if (cxx_dialect >= cxx11 && flag_exceptions)
4936 errval = throw_bad_array_new_length ();
4937 *size = fold_build3 (COND_EXPR, sizetype, size_check,
4938 original_size, errval);
4940 vec_safe_insert (*args, 0, *size);
4941 *args = resolve_args (*args, complain);
4942 if (*args == NULL)
4943 return error_mark_node;
4945 /* Based on:
4947 [expr.new]
4949 If this lookup fails to find the name, or if the allocated type
4950 is not a class type, the allocation function's name is looked
4951 up in the global scope.
4953 we disregard block-scope declarations of "operator new". */
4954 fns = lookup_qualified_name (global_namespace, fnname);
4956 if (align_arg)
4958 vec<tree, va_gc>* align_args
4959 = vec_copy_and_insert (*args, align_arg, 1);
4960 cand = perform_overload_resolution (fns, align_args, &candidates,
4961 &any_viable_p, tf_none);
4962 if (cand)
4963 *args = align_args;
4964 /* If no aligned allocation function matches, try again without the
4965 alignment. */
4968 /* Figure out what function is being called. */
4969 if (!cand)
4970 cand = perform_overload_resolution (fns, *args, &candidates, &any_viable_p,
4971 complain);
4973 /* If no suitable function could be found, issue an error message
4974 and give up. */
4975 if (!cand)
4977 if (complain & tf_error)
4978 print_error_for_call_failure (fns, *args, candidates);
4979 return error_mark_node;
4982 /* If a cookie is required, add some extra space. Whether
4983 or not a cookie is required cannot be determined until
4984 after we know which function was called. */
4985 if (*cookie_size)
4987 bool use_cookie = true;
4988 tree arg_types;
4990 arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
4991 /* Skip the size_t parameter. */
4992 arg_types = TREE_CHAIN (arg_types);
4993 /* Check the remaining parameters (if any). */
4994 if (arg_types
4995 && TREE_CHAIN (arg_types) == void_list_node
4996 && same_type_p (TREE_VALUE (arg_types),
4997 ptr_type_node))
4998 use_cookie = false;
4999 /* If we need a cookie, adjust the number of bytes allocated. */
5000 if (use_cookie)
5002 /* Update the total size. */
5003 *size = size_binop (PLUS_EXPR, original_size, *cookie_size);
5004 if (size_check)
5006 /* Set to (size_t)-1 if the size check fails. */
5007 gcc_assert (size_check != NULL_TREE);
5008 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5009 *size, TYPE_MAX_VALUE (sizetype));
5011 /* Update the argument list to reflect the adjusted size. */
5012 (**args)[0] = *size;
5014 else
5015 *cookie_size = NULL_TREE;
5018 /* Tell our caller which function we decided to call. */
5019 if (fn)
5020 *fn = cand->fn;
5022 /* Build the CALL_EXPR. */
5023 tree ret = build_over_call (cand, LOOKUP_NORMAL, complain);
5025 /* Set this flag for all callers of this function. In addition to
5026 new-expressions, this is called for allocating coroutine state; treat
5027 that as an implicit new-expression. */
5028 tree call = extract_call_expr (ret);
5029 if (TREE_CODE (call) == CALL_EXPR)
5030 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
5032 return ret;
5035 /* Build a new call to operator(). This may change ARGS. */
5037 tree
5038 build_op_call (tree obj, vec<tree, va_gc> **args, tsubst_flags_t complain)
5040 struct z_candidate *candidates = 0, *cand;
5041 tree fns, convs, first_mem_arg = NULL_TREE;
5042 bool any_viable_p;
5043 tree result = NULL_TREE;
5044 void *p;
5046 auto_cond_timevar tv (TV_OVERLOAD);
5048 obj = mark_lvalue_use (obj);
5050 if (error_operand_p (obj))
5051 return error_mark_node;
5053 tree type = TREE_TYPE (obj);
5055 obj = prep_operand (obj);
5057 if (TYPE_PTRMEMFUNC_P (type))
5059 if (complain & tf_error)
5060 /* It's no good looking for an overloaded operator() on a
5061 pointer-to-member-function. */
5062 error ("pointer-to-member function %qE cannot be called without "
5063 "an object; consider using %<.*%> or %<->*%>", obj);
5064 return error_mark_node;
5067 if (TYPE_BINFO (type))
5069 fns = lookup_fnfields (TYPE_BINFO (type), call_op_identifier, 1, complain);
5070 if (fns == error_mark_node)
5071 return error_mark_node;
5073 else
5074 fns = NULL_TREE;
5076 if (args != NULL && *args != NULL)
5078 *args = resolve_args (*args, complain);
5079 if (*args == NULL)
5080 return error_mark_node;
5083 /* Get the high-water mark for the CONVERSION_OBSTACK. */
5084 p = conversion_obstack_alloc (0);
5086 if (fns)
5088 first_mem_arg = obj;
5090 add_candidates (BASELINK_FUNCTIONS (fns),
5091 first_mem_arg, *args, NULL_TREE,
5092 NULL_TREE, false,
5093 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
5094 LOOKUP_NORMAL, &candidates, complain);
5097 convs = lookup_conversions (type);
5099 for (; convs; convs = TREE_CHAIN (convs))
5101 tree totype = TREE_TYPE (convs);
5103 if (TYPE_PTRFN_P (totype)
5104 || TYPE_REFFN_P (totype)
5105 || (TYPE_REF_P (totype)
5106 && TYPE_PTRFN_P (TREE_TYPE (totype))))
5107 for (tree fn : ovl_range (TREE_VALUE (convs)))
5109 if (DECL_NONCONVERTING_P (fn))
5110 continue;
5112 if (TREE_CODE (fn) == TEMPLATE_DECL)
5113 add_template_conv_candidate
5114 (&candidates, fn, obj, *args, totype,
5115 /*access_path=*/NULL_TREE,
5116 /*conversion_path=*/NULL_TREE, complain);
5117 else
5118 add_conv_candidate (&candidates, fn, obj,
5119 *args, /*conversion_path=*/NULL_TREE,
5120 /*access_path=*/NULL_TREE, complain);
5124 /* Be strict here because if we choose a bad conversion candidate, the
5125 errors we get won't mention the call context. */
5126 candidates = splice_viable (candidates, true, &any_viable_p);
5127 if (!any_viable_p)
5129 if (complain & tf_error)
5131 auto_diagnostic_group d;
5132 error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
5133 build_tree_list_vec (*args));
5134 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5136 result = error_mark_node;
5138 else
5140 cand = tourney (candidates, complain);
5141 if (cand == 0)
5143 if (complain & tf_error)
5145 auto_diagnostic_group d;
5146 error ("call of %<(%T) (%A)%> is ambiguous",
5147 TREE_TYPE (obj), build_tree_list_vec (*args));
5148 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5150 result = error_mark_node;
5152 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
5153 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
5154 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, CALL_EXPR))
5155 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5156 else
5158 if (TREE_CODE (cand->fn) == FUNCTION_DECL)
5159 obj = convert_like_with_context (cand->convs[0], obj, cand->fn,
5160 -1, complain);
5161 else
5163 gcc_checking_assert (TYPE_P (cand->fn));
5164 obj = convert_like (cand->convs[0], obj, complain);
5166 obj = convert_from_reference (obj);
5167 result = cp_build_function_call_vec (obj, args, complain);
5171 /* Free all the conversions we allocated. */
5172 obstack_free (&conversion_obstack, p);
5174 return result;
5177 /* Called by op_error to prepare format strings suitable for the error
5178 function. It concatenates a prefix (controlled by MATCH), ERRMSG,
5179 and a suffix (controlled by NTYPES). */
5181 static const char *
5182 op_error_string (const char *errmsg, int ntypes, bool match)
5184 const char *msg;
5186 const char *msgp = concat (match ? G_("ambiguous overload for ")
5187 : G_("no match for "), errmsg, NULL);
5189 if (ntypes == 3)
5190 msg = concat (msgp, G_(" (operand types are %qT, %qT, and %qT)"), NULL);
5191 else if (ntypes == 2)
5192 msg = concat (msgp, G_(" (operand types are %qT and %qT)"), NULL);
5193 else
5194 msg = concat (msgp, G_(" (operand type is %qT)"), NULL);
5196 return msg;
5199 static void
5200 op_error (const op_location_t &loc,
5201 enum tree_code code, enum tree_code code2,
5202 tree arg1, tree arg2, tree arg3, bool match)
5204 bool assop = code == MODIFY_EXPR;
5205 const char *opname = OVL_OP_INFO (assop, assop ? code2 : code)->name;
5207 switch (code)
5209 case COND_EXPR:
5210 if (flag_diagnostics_show_caret)
5211 error_at (loc, op_error_string (G_("ternary %<operator?:%>"),
5212 3, match),
5213 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5214 else
5215 error_at (loc, op_error_string (G_("ternary %<operator?:%> "
5216 "in %<%E ? %E : %E%>"), 3, match),
5217 arg1, arg2, arg3,
5218 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5219 break;
5221 case POSTINCREMENT_EXPR:
5222 case POSTDECREMENT_EXPR:
5223 if (flag_diagnostics_show_caret)
5224 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5225 opname, TREE_TYPE (arg1));
5226 else
5227 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E%s%>"),
5228 1, match),
5229 opname, arg1, opname, TREE_TYPE (arg1));
5230 break;
5232 case ARRAY_REF:
5233 if (flag_diagnostics_show_caret)
5234 error_at (loc, op_error_string (G_("%<operator[]%>"), 2, match),
5235 TREE_TYPE (arg1), TREE_TYPE (arg2));
5236 else
5237 error_at (loc, op_error_string (G_("%<operator[]%> in %<%E[%E]%>"),
5238 2, match),
5239 arg1, arg2, TREE_TYPE (arg1), TREE_TYPE (arg2));
5240 break;
5242 case REALPART_EXPR:
5243 case IMAGPART_EXPR:
5244 if (flag_diagnostics_show_caret)
5245 error_at (loc, op_error_string (G_("%qs"), 1, match),
5246 opname, TREE_TYPE (arg1));
5247 else
5248 error_at (loc, op_error_string (G_("%qs in %<%s %E%>"), 1, match),
5249 opname, opname, arg1, TREE_TYPE (arg1));
5250 break;
5252 case CO_AWAIT_EXPR:
5253 if (flag_diagnostics_show_caret)
5254 error_at (loc, op_error_string (G_("%<operator %s%>"), 1, match),
5255 opname, TREE_TYPE (arg1));
5256 else
5257 error_at (loc, op_error_string (G_("%<operator %s%> in %<%s%E%>"),
5258 1, match),
5259 opname, opname, arg1, TREE_TYPE (arg1));
5260 break;
5262 default:
5263 if (arg2)
5264 if (flag_diagnostics_show_caret)
5266 binary_op_rich_location richloc (loc, arg1, arg2, true);
5267 error_at (&richloc,
5268 op_error_string (G_("%<operator%s%>"), 2, match),
5269 opname, TREE_TYPE (arg1), TREE_TYPE (arg2));
5271 else
5272 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E %s %E%>"),
5273 2, match),
5274 opname, arg1, opname, arg2,
5275 TREE_TYPE (arg1), TREE_TYPE (arg2));
5276 else
5277 if (flag_diagnostics_show_caret)
5278 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5279 opname, TREE_TYPE (arg1));
5280 else
5281 error_at (loc, op_error_string (G_("%<operator%s%> in %<%s%E%>"),
5282 1, match),
5283 opname, opname, arg1, TREE_TYPE (arg1));
5284 break;
5288 /* Return the implicit conversion sequence that could be used to
5289 convert E1 to E2 in [expr.cond]. */
5291 static conversion *
5292 conditional_conversion (tree e1, tree e2, tsubst_flags_t complain)
5294 tree t1 = non_reference (TREE_TYPE (e1));
5295 tree t2 = non_reference (TREE_TYPE (e2));
5296 conversion *conv;
5297 bool good_base;
5299 /* [expr.cond]
5301 If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5302 implicitly converted (clause _conv_) to the type "lvalue reference to
5303 T2", subject to the constraint that in the conversion the
5304 reference must bind directly (_dcl.init.ref_) to an lvalue.
5306 If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5307 implicitly converted to the type "rvalue reference to T2", subject to
5308 the constraint that the reference must bind directly. */
5309 if (glvalue_p (e2))
5311 tree rtype = cp_build_reference_type (t2, !lvalue_p (e2));
5312 conv = implicit_conversion (rtype,
5315 /*c_cast_p=*/false,
5316 LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND
5317 |LOOKUP_ONLYCONVERTING,
5318 complain);
5319 if (conv && !conv->bad_p)
5320 return conv;
5323 /* If E2 is a prvalue or if neither of the conversions above can be done
5324 and at least one of the operands has (possibly cv-qualified) class
5325 type: */
5326 if (!CLASS_TYPE_P (t1) && !CLASS_TYPE_P (t2))
5327 return NULL;
5329 /* [expr.cond]
5331 If E1 and E2 have class type, and the underlying class types are
5332 the same or one is a base class of the other: E1 can be converted
5333 to match E2 if the class of T2 is the same type as, or a base
5334 class of, the class of T1, and the cv-qualification of T2 is the
5335 same cv-qualification as, or a greater cv-qualification than, the
5336 cv-qualification of T1. If the conversion is applied, E1 is
5337 changed to an rvalue of type T2 that still refers to the original
5338 source class object (or the appropriate subobject thereof). */
5339 if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
5340 && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
5342 if (good_base && at_least_as_qualified_p (t2, t1))
5344 conv = build_identity_conv (t1, e1);
5345 if (!same_type_p (TYPE_MAIN_VARIANT (t1),
5346 TYPE_MAIN_VARIANT (t2)))
5347 conv = build_conv (ck_base, t2, conv);
5348 else
5349 conv = build_conv (ck_rvalue, t2, conv);
5350 return conv;
5352 else
5353 return NULL;
5355 else
5356 /* [expr.cond]
5358 Otherwise: E1 can be converted to match E2 if E1 can be implicitly
5359 converted to the type that expression E2 would have if E2 were
5360 converted to an rvalue (or the type it has, if E2 is an rvalue). */
5361 return implicit_conversion (t2, t1, e1, /*c_cast_p=*/false,
5362 LOOKUP_IMPLICIT, complain);
5365 /* Implement [expr.cond]. ARG1, ARG2, and ARG3 are the three
5366 arguments to the conditional expression. */
5368 tree
5369 build_conditional_expr (const op_location_t &loc,
5370 tree arg1, tree arg2, tree arg3,
5371 tsubst_flags_t complain)
5373 tree arg2_type;
5374 tree arg3_type;
5375 tree result = NULL_TREE;
5376 tree result_type = NULL_TREE;
5377 bool is_glvalue = true;
5378 struct z_candidate *candidates = 0;
5379 struct z_candidate *cand;
5380 void *p;
5381 tree orig_arg2, orig_arg3;
5383 auto_cond_timevar tv (TV_OVERLOAD);
5385 /* As a G++ extension, the second argument to the conditional can be
5386 omitted. (So that `a ? : c' is roughly equivalent to `a ? a :
5387 c'.) If the second operand is omitted, make sure it is
5388 calculated only once. */
5389 if (!arg2)
5391 if (complain & tf_error)
5392 pedwarn (loc, OPT_Wpedantic,
5393 "ISO C++ forbids omitting the middle term of "
5394 "a %<?:%> expression");
5396 if ((complain & tf_warning) && !truth_value_p (TREE_CODE (arg1)))
5397 warn_for_omitted_condop (loc, arg1);
5399 /* Make sure that lvalues remain lvalues. See g++.oliva/ext1.C. */
5400 if (glvalue_p (arg1))
5402 arg1 = cp_stabilize_reference (arg1);
5403 arg2 = arg1 = prevent_lifetime_extension (arg1);
5405 else if (TREE_CODE (arg1) == TARGET_EXPR)
5406 /* arg1 can't be a prvalue result of the conditional
5407 expression, since it needs to be materialized for the
5408 conversion to bool, so treat it as an xvalue in arg2. */
5409 arg2 = move (TARGET_EXPR_SLOT (arg1));
5410 else
5411 arg2 = arg1 = cp_save_expr (arg1);
5414 /* If something has already gone wrong, just pass that fact up the
5415 tree. */
5416 if (error_operand_p (arg1)
5417 || error_operand_p (arg2)
5418 || error_operand_p (arg3))
5419 return error_mark_node;
5421 orig_arg2 = arg2;
5422 orig_arg3 = arg3;
5424 if (gnu_vector_type_p (TREE_TYPE (arg1))
5425 && VECTOR_INTEGER_TYPE_P (TREE_TYPE (arg1)))
5427 tree arg1_type = TREE_TYPE (arg1);
5429 /* If arg1 is another cond_expr choosing between -1 and 0,
5430 then we can use its comparison. It may help to avoid
5431 additional comparison, produce more accurate diagnostics
5432 and enables folding. */
5433 if (TREE_CODE (arg1) == VEC_COND_EXPR
5434 && integer_minus_onep (TREE_OPERAND (arg1, 1))
5435 && integer_zerop (TREE_OPERAND (arg1, 2)))
5436 arg1 = TREE_OPERAND (arg1, 0);
5438 arg1 = force_rvalue (arg1, complain);
5439 arg2 = force_rvalue (arg2, complain);
5440 arg3 = force_rvalue (arg3, complain);
5442 /* force_rvalue can return error_mark on valid arguments. */
5443 if (error_operand_p (arg1)
5444 || error_operand_p (arg2)
5445 || error_operand_p (arg3))
5446 return error_mark_node;
5448 arg2_type = TREE_TYPE (arg2);
5449 arg3_type = TREE_TYPE (arg3);
5451 if (!VECTOR_TYPE_P (arg2_type)
5452 && !VECTOR_TYPE_P (arg3_type))
5454 /* Rely on the error messages of the scalar version. */
5455 tree scal = build_conditional_expr (loc, integer_one_node,
5456 orig_arg2, orig_arg3, complain);
5457 if (scal == error_mark_node)
5458 return error_mark_node;
5459 tree stype = TREE_TYPE (scal);
5460 tree ctype = TREE_TYPE (arg1_type);
5461 if (TYPE_SIZE (stype) != TYPE_SIZE (ctype)
5462 || (!INTEGRAL_TYPE_P (stype) && !SCALAR_FLOAT_TYPE_P (stype)))
5464 if (complain & tf_error)
5465 error_at (loc, "inferred scalar type %qT is not an integer or "
5466 "floating-point type of the same size as %qT", stype,
5467 COMPARISON_CLASS_P (arg1)
5468 ? TREE_TYPE (TREE_TYPE (TREE_OPERAND (arg1, 0)))
5469 : ctype);
5470 return error_mark_node;
5473 tree vtype = build_opaque_vector_type (stype,
5474 TYPE_VECTOR_SUBPARTS (arg1_type));
5475 /* We could pass complain & tf_warning to unsafe_conversion_p,
5476 but the warnings (like Wsign-conversion) have already been
5477 given by the scalar build_conditional_expr_1. We still check
5478 unsafe_conversion_p to forbid truncating long long -> float. */
5479 if (unsafe_conversion_p (stype, arg2, NULL_TREE, false))
5481 if (complain & tf_error)
5482 error_at (loc, "conversion of scalar %qH to vector %qI "
5483 "involves truncation", arg2_type, vtype);
5484 return error_mark_node;
5486 if (unsafe_conversion_p (stype, arg3, NULL_TREE, false))
5488 if (complain & tf_error)
5489 error_at (loc, "conversion of scalar %qH to vector %qI "
5490 "involves truncation", arg3_type, vtype);
5491 return error_mark_node;
5494 arg2 = cp_convert (stype, arg2, complain);
5495 arg2 = save_expr (arg2);
5496 arg2 = build_vector_from_val (vtype, arg2);
5497 arg2_type = vtype;
5498 arg3 = cp_convert (stype, arg3, complain);
5499 arg3 = save_expr (arg3);
5500 arg3 = build_vector_from_val (vtype, arg3);
5501 arg3_type = vtype;
5504 if ((gnu_vector_type_p (arg2_type) && !VECTOR_TYPE_P (arg3_type))
5505 || (gnu_vector_type_p (arg3_type) && !VECTOR_TYPE_P (arg2_type)))
5507 enum stv_conv convert_flag =
5508 scalar_to_vector (loc, VEC_COND_EXPR, arg2, arg3,
5509 complain & tf_error);
5511 switch (convert_flag)
5513 case stv_error:
5514 return error_mark_node;
5515 case stv_firstarg:
5517 arg2 = save_expr (arg2);
5518 arg2 = convert (TREE_TYPE (arg3_type), arg2);
5519 arg2 = build_vector_from_val (arg3_type, arg2);
5520 arg2_type = TREE_TYPE (arg2);
5521 break;
5523 case stv_secondarg:
5525 arg3 = save_expr (arg3);
5526 arg3 = convert (TREE_TYPE (arg2_type), arg3);
5527 arg3 = build_vector_from_val (arg2_type, arg3);
5528 arg3_type = TREE_TYPE (arg3);
5529 break;
5531 default:
5532 break;
5536 if (!gnu_vector_type_p (arg2_type)
5537 || !gnu_vector_type_p (arg3_type)
5538 || !same_type_p (arg2_type, arg3_type)
5539 || maybe_ne (TYPE_VECTOR_SUBPARTS (arg1_type),
5540 TYPE_VECTOR_SUBPARTS (arg2_type))
5541 || TYPE_SIZE (arg1_type) != TYPE_SIZE (arg2_type))
5543 if (complain & tf_error)
5544 error_at (loc,
5545 "incompatible vector types in conditional expression: "
5546 "%qT, %qT and %qT", TREE_TYPE (arg1),
5547 TREE_TYPE (orig_arg2), TREE_TYPE (orig_arg3));
5548 return error_mark_node;
5551 if (!COMPARISON_CLASS_P (arg1))
5553 tree cmp_type = truth_type_for (arg1_type);
5554 arg1 = build2 (NE_EXPR, cmp_type, arg1, build_zero_cst (arg1_type));
5556 return build3_loc (loc, VEC_COND_EXPR, arg2_type, arg1, arg2, arg3);
5559 /* [expr.cond]
5561 The first expression is implicitly converted to bool (clause
5562 _conv_). */
5563 arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
5564 LOOKUP_NORMAL);
5565 if (error_operand_p (arg1))
5566 return error_mark_node;
5568 /* [expr.cond]
5570 If either the second or the third operand has type (possibly
5571 cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
5572 array-to-pointer (_conv.array_), and function-to-pointer
5573 (_conv.func_) standard conversions are performed on the second
5574 and third operands. */
5575 arg2_type = unlowered_expr_type (arg2);
5576 arg3_type = unlowered_expr_type (arg3);
5577 if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
5579 /* 'void' won't help in resolving an overloaded expression on the
5580 other side, so require it to resolve by itself. */
5581 if (arg2_type == unknown_type_node)
5583 arg2 = resolve_nondeduced_context_or_error (arg2, complain);
5584 arg2_type = TREE_TYPE (arg2);
5586 if (arg3_type == unknown_type_node)
5588 arg3 = resolve_nondeduced_context_or_error (arg3, complain);
5589 arg3_type = TREE_TYPE (arg3);
5592 /* [expr.cond]
5594 One of the following shall hold:
5596 --The second or the third operand (but not both) is a
5597 throw-expression (_except.throw_); the result is of the type
5598 and value category of the other.
5600 --Both the second and the third operands have type void; the
5601 result is of type void and is a prvalue. */
5602 if (TREE_CODE (arg2) == THROW_EXPR
5603 && TREE_CODE (arg3) != THROW_EXPR)
5605 result_type = arg3_type;
5606 is_glvalue = glvalue_p (arg3);
5608 else if (TREE_CODE (arg2) != THROW_EXPR
5609 && TREE_CODE (arg3) == THROW_EXPR)
5611 result_type = arg2_type;
5612 is_glvalue = glvalue_p (arg2);
5614 else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
5616 result_type = void_type_node;
5617 is_glvalue = false;
5619 else
5621 if (complain & tf_error)
5623 if (VOID_TYPE_P (arg2_type))
5624 error_at (cp_expr_loc_or_loc (arg3, loc),
5625 "second operand to the conditional operator "
5626 "is of type %<void%>, but the third operand is "
5627 "neither a throw-expression nor of type %<void%>");
5628 else
5629 error_at (cp_expr_loc_or_loc (arg2, loc),
5630 "third operand to the conditional operator "
5631 "is of type %<void%>, but the second operand is "
5632 "neither a throw-expression nor of type %<void%>");
5634 return error_mark_node;
5637 goto valid_operands;
5639 /* [expr.cond]
5641 Otherwise, if the second and third operand have different types,
5642 and either has (possibly cv-qualified) class type, or if both are
5643 glvalues of the same value category and the same type except for
5644 cv-qualification, an attempt is made to convert each of those operands
5645 to the type of the other. */
5646 else if (!same_type_p (arg2_type, arg3_type)
5647 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)
5648 || (same_type_ignoring_top_level_qualifiers_p (arg2_type,
5649 arg3_type)
5650 && glvalue_p (arg2) && glvalue_p (arg3)
5651 && lvalue_p (arg2) == lvalue_p (arg3))))
5653 conversion *conv2;
5654 conversion *conv3;
5655 bool converted = false;
5657 /* Get the high-water mark for the CONVERSION_OBSTACK. */
5658 p = conversion_obstack_alloc (0);
5660 conv2 = conditional_conversion (arg2, arg3, complain);
5661 conv3 = conditional_conversion (arg3, arg2, complain);
5663 /* [expr.cond]
5665 If both can be converted, or one can be converted but the
5666 conversion is ambiguous, the program is ill-formed. If
5667 neither can be converted, the operands are left unchanged and
5668 further checking is performed as described below. If exactly
5669 one conversion is possible, that conversion is applied to the
5670 chosen operand and the converted operand is used in place of
5671 the original operand for the remainder of this section. */
5672 if ((conv2 && !conv2->bad_p
5673 && conv3 && !conv3->bad_p)
5674 || (conv2 && conv2->kind == ck_ambig)
5675 || (conv3 && conv3->kind == ck_ambig))
5677 if (complain & tf_error)
5679 error_at (loc, "operands to %<?:%> have different types "
5680 "%qT and %qT",
5681 arg2_type, arg3_type);
5682 if (conv2 && !conv2->bad_p && conv3 && !conv3->bad_p)
5683 inform (loc, " and each type can be converted to the other");
5684 else if (conv2 && conv2->kind == ck_ambig)
5685 convert_like (conv2, arg2, complain);
5686 else
5687 convert_like (conv3, arg3, complain);
5689 result = error_mark_node;
5691 else if (conv2 && !conv2->bad_p)
5693 arg2 = convert_like (conv2, arg2, complain);
5694 arg2 = convert_from_reference (arg2);
5695 arg2_type = TREE_TYPE (arg2);
5696 /* Even if CONV2 is a valid conversion, the result of the
5697 conversion may be invalid. For example, if ARG3 has type
5698 "volatile X", and X does not have a copy constructor
5699 accepting a "volatile X&", then even if ARG2 can be
5700 converted to X, the conversion will fail. */
5701 if (error_operand_p (arg2))
5702 result = error_mark_node;
5703 converted = true;
5705 else if (conv3 && !conv3->bad_p)
5707 arg3 = convert_like (conv3, arg3, complain);
5708 arg3 = convert_from_reference (arg3);
5709 arg3_type = TREE_TYPE (arg3);
5710 if (error_operand_p (arg3))
5711 result = error_mark_node;
5712 converted = true;
5715 /* Free all the conversions we allocated. */
5716 obstack_free (&conversion_obstack, p);
5718 if (result)
5719 return result;
5721 /* If, after the conversion, both operands have class type,
5722 treat the cv-qualification of both operands as if it were the
5723 union of the cv-qualification of the operands.
5725 The standard is not clear about what to do in this
5726 circumstance. For example, if the first operand has type
5727 "const X" and the second operand has a user-defined
5728 conversion to "volatile X", what is the type of the second
5729 operand after this step? Making it be "const X" (matching
5730 the first operand) seems wrong, as that discards the
5731 qualification without actually performing a copy. Leaving it
5732 as "volatile X" seems wrong as that will result in the
5733 conditional expression failing altogether, even though,
5734 according to this step, the one operand could be converted to
5735 the type of the other. */
5736 if (converted
5737 && CLASS_TYPE_P (arg2_type)
5738 && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
5739 arg2_type = arg3_type =
5740 cp_build_qualified_type (arg2_type,
5741 cp_type_quals (arg2_type)
5742 | cp_type_quals (arg3_type));
5745 /* [expr.cond]
5747 If the second and third operands are glvalues of the same value
5748 category and have the same type, the result is of that type and
5749 value category. */
5750 if (((lvalue_p (arg2) && lvalue_p (arg3))
5751 || (xvalue_p (arg2) && xvalue_p (arg3)))
5752 && same_type_p (arg2_type, arg3_type))
5754 result_type = arg2_type;
5755 goto valid_operands;
5758 /* [expr.cond]
5760 Otherwise, the result is an rvalue. If the second and third
5761 operand do not have the same type, and either has (possibly
5762 cv-qualified) class type, overload resolution is used to
5763 determine the conversions (if any) to be applied to the operands
5764 (_over.match.oper_, _over.built_). */
5765 is_glvalue = false;
5766 if (!same_type_p (arg2_type, arg3_type)
5767 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
5769 releasing_vec args;
5770 conversion *conv;
5771 bool any_viable_p;
5773 /* Rearrange the arguments so that add_builtin_candidate only has
5774 to know about two args. In build_builtin_candidate, the
5775 arguments are unscrambled. */
5776 args->quick_push (arg2);
5777 args->quick_push (arg3);
5778 args->quick_push (arg1);
5779 add_builtin_candidates (&candidates,
5780 COND_EXPR,
5781 NOP_EXPR,
5782 ovl_op_identifier (false, COND_EXPR),
5783 args,
5784 LOOKUP_NORMAL, complain);
5786 /* [expr.cond]
5788 If the overload resolution fails, the program is
5789 ill-formed. */
5790 candidates = splice_viable (candidates, false, &any_viable_p);
5791 if (!any_viable_p)
5793 if (complain & tf_error)
5794 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
5795 arg2_type, arg3_type);
5796 return error_mark_node;
5798 cand = tourney (candidates, complain);
5799 if (!cand)
5801 if (complain & tf_error)
5803 auto_diagnostic_group d;
5804 op_error (loc, COND_EXPR, NOP_EXPR, arg1, arg2, arg3, FALSE);
5805 print_z_candidates (loc, candidates);
5807 return error_mark_node;
5810 /* [expr.cond]
5812 Otherwise, the conversions thus determined are applied, and
5813 the converted operands are used in place of the original
5814 operands for the remainder of this section. */
5815 conv = cand->convs[0];
5816 arg1 = convert_like (conv, arg1, complain);
5817 conv = cand->convs[1];
5818 arg2 = convert_like (conv, arg2, complain);
5819 arg2_type = TREE_TYPE (arg2);
5820 conv = cand->convs[2];
5821 arg3 = convert_like (conv, arg3, complain);
5822 arg3_type = TREE_TYPE (arg3);
5825 /* [expr.cond]
5827 Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
5828 and function-to-pointer (_conv.func_) standard conversions are
5829 performed on the second and third operands.
5831 We need to force the lvalue-to-rvalue conversion here for class types,
5832 so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
5833 that isn't wrapped with a TARGET_EXPR plays havoc with exception
5834 regions. */
5836 arg2 = force_rvalue (arg2, complain);
5837 if (!CLASS_TYPE_P (arg2_type))
5838 arg2_type = TREE_TYPE (arg2);
5840 arg3 = force_rvalue (arg3, complain);
5841 if (!CLASS_TYPE_P (arg3_type))
5842 arg3_type = TREE_TYPE (arg3);
5844 if (arg2 == error_mark_node || arg3 == error_mark_node)
5845 return error_mark_node;
5847 /* [expr.cond]
5849 After those conversions, one of the following shall hold:
5851 --The second and third operands have the same type; the result is of
5852 that type. */
5853 if (same_type_p (arg2_type, arg3_type))
5854 result_type = arg2_type;
5855 /* [expr.cond]
5857 --The second and third operands have arithmetic or enumeration
5858 type; the usual arithmetic conversions are performed to bring
5859 them to a common type, and the result is of that type. */
5860 else if ((ARITHMETIC_TYPE_P (arg2_type)
5861 || UNSCOPED_ENUM_P (arg2_type))
5862 && (ARITHMETIC_TYPE_P (arg3_type)
5863 || UNSCOPED_ENUM_P (arg3_type)))
5865 /* In this case, there is always a common type. */
5866 result_type = type_after_usual_arithmetic_conversions (arg2_type,
5867 arg3_type);
5868 if (result_type == error_mark_node
5869 && TREE_CODE (arg2_type) == REAL_TYPE
5870 && TREE_CODE (arg3_type) == REAL_TYPE
5871 && (extended_float_type_p (arg2_type)
5872 || extended_float_type_p (arg3_type))
5873 && cp_compare_floating_point_conversion_ranks (arg2_type,
5874 arg3_type) == 3)
5876 if (complain & tf_error)
5877 error_at (loc, "operands to %<?:%> of types %qT and %qT "
5878 "have unordered conversion rank",
5879 arg2_type, arg3_type);
5880 return error_mark_node;
5883 if (complain & tf_warning)
5884 do_warn_double_promotion (result_type, arg2_type, arg3_type,
5885 "implicit conversion from %qH to %qI to "
5886 "match other result of conditional",
5887 loc);
5889 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
5890 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
5892 tree stripped_orig_arg2 = tree_strip_any_location_wrapper (orig_arg2);
5893 tree stripped_orig_arg3 = tree_strip_any_location_wrapper (orig_arg3);
5894 if (TREE_CODE (stripped_orig_arg2) == CONST_DECL
5895 && TREE_CODE (stripped_orig_arg3) == CONST_DECL
5896 && (DECL_CONTEXT (stripped_orig_arg2)
5897 == DECL_CONTEXT (stripped_orig_arg3)))
5898 /* Two enumerators from the same enumeration can have different
5899 types when the enumeration is still being defined. */;
5900 else if (complain & tf_warning)
5901 warning_at (loc, OPT_Wenum_compare, "enumerated mismatch "
5902 "in conditional expression: %qT vs %qT",
5903 arg2_type, arg3_type);
5905 else if ((complain & tf_warning)
5906 && warn_deprecated_enum_float_conv
5907 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
5908 && TREE_CODE (arg3_type) == REAL_TYPE)
5909 || (TREE_CODE (arg2_type) == REAL_TYPE
5910 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)))
5912 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE)
5913 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
5914 "conditional expression between enumeration type "
5915 "%qT and floating-point type %qT is deprecated",
5916 arg2_type, arg3_type);
5917 else
5918 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
5919 "conditional expression between floating-point "
5920 "type %qT and enumeration type %qT is deprecated",
5921 arg2_type, arg3_type);
5923 else if ((extra_warnings || warn_enum_conversion)
5924 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
5925 && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
5926 || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
5927 && !same_type_p (arg2_type,
5928 type_promotes_to (arg3_type)))))
5930 if (complain & tf_warning)
5932 enum opt_code opt = (warn_enum_conversion
5933 ? OPT_Wenum_conversion
5934 : OPT_Wextra);
5935 warning_at (loc, opt, "enumerated and "
5936 "non-enumerated type in conditional expression");
5940 arg2 = perform_implicit_conversion (result_type, arg2, complain);
5941 arg3 = perform_implicit_conversion (result_type, arg3, complain);
5943 /* [expr.cond]
5945 --The second and third operands have pointer type, or one has
5946 pointer type and the other is a null pointer constant; pointer
5947 conversions (_conv.ptr_) and qualification conversions
5948 (_conv.qual_) are performed to bring them to their composite
5949 pointer type (_expr.rel_). The result is of the composite
5950 pointer type.
5952 --The second and third operands have pointer to member type, or
5953 one has pointer to member type and the other is a null pointer
5954 constant; pointer to member conversions (_conv.mem_) and
5955 qualification conversions (_conv.qual_) are performed to bring
5956 them to a common type, whose cv-qualification shall match the
5957 cv-qualification of either the second or the third operand.
5958 The result is of the common type. */
5959 else if ((null_ptr_cst_p (arg2)
5960 && TYPE_PTR_OR_PTRMEM_P (arg3_type))
5961 || (null_ptr_cst_p (arg3)
5962 && TYPE_PTR_OR_PTRMEM_P (arg2_type))
5963 || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
5964 || (TYPE_PTRDATAMEM_P (arg2_type) && TYPE_PTRDATAMEM_P (arg3_type))
5965 || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
5967 result_type = composite_pointer_type (loc,
5968 arg2_type, arg3_type, arg2,
5969 arg3, CPO_CONDITIONAL_EXPR,
5970 complain);
5971 if (result_type == error_mark_node)
5972 return error_mark_node;
5973 arg2 = perform_implicit_conversion (result_type, arg2, complain);
5974 arg3 = perform_implicit_conversion (result_type, arg3, complain);
5977 if (!result_type)
5979 if (complain & tf_error)
5980 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
5981 arg2_type, arg3_type);
5982 return error_mark_node;
5985 if (arg2 == error_mark_node || arg3 == error_mark_node)
5986 return error_mark_node;
5988 valid_operands:
5989 if (processing_template_decl && is_glvalue)
5991 /* Let lvalue_kind know this was a glvalue. */
5992 tree arg = (result_type == arg2_type ? arg2 : arg3);
5993 result_type = cp_build_reference_type (result_type, xvalue_p (arg));
5996 result = build3_loc (loc, COND_EXPR, result_type, arg1, arg2, arg3);
5998 /* If the ARG2 and ARG3 are the same and don't have side-effects,
5999 warn here, because the COND_EXPR will be turned into ARG2. */
6000 if (warn_duplicated_branches
6001 && (complain & tf_warning)
6002 && (arg2 == arg3 || operand_equal_p (arg2, arg3,
6003 OEP_ADDRESS_OF_SAME_FIELD)))
6004 warning_at (EXPR_LOCATION (result), OPT_Wduplicated_branches,
6005 "this condition has identical branches");
6007 /* We can't use result_type below, as fold might have returned a
6008 throw_expr. */
6010 if (!is_glvalue)
6012 /* Expand both sides into the same slot, hopefully the target of
6013 the ?: expression. We used to check for TARGET_EXPRs here,
6014 but now we sometimes wrap them in NOP_EXPRs so the test would
6015 fail. */
6016 if (CLASS_TYPE_P (TREE_TYPE (result)))
6018 result = get_target_expr (result, complain);
6019 /* Tell gimplify_modify_expr_rhs not to strip this in
6020 assignment context: we want both arms to initialize
6021 the same temporary. */
6022 TARGET_EXPR_NO_ELIDE (result) = true;
6024 /* If this expression is an rvalue, but might be mistaken for an
6025 lvalue, we must add a NON_LVALUE_EXPR. */
6026 result = rvalue (result);
6028 else
6029 result = force_paren_expr (result);
6031 return result;
6034 /* OPERAND is an operand to an expression. Perform necessary steps
6035 required before using it. If OPERAND is NULL_TREE, NULL_TREE is
6036 returned. */
6038 static tree
6039 prep_operand (tree operand)
6041 if (operand)
6043 if (CLASS_TYPE_P (TREE_TYPE (operand))
6044 && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
6045 /* Make sure the template type is instantiated now. */
6046 instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
6049 return operand;
6052 /* True iff CONV represents a conversion sequence which no other can be better
6053 than under [over.ics.rank]: in other words, a "conversion" to the exact same
6054 type (including binding to a reference to the same type). This is stronger
6055 than the standard's "identity" category, which also includes reference
6056 bindings that add cv-qualifiers or change rvalueness. */
6058 static bool
6059 perfect_conversion_p (conversion *conv)
6061 if (CONVERSION_RANK (conv) != cr_identity)
6062 return false;
6063 if (conv->kind == ck_ref_bind)
6065 if (!conv->rvaluedness_matches_p)
6066 return false;
6067 if (!same_type_p (TREE_TYPE (conv->type),
6068 next_conversion (conv)->type))
6069 return false;
6071 if (conv->check_narrowing)
6072 /* Brace elision is imperfect. */
6073 return false;
6074 return true;
6077 /* True if CAND represents a perfect match, i.e. all perfect conversions, so no
6078 other candidate can be a better match. Since the template/non-template
6079 tiebreaker comes immediately after the conversion comparison in
6080 [over.match.best], a perfect non-template candidate is better than all
6081 templates. */
6083 static bool
6084 perfect_candidate_p (z_candidate *cand)
6086 if (cand->viable < 1)
6087 return false;
6088 /* CWG1402 makes an implicitly deleted move op worse than other
6089 candidates. */
6090 if (DECL_DELETED_FN (cand->fn) && DECL_DEFAULTED_FN (cand->fn)
6091 && move_fn_p (cand->fn))
6092 return false;
6093 int len = cand->num_convs;
6094 for (int i = 0; i < len; ++i)
6095 if (!perfect_conversion_p (cand->convs[i]))
6096 return false;
6097 if (conversion *conv = cand->second_conv)
6098 if (!perfect_conversion_p (conv))
6099 return false;
6100 return true;
6103 /* True iff one of CAND's argument conversions is missing. */
6105 static bool
6106 missing_conversion_p (const z_candidate *cand)
6108 for (unsigned i = 0; i < cand->num_convs; ++i)
6110 conversion *conv = cand->convs[i];
6111 if (!conv)
6112 return true;
6113 if (conv->kind == ck_deferred_bad)
6115 /* We don't know whether this conversion is outright invalid or
6116 just bad, so conservatively assume it's missing. */
6117 gcc_checking_assert (conv->bad_p);
6118 return true;
6121 return false;
6124 /* Add each of the viable functions in FNS (a FUNCTION_DECL or
6125 OVERLOAD) to the CANDIDATES, returning an updated list of
6126 CANDIDATES. The ARGS are the arguments provided to the call;
6127 if FIRST_ARG is non-null it is the implicit object argument,
6128 otherwise the first element of ARGS is used if needed. The
6129 EXPLICIT_TARGS are explicit template arguments provided.
6130 TEMPLATE_ONLY is true if only template functions should be
6131 considered. CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
6132 add_function_candidate. */
6134 static void
6135 add_candidates (tree fns, tree first_arg, const vec<tree, va_gc> *args,
6136 tree return_type,
6137 tree explicit_targs, bool template_only,
6138 tree conversion_path, tree access_path,
6139 int flags,
6140 struct z_candidate **candidates,
6141 tsubst_flags_t complain)
6143 tree ctype;
6144 const vec<tree, va_gc> *non_static_args;
6145 bool check_list_ctor = false;
6146 bool check_converting = false;
6147 unification_kind_t strict;
6149 if (!fns)
6150 return;
6152 /* Precalculate special handling of constructors and conversion ops. */
6153 tree fn = OVL_FIRST (fns);
6154 if (DECL_CONV_FN_P (fn))
6156 check_list_ctor = false;
6157 check_converting = (flags & LOOKUP_ONLYCONVERTING) != 0;
6158 if (flags & LOOKUP_NO_CONVERSION)
6159 /* We're doing return_type(x). */
6160 strict = DEDUCE_CONV;
6161 else
6162 /* We're doing x.operator return_type(). */
6163 strict = DEDUCE_EXACT;
6164 /* [over.match.funcs] For conversion functions, the function
6165 is considered to be a member of the class of the implicit
6166 object argument for the purpose of defining the type of
6167 the implicit object parameter. */
6168 ctype = TYPE_MAIN_VARIANT (TREE_TYPE (first_arg));
6170 else
6172 if (DECL_CONSTRUCTOR_P (fn))
6174 check_list_ctor = (flags & LOOKUP_LIST_ONLY) != 0;
6175 /* For list-initialization we consider explicit constructors
6176 and complain if one is chosen. */
6177 check_converting
6178 = ((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
6179 == LOOKUP_ONLYCONVERTING);
6181 strict = DEDUCE_CALL;
6182 ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
6185 if (first_arg)
6186 non_static_args = args;
6187 else
6188 /* Delay creating the implicit this parameter until it is needed. */
6189 non_static_args = NULL;
6191 bool seen_strictly_viable = any_strictly_viable (*candidates);
6192 /* If there's a non-template perfect match, we don't need to consider
6193 templates. So check non-templates first. This optimization is only
6194 really needed for the defaulted copy constructor of tuple and the like
6195 (96926), but it seems like we might as well enable it more generally. */
6196 bool seen_perfect = false;
6197 enum { templates, non_templates, either } which = either;
6198 if (template_only)
6199 which = templates;
6200 else /*if (flags & LOOKUP_DEFAULTED)*/
6201 which = non_templates;
6203 /* During overload resolution, we first consider each function under the
6204 assumption that we'll eventually find a strictly viable candidate.
6205 This allows us to circumvent our defacto behavior when checking
6206 argument conversions and shortcut consideration of the candidate
6207 upon encountering the first bad conversion. If this assumption
6208 turns out to be false, and all candidates end up being non-strictly
6209 viable, then we reconsider such candidates under the defacto behavior.
6210 This trick is important for pruning member function overloads according
6211 to their const/ref-qualifiers (since all 'this' conversions are at
6212 worst bad) without breaking -fpermissive. */
6213 tree bad_fns = NULL_TREE;
6214 bool shortcut_bad_convs = true;
6216 again:
6217 for (tree fn : lkp_range (fns))
6219 if (check_converting && DECL_NONCONVERTING_P (fn))
6220 continue;
6221 if (check_list_ctor && !is_list_ctor (fn))
6222 continue;
6223 if (which == templates && TREE_CODE (fn) != TEMPLATE_DECL)
6224 continue;
6225 if (which == non_templates && TREE_CODE (fn) == TEMPLATE_DECL)
6226 continue;
6228 tree fn_first_arg = NULL_TREE;
6229 const vec<tree, va_gc> *fn_args = args;
6231 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
6233 /* Figure out where the object arg comes from. If this
6234 function is a non-static member and we didn't get an
6235 implicit object argument, move it out of args. */
6236 if (first_arg == NULL_TREE)
6238 unsigned int ix;
6239 tree arg;
6240 vec<tree, va_gc> *tempvec;
6241 vec_alloc (tempvec, args->length () - 1);
6242 for (ix = 1; args->iterate (ix, &arg); ++ix)
6243 tempvec->quick_push (arg);
6244 non_static_args = tempvec;
6245 first_arg = (*args)[0];
6248 fn_first_arg = first_arg;
6249 fn_args = non_static_args;
6252 /* Don't bother reversing an operator with two identical parameters. */
6253 else if (vec_safe_length (args) == 2 && (flags & LOOKUP_REVERSED))
6255 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
6256 if (same_type_p (TREE_VALUE (parmlist),
6257 TREE_VALUE (TREE_CHAIN (parmlist))))
6258 continue;
6261 if (TREE_CODE (fn) == TEMPLATE_DECL)
6263 if (!add_template_candidate (candidates,
6265 ctype,
6266 explicit_targs,
6267 fn_first_arg,
6268 fn_args,
6269 return_type,
6270 access_path,
6271 conversion_path,
6272 flags,
6273 strict,
6274 shortcut_bad_convs,
6275 complain))
6276 continue;
6278 else
6280 add_function_candidate (candidates,
6282 ctype,
6283 fn_first_arg,
6284 fn_args,
6285 access_path,
6286 conversion_path,
6287 flags,
6288 NULL,
6289 shortcut_bad_convs,
6290 complain);
6291 if (perfect_candidate_p (*candidates))
6292 seen_perfect = true;
6295 z_candidate *cand = *candidates;
6296 if (cand->viable == 1)
6297 seen_strictly_viable = true;
6299 if (cand->viable == -1
6300 && shortcut_bad_convs
6301 && missing_conversion_p (cand))
6303 /* This candidate has been tentatively marked non-strictly viable,
6304 and we didn't compute all argument conversions for it (having
6305 stopped at the first bad conversion). Add the function to BAD_FNS
6306 to fully reconsider later if we don't find any strictly viable
6307 candidates. */
6308 if (complain & (tf_error | tf_conv))
6310 bad_fns = lookup_add (fn, bad_fns);
6311 *candidates = (*candidates)->next;
6313 else
6314 /* But if we're in a SFINAE context, just mark this candidate as
6315 unviable outright and avoid potentially reconsidering it.
6316 This is safe to do because in a SFINAE context, performing a bad
6317 conversion is always an error (even with -fpermissive), so a
6318 non-strictly viable candidate is effectively unviable anyway. */
6319 cand->viable = 0;
6322 if (which == non_templates && !seen_perfect)
6324 which = templates;
6325 goto again;
6327 else if (which == templates
6328 && !seen_strictly_viable
6329 && shortcut_bad_convs
6330 && bad_fns)
6332 /* None of the candidates are strictly viable, so consider again those
6333 functions in BAD_FNS, this time without shortcutting bad conversions
6334 so that all their argument conversions are computed. */
6335 which = either;
6336 fns = bad_fns;
6337 shortcut_bad_convs = false;
6338 goto again;
6342 /* Returns 1 if P0145R2 says that the LHS of operator CODE is evaluated first,
6343 -1 if the RHS is evaluated first, or 0 if the order is unspecified. */
6345 static int
6346 op_is_ordered (tree_code code)
6348 switch (code)
6350 // 5. b @= a
6351 case MODIFY_EXPR:
6352 return (flag_strong_eval_order > 1 ? -1 : 0);
6354 // 6. a[b]
6355 case ARRAY_REF:
6356 return (flag_strong_eval_order > 1 ? 1 : 0);
6358 // 1. a.b
6359 // Not overloadable (yet).
6360 // 2. a->b
6361 // Only one argument.
6362 // 3. a->*b
6363 case MEMBER_REF:
6364 // 7. a << b
6365 case LSHIFT_EXPR:
6366 // 8. a >> b
6367 case RSHIFT_EXPR:
6368 // a && b
6369 // Predates P0145R3.
6370 case TRUTH_ANDIF_EXPR:
6371 // a || b
6372 // Predates P0145R3.
6373 case TRUTH_ORIF_EXPR:
6374 // a , b
6375 // Predates P0145R3.
6376 case COMPOUND_EXPR:
6377 return (flag_strong_eval_order ? 1 : 0);
6379 default:
6380 return 0;
6384 /* Subroutine of build_new_op: Add to CANDIDATES all candidates for the
6385 operator indicated by CODE/CODE2. This function calls itself recursively to
6386 handle C++20 rewritten comparison operator candidates.
6388 LOOKUPS, if non-NULL, is the set of pertinent namespace-scope operator
6389 overloads to consider. This parameter is used when instantiating a
6390 dependent operator expression and has the same structure as
6391 DEPENDENT_OPERATOR_TYPE_SAVED_LOOKUPS. */
6393 static tree
6394 add_operator_candidates (z_candidate **candidates,
6395 tree_code code, tree_code code2,
6396 vec<tree, va_gc> *arglist, tree lookups,
6397 int flags, tsubst_flags_t complain)
6399 z_candidate *start_candidates = *candidates;
6400 bool ismodop = code2 != ERROR_MARK;
6401 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
6403 /* LOOKUP_REWRITTEN is set when we're looking for the == or <=> operator to
6404 rewrite from, and also when we're looking for the e.g. < operator to use
6405 on the result of <=>. In the latter case, we don't want the flag set in
6406 the candidate, we just want to suppress looking for rewrites. */
6407 bool rewritten = (flags & LOOKUP_REWRITTEN);
6408 if (rewritten && code != EQ_EXPR && code != SPACESHIP_EXPR)
6409 flags &= ~LOOKUP_REWRITTEN;
6411 bool memonly = false;
6412 switch (code)
6414 /* =, ->, [], () must be non-static member functions. */
6415 case MODIFY_EXPR:
6416 if (code2 != NOP_EXPR)
6417 break;
6418 /* FALLTHRU */
6419 case COMPONENT_REF:
6420 case ARRAY_REF:
6421 memonly = true;
6422 break;
6424 default:
6425 break;
6428 /* Add namespace-scope operators to the list of functions to
6429 consider. */
6430 if (!memonly)
6432 tree fns;
6433 if (!lookups)
6434 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
6435 /* If LOOKUPS is non-NULL, then we're instantiating a dependent operator
6436 expression, and LOOKUPS is the result of stage 1 name lookup. */
6437 else if (tree found = purpose_member (fnname, lookups))
6438 fns = TREE_VALUE (found);
6439 else
6440 fns = NULL_TREE;
6441 fns = lookup_arg_dependent (fnname, fns, arglist);
6442 add_candidates (fns, NULL_TREE, arglist, NULL_TREE,
6443 NULL_TREE, false, NULL_TREE, NULL_TREE,
6444 flags, candidates, complain);
6447 /* Add class-member operators to the candidate set. */
6448 tree arg1_type = TREE_TYPE ((*arglist)[0]);
6449 unsigned nargs = arglist->length () > 1 ? 2 : 1;
6450 tree arg2_type = nargs > 1 ? TREE_TYPE ((*arglist)[1]) : NULL_TREE;
6451 if (CLASS_TYPE_P (arg1_type))
6453 tree fns = lookup_fnfields (arg1_type, fnname, 1, complain);
6454 if (fns == error_mark_node)
6455 return error_mark_node;
6456 if (fns)
6457 add_candidates (BASELINK_FUNCTIONS (fns),
6458 NULL_TREE, arglist, NULL_TREE,
6459 NULL_TREE, false,
6460 BASELINK_BINFO (fns),
6461 BASELINK_ACCESS_BINFO (fns),
6462 flags, candidates, complain);
6464 /* Per [over.match.oper]3.2, if no operand has a class type, then
6465 only non-member functions that have type T1 or reference to
6466 cv-qualified-opt T1 for the first argument, if the first argument
6467 has an enumeration type, or T2 or reference to cv-qualified-opt
6468 T2 for the second argument, if the second argument has an
6469 enumeration type. Filter out those that don't match. */
6470 else if (! arg2_type || ! CLASS_TYPE_P (arg2_type))
6472 struct z_candidate **candp, **next;
6474 for (candp = candidates; *candp != start_candidates; candp = next)
6476 unsigned i;
6477 z_candidate *cand = *candp;
6478 next = &cand->next;
6480 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
6482 for (i = 0; i < nargs; ++i)
6484 tree parmtype = TREE_VALUE (parmlist);
6485 tree argtype = unlowered_expr_type ((*arglist)[i]);
6487 if (TYPE_REF_P (parmtype))
6488 parmtype = TREE_TYPE (parmtype);
6489 if (TREE_CODE (argtype) == ENUMERAL_TYPE
6490 && (same_type_ignoring_top_level_qualifiers_p
6491 (argtype, parmtype)))
6492 break;
6494 parmlist = TREE_CHAIN (parmlist);
6497 /* No argument has an appropriate type, so remove this
6498 candidate function from the list. */
6499 if (i == nargs)
6501 *candp = cand->next;
6502 next = candp;
6507 if (!rewritten)
6509 /* The standard says to rewrite built-in candidates, too,
6510 but there's no point. */
6511 add_builtin_candidates (candidates, code, code2, fnname, arglist,
6512 flags, complain);
6514 /* Maybe add C++20 rewritten comparison candidates. */
6515 tree_code rewrite_code = ERROR_MARK;
6516 if (cxx_dialect >= cxx20
6517 && nargs == 2
6518 && (OVERLOAD_TYPE_P (arg1_type) || OVERLOAD_TYPE_P (arg2_type)))
6519 switch (code)
6521 case LT_EXPR:
6522 case LE_EXPR:
6523 case GT_EXPR:
6524 case GE_EXPR:
6525 case SPACESHIP_EXPR:
6526 rewrite_code = SPACESHIP_EXPR;
6527 break;
6529 case NE_EXPR:
6530 case EQ_EXPR:
6531 rewrite_code = EQ_EXPR;
6532 break;
6534 default:;
6537 if (rewrite_code)
6539 flags |= LOOKUP_REWRITTEN;
6540 if (rewrite_code != code)
6541 /* Add rewritten candidates in same order. */
6542 add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
6543 arglist, lookups, flags, complain);
6545 z_candidate *save_cand = *candidates;
6547 /* Add rewritten candidates in reverse order. */
6548 flags |= LOOKUP_REVERSED;
6549 vec<tree,va_gc> *revlist = make_tree_vector ();
6550 revlist->quick_push ((*arglist)[1]);
6551 revlist->quick_push ((*arglist)[0]);
6552 add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
6553 revlist, lookups, flags, complain);
6555 /* Release the vec if we didn't add a candidate that uses it. */
6556 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
6557 if (c->args == revlist)
6559 revlist = NULL;
6560 break;
6562 release_tree_vector (revlist);
6566 return NULL_TREE;
6569 tree
6570 build_new_op (const op_location_t &loc, enum tree_code code, int flags,
6571 tree arg1, tree arg2, tree arg3, tree lookups,
6572 tree *overload, tsubst_flags_t complain)
6574 struct z_candidate *candidates = 0, *cand;
6575 releasing_vec arglist;
6576 tree result = NULL_TREE;
6577 bool result_valid_p = false;
6578 enum tree_code code2 = ERROR_MARK;
6579 enum tree_code code_orig_arg1 = ERROR_MARK;
6580 enum tree_code code_orig_arg2 = ERROR_MARK;
6581 void *p;
6582 bool strict_p;
6583 bool any_viable_p;
6585 auto_cond_timevar tv (TV_OVERLOAD);
6587 if (error_operand_p (arg1)
6588 || error_operand_p (arg2)
6589 || error_operand_p (arg3))
6590 return error_mark_node;
6592 bool ismodop = code == MODIFY_EXPR;
6593 if (ismodop)
6595 code2 = TREE_CODE (arg3);
6596 arg3 = NULL_TREE;
6599 tree arg1_type = unlowered_expr_type (arg1);
6600 tree arg2_type = arg2 ? unlowered_expr_type (arg2) : NULL_TREE;
6602 arg1 = prep_operand (arg1);
6604 switch (code)
6606 case NEW_EXPR:
6607 case VEC_NEW_EXPR:
6608 case VEC_DELETE_EXPR:
6609 case DELETE_EXPR:
6610 /* Use build_operator_new_call and build_op_delete_call instead. */
6611 gcc_unreachable ();
6613 case CALL_EXPR:
6614 /* Use build_op_call instead. */
6615 gcc_unreachable ();
6617 case TRUTH_ORIF_EXPR:
6618 case TRUTH_ANDIF_EXPR:
6619 case TRUTH_AND_EXPR:
6620 case TRUTH_OR_EXPR:
6621 /* These are saved for the sake of warn_logical_operator. */
6622 code_orig_arg1 = TREE_CODE (arg1);
6623 code_orig_arg2 = TREE_CODE (arg2);
6624 break;
6625 case GT_EXPR:
6626 case LT_EXPR:
6627 case GE_EXPR:
6628 case LE_EXPR:
6629 case EQ_EXPR:
6630 case NE_EXPR:
6631 /* These are saved for the sake of maybe_warn_bool_compare. */
6632 code_orig_arg1 = TREE_CODE (arg1_type);
6633 code_orig_arg2 = TREE_CODE (arg2_type);
6634 break;
6636 default:
6637 break;
6640 arg2 = prep_operand (arg2);
6641 arg3 = prep_operand (arg3);
6643 if (code == COND_EXPR)
6644 /* Use build_conditional_expr instead. */
6645 gcc_unreachable ();
6646 else if (! OVERLOAD_TYPE_P (arg1_type)
6647 && (! arg2 || ! OVERLOAD_TYPE_P (arg2_type)))
6648 goto builtin;
6650 if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
6652 arg2 = integer_zero_node;
6653 arg2_type = integer_type_node;
6656 arglist->quick_push (arg1);
6657 if (arg2 != NULL_TREE)
6658 arglist->quick_push (arg2);
6659 if (arg3 != NULL_TREE)
6660 arglist->quick_push (arg3);
6662 /* Get the high-water mark for the CONVERSION_OBSTACK. */
6663 p = conversion_obstack_alloc (0);
6665 result = add_operator_candidates (&candidates, code, code2, arglist,
6666 lookups, flags, complain);
6667 if (result == error_mark_node)
6668 goto user_defined_result_ready;
6670 switch (code)
6672 case COMPOUND_EXPR:
6673 case ADDR_EXPR:
6674 /* For these, the built-in candidates set is empty
6675 [over.match.oper]/3. We don't want non-strict matches
6676 because exact matches are always possible with built-in
6677 operators. The built-in candidate set for COMPONENT_REF
6678 would be empty too, but since there are no such built-in
6679 operators, we accept non-strict matches for them. */
6680 strict_p = true;
6681 break;
6683 default:
6684 strict_p = false;
6685 break;
6688 candidates = splice_viable (candidates, strict_p, &any_viable_p);
6689 if (!any_viable_p)
6691 switch (code)
6693 case POSTINCREMENT_EXPR:
6694 case POSTDECREMENT_EXPR:
6695 /* Don't try anything fancy if we're not allowed to produce
6696 errors. */
6697 if (!(complain & tf_error))
6698 return error_mark_node;
6700 /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
6701 distinguish between prefix and postfix ++ and
6702 operator++() was used for both, so we allow this with
6703 -fpermissive. */
6704 else
6706 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
6707 const char *msg = (flag_permissive)
6708 ? G_("no %<%D(int)%> declared for postfix %qs,"
6709 " trying prefix operator instead")
6710 : G_("no %<%D(int)%> declared for postfix %qs");
6711 permerror (loc, msg, fnname, OVL_OP_INFO (false, code)->name);
6714 if (!flag_permissive)
6715 return error_mark_node;
6717 if (code == POSTINCREMENT_EXPR)
6718 code = PREINCREMENT_EXPR;
6719 else
6720 code = PREDECREMENT_EXPR;
6721 result = build_new_op (loc, code, flags, arg1, NULL_TREE,
6722 NULL_TREE, lookups, overload, complain);
6723 break;
6725 /* The caller will deal with these. */
6726 case ADDR_EXPR:
6727 case COMPOUND_EXPR:
6728 case COMPONENT_REF:
6729 case CO_AWAIT_EXPR:
6730 result = NULL_TREE;
6731 result_valid_p = true;
6732 break;
6734 default:
6735 if (complain & tf_error)
6737 /* If one of the arguments of the operator represents
6738 an invalid use of member function pointer, try to report
6739 a meaningful error ... */
6740 if (invalid_nonstatic_memfn_p (loc, arg1, tf_error)
6741 || invalid_nonstatic_memfn_p (loc, arg2, tf_error)
6742 || invalid_nonstatic_memfn_p (loc, arg3, tf_error))
6743 /* We displayed the error message. */;
6744 else
6746 /* ... Otherwise, report the more generic
6747 "no matching operator found" error */
6748 auto_diagnostic_group d;
6749 op_error (loc, code, code2, arg1, arg2, arg3, FALSE);
6750 print_z_candidates (loc, candidates);
6753 result = error_mark_node;
6754 break;
6757 else
6759 cand = tourney (candidates, complain);
6760 if (cand == 0)
6762 if (complain & tf_error)
6764 auto_diagnostic_group d;
6765 op_error (loc, code, code2, arg1, arg2, arg3, TRUE);
6766 print_z_candidates (loc, candidates);
6768 result = error_mark_node;
6769 if (overload)
6770 *overload = error_mark_node;
6772 else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
6774 if (overload)
6775 *overload = cand->fn;
6777 if (resolve_args (arglist, complain) == NULL)
6778 result = error_mark_node;
6779 else
6781 tsubst_flags_t ocomplain = complain;
6782 if (cand->rewritten ())
6783 /* We'll wrap this call in another one. */
6784 ocomplain &= ~tf_decltype;
6785 if (cand->reversed ())
6787 /* We swapped these in add_candidate, swap them back now. */
6788 std::swap (cand->convs[0], cand->convs[1]);
6789 if (cand->fn == current_function_decl)
6790 warning_at (loc, 0, "in C++20 this comparison calls the "
6791 "current function recursively with reversed "
6792 "arguments");
6794 result = build_over_call (cand, LOOKUP_NORMAL, ocomplain);
6797 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
6798 /* There won't be a CALL_EXPR. */;
6799 else if (result && result != error_mark_node)
6801 tree call = extract_call_expr (result);
6802 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
6804 /* Specify evaluation order as per P0145R2. */
6805 CALL_EXPR_ORDERED_ARGS (call) = false;
6806 switch (op_is_ordered (code))
6808 case -1:
6809 CALL_EXPR_REVERSE_ARGS (call) = true;
6810 break;
6812 case 1:
6813 CALL_EXPR_ORDERED_ARGS (call) = true;
6814 break;
6816 default:
6817 break;
6821 /* If this was a C++20 rewritten comparison, adjust the result. */
6822 if (cand->rewritten ())
6824 /* FIXME build_min_non_dep_op_overload can't handle rewrites. */
6825 if (overload)
6826 *overload = NULL_TREE;
6827 switch (code)
6829 case EQ_EXPR:
6830 gcc_checking_assert (cand->reversed ());
6831 gcc_fallthrough ();
6832 case NE_EXPR:
6833 /* If a rewritten operator== candidate is selected by
6834 overload resolution for an operator @, its return type
6835 shall be cv bool.... */
6836 if (TREE_CODE (TREE_TYPE (result)) != BOOLEAN_TYPE)
6838 if (complain & tf_error)
6840 auto_diagnostic_group d;
6841 error_at (loc, "return type of %qD is not %qs",
6842 cand->fn, "bool");
6843 inform (loc, "used as rewritten candidate for "
6844 "comparison of %qT and %qT",
6845 arg1_type, arg2_type);
6847 result = error_mark_node;
6849 else if (code == NE_EXPR)
6850 /* !(y == x) or !(x == y) */
6851 result = build1_loc (loc, TRUTH_NOT_EXPR,
6852 boolean_type_node, result);
6853 break;
6855 /* If a rewritten operator<=> candidate is selected by
6856 overload resolution for an operator @, x @ y is
6857 interpreted as 0 @ (y <=> x) if the selected candidate is
6858 a synthesized candidate with reversed order of parameters,
6859 or (x <=> y) @ 0 otherwise, using the selected rewritten
6860 operator<=> candidate. */
6861 case SPACESHIP_EXPR:
6862 if (!cand->reversed ())
6863 /* We're in the build_new_op call below for an outer
6864 reversed call; we don't need to do anything more. */
6865 break;
6866 gcc_fallthrough ();
6867 case LT_EXPR:
6868 case LE_EXPR:
6869 case GT_EXPR:
6870 case GE_EXPR:
6872 tree lhs = result;
6873 tree rhs = integer_zero_node;
6874 if (cand->reversed ())
6875 std::swap (lhs, rhs);
6876 warning_sentinel ws (warn_zero_as_null_pointer_constant);
6877 result = build_new_op (loc, code,
6878 LOOKUP_NORMAL|LOOKUP_REWRITTEN,
6879 lhs, rhs, NULL_TREE, lookups,
6880 NULL, complain);
6882 break;
6884 default:
6885 gcc_unreachable ();
6889 else
6891 /* Give any warnings we noticed during overload resolution. */
6892 if (cand->warnings && (complain & tf_warning))
6894 struct candidate_warning *w;
6895 for (w = cand->warnings; w; w = w->next)
6896 joust (cand, w->loser, 1, complain);
6899 /* Check for comparison of different enum types. */
6900 switch (code)
6902 case GT_EXPR:
6903 case LT_EXPR:
6904 case GE_EXPR:
6905 case LE_EXPR:
6906 case EQ_EXPR:
6907 case NE_EXPR:
6908 if (TREE_CODE (arg1_type) == ENUMERAL_TYPE
6909 && TREE_CODE (arg2_type) == ENUMERAL_TYPE
6910 && (TYPE_MAIN_VARIANT (arg1_type)
6911 != TYPE_MAIN_VARIANT (arg2_type))
6912 && (complain & tf_warning))
6913 warning_at (loc, OPT_Wenum_compare,
6914 "comparison between %q#T and %q#T",
6915 arg1_type, arg2_type);
6916 break;
6917 default:
6918 break;
6921 /* "If a built-in candidate is selected by overload resolution, the
6922 operands of class type are converted to the types of the
6923 corresponding parameters of the selected operation function,
6924 except that the second standard conversion sequence of a
6925 user-defined conversion sequence (12.3.3.1.2) is not applied." */
6926 conversion *conv = cand->convs[0];
6927 if (conv->user_conv_p)
6929 conv = strip_standard_conversion (conv);
6930 arg1 = convert_like (conv, arg1, complain);
6933 if (arg2)
6935 conv = cand->convs[1];
6936 if (conv->user_conv_p)
6938 conv = strip_standard_conversion (conv);
6939 arg2 = convert_like (conv, arg2, complain);
6943 if (arg3)
6945 conv = cand->convs[2];
6946 if (conv->user_conv_p)
6948 conv = strip_standard_conversion (conv);
6949 arg3 = convert_like (conv, arg3, complain);
6955 user_defined_result_ready:
6957 /* Free all the conversions we allocated. */
6958 obstack_free (&conversion_obstack, p);
6960 if (result || result_valid_p)
6961 return result;
6963 builtin:
6964 switch (code)
6966 case MODIFY_EXPR:
6967 return cp_build_modify_expr (loc, arg1, code2, arg2, complain);
6969 case INDIRECT_REF:
6970 return cp_build_indirect_ref (loc, arg1, RO_UNARY_STAR, complain);
6972 case TRUTH_ANDIF_EXPR:
6973 case TRUTH_ORIF_EXPR:
6974 case TRUTH_AND_EXPR:
6975 case TRUTH_OR_EXPR:
6976 if (complain & tf_warning)
6977 warn_logical_operator (loc, code, boolean_type_node,
6978 code_orig_arg1, arg1,
6979 code_orig_arg2, arg2);
6980 /* Fall through. */
6981 case GT_EXPR:
6982 case LT_EXPR:
6983 case GE_EXPR:
6984 case LE_EXPR:
6985 case EQ_EXPR:
6986 case NE_EXPR:
6987 if ((complain & tf_warning)
6988 && ((code_orig_arg1 == BOOLEAN_TYPE)
6989 ^ (code_orig_arg2 == BOOLEAN_TYPE)))
6990 maybe_warn_bool_compare (loc, code, arg1, arg2);
6991 if (complain & tf_warning && warn_tautological_compare)
6992 warn_tautological_cmp (loc, code, arg1, arg2);
6993 /* Fall through. */
6994 case SPACESHIP_EXPR:
6995 case PLUS_EXPR:
6996 case MINUS_EXPR:
6997 case MULT_EXPR:
6998 case TRUNC_DIV_EXPR:
6999 case MAX_EXPR:
7000 case MIN_EXPR:
7001 case LSHIFT_EXPR:
7002 case RSHIFT_EXPR:
7003 case TRUNC_MOD_EXPR:
7004 case BIT_AND_EXPR:
7005 case BIT_IOR_EXPR:
7006 case BIT_XOR_EXPR:
7007 return cp_build_binary_op (loc, code, arg1, arg2, complain);
7009 case UNARY_PLUS_EXPR:
7010 case NEGATE_EXPR:
7011 case BIT_NOT_EXPR:
7012 case TRUTH_NOT_EXPR:
7013 case PREINCREMENT_EXPR:
7014 case POSTINCREMENT_EXPR:
7015 case PREDECREMENT_EXPR:
7016 case POSTDECREMENT_EXPR:
7017 case REALPART_EXPR:
7018 case IMAGPART_EXPR:
7019 case ABS_EXPR:
7020 case CO_AWAIT_EXPR:
7021 return cp_build_unary_op (code, arg1, false, complain);
7023 case ARRAY_REF:
7024 return cp_build_array_ref (input_location, arg1, arg2, complain);
7026 case MEMBER_REF:
7027 return build_m_component_ref (cp_build_indirect_ref (loc, arg1,
7028 RO_ARROW_STAR,
7029 complain),
7030 arg2, complain);
7032 /* The caller will deal with these. */
7033 case ADDR_EXPR:
7034 case COMPONENT_REF:
7035 case COMPOUND_EXPR:
7036 return NULL_TREE;
7038 default:
7039 gcc_unreachable ();
7041 return NULL_TREE;
7044 /* Build a new call to operator[]. This may change ARGS. */
7046 tree
7047 build_op_subscript (const op_location_t &loc, tree obj,
7048 vec<tree, va_gc> **args, tree *overload,
7049 tsubst_flags_t complain)
7051 struct z_candidate *candidates = 0, *cand;
7052 tree fns, first_mem_arg = NULL_TREE;
7053 bool any_viable_p;
7054 tree result = NULL_TREE;
7055 void *p;
7057 auto_cond_timevar tv (TV_OVERLOAD);
7059 obj = mark_lvalue_use (obj);
7061 if (error_operand_p (obj))
7062 return error_mark_node;
7064 tree type = TREE_TYPE (obj);
7066 obj = prep_operand (obj);
7068 if (TYPE_BINFO (type))
7070 fns = lookup_fnfields (TYPE_BINFO (type), ovl_op_identifier (ARRAY_REF),
7071 1, complain);
7072 if (fns == error_mark_node)
7073 return error_mark_node;
7075 else
7076 fns = NULL_TREE;
7078 if (args != NULL && *args != NULL)
7080 *args = resolve_args (*args, complain);
7081 if (*args == NULL)
7082 return error_mark_node;
7085 /* Get the high-water mark for the CONVERSION_OBSTACK. */
7086 p = conversion_obstack_alloc (0);
7088 if (fns)
7090 first_mem_arg = obj;
7092 add_candidates (BASELINK_FUNCTIONS (fns),
7093 first_mem_arg, *args, NULL_TREE,
7094 NULL_TREE, false,
7095 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
7096 LOOKUP_NORMAL, &candidates, complain);
7099 /* Be strict here because if we choose a bad conversion candidate, the
7100 errors we get won't mention the call context. */
7101 candidates = splice_viable (candidates, true, &any_viable_p);
7102 if (!any_viable_p)
7104 if (complain & tf_error)
7106 auto_diagnostic_group d;
7107 error ("no match for call to %<%T::operator[] (%A)%>",
7108 TREE_TYPE (obj), build_tree_list_vec (*args));
7109 print_z_candidates (loc, candidates);
7111 result = error_mark_node;
7113 else
7115 cand = tourney (candidates, complain);
7116 if (cand == 0)
7118 if (complain & tf_error)
7120 auto_diagnostic_group d;
7121 error ("call of %<%T::operator[] (%A)%> is ambiguous",
7122 TREE_TYPE (obj), build_tree_list_vec (*args));
7123 print_z_candidates (loc, candidates);
7125 result = error_mark_node;
7127 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
7128 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
7129 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, ARRAY_REF))
7131 if (overload)
7132 *overload = cand->fn;
7133 result = build_over_call (cand, LOOKUP_NORMAL, complain);
7134 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7135 /* There won't be a CALL_EXPR. */;
7136 else if (result && result != error_mark_node)
7138 tree call = extract_call_expr (result);
7139 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7141 /* Specify evaluation order as per P0145R2. */
7142 CALL_EXPR_ORDERED_ARGS (call) = op_is_ordered (ARRAY_REF) == 1;
7145 else
7146 gcc_unreachable ();
7149 /* Free all the conversions we allocated. */
7150 obstack_free (&conversion_obstack, p);
7152 return result;
7155 /* CALL was returned by some call-building function; extract the actual
7156 CALL_EXPR from any bits that have been tacked on, e.g. by
7157 convert_from_reference. */
7159 tree
7160 extract_call_expr (tree call)
7162 while (TREE_CODE (call) == COMPOUND_EXPR)
7163 call = TREE_OPERAND (call, 1);
7164 if (REFERENCE_REF_P (call))
7165 call = TREE_OPERAND (call, 0);
7166 if (TREE_CODE (call) == TARGET_EXPR)
7167 call = TARGET_EXPR_INITIAL (call);
7168 if (cxx_dialect >= cxx20)
7169 switch (TREE_CODE (call))
7171 /* C++20 rewritten comparison operators. */
7172 case TRUTH_NOT_EXPR:
7173 call = TREE_OPERAND (call, 0);
7174 break;
7175 case LT_EXPR:
7176 case LE_EXPR:
7177 case GT_EXPR:
7178 case GE_EXPR:
7179 case SPACESHIP_EXPR:
7181 tree op0 = TREE_OPERAND (call, 0);
7182 if (integer_zerop (op0))
7183 call = TREE_OPERAND (call, 1);
7184 else
7185 call = op0;
7187 break;
7188 default:;
7191 if (TREE_CODE (call) != CALL_EXPR
7192 && TREE_CODE (call) != AGGR_INIT_EXPR
7193 && call != error_mark_node)
7194 return NULL_TREE;
7195 return call;
7198 /* Returns true if FN has two parameters, of which the second has type
7199 size_t. */
7201 static bool
7202 second_parm_is_size_t (tree fn)
7204 tree t = FUNCTION_ARG_CHAIN (fn);
7205 if (!t || !same_type_p (TREE_VALUE (t), size_type_node))
7206 return false;
7207 t = TREE_CHAIN (t);
7208 if (t == void_list_node)
7209 return true;
7210 return false;
7213 /* True if T, an allocation function, has std::align_val_t as its second
7214 argument. */
7216 bool
7217 aligned_allocation_fn_p (tree t)
7219 if (!aligned_new_threshold)
7220 return false;
7222 tree a = FUNCTION_ARG_CHAIN (t);
7223 return (a && same_type_p (TREE_VALUE (a), align_type_node));
7226 /* True if T is std::destroying_delete_t. */
7228 static bool
7229 std_destroying_delete_t_p (tree t)
7231 return (TYPE_CONTEXT (t) == std_node
7232 && id_equal (TYPE_IDENTIFIER (t), "destroying_delete_t"));
7235 /* A deallocation function with at least two parameters whose second parameter
7236 type is of type std::destroying_delete_t is a destroying operator delete. A
7237 destroying operator delete shall be a class member function named operator
7238 delete. [ Note: Array deletion cannot use a destroying operator
7239 delete. --end note ] */
7241 tree
7242 destroying_delete_p (tree t)
7244 tree a = TYPE_ARG_TYPES (TREE_TYPE (t));
7245 if (!a || !TREE_CHAIN (a))
7246 return NULL_TREE;
7247 tree type = TREE_VALUE (TREE_CHAIN (a));
7248 return std_destroying_delete_t_p (type) ? type : NULL_TREE;
7251 struct dealloc_info
7253 bool sized;
7254 bool aligned;
7255 tree destroying;
7258 /* Returns true iff T, an element of an OVERLOAD chain, is a usual deallocation
7259 function (3.7.4.2 [basic.stc.dynamic.deallocation]). If so, and DI is
7260 non-null, also set *DI. */
7262 static bool
7263 usual_deallocation_fn_p (tree t, dealloc_info *di)
7265 if (di) *di = dealloc_info();
7267 /* A template instance is never a usual deallocation function,
7268 regardless of its signature. */
7269 if (TREE_CODE (t) == TEMPLATE_DECL
7270 || primary_template_specialization_p (t))
7271 return false;
7273 /* A usual deallocation function is a deallocation function whose parameters
7274 after the first are
7275 - optionally, a parameter of type std::destroying_delete_t, then
7276 - optionally, a parameter of type std::size_t, then
7277 - optionally, a parameter of type std::align_val_t. */
7278 bool global = DECL_NAMESPACE_SCOPE_P (t);
7279 tree chain = FUNCTION_ARG_CHAIN (t);
7280 if (chain && destroying_delete_p (t))
7282 if (di) di->destroying = TREE_VALUE (chain);
7283 chain = TREE_CHAIN (chain);
7285 if (chain
7286 && (!global || flag_sized_deallocation)
7287 && same_type_p (TREE_VALUE (chain), size_type_node))
7289 if (di) di->sized = true;
7290 chain = TREE_CHAIN (chain);
7292 if (chain && aligned_new_threshold
7293 && same_type_p (TREE_VALUE (chain), align_type_node))
7295 if (di) di->aligned = true;
7296 chain = TREE_CHAIN (chain);
7298 return (chain == void_list_node);
7301 /* Just return whether FN is a usual deallocation function. */
7303 bool
7304 usual_deallocation_fn_p (tree fn)
7306 return usual_deallocation_fn_p (fn, NULL);
7309 /* Build a call to operator delete. This has to be handled very specially,
7310 because the restrictions on what signatures match are different from all
7311 other call instances. For a normal delete, only a delete taking (void *)
7312 or (void *, size_t) is accepted. For a placement delete, only an exact
7313 match with the placement new is accepted.
7315 CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
7316 ADDR is the pointer to be deleted.
7317 SIZE is the size of the memory block to be deleted.
7318 GLOBAL_P is true if the delete-expression should not consider
7319 class-specific delete operators.
7320 PLACEMENT is the corresponding placement new call, or NULL_TREE.
7322 If this call to "operator delete" is being generated as part to
7323 deallocate memory allocated via a new-expression (as per [expr.new]
7324 which requires that if the initialization throws an exception then
7325 we call a deallocation function), then ALLOC_FN is the allocation
7326 function. */
7328 tree
7329 build_op_delete_call (enum tree_code code, tree addr, tree size,
7330 bool global_p, tree placement,
7331 tree alloc_fn, tsubst_flags_t complain)
7333 tree fn = NULL_TREE;
7334 tree fns, fnname, type, t;
7335 dealloc_info di_fn = { };
7337 if (addr == error_mark_node)
7338 return error_mark_node;
7340 type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
7342 fnname = ovl_op_identifier (false, code);
7344 if (CLASS_TYPE_P (type)
7345 && COMPLETE_TYPE_P (complete_type (type))
7346 && !global_p)
7347 /* In [class.free]
7349 If the result of the lookup is ambiguous or inaccessible, or if
7350 the lookup selects a placement deallocation function, the
7351 program is ill-formed.
7353 Therefore, we ask lookup_fnfields to complain about ambiguity. */
7355 fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1, complain);
7356 if (fns == error_mark_node)
7357 return error_mark_node;
7359 else
7360 fns = NULL_TREE;
7362 if (fns == NULL_TREE)
7363 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
7365 /* Strip const and volatile from addr. */
7366 tree oaddr = addr;
7367 addr = cp_convert (ptr_type_node, addr, complain);
7369 tree excluded_destroying = NULL_TREE;
7371 if (placement)
7373 /* "A declaration of a placement deallocation function matches the
7374 declaration of a placement allocation function if it has the same
7375 number of parameters and, after parameter transformations (8.3.5),
7376 all parameter types except the first are identical."
7378 So we build up the function type we want and ask instantiate_type
7379 to get it for us. */
7380 t = FUNCTION_ARG_CHAIN (alloc_fn);
7381 t = tree_cons (NULL_TREE, ptr_type_node, t);
7382 t = build_function_type (void_type_node, t);
7384 fn = instantiate_type (t, fns, tf_none);
7385 if (fn == error_mark_node)
7386 return NULL_TREE;
7388 fn = MAYBE_BASELINK_FUNCTIONS (fn);
7390 /* "If the lookup finds the two-parameter form of a usual deallocation
7391 function (3.7.4.2) and that function, considered as a placement
7392 deallocation function, would have been selected as a match for the
7393 allocation function, the program is ill-formed." */
7394 if (second_parm_is_size_t (fn))
7396 const char *const msg1
7397 = G_("exception cleanup for this placement new selects "
7398 "non-placement %<operator delete%>");
7399 const char *const msg2
7400 = G_("%qD is a usual (non-placement) deallocation "
7401 "function in C++14 (or with %<-fsized-deallocation%>)");
7403 /* But if the class has an operator delete (void *), then that is
7404 the usual deallocation function, so we shouldn't complain
7405 about using the operator delete (void *, size_t). */
7406 if (DECL_CLASS_SCOPE_P (fn))
7407 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7409 if (usual_deallocation_fn_p (elt)
7410 && FUNCTION_ARG_CHAIN (elt) == void_list_node)
7411 goto ok;
7413 /* Before C++14 a two-parameter global deallocation function is
7414 always a placement deallocation function, but warn if
7415 -Wc++14-compat. */
7416 else if (!flag_sized_deallocation)
7418 if (complain & tf_warning)
7420 auto_diagnostic_group d;
7421 if (warning (OPT_Wc__14_compat, msg1))
7422 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7424 goto ok;
7427 if (complain & tf_warning_or_error)
7429 auto_diagnostic_group d;
7430 if (permerror (input_location, msg1))
7432 /* Only mention C++14 for namespace-scope delete. */
7433 if (DECL_NAMESPACE_SCOPE_P (fn))
7434 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7435 else
7436 inform (DECL_SOURCE_LOCATION (fn),
7437 "%qD is a usual (non-placement) deallocation "
7438 "function", fn);
7441 else
7442 return error_mark_node;
7443 ok:;
7446 else
7447 /* "Any non-placement deallocation function matches a non-placement
7448 allocation function. If the lookup finds a single matching
7449 deallocation function, that function will be called; otherwise, no
7450 deallocation function will be called." */
7451 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7453 dealloc_info di_elt;
7454 if (usual_deallocation_fn_p (elt, &di_elt))
7456 /* If we're called for an EH cleanup in a new-expression, we can't
7457 use a destroying delete; the exception was thrown before the
7458 object was constructed. */
7459 if (alloc_fn && di_elt.destroying)
7461 excluded_destroying = elt;
7462 continue;
7465 if (!fn)
7467 fn = elt;
7468 di_fn = di_elt;
7469 continue;
7472 /* -- If any of the deallocation functions is a destroying
7473 operator delete, all deallocation functions that are not
7474 destroying operator deletes are eliminated from further
7475 consideration. */
7476 if (di_elt.destroying != di_fn.destroying)
7478 if (di_elt.destroying)
7480 fn = elt;
7481 di_fn = di_elt;
7483 continue;
7486 /* -- If the type has new-extended alignment, a function with a
7487 parameter of type std::align_val_t is preferred; otherwise a
7488 function without such a parameter is preferred. If exactly one
7489 preferred function is found, that function is selected and the
7490 selection process terminates. If more than one preferred
7491 function is found, all non-preferred functions are eliminated
7492 from further consideration. */
7493 if (aligned_new_threshold)
7495 bool want_align = type_has_new_extended_alignment (type);
7496 if (di_elt.aligned != di_fn.aligned)
7498 if (want_align == di_elt.aligned)
7500 fn = elt;
7501 di_fn = di_elt;
7503 continue;
7507 /* -- If the deallocation functions have class scope, the one
7508 without a parameter of type std::size_t is selected. */
7509 bool want_size;
7510 if (DECL_CLASS_SCOPE_P (fn))
7511 want_size = false;
7513 /* -- If the type is complete and if, for the second alternative
7514 (delete array) only, the operand is a pointer to a class type
7515 with a non-trivial destructor or a (possibly multi-dimensional)
7516 array thereof, the function with a parameter of type std::size_t
7517 is selected.
7519 -- Otherwise, it is unspecified whether a deallocation function
7520 with a parameter of type std::size_t is selected. */
7521 else
7523 want_size = COMPLETE_TYPE_P (type);
7524 if (code == VEC_DELETE_EXPR
7525 && !TYPE_VEC_NEW_USES_COOKIE (type))
7526 /* We need a cookie to determine the array size. */
7527 want_size = false;
7529 gcc_assert (di_fn.sized != di_elt.sized);
7530 if (want_size == di_elt.sized)
7532 fn = elt;
7533 di_fn = di_elt;
7538 /* If we have a matching function, call it. */
7539 if (fn)
7541 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
7543 /* If the FN is a member function, make sure that it is
7544 accessible. */
7545 if (BASELINK_P (fns))
7546 perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn,
7547 complain);
7549 /* Core issue 901: It's ok to new a type with deleted delete. */
7550 if (DECL_DELETED_FN (fn) && alloc_fn)
7551 return NULL_TREE;
7553 tree ret;
7554 if (placement)
7556 /* The placement args might not be suitable for overload
7557 resolution at this point, so build the call directly. */
7558 int nargs = call_expr_nargs (placement);
7559 tree *argarray = XALLOCAVEC (tree, nargs);
7560 int i;
7561 argarray[0] = addr;
7562 for (i = 1; i < nargs; i++)
7563 argarray[i] = CALL_EXPR_ARG (placement, i);
7564 if (!mark_used (fn, complain) && !(complain & tf_error))
7565 return error_mark_node;
7566 ret = build_cxx_call (fn, nargs, argarray, complain);
7568 else
7570 tree destroying = di_fn.destroying;
7571 if (destroying)
7573 /* Strip const and volatile from addr but retain the type of the
7574 object. */
7575 tree rtype = TREE_TYPE (TREE_TYPE (oaddr));
7576 rtype = cv_unqualified (rtype);
7577 rtype = TYPE_POINTER_TO (rtype);
7578 addr = cp_convert (rtype, oaddr, complain);
7579 destroying = build_functional_cast (input_location,
7580 destroying, NULL_TREE,
7581 complain);
7584 releasing_vec args;
7585 args->quick_push (addr);
7586 if (destroying)
7587 args->quick_push (destroying);
7588 if (di_fn.sized)
7589 args->quick_push (size);
7590 if (di_fn.aligned)
7592 tree al = build_int_cst (align_type_node, TYPE_ALIGN_UNIT (type));
7593 args->quick_push (al);
7595 ret = cp_build_function_call_vec (fn, &args, complain);
7598 /* Set this flag for all callers of this function. In addition to
7599 delete-expressions, this is called for deallocating coroutine state;
7600 treat that as an implicit delete-expression. This is also called for
7601 the delete if the constructor throws in a new-expression, and for a
7602 deleting destructor (which implements a delete-expression). */
7603 /* But leave this flag off for destroying delete to avoid wrong
7604 assumptions in the optimizers. */
7605 tree call = extract_call_expr (ret);
7606 if (TREE_CODE (call) == CALL_EXPR && !destroying_delete_p (fn))
7607 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
7609 return ret;
7612 /* If there's only a destroying delete that we can't use because the
7613 object isn't constructed yet, and we used global new, use global
7614 delete as well. */
7615 if (excluded_destroying
7616 && DECL_NAMESPACE_SCOPE_P (alloc_fn))
7617 return build_op_delete_call (code, addr, size, true, placement,
7618 alloc_fn, complain);
7620 /* [expr.new]
7622 If no unambiguous matching deallocation function can be found,
7623 propagating the exception does not cause the object's memory to
7624 be freed. */
7625 if (alloc_fn)
7627 if ((complain & tf_warning)
7628 && !placement)
7630 bool w = warning (0,
7631 "no corresponding deallocation function for %qD",
7632 alloc_fn);
7633 if (w && excluded_destroying)
7634 inform (DECL_SOURCE_LOCATION (excluded_destroying), "destroying "
7635 "delete %qD cannot be used to release the allocated memory"
7636 " if the initialization throws because the object is not "
7637 "constructed yet", excluded_destroying);
7639 return NULL_TREE;
7642 if (complain & tf_error)
7643 error ("no suitable %<operator %s%> for %qT",
7644 OVL_OP_INFO (false, code)->name, type);
7645 return error_mark_node;
7648 /* Issue diagnostics about a disallowed access of DECL, using DIAG_DECL
7649 in the diagnostics.
7651 If ISSUE_ERROR is true, then issue an error about the access, followed
7652 by a note showing the declaration. Otherwise, just show the note.
7654 DIAG_DECL and DIAG_LOCATION will almost always be the same.
7655 DIAG_LOCATION is just another DECL. NO_ACCESS_REASON is an optional
7656 parameter used to specify why DECL wasn't accessible (e.g. ak_private
7657 would be because DECL was private). If not using NO_ACCESS_REASON,
7658 then it must be ak_none, and the access failure reason will be
7659 figured out by looking at the protection of DECL. */
7661 void
7662 complain_about_access (tree decl, tree diag_decl, tree diag_location,
7663 bool issue_error, access_kind no_access_reason)
7665 /* If we have not already figured out why DECL is inaccessible... */
7666 if (no_access_reason == ak_none)
7668 /* Examine the access of DECL to find out why. */
7669 if (TREE_PRIVATE (decl))
7670 no_access_reason = ak_private;
7671 else if (TREE_PROTECTED (decl))
7672 no_access_reason = ak_protected;
7675 /* Now generate an error message depending on calculated access. */
7676 if (no_access_reason == ak_private)
7678 if (issue_error)
7679 error ("%q#D is private within this context", diag_decl);
7680 inform (DECL_SOURCE_LOCATION (diag_location), "declared private here");
7682 else if (no_access_reason == ak_protected)
7684 if (issue_error)
7685 error ("%q#D is protected within this context", diag_decl);
7686 inform (DECL_SOURCE_LOCATION (diag_location), "declared protected here");
7688 /* Couldn't figure out why DECL is inaccesible, so just say it's
7689 inaccessible. */
7690 else
7692 if (issue_error)
7693 error ("%q#D is inaccessible within this context", diag_decl);
7694 inform (DECL_SOURCE_LOCATION (diag_decl), "declared here");
7698 /* Initialize a temporary of type TYPE with EXPR. The FLAGS are a
7699 bitwise or of LOOKUP_* values. If any errors are warnings are
7700 generated, set *DIAGNOSTIC_FN to "error" or "warning",
7701 respectively. If no diagnostics are generated, set *DIAGNOSTIC_FN
7702 to NULL. */
7704 static tree
7705 build_temp (tree expr, tree type, int flags,
7706 diagnostic_t *diagnostic_kind, tsubst_flags_t complain)
7708 int savew, savee;
7710 *diagnostic_kind = DK_UNSPECIFIED;
7712 /* If the source is a packed field, calling the copy constructor will require
7713 binding the field to the reference parameter to the copy constructor, and
7714 we'll end up with an infinite loop. If we can use a bitwise copy, then
7715 do that now. */
7716 if ((lvalue_kind (expr) & clk_packed)
7717 && CLASS_TYPE_P (TREE_TYPE (expr))
7718 && !type_has_nontrivial_copy_init (TREE_TYPE (expr)))
7719 return get_target_expr (expr, complain);
7721 /* In decltype, we might have decided not to wrap this call in a TARGET_EXPR.
7722 But it turns out to be a subexpression, so perform temporary
7723 materialization now. */
7724 if (TREE_CODE (expr) == CALL_EXPR
7725 && CLASS_TYPE_P (type)
7726 && same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7727 expr = build_cplus_new (type, expr, complain);
7729 savew = warningcount + werrorcount, savee = errorcount;
7730 releasing_vec args (make_tree_vector_single (expr));
7731 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
7732 &args, type, flags, complain);
7733 if (warningcount + werrorcount > savew)
7734 *diagnostic_kind = DK_WARNING;
7735 else if (errorcount > savee)
7736 *diagnostic_kind = DK_ERROR;
7737 return expr;
7740 /* Get any location for EXPR, falling back to input_location.
7742 If the result is in a system header and is the virtual location for
7743 a token coming from the expansion of a macro, unwind it to the
7744 location of the expansion point of the macro (e.g. to avoid the
7745 diagnostic being suppressed for expansions of NULL where "NULL" is
7746 in a system header). */
7748 static location_t
7749 get_location_for_expr_unwinding_for_system_header (tree expr)
7751 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
7752 loc = expansion_point_location_if_in_system_header (loc);
7753 return loc;
7756 /* Perform warnings about peculiar, but valid, conversions from/to NULL.
7757 Also handle a subset of zero as null warnings.
7758 EXPR is implicitly converted to type TOTYPE.
7759 FN and ARGNUM are used for diagnostics. */
7761 static void
7762 conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
7764 /* Issue warnings about peculiar, but valid, uses of NULL. */
7765 if (TREE_CODE (totype) != BOOLEAN_TYPE
7766 && ARITHMETIC_TYPE_P (totype)
7767 && null_node_p (expr))
7769 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
7770 if (fn)
7772 auto_diagnostic_group d;
7773 if (warning_at (loc, OPT_Wconversion_null,
7774 "passing NULL to non-pointer argument %P of %qD",
7775 argnum, fn))
7776 inform (get_fndecl_argument_location (fn, argnum),
7777 " declared here");
7779 else
7780 warning_at (loc, OPT_Wconversion_null,
7781 "converting to non-pointer type %qT from NULL", totype);
7784 /* Issue warnings if "false" is converted to a NULL pointer */
7785 else if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
7786 && TYPE_PTR_P (totype))
7788 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
7789 if (fn)
7791 auto_diagnostic_group d;
7792 if (warning_at (loc, OPT_Wconversion_null,
7793 "converting %<false%> to pointer type for argument "
7794 "%P of %qD", argnum, fn))
7795 inform (get_fndecl_argument_location (fn, argnum),
7796 " declared here");
7798 else
7799 warning_at (loc, OPT_Wconversion_null,
7800 "converting %<false%> to pointer type %qT", totype);
7802 /* Handle zero as null pointer warnings for cases other
7803 than EQ_EXPR and NE_EXPR */
7804 else if ((TYPE_PTR_OR_PTRMEM_P (totype) || NULLPTR_TYPE_P (totype))
7805 && null_ptr_cst_p (expr))
7807 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
7808 maybe_warn_zero_as_null_pointer_constant (expr, loc);
7812 /* We gave a diagnostic during a conversion. If this was in the second
7813 standard conversion sequence of a user-defined conversion sequence, say
7814 which user-defined conversion. */
7816 static void
7817 maybe_print_user_conv_context (conversion *convs)
7819 if (convs->user_conv_p)
7820 for (conversion *t = convs; t; t = next_conversion (t))
7821 if (t->kind == ck_user)
7823 print_z_candidate (0, N_(" after user-defined conversion:"),
7824 t->cand);
7825 break;
7829 /* Locate the parameter with the given index within FNDECL.
7830 ARGNUM is zero based, -1 indicates the `this' argument of a method.
7831 Return the location of the FNDECL itself if there are problems. */
7833 location_t
7834 get_fndecl_argument_location (tree fndecl, int argnum)
7836 /* The locations of implicitly-declared functions are likely to be
7837 more meaningful than those of their parameters. */
7838 if (DECL_ARTIFICIAL (fndecl))
7839 return DECL_SOURCE_LOCATION (fndecl);
7841 int i;
7842 tree param;
7844 /* Locate param by index within DECL_ARGUMENTS (fndecl). */
7845 for (i = 0, param = FUNCTION_FIRST_USER_PARM (fndecl);
7846 i < argnum && param;
7847 i++, param = TREE_CHAIN (param))
7850 /* If something went wrong (e.g. if we have a builtin and thus no arguments),
7851 return the location of FNDECL. */
7852 if (param == NULL)
7853 return DECL_SOURCE_LOCATION (fndecl);
7855 return DECL_SOURCE_LOCATION (param);
7858 /* If FNDECL is non-NULL, issue a note highlighting ARGNUM
7859 within its declaration (or the fndecl itself if something went
7860 wrong). */
7862 void
7863 maybe_inform_about_fndecl_for_bogus_argument_init (tree fn, int argnum)
7865 if (fn)
7866 inform (get_fndecl_argument_location (fn, argnum),
7867 " initializing argument %P of %qD", argnum, fn);
7870 /* Maybe warn about C++20 Conversions to arrays of unknown bound. C is
7871 the conversion, EXPR is the expression we're converting. */
7873 static void
7874 maybe_warn_array_conv (location_t loc, conversion *c, tree expr)
7876 if (cxx_dialect >= cxx20)
7877 return;
7879 tree type = TREE_TYPE (expr);
7880 type = strip_pointer_operator (type);
7882 if (TREE_CODE (type) != ARRAY_TYPE
7883 || TYPE_DOMAIN (type) == NULL_TREE)
7884 return;
7886 if (pedantic && conv_binds_to_array_of_unknown_bound (c))
7887 pedwarn (loc, OPT_Wc__20_extensions,
7888 "conversions to arrays of unknown bound "
7889 "are only available with %<-std=c++20%> or %<-std=gnu++20%>");
7892 /* We call this recursively in convert_like_internal. */
7893 static tree convert_like (conversion *, tree, tree, int, bool, bool,
7894 tsubst_flags_t);
7896 /* Perform the conversions in CONVS on the expression EXPR. FN and
7897 ARGNUM are used for diagnostics. ARGNUM is zero based, -1
7898 indicates the `this' argument of a method. INNER is nonzero when
7899 being called to continue a conversion chain. It is negative when a
7900 reference binding will be applied, positive otherwise. If
7901 ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
7902 conversions will be emitted if appropriate. If C_CAST_P is true,
7903 this conversion is coming from a C-style cast; in that case,
7904 conversions to inaccessible bases are permitted. */
7906 static tree
7907 convert_like_internal (conversion *convs, tree expr, tree fn, int argnum,
7908 bool issue_conversion_warnings, bool c_cast_p,
7909 tsubst_flags_t complain)
7911 tree totype = convs->type;
7912 diagnostic_t diag_kind;
7913 int flags;
7914 location_t loc = cp_expr_loc_or_input_loc (expr);
7916 if (convs->bad_p && !(complain & tf_error))
7917 return error_mark_node;
7919 if (convs->bad_p
7920 && convs->kind != ck_user
7921 && convs->kind != ck_list
7922 && convs->kind != ck_ambig
7923 && (convs->kind != ck_ref_bind
7924 || (convs->user_conv_p && next_conversion (convs)->bad_p))
7925 && (convs->kind != ck_rvalue
7926 || SCALAR_TYPE_P (totype))
7927 && convs->kind != ck_base)
7929 bool complained = false;
7930 conversion *t = convs;
7932 /* Give a helpful error if this is bad because of excess braces. */
7933 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
7934 && SCALAR_TYPE_P (totype)
7935 && CONSTRUCTOR_NELTS (expr) > 0
7936 && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
7938 complained = permerror (loc, "too many braces around initializer "
7939 "for %qT", totype);
7940 while (BRACE_ENCLOSED_INITIALIZER_P (expr)
7941 && CONSTRUCTOR_NELTS (expr) == 1)
7942 expr = CONSTRUCTOR_ELT (expr, 0)->value;
7945 /* Give a helpful error if this is bad because a conversion to bool
7946 from std::nullptr_t requires direct-initialization. */
7947 if (NULLPTR_TYPE_P (TREE_TYPE (expr))
7948 && TREE_CODE (totype) == BOOLEAN_TYPE)
7949 complained = permerror (loc, "converting to %qH from %qI requires "
7950 "direct-initialization",
7951 totype, TREE_TYPE (expr));
7953 if (TREE_CODE (TREE_TYPE (expr)) == REAL_TYPE
7954 && TREE_CODE (totype) == REAL_TYPE
7955 && (extended_float_type_p (TREE_TYPE (expr))
7956 || extended_float_type_p (totype)))
7957 switch (cp_compare_floating_point_conversion_ranks (TREE_TYPE (expr),
7958 totype))
7960 case 2:
7961 pedwarn (loc, 0, "converting to %qH from %qI with greater "
7962 "conversion rank", totype, TREE_TYPE (expr));
7963 complained = true;
7964 break;
7965 case 3:
7966 pedwarn (loc, 0, "converting to %qH from %qI with unordered "
7967 "conversion ranks", totype, TREE_TYPE (expr));
7968 complained = true;
7969 break;
7970 default:
7971 break;
7974 for (; t ; t = next_conversion (t))
7976 if (t->kind == ck_user && t->cand->reason)
7978 auto_diagnostic_group d;
7979 complained = permerror (loc, "invalid user-defined conversion "
7980 "from %qH to %qI", TREE_TYPE (expr),
7981 totype);
7982 if (complained)
7983 print_z_candidate (loc, N_("candidate is:"), t->cand);
7984 expr = convert_like (t, expr, fn, argnum,
7985 /*issue_conversion_warnings=*/false,
7986 /*c_cast_p=*/false, complain);
7987 if (convs->kind == ck_ref_bind)
7988 expr = convert_to_reference (totype, expr, CONV_IMPLICIT,
7989 LOOKUP_NORMAL, NULL_TREE,
7990 complain);
7991 else
7992 expr = cp_convert (totype, expr, complain);
7993 if (complained)
7994 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
7995 return expr;
7997 else if (t->kind == ck_user || !t->bad_p)
7999 expr = convert_like (t, expr, fn, argnum,
8000 /*issue_conversion_warnings=*/false,
8001 /*c_cast_p=*/false, complain);
8002 break;
8004 else if (t->kind == ck_ambig)
8005 return convert_like (t, expr, fn, argnum,
8006 /*issue_conversion_warnings=*/false,
8007 /*c_cast_p=*/false, complain);
8008 else if (t->kind == ck_identity)
8009 break;
8011 if (!complained && expr != error_mark_node)
8013 range_label_for_type_mismatch label (TREE_TYPE (expr), totype);
8014 gcc_rich_location richloc (loc, &label);
8015 complained = permerror (&richloc,
8016 "invalid conversion from %qH to %qI",
8017 TREE_TYPE (expr), totype);
8019 if (complained)
8020 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8022 return cp_convert (totype, expr, complain);
8025 if (issue_conversion_warnings && (complain & tf_warning))
8026 conversion_null_warnings (totype, expr, fn, argnum);
8028 switch (convs->kind)
8030 case ck_user:
8032 struct z_candidate *cand = convs->cand;
8034 if (cand == NULL)
8035 /* We chose the surrogate function from add_conv_candidate, now we
8036 actually need to build the conversion. */
8037 cand = build_user_type_conversion_1 (totype, expr,
8038 LOOKUP_NO_CONVERSION, complain);
8040 tree convfn = cand->fn;
8042 /* When converting from an init list we consider explicit
8043 constructors, but actually trying to call one is an error. */
8044 if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn)
8045 && BRACE_ENCLOSED_INITIALIZER_P (expr)
8046 /* Unless this is for direct-list-initialization. */
8047 && (!CONSTRUCTOR_IS_DIRECT_INIT (expr) || convs->need_temporary_p)
8048 /* And in C++98 a default constructor can't be explicit. */
8049 && cxx_dialect >= cxx11)
8051 if (!(complain & tf_error))
8052 return error_mark_node;
8053 location_t loc = location_of (expr);
8054 if (CONSTRUCTOR_NELTS (expr) == 0
8055 && FUNCTION_FIRST_USER_PARMTYPE (convfn) != void_list_node)
8057 auto_diagnostic_group d;
8058 if (pedwarn (loc, 0, "converting to %qT from initializer list "
8059 "would use explicit constructor %qD",
8060 totype, convfn))
8061 inform (loc, "in C++11 and above a default constructor "
8062 "can be explicit");
8064 else
8065 error ("converting to %qT from initializer list would use "
8066 "explicit constructor %qD", totype, convfn);
8069 /* If we're initializing from {}, it's value-initialization. */
8070 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8071 && CONSTRUCTOR_NELTS (expr) == 0
8072 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype)
8073 && !processing_template_decl)
8075 bool direct = CONSTRUCTOR_IS_DIRECT_INIT (expr);
8076 if (abstract_virtuals_error (NULL_TREE, totype, complain))
8077 return error_mark_node;
8078 expr = build_value_init (totype, complain);
8079 expr = get_target_expr (expr, complain);
8080 if (expr != error_mark_node)
8082 TARGET_EXPR_LIST_INIT_P (expr) = true;
8083 TARGET_EXPR_DIRECT_INIT_P (expr) = direct;
8085 return expr;
8088 /* We don't know here whether EXPR is being used as an lvalue or
8089 rvalue, but we know it's read. */
8090 mark_exp_read (expr);
8092 /* Pass LOOKUP_NO_CONVERSION so rvalue/base handling knows not to allow
8093 any more UDCs. */
8094 expr = build_over_call (cand, LOOKUP_NORMAL|LOOKUP_NO_CONVERSION,
8095 complain);
8097 /* If this is a constructor or a function returning an aggr type,
8098 we need to build up a TARGET_EXPR. */
8099 if (DECL_CONSTRUCTOR_P (convfn))
8101 expr = build_cplus_new (totype, expr, complain);
8103 /* Remember that this was list-initialization. */
8104 if (convs->check_narrowing && expr != error_mark_node)
8105 TARGET_EXPR_LIST_INIT_P (expr) = true;
8108 return expr;
8110 case ck_identity:
8111 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
8113 int nelts = CONSTRUCTOR_NELTS (expr);
8114 if (nelts == 0)
8115 expr = build_value_init (totype, complain);
8116 else if (nelts == 1)
8117 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8118 else
8119 gcc_unreachable ();
8121 expr = mark_use (expr, /*rvalue_p=*/!convs->rvaluedness_matches_p,
8122 /*read_p=*/true, UNKNOWN_LOCATION,
8123 /*reject_builtin=*/true);
8125 if (type_unknown_p (expr))
8126 expr = instantiate_type (totype, expr, complain);
8127 if (expr == null_node
8128 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
8129 /* If __null has been converted to an integer type, we do not want to
8130 continue to warn about uses of EXPR as an integer, rather than as a
8131 pointer. */
8132 expr = build_int_cst (totype, 0);
8133 return expr;
8134 case ck_ambig:
8135 /* We leave bad_p off ck_ambig because overload resolution considers
8136 it valid, it just fails when we try to perform it. So we need to
8137 check complain here, too. */
8138 if (complain & tf_error)
8140 /* Call build_user_type_conversion again for the error. */
8141 int flags = (convs->need_temporary_p
8142 ? LOOKUP_IMPLICIT : LOOKUP_NORMAL);
8143 build_user_type_conversion (totype, convs->u.expr, flags, complain);
8144 gcc_assert (seen_error ());
8145 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8147 return error_mark_node;
8149 case ck_list:
8151 /* Conversion to std::initializer_list<T>. */
8152 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
8153 unsigned len = CONSTRUCTOR_NELTS (expr);
8154 tree array;
8156 if (len)
8158 tree val; unsigned ix;
8160 tree new_ctor = build_constructor (init_list_type_node, NULL);
8162 /* Convert all the elements. */
8163 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
8165 tree sub = convert_like (convs->u.list[ix], val, fn,
8166 argnum, false, false, complain);
8167 if (sub == error_mark_node)
8168 return sub;
8169 if (!BRACE_ENCLOSED_INITIALIZER_P (val)
8170 && !check_narrowing (TREE_TYPE (sub), val, complain))
8171 return error_mark_node;
8172 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor),
8173 NULL_TREE, sub);
8174 if (!TREE_CONSTANT (sub))
8175 TREE_CONSTANT (new_ctor) = false;
8177 /* Build up the array. */
8178 elttype = cp_build_qualified_type
8179 (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
8180 array = build_array_of_n_type (elttype, len);
8181 array = finish_compound_literal (array, new_ctor, complain);
8182 /* Take the address explicitly rather than via decay_conversion
8183 to avoid the error about taking the address of a temporary. */
8184 array = cp_build_addr_expr (array, complain);
8186 else
8187 array = nullptr_node;
8189 array = cp_convert (build_pointer_type (elttype), array, complain);
8190 if (array == error_mark_node)
8191 return error_mark_node;
8193 /* Build up the initializer_list object. Note: fail gracefully
8194 if the object cannot be completed because, for example, no
8195 definition is provided (c++/80956). */
8196 totype = complete_type_or_maybe_complain (totype, NULL_TREE, complain);
8197 if (!totype)
8198 return error_mark_node;
8199 tree field = next_aggregate_field (TYPE_FIELDS (totype));
8200 vec<constructor_elt, va_gc> *vec = NULL;
8201 CONSTRUCTOR_APPEND_ELT (vec, field, array);
8202 field = next_aggregate_field (DECL_CHAIN (field));
8203 CONSTRUCTOR_APPEND_ELT (vec, field, size_int (len));
8204 tree new_ctor = build_constructor (totype, vec);
8205 return get_target_expr (new_ctor, complain);
8208 case ck_aggr:
8209 if (TREE_CODE (totype) == COMPLEX_TYPE)
8211 tree real = CONSTRUCTOR_ELT (expr, 0)->value;
8212 tree imag = CONSTRUCTOR_ELT (expr, 1)->value;
8213 real = perform_implicit_conversion (TREE_TYPE (totype),
8214 real, complain);
8215 imag = perform_implicit_conversion (TREE_TYPE (totype),
8216 imag, complain);
8217 expr = build2 (COMPLEX_EXPR, totype, real, imag);
8218 return expr;
8220 expr = reshape_init (totype, expr, complain);
8221 expr = get_target_expr (digest_init (totype, expr, complain),
8222 complain);
8223 if (expr != error_mark_node)
8224 TARGET_EXPR_LIST_INIT_P (expr) = true;
8225 return expr;
8227 default:
8228 break;
8231 expr = convert_like (next_conversion (convs), expr, fn, argnum,
8232 convs->kind == ck_ref_bind
8233 ? issue_conversion_warnings : false,
8234 c_cast_p, complain & ~tf_no_cleanup);
8235 if (expr == error_mark_node)
8236 return error_mark_node;
8238 switch (convs->kind)
8240 case ck_rvalue:
8241 expr = decay_conversion (expr, complain);
8242 if (expr == error_mark_node)
8244 if (complain & tf_error)
8246 auto_diagnostic_group d;
8247 maybe_print_user_conv_context (convs);
8248 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8250 return error_mark_node;
8253 if (! MAYBE_CLASS_TYPE_P (totype))
8254 return expr;
8256 /* Don't introduce copies when passing arguments along to the inherited
8257 constructor. */
8258 if (current_function_decl
8259 && flag_new_inheriting_ctors
8260 && DECL_INHERITED_CTOR (current_function_decl))
8261 return expr;
8263 if (TREE_CODE (expr) == TARGET_EXPR
8264 && TARGET_EXPR_LIST_INIT_P (expr))
8265 /* Copy-list-initialization doesn't actually involve a copy. */
8266 return expr;
8268 /* Fall through. */
8269 case ck_base:
8270 if (convs->kind == ck_base && !convs->need_temporary_p)
8272 /* We are going to bind a reference directly to a base-class
8273 subobject of EXPR. */
8274 /* Build an expression for `*((base*) &expr)'. */
8275 expr = convert_to_base (expr, totype,
8276 !c_cast_p, /*nonnull=*/true, complain);
8277 return expr;
8280 /* Copy-initialization where the cv-unqualified version of the source
8281 type is the same class as, or a derived class of, the class of the
8282 destination [is treated as direct-initialization]. [dcl.init] */
8283 flags = LOOKUP_NORMAL;
8284 /* This conversion is being done in the context of a user-defined
8285 conversion (i.e. the second step of copy-initialization), so
8286 don't allow any more. */
8287 if (convs->user_conv_p)
8288 flags |= LOOKUP_NO_CONVERSION;
8289 /* We might be performing a conversion of the argument
8290 to the user-defined conversion, i.e., not a conversion of the
8291 result of the user-defined conversion. In which case we skip
8292 explicit constructors. */
8293 if (convs->copy_init_p)
8294 flags |= LOOKUP_ONLYCONVERTING;
8295 if (convs->rvaluedness_matches_p)
8296 /* standard_conversion got LOOKUP_PREFER_RVALUE. */
8297 flags |= LOOKUP_PREFER_RVALUE;
8298 expr = build_temp (expr, totype, flags, &diag_kind, complain);
8299 if (diag_kind && complain)
8301 auto_diagnostic_group d;
8302 maybe_print_user_conv_context (convs);
8303 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8306 return build_cplus_new (totype, expr, complain);
8308 case ck_ref_bind:
8310 tree ref_type = totype;
8312 /* direct_reference_binding might have inserted a ck_qual under
8313 this ck_ref_bind for the benefit of conversion sequence ranking.
8314 Ignore the conversion; we'll create our own below. */
8315 if (next_conversion (convs)->kind == ck_qual
8316 && !convs->need_temporary_p)
8318 gcc_assert (same_type_p (TREE_TYPE (expr),
8319 next_conversion (convs)->type));
8320 /* Strip the cast created by the ck_qual; cp_build_addr_expr
8321 below expects an lvalue. */
8322 STRIP_NOPS (expr);
8325 if (convs->bad_p && !next_conversion (convs)->bad_p)
8327 tree extype = TREE_TYPE (expr);
8328 auto_diagnostic_group d;
8329 if (TYPE_REF_IS_RVALUE (ref_type)
8330 && lvalue_p (expr))
8331 error_at (loc, "cannot bind rvalue reference of type %qH to "
8332 "lvalue of type %qI", totype, extype);
8333 else if (!TYPE_REF_IS_RVALUE (ref_type) && !lvalue_p (expr)
8334 && !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (ref_type)))
8336 conversion *next = next_conversion (convs);
8337 if (next->kind == ck_std)
8339 next = next_conversion (next);
8340 error_at (loc, "cannot bind non-const lvalue reference of "
8341 "type %qH to a value of type %qI",
8342 totype, next->type);
8344 else if (!CP_TYPE_CONST_P (TREE_TYPE (ref_type)))
8345 error_at (loc, "cannot bind non-const lvalue reference of "
8346 "type %qH to an rvalue of type %qI", totype, extype);
8347 else // extype is volatile
8348 error_at (loc, "cannot bind lvalue reference of type "
8349 "%qH to an rvalue of type %qI", totype,
8350 extype);
8352 else if (!reference_compatible_p (TREE_TYPE (totype), extype))
8354 /* If we're converting from T[] to T[N], don't talk
8355 about discarding qualifiers. (Converting from T[N] to
8356 T[] is allowed by P0388R4.) */
8357 if (TREE_CODE (extype) == ARRAY_TYPE
8358 && TYPE_DOMAIN (extype) == NULL_TREE
8359 && TREE_CODE (TREE_TYPE (totype)) == ARRAY_TYPE
8360 && TYPE_DOMAIN (TREE_TYPE (totype)) != NULL_TREE)
8361 error_at (loc, "cannot bind reference of type %qH to %qI "
8362 "due to different array bounds", totype, extype);
8363 else
8364 error_at (loc, "binding reference of type %qH to %qI "
8365 "discards qualifiers", totype, extype);
8367 else
8368 gcc_unreachable ();
8369 maybe_print_user_conv_context (convs);
8370 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8372 return error_mark_node;
8374 else if (complain & tf_warning)
8375 maybe_warn_array_conv (loc, convs, expr);
8377 /* If necessary, create a temporary.
8379 VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
8380 that need temporaries, even when their types are reference
8381 compatible with the type of reference being bound, so the
8382 upcoming call to cp_build_addr_expr doesn't fail. */
8383 if (convs->need_temporary_p
8384 || TREE_CODE (expr) == CONSTRUCTOR
8385 || TREE_CODE (expr) == VA_ARG_EXPR)
8387 /* Otherwise, a temporary of type "cv1 T1" is created and
8388 initialized from the initializer expression using the rules
8389 for a non-reference copy-initialization (8.5). */
8391 tree type = TREE_TYPE (ref_type);
8392 cp_lvalue_kind lvalue = lvalue_kind (expr);
8394 gcc_assert (similar_type_p (type, next_conversion (convs)->type));
8395 if (!CP_TYPE_CONST_NON_VOLATILE_P (type)
8396 && !TYPE_REF_IS_RVALUE (ref_type))
8398 /* If the reference is volatile or non-const, we
8399 cannot create a temporary. */
8400 if (complain & tf_error)
8402 if (lvalue & clk_bitfield)
8403 error_at (loc, "cannot bind bit-field %qE to %qT",
8404 expr, ref_type);
8405 else if (lvalue & clk_packed)
8406 error_at (loc, "cannot bind packed field %qE to %qT",
8407 expr, ref_type);
8408 else
8409 error_at (loc, "cannot bind rvalue %qE to %qT",
8410 expr, ref_type);
8412 return error_mark_node;
8414 /* If the source is a packed field, and we must use a copy
8415 constructor, then building the target expr will require
8416 binding the field to the reference parameter to the
8417 copy constructor, and we'll end up with an infinite
8418 loop. If we can use a bitwise copy, then we'll be
8419 OK. */
8420 if ((lvalue & clk_packed)
8421 && CLASS_TYPE_P (type)
8422 && type_has_nontrivial_copy_init (type))
8424 error_at (loc, "cannot bind packed field %qE to %qT",
8425 expr, ref_type);
8426 return error_mark_node;
8428 if (lvalue & clk_bitfield)
8430 expr = convert_bitfield_to_declared_type (expr);
8431 expr = fold_convert (type, expr);
8434 /* Creating &TARGET_EXPR<> in a template would break when
8435 tsubsting the expression, so use an IMPLICIT_CONV_EXPR
8436 instead. This can happen even when there's no class
8437 involved, e.g., when converting an integer to a reference
8438 type. */
8439 if (processing_template_decl)
8440 return build1 (IMPLICIT_CONV_EXPR, totype, expr);
8441 expr = build_target_expr_with_type (expr, type, complain);
8444 /* Take the address of the thing to which we will bind the
8445 reference. */
8446 expr = cp_build_addr_expr (expr, complain);
8447 if (expr == error_mark_node)
8448 return error_mark_node;
8450 /* Convert it to a pointer to the type referred to by the
8451 reference. This will adjust the pointer if a derived to
8452 base conversion is being performed. */
8453 expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
8454 expr, complain);
8455 /* Convert the pointer to the desired reference type. */
8456 return build_nop (ref_type, expr);
8459 case ck_lvalue:
8460 return decay_conversion (expr, complain);
8462 case ck_fnptr:
8463 /* ??? Should the address of a transaction-safe pointer point to the TM
8464 clone, and this conversion look up the primary function? */
8465 return build_nop (totype, expr);
8467 case ck_qual:
8468 /* Warn about deprecated conversion if appropriate. */
8469 if (complain & tf_warning)
8471 string_conv_p (totype, expr, 1);
8472 maybe_warn_array_conv (loc, convs, expr);
8474 break;
8476 case ck_ptr:
8477 if (convs->base_p)
8478 expr = convert_to_base (expr, totype, !c_cast_p,
8479 /*nonnull=*/false, complain);
8480 return build_nop (totype, expr);
8482 case ck_pmem:
8483 return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
8484 c_cast_p, complain);
8486 default:
8487 break;
8490 if (convs->check_narrowing
8491 && !check_narrowing (totype, expr, complain,
8492 convs->check_narrowing_const_only))
8493 return error_mark_node;
8495 warning_sentinel w (warn_zero_as_null_pointer_constant);
8496 if (issue_conversion_warnings)
8497 expr = cp_convert_and_check (totype, expr, complain);
8498 else
8499 expr = cp_convert (totype, expr, complain);
8501 return expr;
8504 /* Return true if converting FROM to TO is unsafe in a template. */
8506 static bool
8507 conv_unsafe_in_template_p (tree to, tree from)
8509 /* Converting classes involves TARGET_EXPR. */
8510 if (CLASS_TYPE_P (to) || CLASS_TYPE_P (from))
8511 return true;
8513 /* Converting real to integer produces FIX_TRUNC_EXPR which tsubst
8514 doesn't handle. */
8515 if (SCALAR_FLOAT_TYPE_P (from) && INTEGRAL_OR_ENUMERATION_TYPE_P (to))
8516 return true;
8518 /* Converting integer to real isn't a trivial conversion, either. */
8519 if (INTEGRAL_OR_ENUMERATION_TYPE_P (from) && SCALAR_FLOAT_TYPE_P (to))
8520 return true;
8522 return false;
8525 /* Wrapper for convert_like_internal that handles creating
8526 IMPLICIT_CONV_EXPR. */
8528 static tree
8529 convert_like (conversion *convs, tree expr, tree fn, int argnum,
8530 bool issue_conversion_warnings, bool c_cast_p,
8531 tsubst_flags_t complain)
8533 /* Creating &TARGET_EXPR<> in a template breaks when substituting,
8534 and creating a CALL_EXPR in a template breaks in finish_call_expr
8535 so use an IMPLICIT_CONV_EXPR for this conversion. We would have
8536 created such codes e.g. when calling a user-defined conversion
8537 function. */
8538 tree conv_expr = NULL_TREE;
8539 if (processing_template_decl
8540 && convs->kind != ck_identity
8541 && conv_unsafe_in_template_p (convs->type, TREE_TYPE (expr)))
8543 conv_expr = build1 (IMPLICIT_CONV_EXPR, convs->type, expr);
8544 if (convs->kind != ck_ref_bind)
8545 conv_expr = convert_from_reference (conv_expr);
8546 if (!convs->bad_p)
8547 return conv_expr;
8548 /* Do the normal processing to give the bad_p errors. But we still
8549 need to return the IMPLICIT_CONV_EXPR, unless we're returning
8550 error_mark_node. */
8552 expr = convert_like_internal (convs, expr, fn, argnum,
8553 issue_conversion_warnings, c_cast_p, complain);
8554 if (expr == error_mark_node)
8555 return error_mark_node;
8556 return conv_expr ? conv_expr : expr;
8559 /* Convenience wrapper for convert_like. */
8561 static inline tree
8562 convert_like (conversion *convs, tree expr, tsubst_flags_t complain)
8564 return convert_like (convs, expr, NULL_TREE, 0,
8565 /*issue_conversion_warnings=*/true,
8566 /*c_cast_p=*/false, complain);
8569 /* Convenience wrapper for convert_like. */
8571 static inline tree
8572 convert_like_with_context (conversion *convs, tree expr, tree fn, int argnum,
8573 tsubst_flags_t complain)
8575 return convert_like (convs, expr, fn, argnum,
8576 /*issue_conversion_warnings=*/true,
8577 /*c_cast_p=*/false, complain);
8580 /* ARG is being passed to a varargs function. Perform any conversions
8581 required. Return the converted value. */
8583 tree
8584 convert_arg_to_ellipsis (tree arg, tsubst_flags_t complain)
8586 tree arg_type = TREE_TYPE (arg);
8587 location_t loc = cp_expr_loc_or_input_loc (arg);
8589 /* [expr.call]
8591 If the argument has integral or enumeration type that is subject
8592 to the integral promotions (_conv.prom_), or a floating-point
8593 type that is subject to the floating-point promotion
8594 (_conv.fpprom_), the value of the argument is converted to the
8595 promoted type before the call. */
8596 if (TREE_CODE (arg_type) == REAL_TYPE
8597 && (TYPE_PRECISION (arg_type)
8598 < TYPE_PRECISION (double_type_node))
8599 && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (arg_type))
8600 && !extended_float_type_p (arg_type))
8602 if ((complain & tf_warning)
8603 && warn_double_promotion && !c_inhibit_evaluation_warnings)
8604 warning_at (loc, OPT_Wdouble_promotion,
8605 "implicit conversion from %qH to %qI when passing "
8606 "argument to function",
8607 arg_type, double_type_node);
8608 arg = mark_rvalue_use (arg);
8609 arg = convert_to_real_nofold (double_type_node, arg);
8611 else if (NULLPTR_TYPE_P (arg_type))
8613 arg = mark_rvalue_use (arg);
8614 if (TREE_SIDE_EFFECTS (arg))
8616 warning_sentinel w(warn_unused_result);
8617 arg = cp_build_compound_expr (arg, null_pointer_node, complain);
8619 else
8620 arg = null_pointer_node;
8622 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (arg_type))
8624 if (SCOPED_ENUM_P (arg_type))
8626 tree prom = cp_convert (ENUM_UNDERLYING_TYPE (arg_type), arg,
8627 complain);
8628 prom = cp_perform_integral_promotions (prom, complain);
8629 if (abi_version_crosses (6)
8630 && TYPE_MODE (TREE_TYPE (prom)) != TYPE_MODE (arg_type)
8631 && (complain & tf_warning))
8632 warning_at (loc, OPT_Wabi, "scoped enum %qT passed through %<...%>"
8633 " as %qT before %<-fabi-version=6%>, %qT after",
8634 arg_type,
8635 TREE_TYPE (prom), ENUM_UNDERLYING_TYPE (arg_type));
8636 if (!abi_version_at_least (6))
8637 arg = prom;
8639 else
8640 arg = cp_perform_integral_promotions (arg, complain);
8642 else
8643 /* [expr.call]
8645 The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
8646 standard conversions are performed. */
8647 arg = decay_conversion (arg, complain);
8649 arg = require_complete_type (arg, complain);
8650 arg_type = TREE_TYPE (arg);
8652 if (arg != error_mark_node
8653 /* In a template (or ill-formed code), we can have an incomplete type
8654 even after require_complete_type, in which case we don't know
8655 whether it has trivial copy or not. */
8656 && COMPLETE_TYPE_P (arg_type)
8657 && !cp_unevaluated_operand)
8659 /* [expr.call] 5.2.2/7:
8660 Passing a potentially-evaluated argument of class type (Clause 9)
8661 with a non-trivial copy constructor or a non-trivial destructor
8662 with no corresponding parameter is conditionally-supported, with
8663 implementation-defined semantics.
8665 We support it as pass-by-invisible-reference, just like a normal
8666 value parameter.
8668 If the call appears in the context of a sizeof expression,
8669 it is not potentially-evaluated. */
8670 if (type_has_nontrivial_copy_init (arg_type)
8671 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (arg_type))
8673 arg = force_rvalue (arg, complain);
8674 if (complain & tf_warning)
8675 warning (OPT_Wconditionally_supported,
8676 "passing objects of non-trivially-copyable "
8677 "type %q#T through %<...%> is conditionally supported",
8678 arg_type);
8679 return build1 (ADDR_EXPR, build_reference_type (arg_type), arg);
8681 /* Build up a real lvalue-to-rvalue conversion in case the
8682 copy constructor is trivial but not callable. */
8683 else if (CLASS_TYPE_P (arg_type))
8684 force_rvalue (arg, complain);
8688 return arg;
8691 /* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused. */
8693 tree
8694 build_x_va_arg (location_t loc, tree expr, tree type)
8696 if (processing_template_decl)
8698 tree r = build_min (VA_ARG_EXPR, type, expr);
8699 SET_EXPR_LOCATION (r, loc);
8700 return r;
8703 type = complete_type_or_else (type, NULL_TREE);
8705 if (expr == error_mark_node || !type)
8706 return error_mark_node;
8708 expr = mark_lvalue_use (expr);
8710 if (TYPE_REF_P (type))
8712 error ("cannot receive reference type %qT through %<...%>", type);
8713 return error_mark_node;
8716 if (type_has_nontrivial_copy_init (type)
8717 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
8719 /* conditionally-supported behavior [expr.call] 5.2.2/7. Let's treat
8720 it as pass by invisible reference. */
8721 warning_at (loc, OPT_Wconditionally_supported,
8722 "receiving objects of non-trivially-copyable type %q#T "
8723 "through %<...%> is conditionally-supported", type);
8725 tree ref = cp_build_reference_type (type, false);
8726 expr = build_va_arg (loc, expr, ref);
8727 return convert_from_reference (expr);
8730 tree ret = build_va_arg (loc, expr, type);
8731 if (CLASS_TYPE_P (type))
8732 /* Wrap the VA_ARG_EXPR in a TARGET_EXPR now so other code doesn't need to
8733 know how to handle it. */
8734 ret = get_target_expr (ret);
8735 return ret;
8738 /* TYPE has been given to va_arg. Apply the default conversions which
8739 would have happened when passed via ellipsis. Return the promoted
8740 type, or the passed type if there is no change. */
8742 tree
8743 cxx_type_promotes_to (tree type)
8745 tree promote;
8747 /* Perform the array-to-pointer and function-to-pointer
8748 conversions. */
8749 type = type_decays_to (type);
8751 promote = type_promotes_to (type);
8752 if (same_type_p (type, promote))
8753 promote = type;
8755 return promote;
8758 /* ARG is a default argument expression being passed to a parameter of
8759 the indicated TYPE, which is a parameter to FN. PARMNUM is the
8760 zero-based argument number. Do any required conversions. Return
8761 the converted value. */
8763 static GTY(()) vec<tree, va_gc> *default_arg_context;
8764 void
8765 push_defarg_context (tree fn)
8766 { vec_safe_push (default_arg_context, fn); }
8768 void
8769 pop_defarg_context (void)
8770 { default_arg_context->pop (); }
8772 tree
8773 convert_default_arg (tree type, tree arg, tree fn, int parmnum,
8774 tsubst_flags_t complain)
8776 int i;
8777 tree t;
8779 /* See through clones. */
8780 fn = DECL_ORIGIN (fn);
8781 /* And inheriting ctors. */
8782 if (flag_new_inheriting_ctors)
8783 fn = strip_inheriting_ctors (fn);
8785 /* Detect recursion. */
8786 FOR_EACH_VEC_SAFE_ELT (default_arg_context, i, t)
8787 if (t == fn)
8789 if (complain & tf_error)
8790 error ("recursive evaluation of default argument for %q#D", fn);
8791 return error_mark_node;
8794 /* If the ARG is an unparsed default argument expression, the
8795 conversion cannot be performed. */
8796 if (TREE_CODE (arg) == DEFERRED_PARSE)
8798 if (complain & tf_error)
8799 error ("call to %qD uses the default argument for parameter %P, which "
8800 "is not yet defined", fn, parmnum);
8801 return error_mark_node;
8804 push_defarg_context (fn);
8806 if (fn && DECL_TEMPLATE_INFO (fn))
8807 arg = tsubst_default_argument (fn, parmnum, type, arg, complain);
8809 /* Due to:
8811 [dcl.fct.default]
8813 The names in the expression are bound, and the semantic
8814 constraints are checked, at the point where the default
8815 expressions appears.
8817 we must not perform access checks here. */
8818 push_deferring_access_checks (dk_no_check);
8819 /* We must make a copy of ARG, in case subsequent processing
8820 alters any part of it. */
8821 arg = break_out_target_exprs (arg, /*clear location*/true);
8823 arg = convert_for_initialization (0, type, arg, LOOKUP_IMPLICIT,
8824 ICR_DEFAULT_ARGUMENT, fn, parmnum,
8825 complain);
8826 arg = convert_for_arg_passing (type, arg, complain);
8827 pop_deferring_access_checks();
8829 pop_defarg_context ();
8831 return arg;
8834 /* Returns the type which will really be used for passing an argument of
8835 type TYPE. */
8837 tree
8838 type_passed_as (tree type)
8840 /* Pass classes with copy ctors by invisible reference. */
8841 if (TREE_ADDRESSABLE (type))
8842 type = build_reference_type (type);
8843 else if (targetm.calls.promote_prototypes (NULL_TREE)
8844 && INTEGRAL_TYPE_P (type)
8845 && COMPLETE_TYPE_P (type)
8846 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
8847 type = integer_type_node;
8849 return type;
8852 /* Actually perform the appropriate conversion. */
8854 tree
8855 convert_for_arg_passing (tree type, tree val, tsubst_flags_t complain)
8857 tree bitfield_type;
8859 /* If VAL is a bitfield, then -- since it has already been converted
8860 to TYPE -- it cannot have a precision greater than TYPE.
8862 If it has a smaller precision, we must widen it here. For
8863 example, passing "int f:3;" to a function expecting an "int" will
8864 not result in any conversion before this point.
8866 If the precision is the same we must not risk widening. For
8867 example, the COMPONENT_REF for a 32-bit "long long" bitfield will
8868 often have type "int", even though the C++ type for the field is
8869 "long long". If the value is being passed to a function
8870 expecting an "int", then no conversions will be required. But,
8871 if we call convert_bitfield_to_declared_type, the bitfield will
8872 be converted to "long long". */
8873 bitfield_type = is_bitfield_expr_with_lowered_type (val);
8874 if (bitfield_type
8875 && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
8876 val = convert_to_integer_nofold (TYPE_MAIN_VARIANT (bitfield_type), val);
8878 if (val == error_mark_node)
8880 /* Pass classes with copy ctors by invisible reference. */
8881 else if (TREE_ADDRESSABLE (type))
8882 val = build1 (ADDR_EXPR, build_reference_type (type), val);
8883 else if (targetm.calls.promote_prototypes (NULL_TREE)
8884 && INTEGRAL_TYPE_P (type)
8885 && COMPLETE_TYPE_P (type)
8886 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
8887 val = cp_perform_integral_promotions (val, complain);
8888 if (complain & tf_warning)
8890 if (warn_suggest_attribute_format)
8892 tree rhstype = TREE_TYPE (val);
8893 const enum tree_code coder = TREE_CODE (rhstype);
8894 const enum tree_code codel = TREE_CODE (type);
8895 if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
8896 && coder == codel
8897 && check_missing_format_attribute (type, rhstype))
8898 warning (OPT_Wsuggest_attribute_format,
8899 "argument of function call might be a candidate "
8900 "for a format attribute");
8902 maybe_warn_parm_abi (type, cp_expr_loc_or_input_loc (val));
8905 if (complain & tf_warning)
8906 warn_for_address_or_pointer_of_packed_member (type, val);
8908 return val;
8911 /* Returns non-zero iff FN is a function with magic varargs, i.e. ones for
8912 which just decay_conversion or no conversions at all should be done.
8913 This is true for some builtins which don't act like normal functions.
8914 Return 2 if no conversions at all should be done, 1 if just
8915 decay_conversion. Return 3 for special treatment of the 3rd argument
8916 for __builtin_*_overflow_p. */
8919 magic_varargs_p (tree fn)
8921 if (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
8922 switch (DECL_FUNCTION_CODE (fn))
8924 case BUILT_IN_CLASSIFY_TYPE:
8925 case BUILT_IN_CONSTANT_P:
8926 case BUILT_IN_NEXT_ARG:
8927 case BUILT_IN_VA_START:
8928 return 1;
8930 case BUILT_IN_ADD_OVERFLOW_P:
8931 case BUILT_IN_SUB_OVERFLOW_P:
8932 case BUILT_IN_MUL_OVERFLOW_P:
8933 return 3;
8935 default:;
8936 return lookup_attribute ("type generic",
8937 TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
8940 return 0;
8943 /* Returns the decl of the dispatcher function if FN is a function version. */
8945 tree
8946 get_function_version_dispatcher (tree fn)
8948 tree dispatcher_decl = NULL;
8950 if (DECL_LOCAL_DECL_P (fn))
8951 fn = DECL_LOCAL_DECL_ALIAS (fn);
8953 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
8954 && DECL_FUNCTION_VERSIONED (fn));
8956 gcc_assert (targetm.get_function_versions_dispatcher);
8957 dispatcher_decl = targetm.get_function_versions_dispatcher (fn);
8959 if (dispatcher_decl == NULL)
8961 error_at (input_location, "use of multiversioned function "
8962 "without a default");
8963 return NULL;
8966 retrofit_lang_decl (dispatcher_decl);
8967 gcc_assert (dispatcher_decl != NULL);
8968 return dispatcher_decl;
8971 /* fn is a function version dispatcher that is marked used. Mark all the
8972 semantically identical function versions it will dispatch as used. */
8974 void
8975 mark_versions_used (tree fn)
8977 struct cgraph_node *node;
8978 struct cgraph_function_version_info *node_v;
8979 struct cgraph_function_version_info *it_v;
8981 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
8983 node = cgraph_node::get (fn);
8984 if (node == NULL)
8985 return;
8987 gcc_assert (node->dispatcher_function);
8989 node_v = node->function_version ();
8990 if (node_v == NULL)
8991 return;
8993 /* All semantically identical versions are chained. Traverse and mark each
8994 one of them as used. */
8995 it_v = node_v->next;
8996 while (it_v != NULL)
8998 mark_used (it_v->this_node->decl);
8999 it_v = it_v->next;
9003 /* Build a call to "the copy constructor" for the type of A, even if it
9004 wouldn't be selected by normal overload resolution. Used for
9005 diagnostics. */
9007 static tree
9008 call_copy_ctor (tree a, tsubst_flags_t complain)
9010 tree ctype = TYPE_MAIN_VARIANT (TREE_TYPE (a));
9011 tree binfo = TYPE_BINFO (ctype);
9012 tree copy = get_copy_ctor (ctype, complain);
9013 copy = build_baselink (binfo, binfo, copy, NULL_TREE);
9014 tree ob = build_dummy_object (ctype);
9015 releasing_vec args (make_tree_vector_single (a));
9016 tree r = build_new_method_call (ob, copy, &args, NULL_TREE,
9017 LOOKUP_NORMAL, NULL, complain);
9018 return r;
9021 /* Return the base constructor corresponding to COMPLETE_CTOR or NULL_TREE. */
9023 static tree
9024 base_ctor_for (tree complete_ctor)
9026 tree clone;
9027 FOR_EACH_CLONE (clone, DECL_CLONED_FUNCTION (complete_ctor))
9028 if (DECL_BASE_CONSTRUCTOR_P (clone))
9029 return clone;
9030 return NULL_TREE;
9033 /* Try to make EXP suitable to be used as the initializer for a base subobject,
9034 and return whether we were successful. EXP must have already been cleared
9035 by unsafe_copy_elision_p{,_opt}. */
9037 static bool
9038 make_base_init_ok (tree exp)
9040 if (TREE_CODE (exp) == TARGET_EXPR)
9041 exp = TARGET_EXPR_INITIAL (exp);
9042 while (TREE_CODE (exp) == COMPOUND_EXPR)
9043 exp = TREE_OPERAND (exp, 1);
9044 if (TREE_CODE (exp) == COND_EXPR)
9046 bool ret = make_base_init_ok (TREE_OPERAND (exp, 2));
9047 if (tree op1 = TREE_OPERAND (exp, 1))
9049 bool r1 = make_base_init_ok (op1);
9050 /* If unsafe_copy_elision_p was false, the arms should match. */
9051 gcc_assert (r1 == ret);
9053 return ret;
9055 if (TREE_CODE (exp) != AGGR_INIT_EXPR)
9056 /* A trivial copy is OK. */
9057 return true;
9058 if (!AGGR_INIT_VIA_CTOR_P (exp))
9059 /* unsafe_copy_elision_p_opt must have said this is OK. */
9060 return true;
9061 tree fn = cp_get_callee_fndecl_nofold (exp);
9062 if (DECL_BASE_CONSTRUCTOR_P (fn))
9063 return true;
9064 gcc_assert (DECL_COMPLETE_CONSTRUCTOR_P (fn));
9065 fn = base_ctor_for (fn);
9066 if (!fn || DECL_HAS_VTT_PARM_P (fn))
9067 /* The base constructor has more parameters, so we can't just change the
9068 call target. It would be possible to splice in the appropriate
9069 arguments, but probably not worth the complexity. */
9070 return false;
9071 mark_used (fn);
9072 AGGR_INIT_EXPR_FN (exp) = build_address (fn);
9073 return true;
9076 /* Return 2 if T refers to a base, 1 if a potentially-overlapping field,
9077 neither of which can be used for return by invisible reference. We avoid
9078 doing C++17 mandatory copy elision for either of these cases.
9080 This returns non-zero even if the type of T has no tail padding that other
9081 data could be allocated into, because that depends on the particular ABI.
9082 unsafe_copy_elision_p_opt does consider whether there is padding. */
9085 unsafe_return_slot_p (tree t)
9087 /* Check empty bases separately, they don't have fields. */
9088 if (is_empty_base_ref (t))
9089 return 2;
9091 /* A delegating constructor might be used to initialize a base. */
9092 if (current_function_decl
9093 && DECL_CONSTRUCTOR_P (current_function_decl)
9094 && (t == current_class_ref
9095 || tree_strip_nop_conversions (t) == current_class_ptr))
9096 return 2;
9098 STRIP_NOPS (t);
9099 if (TREE_CODE (t) == ADDR_EXPR)
9100 t = TREE_OPERAND (t, 0);
9101 if (TREE_CODE (t) == COMPONENT_REF)
9102 t = TREE_OPERAND (t, 1);
9103 if (TREE_CODE (t) != FIELD_DECL)
9104 return false;
9105 if (!CLASS_TYPE_P (TREE_TYPE (t)))
9106 /* The middle-end will do the right thing for scalar types. */
9107 return false;
9108 if (DECL_FIELD_IS_BASE (t))
9109 return 2;
9110 if (lookup_attribute ("no_unique_address", DECL_ATTRIBUTES (t)))
9111 return 1;
9112 return 0;
9115 /* True IFF EXP is a prvalue that represents return by invisible reference. */
9117 static bool
9118 init_by_return_slot_p (tree exp)
9120 /* Copy elision only happens with a TARGET_EXPR. */
9121 if (TREE_CODE (exp) != TARGET_EXPR)
9122 return false;
9123 tree init = TARGET_EXPR_INITIAL (exp);
9124 /* build_compound_expr pushes COMPOUND_EXPR inside TARGET_EXPR. */
9125 while (TREE_CODE (init) == COMPOUND_EXPR)
9126 init = TREE_OPERAND (init, 1);
9127 if (TREE_CODE (init) == COND_EXPR)
9129 /* We'll end up copying from each of the arms of the COND_EXPR directly
9130 into the target, so look at them. */
9131 if (tree op = TREE_OPERAND (init, 1))
9132 if (init_by_return_slot_p (op))
9133 return true;
9134 return init_by_return_slot_p (TREE_OPERAND (init, 2));
9136 return (TREE_CODE (init) == AGGR_INIT_EXPR
9137 && !AGGR_INIT_VIA_CTOR_P (init));
9140 /* We can't elide a copy from a function returning by value to a
9141 potentially-overlapping subobject, as the callee might clobber tail padding.
9142 Return true iff this could be that case.
9144 Places that use this function (or _opt) to decide to elide a copy should
9145 probably use make_safe_copy_elision instead. */
9147 bool
9148 unsafe_copy_elision_p (tree target, tree exp)
9150 return unsafe_return_slot_p (target) && init_by_return_slot_p (exp);
9153 /* As above, but for optimization allow more cases that are actually safe. */
9155 static bool
9156 unsafe_copy_elision_p_opt (tree target, tree exp)
9158 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (exp));
9159 /* It's safe to elide the copy for a class with no tail padding. */
9160 if (!is_empty_class (type)
9161 && tree_int_cst_equal (TYPE_SIZE (type), CLASSTYPE_SIZE (type)))
9162 return false;
9163 return unsafe_copy_elision_p (target, exp);
9166 /* Try to make EXP suitable to be used as the initializer for TARGET,
9167 and return whether we were successful. */
9169 bool
9170 make_safe_copy_elision (tree target, tree exp)
9172 int uns = unsafe_return_slot_p (target);
9173 if (!uns)
9174 return true;
9175 if (init_by_return_slot_p (exp))
9176 return false;
9177 if (uns == 1)
9178 return true;
9179 return make_base_init_ok (exp);
9182 /* True IFF the result of the conversion C is a prvalue. */
9184 static bool
9185 conv_is_prvalue (conversion *c)
9187 if (c->kind == ck_rvalue)
9188 return true;
9189 if (c->kind == ck_base && c->need_temporary_p)
9190 return true;
9191 if (c->kind == ck_user && !TYPE_REF_P (c->type))
9192 return true;
9193 if (c->kind == ck_identity && c->u.expr
9194 && TREE_CODE (c->u.expr) == TARGET_EXPR)
9195 return true;
9197 return false;
9200 /* True iff C is a conversion that binds a reference to a prvalue. */
9202 static bool
9203 conv_binds_ref_to_prvalue (conversion *c)
9205 if (c->kind != ck_ref_bind)
9206 return false;
9207 if (c->need_temporary_p)
9208 return true;
9210 return conv_is_prvalue (next_conversion (c));
9213 /* True iff C is a conversion that binds a reference to a temporary.
9214 This is a superset of conv_binds_ref_to_prvalue: here we're also
9215 interested in xvalues. */
9217 static bool
9218 conv_binds_ref_to_temporary (conversion *c)
9220 if (conv_binds_ref_to_prvalue (c))
9221 return true;
9222 if (c->kind != ck_ref_bind)
9223 return false;
9224 c = next_conversion (c);
9225 /* This is the case for
9226 struct Base {};
9227 struct Derived : Base {};
9228 const Base& b(Derived{});
9229 where we bind 'b' to the Base subobject of a temporary object of type
9230 Derived. The subobject is an xvalue; the whole object is a prvalue. */
9231 if (c->kind != ck_base)
9232 return false;
9233 c = next_conversion (c);
9234 if (c->kind == ck_identity && c->u.expr)
9236 tree expr = c->u.expr;
9237 while (handled_component_p (expr))
9238 expr = TREE_OPERAND (expr, 0);
9239 if (TREE_CODE (expr) == TARGET_EXPR)
9240 return true;
9242 return false;
9245 /* Return tristate::TS_TRUE if converting EXPR to a reference type TYPE binds
9246 the reference to a temporary. Return tristate::TS_FALSE if converting
9247 EXPR to a reference type TYPE doesn't bind the reference to a temporary. If
9248 the conversion is invalid or bad, return tristate::TS_UNKNOWN. DIRECT_INIT_P
9249 says whether the conversion should be done in direct- or copy-initialization
9250 context. */
9252 tristate
9253 ref_conv_binds_to_temporary (tree type, tree expr, bool direct_init_p/*=false*/)
9255 gcc_assert (TYPE_REF_P (type));
9257 /* Get the high-water mark for the CONVERSION_OBSTACK. */
9258 void *p = conversion_obstack_alloc (0);
9260 const int flags = direct_init_p ? LOOKUP_NORMAL : LOOKUP_IMPLICIT;
9261 conversion *conv = implicit_conversion (type, TREE_TYPE (expr), expr,
9262 /*c_cast_p=*/false, flags, tf_none);
9263 tristate ret (tristate::TS_UNKNOWN);
9264 if (conv && !conv->bad_p)
9265 ret = tristate (conv_binds_ref_to_temporary (conv));
9267 /* Free all the conversions we allocated. */
9268 obstack_free (&conversion_obstack, p);
9270 return ret;
9273 /* Call the trivial destructor for INSTANCE, which can be either an lvalue of
9274 class type or a pointer to class type. If NO_PTR_DEREF is true and
9275 INSTANCE has pointer type, clobber the pointer rather than what it points
9276 to. */
9278 tree
9279 build_trivial_dtor_call (tree instance, bool no_ptr_deref)
9281 gcc_assert (!is_dummy_object (instance));
9283 if (!flag_lifetime_dse)
9285 no_clobber:
9286 return fold_convert (void_type_node, instance);
9289 if (INDIRECT_TYPE_P (TREE_TYPE (instance))
9290 && (!no_ptr_deref || TYPE_REF_P (TREE_TYPE (instance))))
9292 if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (instance))))
9293 goto no_clobber;
9294 instance = cp_build_fold_indirect_ref (instance);
9297 /* A trivial destructor should still clobber the object. */
9298 tree clobber = build_clobber (TREE_TYPE (instance));
9299 return build2 (MODIFY_EXPR, void_type_node,
9300 instance, clobber);
9303 /* Return true if in an immediate function context, or an unevaluated operand,
9304 or a subexpression of an immediate invocation. */
9306 bool
9307 in_immediate_context ()
9309 return (cp_unevaluated_operand != 0
9310 || (current_function_decl != NULL_TREE
9311 && DECL_IMMEDIATE_FUNCTION_P (current_function_decl))
9312 || (current_binding_level->kind == sk_function_parms
9313 && current_binding_level->immediate_fn_ctx_p)
9314 || in_consteval_if_p);
9317 /* Return true if a call to FN with number of arguments NARGS
9318 is an immediate invocation. */
9320 static bool
9321 immediate_invocation_p (tree fn, int nargs)
9323 return (TREE_CODE (fn) == FUNCTION_DECL
9324 && DECL_IMMEDIATE_FUNCTION_P (fn)
9325 && !in_immediate_context ()
9326 /* As an exception, we defer std::source_location::current ()
9327 invocations until genericization because LWG3396 mandates
9328 special behavior for it. */
9329 && (nargs > 1 || !source_location_current_p (fn)));
9332 /* temp_override for in_consteval_if_p, which can't use make_temp_override
9333 because it is a bitfield. */
9335 struct in_consteval_if_p_temp_override {
9336 bool save_in_consteval_if_p;
9337 in_consteval_if_p_temp_override ()
9338 : save_in_consteval_if_p (in_consteval_if_p) {}
9339 void reset () { in_consteval_if_p = save_in_consteval_if_p; }
9340 ~in_consteval_if_p_temp_override ()
9341 { reset (); }
9344 /* Subroutine of the various build_*_call functions. Overload resolution
9345 has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
9346 ARGS is a TREE_LIST of the unconverted arguments to the call. FLAGS is a
9347 bitmask of various LOOKUP_* flags which apply to the call itself. */
9349 static tree
9350 build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
9352 tree fn = cand->fn;
9353 const vec<tree, va_gc> *args = cand->args;
9354 tree first_arg = cand->first_arg;
9355 conversion **convs = cand->convs;
9356 conversion *conv;
9357 tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
9358 int parmlen;
9359 tree val;
9360 int i = 0;
9361 int j = 0;
9362 unsigned int arg_index = 0;
9363 int is_method = 0;
9364 int nargs;
9365 tree *argarray;
9366 bool already_used = false;
9368 /* In a template, there is no need to perform all of the work that
9369 is normally done. We are only interested in the type of the call
9370 expression, i.e., the return type of the function. Any semantic
9371 errors will be deferred until the template is instantiated. */
9372 if (processing_template_decl)
9374 if (undeduced_auto_decl (fn))
9375 mark_used (fn, complain);
9376 else
9377 /* Otherwise set TREE_USED for the benefit of -Wunused-function.
9378 See PR80598. */
9379 TREE_USED (fn) = 1;
9381 tree return_type = TREE_TYPE (TREE_TYPE (fn));
9382 tree callee;
9383 if (first_arg == NULL_TREE)
9385 callee = build_addr_func (fn, complain);
9386 if (callee == error_mark_node)
9387 return error_mark_node;
9389 else
9391 callee = build_baselink (cand->conversion_path, cand->access_path,
9392 fn, NULL_TREE);
9393 callee = build_min (COMPONENT_REF, TREE_TYPE (fn),
9394 first_arg, callee, NULL_TREE);
9397 tree expr = build_call_vec (return_type, callee, args);
9398 SET_EXPR_LOCATION (expr, input_location);
9399 if (TREE_THIS_VOLATILE (fn) && cfun)
9400 current_function_returns_abnormally = 1;
9401 if (immediate_invocation_p (fn, vec_safe_length (args)))
9403 tree obj_arg = NULL_TREE, exprimm = expr;
9404 if (DECL_CONSTRUCTOR_P (fn))
9405 obj_arg = first_arg;
9406 if (obj_arg
9407 && is_dummy_object (obj_arg)
9408 && !type_dependent_expression_p (obj_arg))
9410 exprimm = build_cplus_new (DECL_CONTEXT (fn), expr, complain);
9411 obj_arg = NULL_TREE;
9413 /* Look through *(const T *)&obj. */
9414 else if (obj_arg && TREE_CODE (obj_arg) == INDIRECT_REF)
9416 tree addr = TREE_OPERAND (obj_arg, 0);
9417 STRIP_NOPS (addr);
9418 if (TREE_CODE (addr) == ADDR_EXPR)
9420 tree typeo = TREE_TYPE (obj_arg);
9421 tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
9422 if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
9423 obj_arg = TREE_OPERAND (addr, 0);
9426 fold_non_dependent_expr (exprimm, complain,
9427 /*manifestly_const_eval=*/true,
9428 obj_arg);
9430 return convert_from_reference (expr);
9433 /* Give any warnings we noticed during overload resolution. */
9434 if (cand->warnings && (complain & tf_warning))
9436 struct candidate_warning *w;
9437 for (w = cand->warnings; w; w = w->next)
9438 joust (cand, w->loser, 1, complain);
9441 /* Core issue 2327: P0135 doesn't say how to handle the case where the
9442 argument to the copy constructor ends up being a prvalue after
9443 conversion. Let's do the normal processing, but pretend we aren't
9444 actually using the copy constructor. */
9445 bool force_elide = false;
9446 if (cxx_dialect >= cxx17
9447 && cand->num_convs == 1
9448 && DECL_COMPLETE_CONSTRUCTOR_P (fn)
9449 && (DECL_COPY_CONSTRUCTOR_P (fn)
9450 || DECL_MOVE_CONSTRUCTOR_P (fn))
9451 && !unsafe_return_slot_p (first_arg)
9452 && conv_binds_ref_to_prvalue (convs[0]))
9454 force_elide = true;
9455 goto not_really_used;
9458 /* OK, we're actually calling this inherited constructor; set its deletedness
9459 appropriately. We can get away with doing this here because calling is
9460 the only way to refer to a constructor. */
9461 if (DECL_INHERITED_CTOR (fn)
9462 && !deduce_inheriting_ctor (fn))
9464 if (complain & tf_error)
9465 mark_used (fn);
9466 return error_mark_node;
9469 /* Make =delete work with SFINAE. */
9470 if (DECL_DELETED_FN (fn))
9472 if (complain & tf_error)
9473 mark_used (fn);
9474 return error_mark_node;
9477 if (DECL_FUNCTION_MEMBER_P (fn))
9479 tree access_fn;
9480 /* If FN is a template function, two cases must be considered.
9481 For example:
9483 struct A {
9484 protected:
9485 template <class T> void f();
9487 template <class T> struct B {
9488 protected:
9489 void g();
9491 struct C : A, B<int> {
9492 using A::f; // #1
9493 using B<int>::g; // #2
9496 In case #1 where `A::f' is a member template, DECL_ACCESS is
9497 recorded in the primary template but not in its specialization.
9498 We check access of FN using its primary template.
9500 In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
9501 because it is a member of class template B, DECL_ACCESS is
9502 recorded in the specialization `B<int>::g'. We cannot use its
9503 primary template because `B<T>::g' and `B<int>::g' may have
9504 different access. */
9505 if (DECL_TEMPLATE_INFO (fn)
9506 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
9507 access_fn = DECL_TI_TEMPLATE (fn);
9508 else
9509 access_fn = fn;
9510 if (!perform_or_defer_access_check (cand->access_path, access_fn,
9511 fn, complain))
9512 return error_mark_node;
9515 /* If we're checking for implicit delete, don't bother with argument
9516 conversions. */
9517 if (flags & LOOKUP_SPECULATIVE)
9519 if (cand->viable == 1)
9520 return fn;
9521 else if (!(complain & tf_error))
9522 /* Reject bad conversions now. */
9523 return error_mark_node;
9524 /* else continue to get conversion error. */
9527 not_really_used:
9529 /* N3276 magic doesn't apply to nested calls. */
9530 tsubst_flags_t decltype_flag = (complain & tf_decltype);
9531 complain &= ~tf_decltype;
9532 /* No-Cleanup doesn't apply to nested calls either. */
9533 tsubst_flags_t no_cleanup_complain = complain;
9534 complain &= ~tf_no_cleanup;
9536 /* Find maximum size of vector to hold converted arguments. */
9537 parmlen = list_length (parm);
9538 nargs = vec_safe_length (args) + (first_arg != NULL_TREE ? 1 : 0);
9539 if (parmlen > nargs)
9540 nargs = parmlen;
9541 argarray = XALLOCAVEC (tree, nargs);
9543 in_consteval_if_p_temp_override icip;
9544 /* If the call is immediate function invocation, make sure
9545 taking address of immediate functions is allowed in its arguments. */
9546 if (immediate_invocation_p (STRIP_TEMPLATE (fn), nargs))
9547 in_consteval_if_p = true;
9549 /* The implicit parameters to a constructor are not considered by overload
9550 resolution, and must be of the proper type. */
9551 if (DECL_CONSTRUCTOR_P (fn))
9553 tree object_arg;
9554 if (first_arg != NULL_TREE)
9556 object_arg = first_arg;
9557 first_arg = NULL_TREE;
9559 else
9561 object_arg = (*args)[arg_index];
9562 ++arg_index;
9564 argarray[j++] = build_this (object_arg);
9565 parm = TREE_CHAIN (parm);
9566 /* We should never try to call the abstract constructor. */
9567 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
9569 if (DECL_HAS_VTT_PARM_P (fn))
9571 argarray[j++] = (*args)[arg_index];
9572 ++arg_index;
9573 parm = TREE_CHAIN (parm);
9576 if (cxx_dialect < cxx20
9577 && (cand->flags & LOOKUP_PREFER_RVALUE))
9579 /* The implicit move specified in 15.8.3/3 fails "...if the type of
9580 the first parameter of the selected constructor is not an rvalue
9581 reference to the object's type (possibly cv-qualified)...." */
9582 gcc_assert (!(complain & tf_error));
9583 tree ptype = convs[0]->type;
9584 /* Allow calling a by-value converting constructor even though it
9585 isn't permitted by the above, because we've allowed it since GCC 5
9586 (PR58051) and it's allowed in C++20. But don't call a copy
9587 constructor. */
9588 if ((TYPE_REF_P (ptype) && !TYPE_REF_IS_RVALUE (ptype))
9589 || CONVERSION_RANK (convs[0]) > cr_exact)
9590 return error_mark_node;
9593 /* Bypass access control for 'this' parameter. */
9594 else if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
9596 tree arg = build_this (first_arg != NULL_TREE
9597 ? first_arg
9598 : (*args)[arg_index]);
9599 tree argtype = TREE_TYPE (arg);
9601 if (arg == error_mark_node)
9602 return error_mark_node;
9604 if (convs[i]->bad_p)
9606 if (complain & tf_error)
9608 auto_diagnostic_group d;
9609 if (permerror (input_location, "passing %qT as %<this%> "
9610 "argument discards qualifiers",
9611 TREE_TYPE (argtype)))
9612 inform (DECL_SOURCE_LOCATION (fn), " in call to %qD", fn);
9614 else
9615 return error_mark_node;
9618 /* The class where FN is defined. */
9619 tree ctx = DECL_CONTEXT (fn);
9621 /* See if the function member or the whole class type is declared
9622 final and the call can be devirtualized. */
9623 if (DECL_FINAL_P (fn) || CLASSTYPE_FINAL (ctx))
9624 flags |= LOOKUP_NONVIRTUAL;
9626 /* [class.mfct.non-static]: If a non-static member function of a class
9627 X is called for an object that is not of type X, or of a type
9628 derived from X, the behavior is undefined.
9630 So we can assume that anything passed as 'this' is non-null, and
9631 optimize accordingly. */
9632 /* Check that the base class is accessible. */
9633 if (!accessible_base_p (TREE_TYPE (argtype),
9634 BINFO_TYPE (cand->conversion_path), true))
9636 if (complain & tf_error)
9637 error ("%qT is not an accessible base of %qT",
9638 BINFO_TYPE (cand->conversion_path),
9639 TREE_TYPE (argtype));
9640 else
9641 return error_mark_node;
9643 /* If fn was found by a using declaration, the conversion path
9644 will be to the derived class, not the base declaring fn. We
9645 must convert to the base. */
9646 tree base_binfo = cand->conversion_path;
9647 if (BINFO_TYPE (base_binfo) != ctx)
9649 base_binfo = lookup_base (base_binfo, ctx, ba_unique, NULL, complain);
9650 if (base_binfo == error_mark_node)
9651 return error_mark_node;
9654 /* If we know the dynamic type of the object, look up the final overrider
9655 in the BINFO. */
9656 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0
9657 && resolves_to_fixed_type_p (arg))
9659 tree ov = lookup_vfn_in_binfo (DECL_VINDEX (fn), base_binfo);
9661 /* And unwind base_binfo to match. If we don't find the type we're
9662 looking for in BINFO_INHERITANCE_CHAIN, we're looking at diamond
9663 inheritance; for now do a normal virtual call in that case. */
9664 tree octx = DECL_CONTEXT (ov);
9665 tree obinfo = base_binfo;
9666 while (obinfo && !SAME_BINFO_TYPE_P (BINFO_TYPE (obinfo), octx))
9667 obinfo = BINFO_INHERITANCE_CHAIN (obinfo);
9668 if (obinfo)
9670 fn = ov;
9671 base_binfo = obinfo;
9672 flags |= LOOKUP_NONVIRTUAL;
9676 tree converted_arg = build_base_path (PLUS_EXPR, arg,
9677 base_binfo, 1, complain);
9679 argarray[j++] = converted_arg;
9680 parm = TREE_CHAIN (parm);
9681 if (first_arg != NULL_TREE)
9682 first_arg = NULL_TREE;
9683 else
9684 ++arg_index;
9685 ++i;
9686 is_method = 1;
9689 gcc_assert (first_arg == NULL_TREE);
9690 for (; arg_index < vec_safe_length (args) && parm;
9691 parm = TREE_CHAIN (parm), ++arg_index, ++i)
9693 tree type = TREE_VALUE (parm);
9694 tree arg = (*args)[arg_index];
9695 bool conversion_warning = true;
9697 conv = convs[i];
9699 /* If the argument is NULL and used to (implicitly) instantiate a
9700 template function (and bind one of the template arguments to
9701 the type of 'long int'), we don't want to warn about passing NULL
9702 to non-pointer argument.
9703 For example, if we have this template function:
9705 template<typename T> void func(T x) {}
9707 we want to warn (when -Wconversion is enabled) in this case:
9709 void foo() {
9710 func<int>(NULL);
9713 but not in this case:
9715 void foo() {
9716 func(NULL);
9719 if (null_node_p (arg)
9720 && DECL_TEMPLATE_INFO (fn)
9721 && cand->template_decl
9722 && !cand->explicit_targs)
9723 conversion_warning = false;
9725 /* Set user_conv_p on the argument conversions, so rvalue/base handling
9726 knows not to allow any more UDCs. This needs to happen after we
9727 process cand->warnings. */
9728 if (flags & LOOKUP_NO_CONVERSION)
9729 conv->user_conv_p = true;
9731 tsubst_flags_t arg_complain = complain;
9732 if (!conversion_warning)
9733 arg_complain &= ~tf_warning;
9735 if (arg_complain & tf_warning)
9736 maybe_warn_pessimizing_move (arg, type, /*return_p*/false);
9738 val = convert_like_with_context (conv, arg, fn, i - is_method,
9739 arg_complain);
9740 val = convert_for_arg_passing (type, val, arg_complain);
9742 if (val == error_mark_node)
9743 return error_mark_node;
9744 else
9745 argarray[j++] = val;
9748 /* Default arguments */
9749 for (; parm && parm != void_list_node; parm = TREE_CHAIN (parm), i++)
9751 if (TREE_VALUE (parm) == error_mark_node)
9752 return error_mark_node;
9753 val = convert_default_arg (TREE_VALUE (parm),
9754 TREE_PURPOSE (parm),
9755 fn, i - is_method,
9756 complain);
9757 if (val == error_mark_node)
9758 return error_mark_node;
9759 argarray[j++] = val;
9762 /* Ellipsis */
9763 int magic = magic_varargs_p (fn);
9764 for (; arg_index < vec_safe_length (args); ++arg_index)
9766 tree a = (*args)[arg_index];
9767 if ((magic == 3 && arg_index == 2) || magic == 2)
9769 /* Do no conversions for certain magic varargs. */
9770 a = mark_type_use (a);
9771 if (TREE_CODE (a) == FUNCTION_DECL && reject_gcc_builtin (a))
9772 return error_mark_node;
9774 else if (magic != 0)
9775 /* For other magic varargs only do decay_conversion. */
9776 a = decay_conversion (a, complain);
9777 else if (DECL_CONSTRUCTOR_P (fn)
9778 && same_type_ignoring_top_level_qualifiers_p (DECL_CONTEXT (fn),
9779 TREE_TYPE (a)))
9781 /* Avoid infinite recursion trying to call A(...). */
9782 if (complain & tf_error)
9783 /* Try to call the actual copy constructor for a good error. */
9784 call_copy_ctor (a, complain);
9785 return error_mark_node;
9787 else
9788 a = convert_arg_to_ellipsis (a, complain);
9789 if (a == error_mark_node)
9790 return error_mark_node;
9791 argarray[j++] = a;
9794 gcc_assert (j <= nargs);
9795 nargs = j;
9796 icip.reset ();
9798 /* Avoid performing argument transformation if warnings are disabled.
9799 When tf_warning is set and at least one of the warnings is active
9800 the check_function_arguments function might warn about something. */
9802 bool warned_p = false;
9803 if ((complain & tf_warning)
9804 && (warn_nonnull
9805 || warn_format
9806 || warn_suggest_attribute_format
9807 || warn_restrict))
9809 tree *fargs = (!nargs ? argarray
9810 : (tree *) alloca (nargs * sizeof (tree)));
9811 for (j = 0; j < nargs; j++)
9813 /* For -Wformat undo the implicit passing by hidden reference
9814 done by convert_arg_to_ellipsis. */
9815 if (TREE_CODE (argarray[j]) == ADDR_EXPR
9816 && TYPE_REF_P (TREE_TYPE (argarray[j])))
9817 fargs[j] = TREE_OPERAND (argarray[j], 0);
9818 else
9819 fargs[j] = argarray[j];
9822 warned_p = check_function_arguments (input_location, fn, TREE_TYPE (fn),
9823 nargs, fargs, NULL);
9826 if (DECL_INHERITED_CTOR (fn))
9828 /* Check for passing ellipsis arguments to an inherited constructor. We
9829 could handle this by open-coding the inherited constructor rather than
9830 defining it, but let's not bother now. */
9831 if (!cp_unevaluated_operand
9832 && cand->num_convs
9833 && cand->convs[cand->num_convs-1]->ellipsis_p)
9835 if (complain & tf_error)
9837 sorry ("passing arguments to ellipsis of inherited constructor "
9838 "%qD", cand->fn);
9839 inform (DECL_SOURCE_LOCATION (cand->fn), "declared here");
9841 return error_mark_node;
9844 /* A base constructor inheriting from a virtual base doesn't get the
9845 inherited arguments, just this and __vtt. */
9846 if (ctor_omit_inherited_parms (fn))
9847 nargs = 2;
9850 /* Avoid actually calling copy constructors and copy assignment operators,
9851 if possible. */
9853 if (! flag_elide_constructors && !force_elide)
9854 /* Do things the hard way. */;
9855 else if (cand->num_convs == 1
9856 && (DECL_COPY_CONSTRUCTOR_P (fn)
9857 || DECL_MOVE_CONSTRUCTOR_P (fn))
9858 /* It's unsafe to elide the constructor when handling
9859 a noexcept-expression, it may evaluate to the wrong
9860 value (c++/53025). */
9861 && (force_elide || cp_noexcept_operand == 0))
9863 tree targ;
9864 tree arg = argarray[num_artificial_parms_for (fn)];
9865 tree fa = argarray[0];
9866 bool trivial = trivial_fn_p (fn);
9868 /* Pull out the real argument, disregarding const-correctness. */
9869 targ = arg;
9870 /* Strip the reference binding for the constructor parameter. */
9871 if (CONVERT_EXPR_P (targ)
9872 && TYPE_REF_P (TREE_TYPE (targ)))
9873 targ = TREE_OPERAND (targ, 0);
9874 /* But don't strip any other reference bindings; binding a temporary to a
9875 reference prevents copy elision. */
9876 while ((CONVERT_EXPR_P (targ)
9877 && !TYPE_REF_P (TREE_TYPE (targ)))
9878 || TREE_CODE (targ) == NON_LVALUE_EXPR)
9879 targ = TREE_OPERAND (targ, 0);
9880 if (TREE_CODE (targ) == ADDR_EXPR)
9882 targ = TREE_OPERAND (targ, 0);
9883 if (!same_type_ignoring_top_level_qualifiers_p
9884 (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
9885 targ = NULL_TREE;
9887 else
9888 targ = NULL_TREE;
9890 if (targ)
9891 arg = targ;
9892 else
9893 arg = cp_build_fold_indirect_ref (arg);
9895 /* In C++17 we shouldn't be copying a TARGET_EXPR except into a
9896 potentially-overlapping subobject. */
9897 if (CHECKING_P && cxx_dialect >= cxx17)
9898 gcc_assert (TREE_CODE (arg) != TARGET_EXPR
9899 || force_elide
9900 /* It's from binding the ref parm to a packed field. */
9901 || convs[0]->need_temporary_p
9902 || seen_error ()
9903 /* See unsafe_copy_elision_p. */
9904 || unsafe_return_slot_p (fa));
9906 bool unsafe = unsafe_copy_elision_p_opt (fa, arg);
9907 bool eliding_temp = (TREE_CODE (arg) == TARGET_EXPR && !unsafe);
9909 /* [class.copy]: the copy constructor is implicitly defined even if the
9910 implementation elided its use. But don't warn about deprecation when
9911 eliding a temporary, as then no copy is actually performed. */
9912 warning_sentinel s (warn_deprecated_copy, eliding_temp);
9913 if (force_elide)
9914 /* The language says this isn't called. */;
9915 else if (!trivial)
9917 if (!mark_used (fn, complain) && !(complain & tf_error))
9918 return error_mark_node;
9919 already_used = true;
9921 else
9922 cp_handle_deprecated_or_unavailable (fn, complain);
9924 if (eliding_temp && DECL_BASE_CONSTRUCTOR_P (fn)
9925 && !make_base_init_ok (arg))
9926 unsafe = true;
9928 /* If we're creating a temp and we already have one, don't create a
9929 new one. If we're not creating a temp but we get one, use
9930 INIT_EXPR to collapse the temp into our target. Otherwise, if the
9931 ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
9932 temp or an INIT_EXPR otherwise. */
9933 if (is_dummy_object (fa))
9935 if (TREE_CODE (arg) == TARGET_EXPR)
9936 return arg;
9937 else if (trivial)
9938 return force_target_expr (DECL_CONTEXT (fn), arg, complain);
9940 else if ((trivial || TREE_CODE (arg) == TARGET_EXPR)
9941 && !unsafe)
9943 tree to = cp_build_fold_indirect_ref (fa);
9944 val = cp_build_init_expr (to, arg);
9945 return val;
9948 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
9949 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR)
9950 && trivial_fn_p (fn))
9952 /* Don't use cp_build_fold_indirect_ref, op= returns an lvalue even if
9953 the object argument isn't one. */
9954 tree to = cp_build_indirect_ref (input_location, argarray[0],
9955 RO_ARROW, complain);
9956 tree type = TREE_TYPE (to);
9957 tree as_base = CLASSTYPE_AS_BASE (type);
9958 tree arg = argarray[1];
9959 location_t loc = cp_expr_loc_or_input_loc (arg);
9961 if (is_really_empty_class (type, /*ignore_vptr*/true))
9963 /* Avoid copying empty classes. */
9964 val = build2 (COMPOUND_EXPR, type, arg, to);
9965 suppress_warning (val, OPT_Wunused);
9967 else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
9969 if (is_std_init_list (type)
9970 && conv_binds_ref_to_prvalue (convs[1]))
9971 warning_at (loc, OPT_Winit_list_lifetime,
9972 "assignment from temporary %<initializer_list%> does "
9973 "not extend the lifetime of the underlying array");
9974 arg = cp_build_fold_indirect_ref (arg);
9975 val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
9977 else
9979 /* We must only copy the non-tail padding parts. */
9980 tree arg0, arg2, t;
9981 tree array_type, alias_set;
9983 arg2 = TYPE_SIZE_UNIT (as_base);
9984 to = cp_stabilize_reference (to);
9985 arg0 = cp_build_addr_expr (to, complain);
9987 array_type = build_array_type (unsigned_char_type_node,
9988 build_index_type
9989 (size_binop (MINUS_EXPR,
9990 arg2, size_int (1))));
9991 alias_set = build_int_cst (build_pointer_type (type), 0);
9992 t = build2 (MODIFY_EXPR, void_type_node,
9993 build2 (MEM_REF, array_type, arg0, alias_set),
9994 build2 (MEM_REF, array_type, arg, alias_set));
9995 val = build2 (COMPOUND_EXPR, TREE_TYPE (to), t, to);
9996 suppress_warning (val, OPT_Wunused);
9999 cp_handle_deprecated_or_unavailable (fn, complain);
10001 return val;
10003 else if (trivial_fn_p (fn))
10005 if (DECL_DESTRUCTOR_P (fn))
10006 return build_trivial_dtor_call (argarray[0]);
10007 else if (default_ctor_p (fn))
10009 if (is_dummy_object (argarray[0]))
10010 return force_target_expr (DECL_CONTEXT (fn), void_node,
10011 no_cleanup_complain);
10012 else
10013 return cp_build_fold_indirect_ref (argarray[0]);
10017 gcc_assert (!force_elide);
10019 if (!already_used
10020 && !mark_used (fn, complain))
10021 return error_mark_node;
10023 /* Warn if the built-in writes to an object of a non-trivial type. */
10024 if (warn_class_memaccess
10025 && vec_safe_length (args) >= 2
10026 && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
10027 maybe_warn_class_memaccess (input_location, fn, args);
10029 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
10031 tree t;
10032 tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
10033 DECL_CONTEXT (fn),
10034 ba_any, NULL, complain);
10035 gcc_assert (binfo && binfo != error_mark_node);
10037 argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1,
10038 complain);
10039 if (TREE_SIDE_EFFECTS (argarray[0]))
10040 argarray[0] = save_expr (argarray[0]);
10041 t = build_pointer_type (TREE_TYPE (fn));
10042 fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
10043 TREE_TYPE (fn) = t;
10045 else
10047 /* If FN is marked deprecated, then we've already issued a deprecated-use
10048 warning from mark_used above, so avoid redundantly issuing another one
10049 from build_addr_func. */
10050 warning_sentinel w (warn_deprecated_decl);
10052 fn = build_addr_func (fn, complain);
10053 if (fn == error_mark_node)
10054 return error_mark_node;
10057 tree call = build_cxx_call (fn, nargs, argarray, complain|decltype_flag);
10058 if (call == error_mark_node)
10059 return call;
10060 if (cand->flags & LOOKUP_LIST_INIT_CTOR)
10062 tree c = extract_call_expr (call);
10063 /* build_new_op will clear this when appropriate. */
10064 CALL_EXPR_ORDERED_ARGS (c) = true;
10066 if (warned_p)
10068 tree c = extract_call_expr (call);
10069 if (TREE_CODE (c) == CALL_EXPR)
10070 suppress_warning (c /* Suppress all warnings. */);
10072 if (TREE_CODE (fn) == ADDR_EXPR)
10074 tree fndecl = STRIP_TEMPLATE (TREE_OPERAND (fn, 0));
10075 if (immediate_invocation_p (fndecl, nargs))
10077 tree obj_arg = NULL_TREE;
10078 /* Undo convert_from_reference called by build_cxx_call. */
10079 if (REFERENCE_REF_P (call))
10080 call = TREE_OPERAND (call, 0);
10081 if (DECL_CONSTRUCTOR_P (fndecl))
10082 obj_arg = cand->first_arg ? cand->first_arg : (*args)[0];
10083 if (obj_arg && is_dummy_object (obj_arg))
10085 call = build_cplus_new (DECL_CONTEXT (fndecl), call, complain);
10086 obj_arg = NULL_TREE;
10088 /* Look through *(const T *)&obj. */
10089 else if (obj_arg && TREE_CODE (obj_arg) == INDIRECT_REF)
10091 tree addr = TREE_OPERAND (obj_arg, 0);
10092 STRIP_NOPS (addr);
10093 if (TREE_CODE (addr) == ADDR_EXPR)
10095 tree typeo = TREE_TYPE (obj_arg);
10096 tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
10097 if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
10098 obj_arg = TREE_OPERAND (addr, 0);
10101 call = cxx_constant_value (call, obj_arg, complain);
10102 if (obj_arg && !error_operand_p (call))
10103 call = cp_build_init_expr (obj_arg, call);
10104 call = convert_from_reference (call);
10107 return call;
10110 namespace
10113 /* Return the DECL of the first non-static subobject of class TYPE
10114 that satisfies the predicate PRED or null if none can be found. */
10116 template <class Predicate>
10117 tree
10118 first_non_static_field (tree type, Predicate pred)
10120 if (!type || !CLASS_TYPE_P (type))
10121 return NULL_TREE;
10123 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
10125 if (TREE_CODE (field) != FIELD_DECL)
10126 continue;
10127 if (TREE_STATIC (field))
10128 continue;
10129 if (pred (field))
10130 return field;
10133 int i = 0;
10135 for (tree base_binfo, binfo = TYPE_BINFO (type);
10136 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
10138 tree base = TREE_TYPE (base_binfo);
10139 if (pred (base))
10140 return base;
10141 if (tree field = first_non_static_field (base, pred))
10142 return field;
10145 return NULL_TREE;
10148 struct NonPublicField
10150 bool operator() (const_tree t) const
10152 return DECL_P (t) && (TREE_PRIVATE (t) || TREE_PROTECTED (t));
10156 /* Return the DECL of the first non-public subobject of class TYPE
10157 or null if none can be found. */
10159 static inline tree
10160 first_non_public_field (tree type)
10162 return first_non_static_field (type, NonPublicField ());
10165 struct NonTrivialField
10167 bool operator() (const_tree t) const
10169 return !trivial_type_p (DECL_P (t) ? TREE_TYPE (t) : t);
10173 /* Return the DECL of the first non-trivial subobject of class TYPE
10174 or null if none can be found. */
10176 static inline tree
10177 first_non_trivial_field (tree type)
10179 return first_non_static_field (type, NonTrivialField ());
10182 } /* unnamed namespace */
10184 /* Return true if all copy and move assignment operator overloads for
10185 class TYPE are trivial and at least one of them is not deleted and,
10186 when ACCESS is set, accessible. Return false otherwise. Set
10187 HASASSIGN to true when the TYPE has a (not necessarily trivial)
10188 copy or move assignment. */
10190 static bool
10191 has_trivial_copy_assign_p (tree type, bool access, bool *hasassign)
10193 tree fns = get_class_binding (type, assign_op_identifier);
10194 bool all_trivial = true;
10196 /* Iterate over overloads of the assignment operator, checking
10197 accessible copy assignments for triviality. */
10199 for (tree f : ovl_range (fns))
10201 /* Skip operators that aren't copy assignments. */
10202 if (!copy_fn_p (f))
10203 continue;
10205 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10206 || accessible_p (TYPE_BINFO (type), f, true));
10208 /* Skip template assignment operators and deleted functions. */
10209 if (TREE_CODE (f) != FUNCTION_DECL || DECL_DELETED_FN (f))
10210 continue;
10212 if (accessible)
10213 *hasassign = true;
10215 if (!accessible || !trivial_fn_p (f))
10216 all_trivial = false;
10218 /* Break early when both properties have been determined. */
10219 if (*hasassign && !all_trivial)
10220 break;
10223 /* Return true if they're all trivial and one of the expressions
10224 TYPE() = TYPE() or TYPE() = (TYPE&)() is valid. */
10225 tree ref = cp_build_reference_type (type, false);
10226 return (all_trivial
10227 && (is_trivially_xible (MODIFY_EXPR, type, type)
10228 || is_trivially_xible (MODIFY_EXPR, type, ref)));
10231 /* Return true if all copy and move ctor overloads for class TYPE are
10232 trivial and at least one of them is not deleted and, when ACCESS is
10233 set, accessible. Return false otherwise. Set each element of HASCTOR[]
10234 to true when the TYPE has a (not necessarily trivial) default and copy
10235 (or move) ctor, respectively. */
10237 static bool
10238 has_trivial_copy_p (tree type, bool access, bool hasctor[2])
10240 tree fns = get_class_binding (type, complete_ctor_identifier);
10241 bool all_trivial = true;
10243 for (tree f : ovl_range (fns))
10245 /* Skip template constructors. */
10246 if (TREE_CODE (f) != FUNCTION_DECL)
10247 continue;
10249 bool cpy_or_move_ctor_p = copy_fn_p (f);
10251 /* Skip ctors other than default, copy, and move. */
10252 if (!cpy_or_move_ctor_p && !default_ctor_p (f))
10253 continue;
10255 if (DECL_DELETED_FN (f))
10256 continue;
10258 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10259 || accessible_p (TYPE_BINFO (type), f, true));
10261 if (accessible)
10262 hasctor[cpy_or_move_ctor_p] = true;
10264 if (cpy_or_move_ctor_p && (!accessible || !trivial_fn_p (f)))
10265 all_trivial = false;
10267 /* Break early when both properties have been determined. */
10268 if (hasctor[0] && hasctor[1] && !all_trivial)
10269 break;
10272 return all_trivial;
10275 /* Issue a warning on a call to the built-in function FNDECL if it is
10276 a raw memory write whose destination is not an object of (something
10277 like) trivial or standard layout type with a non-deleted assignment
10278 and copy ctor. Detects const correctness violations, corrupting
10279 references, virtual table pointers, and bypassing non-trivial
10280 assignments. */
10282 static void
10283 maybe_warn_class_memaccess (location_t loc, tree fndecl,
10284 const vec<tree, va_gc> *args)
10286 /* Except for bcopy where it's second, the destination pointer is
10287 the first argument for all functions handled here. Compute
10288 the index of the destination and source arguments. */
10289 unsigned dstidx = DECL_FUNCTION_CODE (fndecl) == BUILT_IN_BCOPY;
10290 unsigned srcidx = !dstidx;
10292 tree dest = (*args)[dstidx];
10293 if (!TREE_TYPE (dest)
10294 || (TREE_CODE (TREE_TYPE (dest)) != ARRAY_TYPE
10295 && !INDIRECT_TYPE_P (TREE_TYPE (dest))))
10296 return;
10298 tree srctype = NULL_TREE;
10300 /* Determine the type of the pointed-to object and whether it's
10301 a complete class type. */
10302 tree desttype = TREE_TYPE (TREE_TYPE (dest));
10304 if (!desttype || !COMPLETE_TYPE_P (desttype) || !CLASS_TYPE_P (desttype))
10305 return;
10307 /* Check to see if the raw memory call is made by a non-static member
10308 function with THIS as the destination argument for the destination
10309 type. If so, and if the class has no non-trivial bases or members,
10310 be more permissive. */
10311 if (current_function_decl
10312 && DECL_NONSTATIC_MEMBER_FUNCTION_P (current_function_decl)
10313 && is_this_parameter (tree_strip_nop_conversions (dest)))
10315 tree ctx = DECL_CONTEXT (current_function_decl);
10316 bool special = same_type_ignoring_top_level_qualifiers_p (ctx, desttype);
10317 tree binfo = TYPE_BINFO (ctx);
10319 if (special
10320 && !BINFO_VTABLE (binfo)
10321 && !first_non_trivial_field (desttype))
10322 return;
10325 /* True if the class is trivial. */
10326 bool trivial = trivial_type_p (desttype);
10328 /* Set to true if DESTYPE has an accessible copy assignment. */
10329 bool hasassign = false;
10330 /* True if all of the class' overloaded copy assignment operators
10331 are all trivial (and not deleted) and at least one of them is
10332 accessible. */
10333 bool trivassign = has_trivial_copy_assign_p (desttype, true, &hasassign);
10335 /* Set to true if DESTTYPE has an accessible default and copy ctor,
10336 respectively. */
10337 bool hasctors[2] = { false, false };
10339 /* True if all of the class' overloaded copy constructors are all
10340 trivial (and not deleted) and at least one of them is accessible. */
10341 bool trivcopy = has_trivial_copy_p (desttype, true, hasctors);
10343 /* Set FLD to the first private/protected member of the class. */
10344 tree fld = trivial ? first_non_public_field (desttype) : NULL_TREE;
10346 /* The warning format string. */
10347 const char *warnfmt = NULL;
10348 /* A suggested alternative to offer instead of the raw memory call.
10349 Empty string when none can be come up with. */
10350 const char *suggest = "";
10351 bool warned = false;
10353 switch (DECL_FUNCTION_CODE (fndecl))
10355 case BUILT_IN_MEMSET:
10356 if (!integer_zerop (maybe_constant_value ((*args)[1])))
10358 /* Diagnose setting non-copy-assignable or non-trivial types,
10359 or types with a private member, to (potentially) non-zero
10360 bytes. Since the value of the bytes being written is unknown,
10361 suggest using assignment instead (if one exists). Also warn
10362 for writes into objects for which zero-initialization doesn't
10363 mean all bits clear (pointer-to-member data, where null is all
10364 bits set). Since the value being written is (most likely)
10365 non-zero, simply suggest assignment (but not copy assignment). */
10366 suggest = "; use assignment instead";
10367 if (!trivassign)
10368 warnfmt = G_("%qD writing to an object of type %#qT with "
10369 "no trivial copy-assignment");
10370 else if (!trivial)
10371 warnfmt = G_("%qD writing to an object of non-trivial type %#qT%s");
10372 else if (fld)
10374 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10375 warned = warning_at (loc, OPT_Wclass_memaccess,
10376 "%qD writing to an object of type %#qT with "
10377 "%qs member %qD",
10378 fndecl, desttype, access, fld);
10380 else if (!zero_init_p (desttype))
10381 warnfmt = G_("%qD writing to an object of type %#qT containing "
10382 "a pointer to data member%s");
10384 break;
10386 /* Fall through. */
10388 case BUILT_IN_BZERO:
10389 /* Similarly to the above, diagnose clearing non-trivial or non-
10390 standard layout objects, or objects of types with no assignmenmt.
10391 Since the value being written is known to be zero, suggest either
10392 copy assignment, copy ctor, or default ctor as an alternative,
10393 depending on what's available. */
10395 if (hasassign && hasctors[0])
10396 suggest = G_("; use assignment or value-initialization instead");
10397 else if (hasassign)
10398 suggest = G_("; use assignment instead");
10399 else if (hasctors[0])
10400 suggest = G_("; use value-initialization instead");
10402 if (!trivassign)
10403 warnfmt = G_("%qD clearing an object of type %#qT with "
10404 "no trivial copy-assignment%s");
10405 else if (!trivial)
10406 warnfmt = G_("%qD clearing an object of non-trivial type %#qT%s");
10407 else if (!zero_init_p (desttype))
10408 warnfmt = G_("%qD clearing an object of type %#qT containing "
10409 "a pointer-to-member%s");
10410 break;
10412 case BUILT_IN_BCOPY:
10413 case BUILT_IN_MEMCPY:
10414 case BUILT_IN_MEMMOVE:
10415 case BUILT_IN_MEMPCPY:
10416 /* Determine the type of the source object. */
10417 srctype = TREE_TYPE ((*args)[srcidx]);
10418 if (!srctype || !INDIRECT_TYPE_P (srctype))
10419 srctype = void_type_node;
10420 else
10421 srctype = TREE_TYPE (srctype);
10423 /* Since it's impossible to determine wheter the byte copy is
10424 being used in place of assignment to an existing object or
10425 as a substitute for initialization, assume it's the former.
10426 Determine the best alternative to use instead depending on
10427 what's not deleted. */
10428 if (hasassign && hasctors[1])
10429 suggest = G_("; use copy-assignment or copy-initialization instead");
10430 else if (hasassign)
10431 suggest = G_("; use copy-assignment instead");
10432 else if (hasctors[1])
10433 suggest = G_("; use copy-initialization instead");
10435 if (!trivassign)
10436 warnfmt = G_("%qD writing to an object of type %#qT with no trivial "
10437 "copy-assignment%s");
10438 else if (!trivially_copyable_p (desttype))
10439 warnfmt = G_("%qD writing to an object of non-trivially copyable "
10440 "type %#qT%s");
10441 else if (!trivcopy)
10442 warnfmt = G_("%qD writing to an object with a deleted copy constructor");
10444 else if (!trivial
10445 && !VOID_TYPE_P (srctype)
10446 && !is_byte_access_type (srctype)
10447 && !same_type_ignoring_top_level_qualifiers_p (desttype,
10448 srctype))
10450 /* Warn when copying into a non-trivial object from an object
10451 of a different type other than void or char. */
10452 warned = warning_at (loc, OPT_Wclass_memaccess,
10453 "%qD copying an object of non-trivial type "
10454 "%#qT from an array of %#qT",
10455 fndecl, desttype, srctype);
10457 else if (fld
10458 && !VOID_TYPE_P (srctype)
10459 && !is_byte_access_type (srctype)
10460 && !same_type_ignoring_top_level_qualifiers_p (desttype,
10461 srctype))
10463 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10464 warned = warning_at (loc, OPT_Wclass_memaccess,
10465 "%qD copying an object of type %#qT with "
10466 "%qs member %qD from an array of %#qT; use "
10467 "assignment or copy-initialization instead",
10468 fndecl, desttype, access, fld, srctype);
10470 else if (!trivial && vec_safe_length (args) > 2)
10472 tree sz = maybe_constant_value ((*args)[2]);
10473 if (!tree_fits_uhwi_p (sz))
10474 break;
10476 /* Finally, warn on partial copies. */
10477 unsigned HOST_WIDE_INT typesize
10478 = tree_to_uhwi (TYPE_SIZE_UNIT (desttype));
10479 if (typesize == 0)
10480 break;
10481 if (unsigned HOST_WIDE_INT partial = tree_to_uhwi (sz) % typesize)
10482 warned = warning_at (loc, OPT_Wclass_memaccess,
10483 (typesize - partial > 1
10484 ? G_("%qD writing to an object of "
10485 "a non-trivial type %#qT leaves %wu "
10486 "bytes unchanged")
10487 : G_("%qD writing to an object of "
10488 "a non-trivial type %#qT leaves %wu "
10489 "byte unchanged")),
10490 fndecl, desttype, typesize - partial);
10492 break;
10494 case BUILT_IN_REALLOC:
10496 if (!trivially_copyable_p (desttype))
10497 warnfmt = G_("%qD moving an object of non-trivially copyable type "
10498 "%#qT; use %<new%> and %<delete%> instead");
10499 else if (!trivcopy)
10500 warnfmt = G_("%qD moving an object of type %#qT with deleted copy "
10501 "constructor; use %<new%> and %<delete%> instead");
10502 else if (!get_dtor (desttype, tf_none))
10503 warnfmt = G_("%qD moving an object of type %#qT with deleted "
10504 "destructor");
10505 else if (!trivial)
10507 tree sz = maybe_constant_value ((*args)[1]);
10508 if (TREE_CODE (sz) == INTEGER_CST
10509 && tree_int_cst_lt (sz, TYPE_SIZE_UNIT (desttype)))
10510 /* Finally, warn on reallocation into insufficient space. */
10511 warned = warning_at (loc, OPT_Wclass_memaccess,
10512 "%qD moving an object of non-trivial type "
10513 "%#qT and size %E into a region of size %E",
10514 fndecl, desttype, TYPE_SIZE_UNIT (desttype),
10515 sz);
10517 break;
10519 default:
10520 return;
10523 if (warnfmt)
10525 if (suggest)
10526 warned = warning_at (loc, OPT_Wclass_memaccess,
10527 warnfmt, fndecl, desttype, suggest);
10528 else
10529 warned = warning_at (loc, OPT_Wclass_memaccess,
10530 warnfmt, fndecl, desttype);
10533 if (warned)
10534 inform (location_of (desttype), "%#qT declared here", desttype);
10537 /* Build and return a call to FN, using NARGS arguments in ARGARRAY.
10538 If FN is the result of resolving an overloaded target built-in,
10539 ORIG_FNDECL is the original function decl, otherwise it is null.
10540 This function performs no overload resolution, conversion, or other
10541 high-level operations. */
10543 tree
10544 build_cxx_call (tree fn, int nargs, tree *argarray,
10545 tsubst_flags_t complain, tree orig_fndecl)
10547 tree fndecl;
10549 /* Remember roughly where this call is. */
10550 location_t loc = cp_expr_loc_or_input_loc (fn);
10551 fn = build_call_a (fn, nargs, argarray);
10552 SET_EXPR_LOCATION (fn, loc);
10554 fndecl = get_callee_fndecl (fn);
10555 if (!orig_fndecl)
10556 orig_fndecl = fndecl;
10558 /* Check that arguments to builtin functions match the expectations. */
10559 if (fndecl
10560 && !processing_template_decl
10561 && fndecl_built_in_p (fndecl))
10563 int i;
10565 /* We need to take care that values to BUILT_IN_NORMAL
10566 are reduced. */
10567 for (i = 0; i < nargs; i++)
10568 argarray[i] = maybe_constant_value (argarray[i]);
10570 if (!check_builtin_function_arguments (EXPR_LOCATION (fn), vNULL, fndecl,
10571 orig_fndecl, nargs, argarray))
10572 return error_mark_node;
10573 else if (fndecl_built_in_p (fndecl, BUILT_IN_CLEAR_PADDING))
10575 tree arg0 = argarray[0];
10576 STRIP_NOPS (arg0);
10577 if (TREE_CODE (arg0) == ADDR_EXPR
10578 && DECL_P (TREE_OPERAND (arg0, 0))
10579 && same_type_ignoring_top_level_qualifiers_p
10580 (TREE_TYPE (TREE_TYPE (argarray[0])),
10581 TREE_TYPE (TREE_TYPE (arg0))))
10582 /* For __builtin_clear_padding (&var) we know the type
10583 is for a complete object, so there is no risk in clearing
10584 padding that is reused in some derived class member. */;
10585 else if (!trivially_copyable_p (TREE_TYPE (TREE_TYPE (argarray[0]))))
10587 error_at (EXPR_LOC_OR_LOC (argarray[0], input_location),
10588 "argument %u in call to function %qE "
10589 "has pointer to a non-trivially-copyable type (%qT)",
10590 1, fndecl, TREE_TYPE (argarray[0]));
10591 return error_mark_node;
10596 if (VOID_TYPE_P (TREE_TYPE (fn)))
10597 return fn;
10599 /* 5.2.2/11: If a function call is a prvalue of object type: if the
10600 function call is either the operand of a decltype-specifier or the
10601 right operand of a comma operator that is the operand of a
10602 decltype-specifier, a temporary object is not introduced for the
10603 prvalue. The type of the prvalue may be incomplete. */
10604 if (!(complain & tf_decltype))
10606 fn = require_complete_type (fn, complain);
10607 if (fn == error_mark_node)
10608 return error_mark_node;
10610 if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
10612 fn = build_cplus_new (TREE_TYPE (fn), fn, complain);
10613 maybe_warn_parm_abi (TREE_TYPE (fn), loc);
10616 return convert_from_reference (fn);
10619 /* Returns the value to use for the in-charge parameter when making a
10620 call to a function with the indicated NAME.
10622 FIXME:Can't we find a neater way to do this mapping? */
10624 tree
10625 in_charge_arg_for_name (tree name)
10627 if (IDENTIFIER_CTOR_P (name))
10629 if (name == complete_ctor_identifier)
10630 return integer_one_node;
10631 gcc_checking_assert (name == base_ctor_identifier);
10633 else
10635 if (name == complete_dtor_identifier)
10636 return integer_two_node;
10637 else if (name == deleting_dtor_identifier)
10638 return integer_three_node;
10639 gcc_checking_assert (name == base_dtor_identifier);
10642 return integer_zero_node;
10645 /* We've built up a constructor call RET. Complain if it delegates to the
10646 constructor we're currently compiling. */
10648 static void
10649 check_self_delegation (tree ret)
10651 if (TREE_CODE (ret) == TARGET_EXPR)
10652 ret = TARGET_EXPR_INITIAL (ret);
10653 tree fn = cp_get_callee_fndecl_nofold (ret);
10654 if (fn && DECL_ABSTRACT_ORIGIN (fn) == current_function_decl)
10655 error ("constructor delegates to itself");
10658 /* Build a call to a constructor, destructor, or an assignment
10659 operator for INSTANCE, an expression with class type. NAME
10660 indicates the special member function to call; *ARGS are the
10661 arguments. ARGS may be NULL. This may change ARGS. BINFO
10662 indicates the base of INSTANCE that is to be passed as the `this'
10663 parameter to the member function called.
10665 FLAGS are the LOOKUP_* flags to use when processing the call.
10667 If NAME indicates a complete object constructor, INSTANCE may be
10668 NULL_TREE. In this case, the caller will call build_cplus_new to
10669 store the newly constructed object into a VAR_DECL. */
10671 tree
10672 build_special_member_call (tree instance, tree name, vec<tree, va_gc> **args,
10673 tree binfo, int flags, tsubst_flags_t complain)
10675 tree fns;
10676 /* The type of the subobject to be constructed or destroyed. */
10677 tree class_type;
10678 vec<tree, va_gc> *allocated = NULL;
10679 tree ret;
10681 gcc_assert (IDENTIFIER_CDTOR_P (name) || name == assign_op_identifier);
10683 if (error_operand_p (instance))
10684 return error_mark_node;
10686 if (IDENTIFIER_DTOR_P (name))
10688 gcc_assert (args == NULL || vec_safe_is_empty (*args));
10689 if (!type_build_dtor_call (TREE_TYPE (instance)))
10690 /* Shortcut to avoid lazy destructor declaration. */
10691 return build_trivial_dtor_call (instance);
10694 if (TYPE_P (binfo))
10696 /* Resolve the name. */
10697 if (!complete_type_or_maybe_complain (binfo, NULL_TREE, complain))
10698 return error_mark_node;
10700 binfo = TYPE_BINFO (binfo);
10703 gcc_assert (binfo != NULL_TREE);
10705 class_type = BINFO_TYPE (binfo);
10707 /* Handle the special case where INSTANCE is NULL_TREE. */
10708 if (name == complete_ctor_identifier && !instance)
10709 instance = build_dummy_object (class_type);
10710 else
10712 /* Convert to the base class, if necessary. */
10713 if (!same_type_ignoring_top_level_qualifiers_p
10714 (TREE_TYPE (instance), BINFO_TYPE (binfo)))
10716 if (IDENTIFIER_CDTOR_P (name))
10717 /* For constructors and destructors, either the base is
10718 non-virtual, or it is virtual but we are doing the
10719 conversion from a constructor or destructor for the
10720 complete object. In either case, we can convert
10721 statically. */
10722 instance = convert_to_base_statically (instance, binfo);
10723 else
10725 /* However, for assignment operators, we must convert
10726 dynamically if the base is virtual. */
10727 gcc_checking_assert (name == assign_op_identifier);
10728 instance = build_base_path (PLUS_EXPR, instance,
10729 binfo, /*nonnull=*/1, complain);
10734 gcc_assert (instance != NULL_TREE);
10736 /* In C++17, "If the initializer expression is a prvalue and the
10737 cv-unqualified version of the source type is the same class as the class
10738 of the destination, the initializer expression is used to initialize the
10739 destination object." Handle that here to avoid doing overload
10740 resolution. */
10741 if (cxx_dialect >= cxx17
10742 && args && vec_safe_length (*args) == 1
10743 && !unsafe_return_slot_p (instance))
10745 tree arg = (**args)[0];
10747 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
10748 && !TYPE_HAS_LIST_CTOR (class_type)
10749 && !CONSTRUCTOR_IS_DESIGNATED_INIT (arg)
10750 && CONSTRUCTOR_NELTS (arg) == 1)
10751 arg = CONSTRUCTOR_ELT (arg, 0)->value;
10753 if ((TREE_CODE (arg) == TARGET_EXPR
10754 || TREE_CODE (arg) == CONSTRUCTOR)
10755 && (same_type_ignoring_top_level_qualifiers_p
10756 (class_type, TREE_TYPE (arg))))
10758 if (is_dummy_object (instance))
10759 return arg;
10760 else if (TREE_CODE (arg) == TARGET_EXPR)
10761 TARGET_EXPR_DIRECT_INIT_P (arg) = true;
10763 if ((complain & tf_error)
10764 && (flags & LOOKUP_DELEGATING_CONS))
10765 check_self_delegation (arg);
10766 /* Avoid change of behavior on Wunused-var-2.C. */
10767 instance = mark_lvalue_use (instance);
10768 return cp_build_init_expr (instance, arg);
10772 fns = lookup_fnfields (binfo, name, 1, complain);
10774 /* When making a call to a constructor or destructor for a subobject
10775 that uses virtual base classes, pass down a pointer to a VTT for
10776 the subobject. */
10777 if ((name == base_ctor_identifier
10778 || name == base_dtor_identifier)
10779 && CLASSTYPE_VBASECLASSES (class_type))
10781 tree vtt;
10782 tree sub_vtt;
10784 /* If the current function is a complete object constructor
10785 or destructor, then we fetch the VTT directly.
10786 Otherwise, we look it up using the VTT we were given. */
10787 vtt = DECL_CHAIN (CLASSTYPE_VTABLES (current_class_type));
10788 vtt = decay_conversion (vtt, complain);
10789 if (vtt == error_mark_node)
10790 return error_mark_node;
10791 vtt = build_if_in_charge (vtt, current_vtt_parm);
10792 if (BINFO_SUBVTT_INDEX (binfo))
10793 sub_vtt = fold_build_pointer_plus (vtt, BINFO_SUBVTT_INDEX (binfo));
10794 else
10795 sub_vtt = vtt;
10797 if (args == NULL)
10799 allocated = make_tree_vector ();
10800 args = &allocated;
10803 vec_safe_insert (*args, 0, sub_vtt);
10806 ret = build_new_method_call (instance, fns, args,
10807 TYPE_BINFO (BINFO_TYPE (binfo)),
10808 flags, /*fn=*/NULL,
10809 complain);
10811 if (allocated != NULL)
10812 release_tree_vector (allocated);
10814 if ((complain & tf_error)
10815 && (flags & LOOKUP_DELEGATING_CONS)
10816 && name == complete_ctor_identifier)
10817 check_self_delegation (ret);
10819 return ret;
10822 /* Return the NAME, as a C string. The NAME indicates a function that
10823 is a member of TYPE. *FREE_P is set to true if the caller must
10824 free the memory returned.
10826 Rather than go through all of this, we should simply set the names
10827 of constructors and destructors appropriately, and dispense with
10828 ctor_identifier, dtor_identifier, etc. */
10830 static char *
10831 name_as_c_string (tree name, tree type, bool *free_p)
10833 const char *pretty_name;
10835 /* Assume that we will not allocate memory. */
10836 *free_p = false;
10837 /* Constructors and destructors are special. */
10838 if (IDENTIFIER_CDTOR_P (name))
10840 pretty_name
10841 = identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type)));
10842 /* For a destructor, add the '~'. */
10843 if (IDENTIFIER_DTOR_P (name))
10845 pretty_name = concat ("~", pretty_name, NULL);
10846 /* Remember that we need to free the memory allocated. */
10847 *free_p = true;
10850 else if (IDENTIFIER_CONV_OP_P (name))
10852 pretty_name = concat ("operator ",
10853 type_as_string_translate (TREE_TYPE (name),
10854 TFF_PLAIN_IDENTIFIER),
10855 NULL);
10856 /* Remember that we need to free the memory allocated. */
10857 *free_p = true;
10859 else
10860 pretty_name = identifier_to_locale (IDENTIFIER_POINTER (name));
10862 return CONST_CAST (char *, pretty_name);
10865 /* If CANDIDATES contains exactly one candidate, return it, otherwise
10866 return NULL. */
10868 static z_candidate *
10869 single_z_candidate (z_candidate *candidates)
10871 if (candidates == NULL)
10872 return NULL;
10874 if (candidates->next)
10875 return NULL;
10877 return candidates;
10880 /* If CANDIDATE is invalid due to a bad argument type, return the
10881 pertinent conversion_info.
10883 Otherwise, return NULL. */
10885 static const conversion_info *
10886 maybe_get_bad_conversion_for_unmatched_call (const z_candidate *candidate)
10888 /* Must be an rr_arg_conversion or rr_bad_arg_conversion. */
10889 rejection_reason *r = candidate->reason;
10891 if (r == NULL)
10892 return NULL;
10894 switch (r->code)
10896 default:
10897 return NULL;
10899 case rr_arg_conversion:
10900 return &r->u.conversion;
10902 case rr_bad_arg_conversion:
10903 return &r->u.bad_conversion;
10907 /* Issue an error and note complaining about a bad argument type at a
10908 callsite with a single candidate FNDECL.
10910 ARG_LOC is the location of the argument (or UNKNOWN_LOCATION, in which
10911 case input_location is used).
10912 FROM_TYPE is the type of the actual argument; TO_TYPE is the type of
10913 the formal parameter. */
10915 void
10916 complain_about_bad_argument (location_t arg_loc,
10917 tree from_type, tree to_type,
10918 tree fndecl, int parmnum)
10920 auto_diagnostic_group d;
10921 range_label_for_type_mismatch rhs_label (from_type, to_type);
10922 range_label *label = &rhs_label;
10923 if (arg_loc == UNKNOWN_LOCATION)
10925 arg_loc = input_location;
10926 label = NULL;
10928 gcc_rich_location richloc (arg_loc, label);
10929 error_at (&richloc,
10930 "cannot convert %qH to %qI",
10931 from_type, to_type);
10932 maybe_inform_about_fndecl_for_bogus_argument_init (fndecl,
10933 parmnum);
10936 /* Subroutine of build_new_method_call_1, for where there are no viable
10937 candidates for the call. */
10939 static void
10940 complain_about_no_candidates_for_method_call (tree instance,
10941 z_candidate *candidates,
10942 tree explicit_targs,
10943 tree basetype,
10944 tree optype, tree name,
10945 bool skip_first_for_error,
10946 vec<tree, va_gc> *user_args)
10948 auto_diagnostic_group d;
10949 if (!COMPLETE_OR_OPEN_TYPE_P (basetype))
10950 cxx_incomplete_type_error (instance, basetype);
10951 else if (optype)
10952 error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
10953 basetype, optype, build_tree_list_vec (user_args),
10954 TREE_TYPE (instance));
10955 else
10957 /* Special-case for when there's a single candidate that's failing
10958 due to a bad argument type. */
10959 if (z_candidate *candidate = single_z_candidate (candidates))
10960 if (const conversion_info *conv
10961 = maybe_get_bad_conversion_for_unmatched_call (candidate))
10963 tree from_type = conv->from;
10964 if (!TYPE_P (conv->from))
10965 from_type = lvalue_type (conv->from);
10966 complain_about_bad_argument (conv->loc,
10967 from_type, conv->to_type,
10968 candidate->fn, conv->n_arg);
10969 return;
10972 tree arglist = build_tree_list_vec (user_args);
10973 tree errname = name;
10974 bool twiddle = false;
10975 if (IDENTIFIER_CDTOR_P (errname))
10977 twiddle = IDENTIFIER_DTOR_P (errname);
10978 errname = constructor_name (basetype);
10980 if (explicit_targs)
10981 errname = lookup_template_function (errname, explicit_targs);
10982 if (skip_first_for_error)
10983 arglist = TREE_CHAIN (arglist);
10984 error ("no matching function for call to %<%T::%s%E(%A)%#V%>",
10985 basetype, &"~"[!twiddle], errname, arglist,
10986 TREE_TYPE (instance));
10988 print_z_candidates (location_of (name), candidates);
10991 /* Build a call to "INSTANCE.FN (ARGS)". If FN_P is non-NULL, it will
10992 be set, upon return, to the function called. ARGS may be NULL.
10993 This may change ARGS. */
10995 tree
10996 build_new_method_call (tree instance, tree fns, vec<tree, va_gc> **args,
10997 tree conversion_path, int flags,
10998 tree *fn_p, tsubst_flags_t complain)
11000 struct z_candidate *candidates = 0, *cand;
11001 tree explicit_targs = NULL_TREE;
11002 tree basetype = NULL_TREE;
11003 tree access_binfo;
11004 tree optype;
11005 tree first_mem_arg = NULL_TREE;
11006 tree name;
11007 bool skip_first_for_error;
11008 vec<tree, va_gc> *user_args;
11009 tree call;
11010 tree fn;
11011 int template_only = 0;
11012 bool any_viable_p;
11013 tree orig_instance;
11014 tree orig_fns;
11015 vec<tree, va_gc> *orig_args = NULL;
11016 void *p;
11018 auto_cond_timevar tv (TV_OVERLOAD);
11020 gcc_assert (instance != NULL_TREE);
11022 /* We don't know what function we're going to call, yet. */
11023 if (fn_p)
11024 *fn_p = NULL_TREE;
11026 if (error_operand_p (instance)
11027 || !fns || error_operand_p (fns))
11028 return error_mark_node;
11030 if (!BASELINK_P (fns))
11032 if (complain & tf_error)
11033 error ("call to non-function %qD", fns);
11034 return error_mark_node;
11037 orig_instance = instance;
11038 orig_fns = fns;
11040 /* Dismantle the baselink to collect all the information we need. */
11041 if (!conversion_path)
11042 conversion_path = BASELINK_BINFO (fns);
11043 access_binfo = BASELINK_ACCESS_BINFO (fns);
11044 optype = BASELINK_OPTYPE (fns);
11045 fns = BASELINK_FUNCTIONS (fns);
11046 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11048 explicit_targs = TREE_OPERAND (fns, 1);
11049 fns = TREE_OPERAND (fns, 0);
11050 template_only = 1;
11052 gcc_assert (OVL_P (fns));
11053 fn = OVL_FIRST (fns);
11054 name = DECL_NAME (fn);
11056 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
11057 gcc_assert (CLASS_TYPE_P (basetype));
11059 user_args = args == NULL ? NULL : *args;
11060 /* Under DR 147 A::A() is an invalid constructor call,
11061 not a functional cast. */
11062 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
11064 if (! (complain & tf_error))
11065 return error_mark_node;
11067 basetype = DECL_CONTEXT (fn);
11068 name = constructor_name (basetype);
11069 auto_diagnostic_group d;
11070 if (permerror (input_location,
11071 "cannot call constructor %<%T::%D%> directly",
11072 basetype, name))
11073 inform (input_location, "for a function-style cast, remove the "
11074 "redundant %<::%D%>", name);
11075 call = build_functional_cast (input_location, basetype,
11076 build_tree_list_vec (user_args),
11077 complain);
11078 return call;
11081 if (processing_template_decl)
11083 orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
11084 instance = build_non_dependent_expr (instance);
11085 if (args != NULL)
11086 make_args_non_dependent (*args);
11089 /* Process the argument list. */
11090 if (args != NULL && *args != NULL)
11092 *args = resolve_args (*args, complain);
11093 if (*args == NULL)
11094 return error_mark_node;
11095 user_args = *args;
11098 /* Consider the object argument to be used even if we end up selecting a
11099 static member function. */
11100 instance = mark_type_use (instance);
11102 /* Figure out whether to skip the first argument for the error
11103 message we will display to users if an error occurs. We don't
11104 want to display any compiler-generated arguments. The "this"
11105 pointer hasn't been added yet. However, we must remove the VTT
11106 pointer if this is a call to a base-class constructor or
11107 destructor. */
11108 skip_first_for_error = false;
11109 if (IDENTIFIER_CDTOR_P (name))
11111 /* Callers should explicitly indicate whether they want to ctor
11112 the complete object or just the part without virtual bases. */
11113 gcc_assert (name != ctor_identifier);
11115 /* Remove the VTT pointer, if present. */
11116 if ((name == base_ctor_identifier || name == base_dtor_identifier)
11117 && CLASSTYPE_VBASECLASSES (basetype))
11118 skip_first_for_error = true;
11120 /* It's OK to call destructors and constructors on cv-qualified
11121 objects. Therefore, convert the INSTANCE to the unqualified
11122 type, if necessary. */
11123 if (!same_type_p (basetype, TREE_TYPE (instance)))
11125 instance = build_this (instance);
11126 instance = build_nop (build_pointer_type (basetype), instance);
11127 instance = build_fold_indirect_ref (instance);
11130 else
11131 gcc_assert (!DECL_DESTRUCTOR_P (fn) && !DECL_CONSTRUCTOR_P (fn));
11133 /* For the overload resolution we need to find the actual `this`
11134 that would be captured if the call turns out to be to a
11135 non-static member function. Do not actually capture it at this
11136 point. */
11137 if (DECL_CONSTRUCTOR_P (fn))
11138 /* Constructors don't use the enclosing 'this'. */
11139 first_mem_arg = instance;
11140 else
11141 first_mem_arg = maybe_resolve_dummy (instance, false);
11143 /* Get the high-water mark for the CONVERSION_OBSTACK. */
11144 p = conversion_obstack_alloc (0);
11146 /* The number of arguments artificial parms in ARGS; we subtract one because
11147 there's no 'this' in ARGS. */
11148 unsigned skip = num_artificial_parms_for (fn) - 1;
11150 /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
11151 initializer, not T({ }). */
11152 if (DECL_CONSTRUCTOR_P (fn)
11153 && vec_safe_length (user_args) > skip
11154 && DIRECT_LIST_INIT_P ((*user_args)[skip]))
11156 tree init_list = (*user_args)[skip];
11157 tree init = NULL_TREE;
11159 gcc_assert (user_args->length () == skip + 1
11160 && !(flags & LOOKUP_ONLYCONVERTING));
11162 /* If the initializer list has no elements and T is a class type with
11163 a default constructor, the object is value-initialized. Handle
11164 this here so we don't need to handle it wherever we use
11165 build_special_member_call. */
11166 if (CONSTRUCTOR_NELTS (init_list) == 0
11167 && TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
11168 /* For a user-provided default constructor, use the normal
11169 mechanisms so that protected access works. */
11170 && type_has_non_user_provided_default_constructor (basetype)
11171 && !processing_template_decl)
11172 init = build_value_init (basetype, complain);
11174 /* If BASETYPE is an aggregate, we need to do aggregate
11175 initialization. */
11176 else if (CP_AGGREGATE_TYPE_P (basetype))
11178 init = reshape_init (basetype, init_list, complain);
11179 init = digest_init (basetype, init, complain);
11182 if (init)
11184 if (is_dummy_object (instance))
11185 return get_target_expr (init, complain);
11186 return cp_build_init_expr (instance, init);
11189 /* Otherwise go ahead with overload resolution. */
11190 add_list_candidates (fns, first_mem_arg, user_args,
11191 basetype, explicit_targs, template_only,
11192 conversion_path, access_binfo, flags,
11193 &candidates, complain);
11195 else
11196 add_candidates (fns, first_mem_arg, user_args, optype,
11197 explicit_targs, template_only, conversion_path,
11198 access_binfo, flags, &candidates, complain);
11200 any_viable_p = false;
11201 candidates = splice_viable (candidates, false, &any_viable_p);
11203 if (!any_viable_p)
11205 /* [dcl.init], 17.6.2.2:
11207 Otherwise, if no constructor is viable, the destination type is
11208 a (possibly cv-qualified) aggregate class A, and the initializer
11209 is a parenthesized expression-list, the object is initialized as
11210 follows...
11212 We achieve this by building up a CONSTRUCTOR, as for list-init,
11213 and setting CONSTRUCTOR_IS_PAREN_INIT to distinguish between
11214 the two. */
11215 if (DECL_CONSTRUCTOR_P (fn)
11216 && !(flags & LOOKUP_ONLYCONVERTING)
11217 && cxx_dialect >= cxx20
11218 && CP_AGGREGATE_TYPE_P (basetype)
11219 && !vec_safe_is_empty (user_args))
11221 /* Create a CONSTRUCTOR from ARGS, e.g. {1, 2} from <1, 2>. */
11222 tree ctor = build_constructor_from_vec (init_list_type_node,
11223 user_args);
11224 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
11225 CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
11226 if (is_dummy_object (instance))
11227 return ctor;
11228 else
11230 ctor = digest_init (basetype, ctor, complain);
11231 if (ctor == error_mark_node)
11232 return error_mark_node;
11233 return cp_build_init_expr (instance, ctor);
11236 if (complain & tf_error)
11237 complain_about_no_candidates_for_method_call (instance, candidates,
11238 explicit_targs, basetype,
11239 optype, name,
11240 skip_first_for_error,
11241 user_args);
11242 call = error_mark_node;
11244 else
11246 cand = tourney (candidates, complain);
11247 if (cand == 0)
11249 char *pretty_name;
11250 bool free_p;
11251 tree arglist;
11253 if (complain & tf_error)
11255 pretty_name = name_as_c_string (name, basetype, &free_p);
11256 arglist = build_tree_list_vec (user_args);
11257 if (skip_first_for_error)
11258 arglist = TREE_CHAIN (arglist);
11259 auto_diagnostic_group d;
11260 if (!any_strictly_viable (candidates))
11261 error ("no matching function for call to %<%s(%A)%>",
11262 pretty_name, arglist);
11263 else
11264 error ("call of overloaded %<%s(%A)%> is ambiguous",
11265 pretty_name, arglist);
11266 print_z_candidates (location_of (name), candidates);
11267 if (free_p)
11268 free (pretty_name);
11270 call = error_mark_node;
11271 if (fn_p)
11272 *fn_p = error_mark_node;
11274 else
11276 fn = cand->fn;
11277 call = NULL_TREE;
11279 if (!(flags & LOOKUP_NONVIRTUAL)
11280 && DECL_PURE_VIRTUAL_P (fn)
11281 && instance == current_class_ref
11282 && (complain & tf_warning))
11284 /* This is not an error, it is runtime undefined
11285 behavior. */
11286 if (!current_function_decl)
11287 warning (0, "pure virtual %q#D called from "
11288 "non-static data member initializer", fn);
11289 else if (DECL_CONSTRUCTOR_P (current_function_decl)
11290 || DECL_DESTRUCTOR_P (current_function_decl))
11291 warning (0, (DECL_CONSTRUCTOR_P (current_function_decl)
11292 ? G_("pure virtual %q#D called from constructor")
11293 : G_("pure virtual %q#D called from destructor")),
11294 fn);
11297 if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
11298 && !DECL_CONSTRUCTOR_P (fn)
11299 && is_dummy_object (instance))
11301 instance = maybe_resolve_dummy (instance, true);
11302 if (instance == error_mark_node)
11303 call = error_mark_node;
11304 else if (!is_dummy_object (instance))
11306 /* We captured 'this' in the current lambda now that
11307 we know we really need it. */
11308 cand->first_arg = instance;
11310 else if (current_class_ptr && any_dependent_bases_p ())
11311 /* We can't tell until instantiation time whether we can use
11312 *this as the implicit object argument. */;
11313 else
11315 if (complain & tf_error)
11316 error ("cannot call member function %qD without object",
11317 fn);
11318 call = error_mark_node;
11322 if (call != error_mark_node)
11324 /* Now we know what function is being called. */
11325 if (fn_p)
11326 *fn_p = fn;
11327 /* Build the actual CALL_EXPR. */
11328 call = build_over_call (cand, flags, complain);
11330 /* Suppress warnings for if (my_struct.operator= (x)) where
11331 my_struct is implicitly converted to bool. */
11332 if (TREE_CODE (call) == MODIFY_EXPR)
11333 suppress_warning (call, OPT_Wparentheses);
11335 /* In an expression of the form `a->f()' where `f' turns
11336 out to be a static member function, `a' is
11337 none-the-less evaluated. */
11338 if (TREE_CODE (TREE_TYPE (fn)) != METHOD_TYPE
11339 && !is_dummy_object (instance)
11340 && TREE_SIDE_EFFECTS (instance))
11342 /* But avoid the implicit lvalue-rvalue conversion when 'a'
11343 is volatile. */
11344 tree a = instance;
11345 if (TREE_THIS_VOLATILE (a))
11346 a = build_this (a);
11347 if (TREE_SIDE_EFFECTS (a))
11348 call = build2 (COMPOUND_EXPR, TREE_TYPE (call), a, call);
11350 else if (call != error_mark_node
11351 && DECL_DESTRUCTOR_P (cand->fn)
11352 && !VOID_TYPE_P (TREE_TYPE (call)))
11353 /* An explicit call of the form "x->~X()" has type
11354 "void". However, on platforms where destructors
11355 return "this" (i.e., those where
11356 targetm.cxx.cdtor_returns_this is true), such calls
11357 will appear to have a return value of pointer type
11358 to the low-level call machinery. We do not want to
11359 change the low-level machinery, since we want to be
11360 able to optimize "delete f()" on such platforms as
11361 "operator delete(~X(f()))" (rather than generating
11362 "t = f(), ~X(t), operator delete (t)"). */
11363 call = build_nop (void_type_node, call);
11368 if (processing_template_decl && call != error_mark_node)
11370 bool cast_to_void = false;
11372 if (TREE_CODE (call) == COMPOUND_EXPR)
11373 call = TREE_OPERAND (call, 1);
11374 else if (TREE_CODE (call) == NOP_EXPR)
11376 cast_to_void = true;
11377 call = TREE_OPERAND (call, 0);
11379 if (INDIRECT_REF_P (call))
11380 call = TREE_OPERAND (call, 0);
11382 /* Prune all but the selected function from the original overload
11383 set so that we can avoid some duplicate work at instantiation time. */
11384 if (really_overloaded_fn (fns))
11386 if (DECL_TEMPLATE_INFO (fn)
11387 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
11389 /* Use the selected template, not the specialization, so that
11390 this looks like an actual lookup result for sake of
11391 filter_memfn_lookup. */
11393 if (OVL_SINGLE_P (fns))
11394 /* If the original overload set consists of a single function
11395 template, this isn't beneficial. */
11396 goto skip_prune;
11398 fn = ovl_make (DECL_TI_TEMPLATE (fn));
11399 if (template_only)
11400 fn = lookup_template_function (fn, explicit_targs);
11402 orig_fns = copy_node (orig_fns);
11403 BASELINK_FUNCTIONS (orig_fns) = fn;
11404 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (orig_fns) = true;
11407 skip_prune:
11408 call = (build_min_non_dep_call_vec
11409 (call,
11410 build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
11411 orig_instance, orig_fns, NULL_TREE),
11412 orig_args));
11413 SET_EXPR_LOCATION (call, input_location);
11414 call = convert_from_reference (call);
11415 if (cast_to_void)
11416 call = build_nop (void_type_node, call);
11419 /* Free all the conversions we allocated. */
11420 obstack_free (&conversion_obstack, p);
11422 if (orig_args != NULL)
11423 release_tree_vector (orig_args);
11425 return call;
11428 /* Returns true iff standard conversion sequence ICS1 is a proper
11429 subsequence of ICS2. */
11431 static bool
11432 is_subseq (conversion *ics1, conversion *ics2)
11434 /* We can assume that a conversion of the same code
11435 between the same types indicates a subsequence since we only get
11436 here if the types we are converting from are the same. */
11438 while (ics1->kind == ck_rvalue
11439 || ics1->kind == ck_lvalue)
11440 ics1 = next_conversion (ics1);
11442 while (1)
11444 while (ics2->kind == ck_rvalue
11445 || ics2->kind == ck_lvalue)
11446 ics2 = next_conversion (ics2);
11448 if (ics2->kind == ck_user
11449 || !has_next (ics2->kind))
11450 /* At this point, ICS1 cannot be a proper subsequence of
11451 ICS2. We can get a USER_CONV when we are comparing the
11452 second standard conversion sequence of two user conversion
11453 sequences. */
11454 return false;
11456 ics2 = next_conversion (ics2);
11458 while (ics2->kind == ck_rvalue
11459 || ics2->kind == ck_lvalue)
11460 ics2 = next_conversion (ics2);
11462 if (ics2->kind == ics1->kind
11463 && same_type_p (ics2->type, ics1->type)
11464 && (ics1->kind == ck_identity
11465 || same_type_p (next_conversion (ics2)->type,
11466 next_conversion (ics1)->type)))
11467 return true;
11471 /* Returns nonzero iff DERIVED is derived from BASE. The inputs may
11472 be any _TYPE nodes. */
11474 bool
11475 is_properly_derived_from (tree derived, tree base)
11477 if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
11478 return false;
11480 /* We only allow proper derivation here. The DERIVED_FROM_P macro
11481 considers every class derived from itself. */
11482 return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
11483 && DERIVED_FROM_P (base, derived));
11486 /* We build the ICS for an implicit object parameter as a pointer
11487 conversion sequence. However, such a sequence should be compared
11488 as if it were a reference conversion sequence. If ICS is the
11489 implicit conversion sequence for an implicit object parameter,
11490 modify it accordingly. */
11492 static void
11493 maybe_handle_implicit_object (conversion **ics)
11495 if ((*ics)->this_p)
11497 /* [over.match.funcs]
11499 For non-static member functions, the type of the
11500 implicit object parameter is "reference to cv X"
11501 where X is the class of which the function is a
11502 member and cv is the cv-qualification on the member
11503 function declaration. */
11504 conversion *t = *ics;
11505 tree reference_type;
11507 /* The `this' parameter is a pointer to a class type. Make the
11508 implicit conversion talk about a reference to that same class
11509 type. */
11510 reference_type = TREE_TYPE (t->type);
11511 reference_type = build_reference_type (reference_type);
11513 if (t->kind == ck_qual)
11514 t = next_conversion (t);
11515 if (t->kind == ck_ptr)
11516 t = next_conversion (t);
11517 t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
11518 t = direct_reference_binding (reference_type, t);
11519 t->this_p = 1;
11520 t->rvaluedness_matches_p = 0;
11521 *ics = t;
11525 /* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
11526 and return the initial reference binding conversion. Otherwise,
11527 leave *ICS unchanged and return NULL. */
11529 static conversion *
11530 maybe_handle_ref_bind (conversion **ics)
11532 if ((*ics)->kind == ck_ref_bind)
11534 conversion *old_ics = *ics;
11535 *ics = next_conversion (old_ics);
11536 (*ics)->user_conv_p = old_ics->user_conv_p;
11537 return old_ics;
11540 return NULL;
11543 /* Get the expression at the beginning of the conversion chain C. */
11545 static tree
11546 conv_get_original_expr (conversion *c)
11548 for (; c; c = next_conversion (c))
11549 if (c->kind == ck_identity || c->kind == ck_ambig || c->kind == ck_aggr)
11550 return c->u.expr;
11551 return NULL_TREE;
11554 /* Return a tree representing the number of elements initialized by the
11555 list-initialization C. The caller must check that C converts to an
11556 array type. */
11558 static tree
11559 nelts_initialized_by_list_init (conversion *c)
11561 /* If the array we're converting to has a dimension, we'll use that. */
11562 if (TYPE_DOMAIN (c->type))
11563 return array_type_nelts_top (c->type);
11564 else
11566 /* Otherwise, we look at how many elements the constructor we're
11567 initializing from has. */
11568 tree ctor = conv_get_original_expr (c);
11569 return size_int (CONSTRUCTOR_NELTS (ctor));
11573 /* True iff C is a conversion that binds a reference or a pointer to
11574 an array of unknown bound. */
11576 static inline bool
11577 conv_binds_to_array_of_unknown_bound (conversion *c)
11579 /* ck_ref_bind won't have the reference stripped. */
11580 tree type = non_reference (c->type);
11581 /* ck_qual won't have the pointer stripped. */
11582 type = strip_pointer_operator (type);
11583 return (TREE_CODE (type) == ARRAY_TYPE
11584 && TYPE_DOMAIN (type) == NULL_TREE);
11587 /* Compare two implicit conversion sequences according to the rules set out in
11588 [over.ics.rank]. Return values:
11590 1: ics1 is better than ics2
11591 -1: ics2 is better than ics1
11592 0: ics1 and ics2 are indistinguishable */
11594 static int
11595 compare_ics (conversion *ics1, conversion *ics2)
11597 tree from_type1;
11598 tree from_type2;
11599 tree to_type1;
11600 tree to_type2;
11601 tree deref_from_type1 = NULL_TREE;
11602 tree deref_from_type2 = NULL_TREE;
11603 tree deref_to_type1 = NULL_TREE;
11604 tree deref_to_type2 = NULL_TREE;
11605 conversion_rank rank1, rank2;
11607 /* REF_BINDING is nonzero if the result of the conversion sequence
11608 is a reference type. In that case REF_CONV is the reference
11609 binding conversion. */
11610 conversion *ref_conv1;
11611 conversion *ref_conv2;
11613 /* Compare badness before stripping the reference conversion. */
11614 if (ics1->bad_p > ics2->bad_p)
11615 return -1;
11616 else if (ics1->bad_p < ics2->bad_p)
11617 return 1;
11619 /* Handle implicit object parameters. */
11620 maybe_handle_implicit_object (&ics1);
11621 maybe_handle_implicit_object (&ics2);
11623 /* Handle reference parameters. */
11624 ref_conv1 = maybe_handle_ref_bind (&ics1);
11625 ref_conv2 = maybe_handle_ref_bind (&ics2);
11627 /* List-initialization sequence L1 is a better conversion sequence than
11628 list-initialization sequence L2 if L1 converts to
11629 std::initializer_list<X> for some X and L2 does not. */
11630 if (ics1->kind == ck_list && ics2->kind != ck_list)
11631 return 1;
11632 if (ics2->kind == ck_list && ics1->kind != ck_list)
11633 return -1;
11635 /* [over.ics.rank]
11637 When comparing the basic forms of implicit conversion sequences (as
11638 defined in _over.best.ics_)
11640 --a standard conversion sequence (_over.ics.scs_) is a better
11641 conversion sequence than a user-defined conversion sequence
11642 or an ellipsis conversion sequence, and
11644 --a user-defined conversion sequence (_over.ics.user_) is a
11645 better conversion sequence than an ellipsis conversion sequence
11646 (_over.ics.ellipsis_). */
11647 /* Use BAD_CONVERSION_RANK because we already checked for a badness
11648 mismatch. If both ICS are bad, we try to make a decision based on
11649 what would have happened if they'd been good. This is not an
11650 extension, we'll still give an error when we build up the call; this
11651 just helps us give a more helpful error message. */
11652 rank1 = BAD_CONVERSION_RANK (ics1);
11653 rank2 = BAD_CONVERSION_RANK (ics2);
11655 if (rank1 > rank2)
11656 return -1;
11657 else if (rank1 < rank2)
11658 return 1;
11660 if (ics1->ellipsis_p)
11661 /* Both conversions are ellipsis conversions. */
11662 return 0;
11664 /* User-defined conversion sequence U1 is a better conversion sequence
11665 than another user-defined conversion sequence U2 if they contain the
11666 same user-defined conversion operator or constructor and if the sec-
11667 ond standard conversion sequence of U1 is better than the second
11668 standard conversion sequence of U2. */
11670 /* Handle list-conversion with the same code even though it isn't always
11671 ranked as a user-defined conversion and it doesn't have a second
11672 standard conversion sequence; it will still have the desired effect.
11673 Specifically, we need to do the reference binding comparison at the
11674 end of this function. */
11676 if (ics1->user_conv_p || ics1->kind == ck_list
11677 || ics1->kind == ck_aggr || ics2->kind == ck_aggr)
11679 conversion *t1 = strip_standard_conversion (ics1);
11680 conversion *t2 = strip_standard_conversion (ics2);
11682 if (!t1 || !t2 || t1->kind != t2->kind)
11683 return 0;
11684 else if (t1->kind == ck_user)
11686 tree f1 = t1->cand ? t1->cand->fn : t1->type;
11687 tree f2 = t2->cand ? t2->cand->fn : t2->type;
11688 if (f1 != f2)
11689 return 0;
11691 /* List-initialization sequence L1 is a better conversion sequence than
11692 list-initialization sequence L2 if
11694 -- L1 and L2 convert to arrays of the same element type, and either
11695 the number of elements n1 initialized by L1 is less than the number
11696 of elements n2 initialized by L2, or n1=n2 and L2 converts to an array
11697 of unknown bound and L1 does not. (Added in CWG 1307 and extended by
11698 P0388R4.) */
11699 else if (t1->kind == ck_aggr
11700 && TREE_CODE (t1->type) == ARRAY_TYPE
11701 && TREE_CODE (t2->type) == ARRAY_TYPE
11702 && same_type_p (TREE_TYPE (t1->type), TREE_TYPE (t2->type)))
11704 tree n1 = nelts_initialized_by_list_init (t1);
11705 tree n2 = nelts_initialized_by_list_init (t2);
11706 if (tree_int_cst_lt (n1, n2))
11707 return 1;
11708 else if (tree_int_cst_lt (n2, n1))
11709 return -1;
11710 /* The n1 == n2 case. */
11711 bool c1 = conv_binds_to_array_of_unknown_bound (t1);
11712 bool c2 = conv_binds_to_array_of_unknown_bound (t2);
11713 if (c1 && !c2)
11714 return -1;
11715 else if (!c1 && c2)
11716 return 1;
11717 else
11718 return 0;
11720 else
11722 /* For ambiguous or aggregate conversions, use the target type as
11723 a proxy for the conversion function. */
11724 if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
11725 return 0;
11728 /* We can just fall through here, after setting up
11729 FROM_TYPE1 and FROM_TYPE2. */
11730 from_type1 = t1->type;
11731 from_type2 = t2->type;
11733 else
11735 conversion *t1;
11736 conversion *t2;
11738 /* We're dealing with two standard conversion sequences.
11740 [over.ics.rank]
11742 Standard conversion sequence S1 is a better conversion
11743 sequence than standard conversion sequence S2 if
11745 --S1 is a proper subsequence of S2 (comparing the conversion
11746 sequences in the canonical form defined by _over.ics.scs_,
11747 excluding any Lvalue Transformation; the identity
11748 conversion sequence is considered to be a subsequence of
11749 any non-identity conversion sequence */
11751 t1 = ics1;
11752 while (t1->kind != ck_identity)
11753 t1 = next_conversion (t1);
11754 from_type1 = t1->type;
11756 t2 = ics2;
11757 while (t2->kind != ck_identity)
11758 t2 = next_conversion (t2);
11759 from_type2 = t2->type;
11762 /* One sequence can only be a subsequence of the other if they start with
11763 the same type. They can start with different types when comparing the
11764 second standard conversion sequence in two user-defined conversion
11765 sequences. */
11766 if (same_type_p (from_type1, from_type2))
11768 if (is_subseq (ics1, ics2))
11769 return 1;
11770 if (is_subseq (ics2, ics1))
11771 return -1;
11774 /* [over.ics.rank]
11776 Or, if not that,
11778 --the rank of S1 is better than the rank of S2 (by the rules
11779 defined below):
11781 Standard conversion sequences are ordered by their ranks: an Exact
11782 Match is a better conversion than a Promotion, which is a better
11783 conversion than a Conversion.
11785 Two conversion sequences with the same rank are indistinguishable
11786 unless one of the following rules applies:
11788 --A conversion that does not a convert a pointer, pointer to member,
11789 or std::nullptr_t to bool is better than one that does.
11791 The ICS_STD_RANK automatically handles the pointer-to-bool rule,
11792 so that we do not have to check it explicitly. */
11793 if (ics1->rank < ics2->rank)
11794 return 1;
11795 else if (ics2->rank < ics1->rank)
11796 return -1;
11798 to_type1 = ics1->type;
11799 to_type2 = ics2->type;
11801 /* A conversion from scalar arithmetic type to complex is worse than a
11802 conversion between scalar arithmetic types. */
11803 if (same_type_p (from_type1, from_type2)
11804 && ARITHMETIC_TYPE_P (from_type1)
11805 && ARITHMETIC_TYPE_P (to_type1)
11806 && ARITHMETIC_TYPE_P (to_type2)
11807 && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
11808 != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
11810 if (TREE_CODE (to_type1) == COMPLEX_TYPE)
11811 return -1;
11812 else
11813 return 1;
11817 /* A conversion in either direction between floating-point type FP1 and
11818 floating-point type FP2 is better than a conversion in the same
11819 direction between FP1 and arithmetic type T3 if
11820 - the floating-point conversion rank of FP1 is equal to the rank of
11821 FP2, and
11822 - T3 is not a floating-point type, or T3 is a floating-point type
11823 whose rank is not equal to the rank of FP1, or the floating-point
11824 conversion subrank of FP2 is greater than the subrank of T3. */
11825 tree fp1 = from_type1;
11826 tree fp2 = to_type1;
11827 tree fp3 = from_type2;
11828 tree t3 = to_type2;
11829 int ret = 1;
11830 if (TYPE_MAIN_VARIANT (fp2) == TYPE_MAIN_VARIANT (t3))
11832 std::swap (fp1, fp2);
11833 std::swap (fp3, t3);
11835 if (TYPE_MAIN_VARIANT (fp1) == TYPE_MAIN_VARIANT (fp3)
11836 && TREE_CODE (fp1) == REAL_TYPE
11837 /* Only apply this rule if at least one of the 3 types is
11838 extended floating-point type, otherwise keep them as
11839 before for compatibility reasons with types like __float128.
11840 float, double and long double alone have different conversion
11841 ranks and so when just those 3 types are involved, this
11842 rule doesn't trigger. */
11843 && (extended_float_type_p (fp1)
11844 || (TREE_CODE (fp2) == REAL_TYPE && extended_float_type_p (fp2))
11845 || (TREE_CODE (t3) == REAL_TYPE && extended_float_type_p (t3))))
11847 if (TREE_CODE (fp2) != REAL_TYPE)
11849 ret = -ret;
11850 std::swap (fp2, t3);
11852 if (TREE_CODE (fp2) == REAL_TYPE)
11854 /* cp_compare_floating_point_conversion_ranks returns -1, 0 or 1
11855 if the conversion rank is equal (-1 or 1 if the subrank is
11856 different). */
11857 if (IN_RANGE (cp_compare_floating_point_conversion_ranks (fp1,
11858 fp2),
11859 -1, 1))
11861 /* Conversion ranks of FP1 and FP2 are equal. */
11862 if (TREE_CODE (t3) != REAL_TYPE
11863 || !IN_RANGE (cp_compare_floating_point_conversion_ranks
11864 (fp1, t3),
11865 -1, 1))
11866 /* FP1 <-> FP2 conversion is better. */
11867 return ret;
11868 int c = cp_compare_floating_point_conversion_ranks (fp2, t3);
11869 gcc_assert (IN_RANGE (c, -1, 1));
11870 if (c == 1)
11871 /* Conversion subrank of FP2 is greater than subrank of T3.
11872 FP1 <-> FP2 conversion is better. */
11873 return ret;
11874 else if (c == -1)
11875 /* Conversion subrank of FP2 is less than subrank of T3.
11876 FP1 <-> T3 conversion is better. */
11877 return -ret;
11879 else if (TREE_CODE (t3) == REAL_TYPE
11880 && IN_RANGE (cp_compare_floating_point_conversion_ranks
11881 (fp1, t3),
11882 -1, 1))
11883 /* Conversion ranks of FP1 and FP2 are not equal, conversion
11884 ranks of FP1 and T3 are equal.
11885 FP1 <-> T3 conversion is better. */
11886 return -ret;
11891 if (TYPE_PTR_P (from_type1)
11892 && TYPE_PTR_P (from_type2)
11893 && TYPE_PTR_P (to_type1)
11894 && TYPE_PTR_P (to_type2))
11896 deref_from_type1 = TREE_TYPE (from_type1);
11897 deref_from_type2 = TREE_TYPE (from_type2);
11898 deref_to_type1 = TREE_TYPE (to_type1);
11899 deref_to_type2 = TREE_TYPE (to_type2);
11901 /* The rules for pointers to members A::* are just like the rules
11902 for pointers A*, except opposite: if B is derived from A then
11903 A::* converts to B::*, not vice versa. For that reason, we
11904 switch the from_ and to_ variables here. */
11905 else if ((TYPE_PTRDATAMEM_P (from_type1) && TYPE_PTRDATAMEM_P (from_type2)
11906 && TYPE_PTRDATAMEM_P (to_type1) && TYPE_PTRDATAMEM_P (to_type2))
11907 || (TYPE_PTRMEMFUNC_P (from_type1)
11908 && TYPE_PTRMEMFUNC_P (from_type2)
11909 && TYPE_PTRMEMFUNC_P (to_type1)
11910 && TYPE_PTRMEMFUNC_P (to_type2)))
11912 deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
11913 deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
11914 deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
11915 deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
11918 if (deref_from_type1 != NULL_TREE
11919 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
11920 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
11922 /* This was one of the pointer or pointer-like conversions.
11924 [over.ics.rank]
11926 --If class B is derived directly or indirectly from class A,
11927 conversion of B* to A* is better than conversion of B* to
11928 void*, and conversion of A* to void* is better than
11929 conversion of B* to void*. */
11930 if (VOID_TYPE_P (deref_to_type1)
11931 && VOID_TYPE_P (deref_to_type2))
11933 if (is_properly_derived_from (deref_from_type1,
11934 deref_from_type2))
11935 return -1;
11936 else if (is_properly_derived_from (deref_from_type2,
11937 deref_from_type1))
11938 return 1;
11940 else if (VOID_TYPE_P (deref_to_type1)
11941 || VOID_TYPE_P (deref_to_type2))
11943 if (same_type_p (deref_from_type1, deref_from_type2))
11945 if (VOID_TYPE_P (deref_to_type2))
11947 if (is_properly_derived_from (deref_from_type1,
11948 deref_to_type1))
11949 return 1;
11951 /* We know that DEREF_TO_TYPE1 is `void' here. */
11952 else if (is_properly_derived_from (deref_from_type1,
11953 deref_to_type2))
11954 return -1;
11957 else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
11958 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
11960 /* [over.ics.rank]
11962 --If class B is derived directly or indirectly from class A
11963 and class C is derived directly or indirectly from B,
11965 --conversion of C* to B* is better than conversion of C* to
11968 --conversion of B* to A* is better than conversion of C* to
11969 A* */
11970 if (same_type_p (deref_from_type1, deref_from_type2))
11972 if (is_properly_derived_from (deref_to_type1,
11973 deref_to_type2))
11974 return 1;
11975 else if (is_properly_derived_from (deref_to_type2,
11976 deref_to_type1))
11977 return -1;
11979 else if (same_type_p (deref_to_type1, deref_to_type2))
11981 if (is_properly_derived_from (deref_from_type2,
11982 deref_from_type1))
11983 return 1;
11984 else if (is_properly_derived_from (deref_from_type1,
11985 deref_from_type2))
11986 return -1;
11990 else if (CLASS_TYPE_P (non_reference (from_type1))
11991 && same_type_p (from_type1, from_type2))
11993 tree from = non_reference (from_type1);
11995 /* [over.ics.rank]
11997 --binding of an expression of type C to a reference of type
11998 B& is better than binding an expression of type C to a
11999 reference of type A&
12001 --conversion of C to B is better than conversion of C to A, */
12002 if (is_properly_derived_from (from, to_type1)
12003 && is_properly_derived_from (from, to_type2))
12005 if (is_properly_derived_from (to_type1, to_type2))
12006 return 1;
12007 else if (is_properly_derived_from (to_type2, to_type1))
12008 return -1;
12011 else if (CLASS_TYPE_P (non_reference (to_type1))
12012 && same_type_p (to_type1, to_type2))
12014 tree to = non_reference (to_type1);
12016 /* [over.ics.rank]
12018 --binding of an expression of type B to a reference of type
12019 A& is better than binding an expression of type C to a
12020 reference of type A&,
12022 --conversion of B to A is better than conversion of C to A */
12023 if (is_properly_derived_from (from_type1, to)
12024 && is_properly_derived_from (from_type2, to))
12026 if (is_properly_derived_from (from_type2, from_type1))
12027 return 1;
12028 else if (is_properly_derived_from (from_type1, from_type2))
12029 return -1;
12033 /* [over.ics.rank]
12035 --S1 and S2 differ only in their qualification conversion and yield
12036 similar types T1 and T2 (_conv.qual_), respectively, and the cv-
12037 qualification signature of type T1 is a proper subset of the cv-
12038 qualification signature of type T2 */
12039 if (ics1->kind == ck_qual
12040 && ics2->kind == ck_qual
12041 && same_type_p (from_type1, from_type2))
12043 int result = comp_cv_qual_signature (to_type1, to_type2);
12044 if (result != 0)
12045 return result;
12048 /* [over.ics.rank]
12050 --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
12051 to an implicit object parameter of a non-static member function
12052 declared without a ref-qualifier, and either S1 binds an lvalue
12053 reference to an lvalue and S2 binds an rvalue reference or S1 binds an
12054 rvalue reference to an rvalue and S2 binds an lvalue reference (C++0x
12055 draft standard, 13.3.3.2)
12057 --S1 and S2 are reference bindings (_dcl.init.ref_), and the
12058 types to which the references refer are the same type except for
12059 top-level cv-qualifiers, and the type to which the reference
12060 initialized by S2 refers is more cv-qualified than the type to
12061 which the reference initialized by S1 refers.
12063 DR 1328 [over.match.best]: the context is an initialization by
12064 conversion function for direct reference binding (13.3.1.6) of a
12065 reference to function type, the return type of F1 is the same kind of
12066 reference (i.e. lvalue or rvalue) as the reference being initialized,
12067 and the return type of F2 is not. */
12069 if (ref_conv1 && ref_conv2)
12071 if (!ref_conv1->this_p && !ref_conv2->this_p
12072 && (ref_conv1->rvaluedness_matches_p
12073 != ref_conv2->rvaluedness_matches_p)
12074 && (same_type_p (ref_conv1->type, ref_conv2->type)
12075 || (TYPE_REF_IS_RVALUE (ref_conv1->type)
12076 != TYPE_REF_IS_RVALUE (ref_conv2->type))))
12078 if (ref_conv1->bad_p
12079 && !same_type_p (TREE_TYPE (ref_conv1->type),
12080 TREE_TYPE (ref_conv2->type)))
12081 /* Don't prefer a bad conversion that drops cv-quals to a bad
12082 conversion with the wrong rvalueness. */
12083 return 0;
12084 return (ref_conv1->rvaluedness_matches_p
12085 - ref_conv2->rvaluedness_matches_p);
12088 if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
12090 /* Per P0388R4:
12092 void f (int(&)[]), // (1)
12093 f (int(&)[1]), // (2)
12094 f (int*); // (3)
12096 (2) is better than (1), but (3) should be equal to (1) and to
12097 (2). For that reason we don't use ck_qual for (1) which would
12098 give it the cr_exact rank while (3) remains ck_identity.
12099 Therefore we compare (1) and (2) here. For (1) we'll have
12101 ck_ref_bind <- ck_identity
12102 int[] & int[1]
12104 so to handle this we must look at ref_conv. */
12105 bool c1 = conv_binds_to_array_of_unknown_bound (ref_conv1);
12106 bool c2 = conv_binds_to_array_of_unknown_bound (ref_conv2);
12107 if (c1 && !c2)
12108 return -1;
12109 else if (!c1 && c2)
12110 return 1;
12112 int q1 = cp_type_quals (TREE_TYPE (ref_conv1->type));
12113 int q2 = cp_type_quals (TREE_TYPE (ref_conv2->type));
12114 if (ref_conv1->bad_p)
12116 /* Prefer the one that drops fewer cv-quals. */
12117 tree ftype = next_conversion (ref_conv1)->type;
12118 int fquals = cp_type_quals (ftype);
12119 q1 ^= fquals;
12120 q2 ^= fquals;
12122 return comp_cv_qualification (q2, q1);
12126 /* [over.ics.rank]
12128 Per CWG 1601:
12129 -- A conversion that promotes an enumeration whose underlying type
12130 is fixed to its underlying type is better than one that promotes to
12131 the promoted underlying type, if the two are different. */
12132 if (ics1->rank == cr_promotion
12133 && ics2->rank == cr_promotion
12134 && UNSCOPED_ENUM_P (from_type1)
12135 && ENUM_FIXED_UNDERLYING_TYPE_P (from_type1)
12136 && same_type_p (from_type1, from_type2))
12138 tree utype = ENUM_UNDERLYING_TYPE (from_type1);
12139 tree prom = type_promotes_to (from_type1);
12140 if (!same_type_p (utype, prom))
12142 if (same_type_p (to_type1, utype)
12143 && same_type_p (to_type2, prom))
12144 return 1;
12145 else if (same_type_p (to_type2, utype)
12146 && same_type_p (to_type1, prom))
12147 return -1;
12151 /* Neither conversion sequence is better than the other. */
12152 return 0;
12155 /* The source type for this standard conversion sequence. */
12157 static tree
12158 source_type (conversion *t)
12160 return strip_standard_conversion (t)->type;
12163 /* Note a warning about preferring WINNER to LOSER. We do this by storing
12164 a pointer to LOSER and re-running joust to produce the warning if WINNER
12165 is actually used. */
12167 static void
12168 add_warning (struct z_candidate *winner, struct z_candidate *loser)
12170 candidate_warning *cw = (candidate_warning *)
12171 conversion_obstack_alloc (sizeof (candidate_warning));
12172 cw->loser = loser;
12173 cw->next = winner->warnings;
12174 winner->warnings = cw;
12177 /* CAND is a constructor candidate in joust in C++17 and up. If it copies a
12178 prvalue returned from a conversion function, replace CAND with the candidate
12179 for the conversion and return true. Otherwise, return false. */
12181 static bool
12182 joust_maybe_elide_copy (z_candidate *&cand)
12184 tree fn = cand->fn;
12185 if (!DECL_COPY_CONSTRUCTOR_P (fn) && !DECL_MOVE_CONSTRUCTOR_P (fn))
12186 return false;
12187 conversion *conv = cand->convs[0];
12188 gcc_checking_assert (conv->kind == ck_ref_bind);
12189 conv = next_conversion (conv);
12190 if (conv->kind == ck_user && !TYPE_REF_P (conv->type))
12192 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
12193 (conv->type, DECL_CONTEXT (fn)));
12194 z_candidate *uc = conv->cand;
12195 if (DECL_CONV_FN_P (uc->fn))
12197 cand = uc;
12198 return true;
12201 return false;
12204 /* True if the defining declarations of the two candidates have equivalent
12205 parameters. */
12207 static bool
12208 cand_parms_match (z_candidate *c1, z_candidate *c2)
12210 tree fn1 = c1->fn;
12211 tree fn2 = c2->fn;
12212 if (fn1 == fn2)
12213 return true;
12214 if (identifier_p (fn1) || identifier_p (fn2))
12215 return false;
12216 /* We don't look at c1->template_decl because that's only set for primary
12217 templates, not e.g. non-template member functions of class templates. */
12218 tree t1 = most_general_template (fn1);
12219 tree t2 = most_general_template (fn2);
12220 if (t1 || t2)
12222 if (!t1 || !t2)
12223 return false;
12224 if (t1 == t2)
12225 return true;
12226 fn1 = DECL_TEMPLATE_RESULT (t1);
12227 fn2 = DECL_TEMPLATE_RESULT (t2);
12229 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
12230 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (fn2));
12231 if (DECL_FUNCTION_MEMBER_P (fn1)
12232 && DECL_FUNCTION_MEMBER_P (fn2)
12233 && (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn1)
12234 != DECL_NONSTATIC_MEMBER_FUNCTION_P (fn2)))
12236 /* Ignore 'this' when comparing the parameters of a static member
12237 function with those of a non-static one. */
12238 parms1 = skip_artificial_parms_for (fn1, parms1);
12239 parms2 = skip_artificial_parms_for (fn2, parms2);
12241 return compparms (parms1, parms2);
12244 /* Compare two candidates for overloading as described in
12245 [over.match.best]. Return values:
12247 1: cand1 is better than cand2
12248 -1: cand2 is better than cand1
12249 0: cand1 and cand2 are indistinguishable */
12251 static int
12252 joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn,
12253 tsubst_flags_t complain)
12255 int winner = 0;
12256 int off1 = 0, off2 = 0;
12257 size_t i;
12258 size_t len;
12260 /* Candidates that involve bad conversions are always worse than those
12261 that don't. */
12262 if (cand1->viable > cand2->viable)
12263 return 1;
12264 if (cand1->viable < cand2->viable)
12265 return -1;
12267 /* If we have two pseudo-candidates for conversions to the same type,
12268 or two candidates for the same function, arbitrarily pick one. */
12269 if (cand1->fn == cand2->fn
12270 && cand1->reversed () == cand2->reversed ()
12271 && (IS_TYPE_OR_DECL_P (cand1->fn)))
12272 return 1;
12274 /* Prefer a non-deleted function over an implicitly deleted move
12275 constructor or assignment operator. This differs slightly from the
12276 wording for issue 1402 (which says the move op is ignored by overload
12277 resolution), but this way produces better error messages. */
12278 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12279 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12280 && DECL_DELETED_FN (cand1->fn) != DECL_DELETED_FN (cand2->fn))
12282 if (DECL_DELETED_FN (cand1->fn) && DECL_DEFAULTED_FN (cand1->fn)
12283 && move_fn_p (cand1->fn))
12284 return -1;
12285 if (DECL_DELETED_FN (cand2->fn) && DECL_DEFAULTED_FN (cand2->fn)
12286 && move_fn_p (cand2->fn))
12287 return 1;
12290 /* a viable function F1
12291 is defined to be a better function than another viable function F2 if
12292 for all arguments i, ICSi(F1) is not a worse conversion sequence than
12293 ICSi(F2), and then */
12295 /* for some argument j, ICSj(F1) is a better conversion sequence than
12296 ICSj(F2) */
12298 /* For comparing static and non-static member functions, we ignore
12299 the implicit object parameter of the non-static function. The
12300 standard says to pretend that the static function has an object
12301 parm, but that won't work with operator overloading. */
12302 len = cand1->num_convs;
12303 if (len != cand2->num_convs)
12305 int static_1 = (TREE_CODE (cand1->fn) == FUNCTION_DECL
12306 && DECL_STATIC_FUNCTION_P (cand1->fn));
12307 int static_2 = (TREE_CODE (cand2->fn) == FUNCTION_DECL
12308 && DECL_STATIC_FUNCTION_P (cand2->fn));
12310 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12311 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12312 && DECL_CONSTRUCTOR_P (cand1->fn)
12313 && is_list_ctor (cand1->fn) != is_list_ctor (cand2->fn))
12314 /* We're comparing a near-match list constructor and a near-match
12315 non-list constructor. Just treat them as unordered. */
12316 return 0;
12318 gcc_assert (static_1 != static_2);
12320 if (static_1)
12322 /* C++23 [over.best.ics.general] says:
12323 When the parameter is the implicit object parameter of a static
12324 member function, the implicit conversion sequence is a standard
12325 conversion sequence that is neither better nor worse than any
12326 other standard conversion sequence. */
12327 if (CONVERSION_RANK (cand2->convs[0]) >= cr_user)
12328 winner = 1;
12329 off2 = 1;
12331 else
12333 if (CONVERSION_RANK (cand1->convs[0]) >= cr_user)
12334 winner = -1;
12335 off1 = 1;
12336 --len;
12340 /* Handle C++17 copy elision in [over.match.ctor] (direct-init) context. The
12341 standard currently says that only constructors are candidates, but if one
12342 copies a prvalue returned by a conversion function we want to treat the
12343 conversion as the candidate instead.
12345 Clang does something similar, as discussed at
12346 http://lists.isocpp.org/core/2017/10/3166.php
12347 http://lists.isocpp.org/core/2019/03/5721.php */
12348 int elided_tiebreaker = 0;
12349 if (len == 1 && cxx_dialect >= cxx17
12350 && DECL_P (cand1->fn)
12351 && DECL_COMPLETE_CONSTRUCTOR_P (cand1->fn)
12352 && !(cand1->flags & LOOKUP_ONLYCONVERTING))
12354 bool elided1 = joust_maybe_elide_copy (cand1);
12355 bool elided2 = joust_maybe_elide_copy (cand2);
12356 /* As a tiebreaker below we will prefer a constructor to a conversion
12357 operator exposed this way. */
12358 elided_tiebreaker = elided2 - elided1;
12361 for (i = 0; i < len; ++i)
12363 conversion *t1 = cand1->convs[i + off1];
12364 conversion *t2 = cand2->convs[i + off2];
12365 int comp = compare_ics (t1, t2);
12367 if (comp != 0)
12369 if ((complain & tf_warning)
12370 && warn_sign_promo
12371 && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
12372 == cr_std + cr_promotion)
12373 && t1->kind == ck_std
12374 && t2->kind == ck_std
12375 && TREE_CODE (t1->type) == INTEGER_TYPE
12376 && TREE_CODE (t2->type) == INTEGER_TYPE
12377 && (TYPE_PRECISION (t1->type)
12378 == TYPE_PRECISION (t2->type))
12379 && (TYPE_UNSIGNED (next_conversion (t1)->type)
12380 || (TREE_CODE (next_conversion (t1)->type)
12381 == ENUMERAL_TYPE)))
12383 tree type = next_conversion (t1)->type;
12384 tree type1, type2;
12385 struct z_candidate *w, *l;
12386 if (comp > 0)
12387 type1 = t1->type, type2 = t2->type,
12388 w = cand1, l = cand2;
12389 else
12390 type1 = t2->type, type2 = t1->type,
12391 w = cand2, l = cand1;
12393 if (warn)
12395 warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
12396 type, type1, type2);
12397 warning (OPT_Wsign_promo, " in call to %qD", w->fn);
12399 else
12400 add_warning (w, l);
12403 if (winner && comp != winner)
12405 /* Ambiguity between normal and reversed comparison operators
12406 with the same parameter types; prefer the normal one. */
12407 if ((cand1->reversed () != cand2->reversed ())
12408 && cand_parms_match (cand1, cand2))
12409 return cand1->reversed () ? -1 : 1;
12411 winner = 0;
12412 goto tweak;
12414 winner = comp;
12418 /* warn about confusing overload resolution for user-defined conversions,
12419 either between a constructor and a conversion op, or between two
12420 conversion ops. */
12421 if ((complain & tf_warning)
12422 /* In C++17, the constructor might have been elided, which means that
12423 an originally null ->second_conv could become non-null. */
12424 && winner && warn_conversion && cand1->second_conv && cand2->second_conv
12425 && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
12426 && winner != compare_ics (cand1->second_conv, cand2->second_conv))
12428 struct z_candidate *w, *l;
12429 bool give_warning = false;
12431 if (winner == 1)
12432 w = cand1, l = cand2;
12433 else
12434 w = cand2, l = cand1;
12436 /* We don't want to complain about `X::operator T1 ()'
12437 beating `X::operator T2 () const', when T2 is a no less
12438 cv-qualified version of T1. */
12439 if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
12440 && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
12442 tree t = TREE_TYPE (TREE_TYPE (l->fn));
12443 tree f = TREE_TYPE (TREE_TYPE (w->fn));
12445 if (TREE_CODE (t) == TREE_CODE (f) && INDIRECT_TYPE_P (t))
12447 t = TREE_TYPE (t);
12448 f = TREE_TYPE (f);
12450 if (!comp_ptr_ttypes (t, f))
12451 give_warning = true;
12453 else
12454 give_warning = true;
12456 if (!give_warning)
12457 /*NOP*/;
12458 else if (warn)
12460 tree source = source_type (w->convs[0]);
12461 if (INDIRECT_TYPE_P (source))
12462 source = TREE_TYPE (source);
12463 auto_diagnostic_group d;
12464 if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
12465 && warning (OPT_Wconversion, " for conversion from %qH to %qI",
12466 source, w->second_conv->type))
12468 inform (input_location, " because conversion sequence "
12469 "for the argument is better");
12472 else
12473 add_warning (w, l);
12476 if (winner)
12477 return winner;
12479 /* Put this tiebreaker first, so that we don't try to look at second_conv of
12480 a constructor candidate that doesn't have one. */
12481 if (elided_tiebreaker)
12482 return elided_tiebreaker;
12484 /* DR 495 moved this tiebreaker above the template ones. */
12485 /* or, if not that,
12486 the context is an initialization by user-defined conversion (see
12487 _dcl.init_ and _over.match.user_) and the standard conversion
12488 sequence from the return type of F1 to the destination type (i.e.,
12489 the type of the entity being initialized) is a better conversion
12490 sequence than the standard conversion sequence from the return type
12491 of F2 to the destination type. */
12493 if (cand1->second_conv)
12495 winner = compare_ics (cand1->second_conv, cand2->second_conv);
12496 if (winner)
12497 return winner;
12500 /* or, if not that,
12501 F1 is a non-template function and F2 is a template function
12502 specialization. */
12504 if (!cand1->template_decl && cand2->template_decl)
12505 return 1;
12506 else if (cand1->template_decl && !cand2->template_decl)
12507 return -1;
12509 /* or, if not that,
12510 F1 and F2 are template functions and the function template for F1 is
12511 more specialized than the template for F2 according to the partial
12512 ordering rules. */
12514 if (cand1->template_decl && cand2->template_decl)
12516 winner = more_specialized_fn
12517 (TI_TEMPLATE (cand1->template_decl),
12518 TI_TEMPLATE (cand2->template_decl),
12519 /* [temp.func.order]: The presence of unused ellipsis and default
12520 arguments has no effect on the partial ordering of function
12521 templates. add_function_candidate() will not have
12522 counted the "this" argument for constructors. */
12523 cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
12524 if (winner)
12525 return winner;
12528 /* Concepts: F1 and F2 are non-template functions with the same
12529 parameter-type-lists, and F1 is more constrained than F2 according to the
12530 partial ordering of constraints described in 13.5.4. */
12532 if (flag_concepts && DECL_P (cand1->fn) && DECL_P (cand2->fn)
12533 && !cand1->template_decl && !cand2->template_decl
12534 && cand_parms_match (cand1, cand2))
12536 winner = more_constrained (cand1->fn, cand2->fn);
12537 if (winner)
12538 return winner;
12541 /* F2 is a rewritten candidate (12.4.1.2) and F1 is not, or F1 and F2 are
12542 rewritten candidates, and F2 is a synthesized candidate with reversed
12543 order of parameters and F1 is not. */
12544 if (cand1->rewritten ())
12546 if (!cand2->rewritten ())
12547 return -1;
12548 if (!cand1->reversed () && cand2->reversed ())
12549 return 1;
12550 if (cand1->reversed () && !cand2->reversed ())
12551 return -1;
12553 else if (cand2->rewritten ())
12554 return 1;
12556 /* F1 is generated from a deduction-guide (13.3.1.8) and F2 is not */
12557 if (deduction_guide_p (cand1->fn))
12559 gcc_assert (deduction_guide_p (cand2->fn));
12560 /* We distinguish between candidates from an explicit deduction guide and
12561 candidates built from a constructor based on DECL_ARTIFICIAL. */
12562 int art1 = DECL_ARTIFICIAL (cand1->fn);
12563 int art2 = DECL_ARTIFICIAL (cand2->fn);
12564 if (art1 != art2)
12565 return art2 - art1;
12567 if (art1)
12569 /* Prefer the special copy guide over a declared copy/move
12570 constructor. */
12571 if (copy_guide_p (cand1->fn))
12572 return 1;
12573 if (copy_guide_p (cand2->fn))
12574 return -1;
12576 /* Prefer a candidate generated from a non-template constructor. */
12577 int tg1 = template_guide_p (cand1->fn);
12578 int tg2 = template_guide_p (cand2->fn);
12579 if (tg1 != tg2)
12580 return tg2 - tg1;
12584 /* F1 is a member of a class D, F2 is a member of a base class B of D, and
12585 for all arguments the corresponding parameters of F1 and F2 have the same
12586 type (CWG 2273/2277). */
12587 if (DECL_P (cand1->fn) && DECL_CLASS_SCOPE_P (cand1->fn)
12588 && !DECL_CONV_FN_P (cand1->fn)
12589 && DECL_P (cand2->fn) && DECL_CLASS_SCOPE_P (cand2->fn)
12590 && !DECL_CONV_FN_P (cand2->fn))
12592 tree base1 = DECL_CONTEXT (strip_inheriting_ctors (cand1->fn));
12593 tree base2 = DECL_CONTEXT (strip_inheriting_ctors (cand2->fn));
12595 bool used1 = false;
12596 bool used2 = false;
12597 if (base1 == base2)
12598 /* No difference. */;
12599 else if (DERIVED_FROM_P (base1, base2))
12600 used1 = true;
12601 else if (DERIVED_FROM_P (base2, base1))
12602 used2 = true;
12604 if (int diff = used2 - used1)
12606 for (i = 0; i < len; ++i)
12608 conversion *t1 = cand1->convs[i + off1];
12609 conversion *t2 = cand2->convs[i + off2];
12610 if (!same_type_p (t1->type, t2->type))
12611 break;
12613 if (i == len)
12614 return diff;
12618 /* Check whether we can discard a builtin candidate, either because we
12619 have two identical ones or matching builtin and non-builtin candidates.
12621 (Pedantically in the latter case the builtin which matched the user
12622 function should not be added to the overload set, but we spot it here.
12624 [over.match.oper]
12625 ... the builtin candidates include ...
12626 - do not have the same parameter type list as any non-template
12627 non-member candidate. */
12629 if (identifier_p (cand1->fn) || identifier_p (cand2->fn))
12631 for (i = 0; i < len; ++i)
12632 if (!same_type_p (cand1->convs[i]->type,
12633 cand2->convs[i]->type))
12634 break;
12635 if (i == cand1->num_convs)
12637 if (cand1->fn == cand2->fn)
12638 /* Two built-in candidates; arbitrarily pick one. */
12639 return 1;
12640 else if (identifier_p (cand1->fn))
12641 /* cand1 is built-in; prefer cand2. */
12642 return -1;
12643 else
12644 /* cand2 is built-in; prefer cand1. */
12645 return 1;
12649 /* For candidates of a multi-versioned function, make the version with
12650 the highest priority win. This version will be checked for dispatching
12651 first. If this version can be inlined into the caller, the front-end
12652 will simply make a direct call to this function. */
12654 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12655 && DECL_FUNCTION_VERSIONED (cand1->fn)
12656 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12657 && DECL_FUNCTION_VERSIONED (cand2->fn))
12659 tree f1 = TREE_TYPE (cand1->fn);
12660 tree f2 = TREE_TYPE (cand2->fn);
12661 tree p1 = TYPE_ARG_TYPES (f1);
12662 tree p2 = TYPE_ARG_TYPES (f2);
12664 /* Check if cand1->fn and cand2->fn are versions of the same function. It
12665 is possible that cand1->fn and cand2->fn are function versions but of
12666 different functions. Check types to see if they are versions of the same
12667 function. */
12668 if (compparms (p1, p2)
12669 && same_type_p (TREE_TYPE (f1), TREE_TYPE (f2)))
12671 /* Always make the version with the higher priority, more
12672 specialized, win. */
12673 gcc_assert (targetm.compare_version_priority);
12674 if (targetm.compare_version_priority (cand1->fn, cand2->fn) >= 0)
12675 return 1;
12676 else
12677 return -1;
12681 /* If the two function declarations represent the same function (this can
12682 happen with declarations in multiple scopes and arg-dependent lookup),
12683 arbitrarily choose one. But first make sure the default args we're
12684 using match. */
12685 if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
12686 && equal_functions (cand1->fn, cand2->fn))
12688 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
12689 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
12691 gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
12693 for (i = 0; i < len; ++i)
12695 /* Don't crash if the fn is variadic. */
12696 if (!parms1)
12697 break;
12698 parms1 = TREE_CHAIN (parms1);
12699 parms2 = TREE_CHAIN (parms2);
12702 if (off1)
12703 parms1 = TREE_CHAIN (parms1);
12704 else if (off2)
12705 parms2 = TREE_CHAIN (parms2);
12707 for (; parms1; ++i)
12709 if (!cp_tree_equal (TREE_PURPOSE (parms1),
12710 TREE_PURPOSE (parms2)))
12712 if (warn)
12714 if (complain & tf_error)
12716 auto_diagnostic_group d;
12717 if (permerror (input_location,
12718 "default argument mismatch in "
12719 "overload resolution"))
12721 inform (DECL_SOURCE_LOCATION (cand1->fn),
12722 " candidate 1: %q#F", cand1->fn);
12723 inform (DECL_SOURCE_LOCATION (cand2->fn),
12724 " candidate 2: %q#F", cand2->fn);
12727 else
12728 return 0;
12730 else
12731 add_warning (cand1, cand2);
12732 break;
12734 parms1 = TREE_CHAIN (parms1);
12735 parms2 = TREE_CHAIN (parms2);
12738 return 1;
12741 tweak:
12743 /* Extension: If the worst conversion for one candidate is better than the
12744 worst conversion for the other, take the first. */
12745 if (!pedantic && (complain & tf_warning_or_error))
12747 conversion_rank rank1 = cr_identity, rank2 = cr_identity;
12748 struct z_candidate *w = 0, *l = 0;
12750 for (i = 0; i < len; ++i)
12752 if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
12753 rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
12754 if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
12755 rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
12757 if (rank1 < rank2)
12758 winner = 1, w = cand1, l = cand2;
12759 if (rank1 > rank2)
12760 winner = -1, w = cand2, l = cand1;
12761 if (winner)
12763 /* Don't choose a deleted function over ambiguity. */
12764 if (DECL_P (w->fn) && DECL_DELETED_FN (w->fn))
12765 return 0;
12766 if (warn)
12768 auto_diagnostic_group d;
12769 if (pedwarn (input_location, 0,
12770 "ISO C++ says that these are ambiguous, even "
12771 "though the worst conversion for the first is "
12772 "better than the worst conversion for the second:"))
12774 print_z_candidate (input_location, N_("candidate 1:"), w);
12775 print_z_candidate (input_location, N_("candidate 2:"), l);
12778 else
12779 add_warning (w, l);
12780 return winner;
12784 gcc_assert (!winner);
12785 return 0;
12788 /* Given a list of candidates for overloading, find the best one, if any.
12789 This algorithm has a worst case of O(2n) (winner is last), and a best
12790 case of O(n/2) (totally ambiguous); much better than a sorting
12791 algorithm. */
12793 static struct z_candidate *
12794 tourney (struct z_candidate *candidates, tsubst_flags_t complain)
12796 struct z_candidate *champ = candidates, *challenger;
12797 int fate;
12798 int champ_compared_to_predecessor = 0;
12800 /* Walk through the list once, comparing each current champ to the next
12801 candidate, knocking out a candidate or two with each comparison. */
12803 for (challenger = champ->next; challenger; )
12805 fate = joust (champ, challenger, 0, complain);
12806 if (fate == 1)
12807 challenger = challenger->next;
12808 else
12810 if (fate == 0)
12812 champ = challenger->next;
12813 if (champ == 0)
12814 return NULL;
12815 champ_compared_to_predecessor = 0;
12817 else
12819 champ = challenger;
12820 champ_compared_to_predecessor = 1;
12823 challenger = champ->next;
12827 /* Make sure the champ is better than all the candidates it hasn't yet
12828 been compared to. */
12830 for (challenger = candidates;
12831 challenger != champ
12832 && !(champ_compared_to_predecessor && challenger->next == champ);
12833 challenger = challenger->next)
12835 fate = joust (champ, challenger, 0, complain);
12836 if (fate != 1)
12837 return NULL;
12840 return champ;
12843 /* Returns nonzero if things of type FROM can be converted to TO. */
12845 bool
12846 can_convert (tree to, tree from, tsubst_flags_t complain)
12848 tree arg = NULL_TREE;
12849 /* implicit_conversion only considers user-defined conversions
12850 if it has an expression for the call argument list. */
12851 if (CLASS_TYPE_P (from) || CLASS_TYPE_P (to))
12852 arg = build_stub_object (from);
12853 return can_convert_arg (to, from, arg, LOOKUP_IMPLICIT, complain);
12856 /* Returns nonzero if things of type FROM can be converted to TO with a
12857 standard conversion. */
12859 bool
12860 can_convert_standard (tree to, tree from, tsubst_flags_t complain)
12862 return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT, complain);
12865 /* Returns nonzero if ARG (of type FROM) can be converted to TO. */
12867 bool
12868 can_convert_arg (tree to, tree from, tree arg, int flags,
12869 tsubst_flags_t complain)
12871 conversion *t;
12872 void *p;
12873 bool ok_p;
12875 /* Get the high-water mark for the CONVERSION_OBSTACK. */
12876 p = conversion_obstack_alloc (0);
12877 /* We want to discard any access checks done for this test,
12878 as we might not be in the appropriate access context and
12879 we'll do the check again when we actually perform the
12880 conversion. */
12881 push_deferring_access_checks (dk_deferred);
12883 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
12884 flags, complain);
12885 ok_p = (t && !t->bad_p);
12887 /* Discard the access checks now. */
12888 pop_deferring_access_checks ();
12889 /* Free all the conversions we allocated. */
12890 obstack_free (&conversion_obstack, p);
12892 return ok_p;
12895 /* Like can_convert_arg, but allows dubious conversions as well. */
12897 bool
12898 can_convert_arg_bad (tree to, tree from, tree arg, int flags,
12899 tsubst_flags_t complain)
12901 conversion *t;
12902 void *p;
12904 /* Get the high-water mark for the CONVERSION_OBSTACK. */
12905 p = conversion_obstack_alloc (0);
12906 /* Try to perform the conversion. */
12907 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
12908 flags, complain);
12909 /* Free all the conversions we allocated. */
12910 obstack_free (&conversion_obstack, p);
12912 return t != NULL;
12915 /* Return an IMPLICIT_CONV_EXPR from EXPR to TYPE with bits set from overload
12916 resolution FLAGS. */
12918 tree
12919 build_implicit_conv_flags (tree type, tree expr, int flags)
12921 /* In a template, we are only concerned about determining the
12922 type of non-dependent expressions, so we do not have to
12923 perform the actual conversion. But for initializers, we
12924 need to be able to perform it at instantiation
12925 (or instantiate_non_dependent_expr) time. */
12926 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
12927 if (!(flags & LOOKUP_ONLYCONVERTING))
12928 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
12929 if (flags & LOOKUP_NO_NARROWING)
12930 IMPLICIT_CONV_EXPR_BRACED_INIT (expr) = true;
12931 return expr;
12934 /* Convert EXPR to TYPE. Return the converted expression.
12936 Note that we allow bad conversions here because by the time we get to
12937 this point we are committed to doing the conversion. If we end up
12938 doing a bad conversion, convert_like will complain. */
12940 tree
12941 perform_implicit_conversion_flags (tree type, tree expr,
12942 tsubst_flags_t complain, int flags)
12944 conversion *conv;
12945 void *p;
12946 location_t loc = cp_expr_loc_or_input_loc (expr);
12948 if (TYPE_REF_P (type))
12949 expr = mark_lvalue_use (expr);
12950 else
12951 expr = mark_rvalue_use (expr);
12953 if (error_operand_p (expr))
12954 return error_mark_node;
12956 /* Get the high-water mark for the CONVERSION_OBSTACK. */
12957 p = conversion_obstack_alloc (0);
12959 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
12960 /*c_cast_p=*/false,
12961 flags, complain);
12963 if (!conv)
12965 if (complain & tf_error)
12966 implicit_conversion_error (loc, type, expr);
12967 expr = error_mark_node;
12969 else if (processing_template_decl && conv->kind != ck_identity)
12970 expr = build_implicit_conv_flags (type, expr, flags);
12971 else
12973 /* Give a conversion call the same location as expr. */
12974 iloc_sentinel il (loc);
12975 expr = convert_like (conv, expr, complain);
12978 /* Free all the conversions we allocated. */
12979 obstack_free (&conversion_obstack, p);
12981 return expr;
12984 tree
12985 perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
12987 return perform_implicit_conversion_flags (type, expr, complain,
12988 LOOKUP_IMPLICIT);
12991 /* Convert EXPR to TYPE (as a direct-initialization) if that is
12992 permitted. If the conversion is valid, the converted expression is
12993 returned. Otherwise, NULL_TREE is returned, except in the case
12994 that TYPE is a class type; in that case, an error is issued. If
12995 C_CAST_P is true, then this direct-initialization is taking
12996 place as part of a static_cast being attempted as part of a C-style
12997 cast. */
12999 tree
13000 perform_direct_initialization_if_possible (tree type,
13001 tree expr,
13002 bool c_cast_p,
13003 tsubst_flags_t complain)
13005 conversion *conv;
13006 void *p;
13008 if (type == error_mark_node || error_operand_p (expr))
13009 return error_mark_node;
13010 /* [dcl.init]
13012 If the destination type is a (possibly cv-qualified) class type:
13014 -- If the initialization is direct-initialization ...,
13015 constructors are considered.
13017 -- If overload resolution is successful, the selected constructor
13018 is called to initialize the object, with the initializer expression
13019 or expression-list as its argument(s).
13021 -- Otherwise, if no constructor is viable, the destination type is
13022 a (possibly cv-qualified) aggregate class A, and the initializer is
13023 a parenthesized expression-list, the object is initialized as
13024 follows... */
13025 if (CLASS_TYPE_P (type))
13027 releasing_vec args (make_tree_vector_single (expr));
13028 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
13029 &args, type, LOOKUP_NORMAL, complain);
13030 return build_cplus_new (type, expr, complain);
13033 /* Get the high-water mark for the CONVERSION_OBSTACK. */
13034 p = conversion_obstack_alloc (0);
13036 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
13037 c_cast_p,
13038 LOOKUP_NORMAL, complain);
13039 if (!conv || conv->bad_p)
13040 expr = NULL_TREE;
13041 else if (processing_template_decl && conv->kind != ck_identity)
13043 /* In a template, we are only concerned about determining the
13044 type of non-dependent expressions, so we do not have to
13045 perform the actual conversion. But for initializers, we
13046 need to be able to perform it at instantiation
13047 (or instantiate_non_dependent_expr) time. */
13048 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
13049 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13051 else
13052 expr = convert_like (conv, expr, NULL_TREE, 0,
13053 /*issue_conversion_warnings=*/false,
13054 c_cast_p, complain);
13056 /* Free all the conversions we allocated. */
13057 obstack_free (&conversion_obstack, p);
13059 return expr;
13062 /* When initializing a reference that lasts longer than a full-expression,
13063 this special rule applies:
13065 [class.temporary]
13067 The temporary to which the reference is bound or the temporary
13068 that is the complete object to which the reference is bound
13069 persists for the lifetime of the reference.
13071 The temporaries created during the evaluation of the expression
13072 initializing the reference, except the temporary to which the
13073 reference is bound, are destroyed at the end of the
13074 full-expression in which they are created.
13076 In that case, we store the converted expression into a new
13077 VAR_DECL in a new scope.
13079 However, we want to be careful not to create temporaries when
13080 they are not required. For example, given:
13082 struct B {};
13083 struct D : public B {};
13084 D f();
13085 const B& b = f();
13087 there is no need to copy the return value from "f"; we can just
13088 extend its lifetime. Similarly, given:
13090 struct S {};
13091 struct T { operator S(); };
13092 T t;
13093 const S& s = t;
13095 we can extend the lifetime of the return value of the conversion
13096 operator.
13098 The next several functions are involved in this lifetime extension. */
13100 /* DECL is a VAR_DECL or FIELD_DECL whose type is a REFERENCE_TYPE. The
13101 reference is being bound to a temporary. Create and return a new
13102 VAR_DECL with the indicated TYPE; this variable will store the value to
13103 which the reference is bound. */
13105 tree
13106 make_temporary_var_for_ref_to_temp (tree decl, tree type)
13108 tree var = create_temporary_var (type);
13110 /* Register the variable. */
13111 if (VAR_P (decl)
13112 && (TREE_STATIC (decl) || CP_DECL_THREAD_LOCAL_P (decl)))
13114 /* Namespace-scope or local static; give it a mangled name. */
13116 /* If an initializer is visible to multiple translation units, those
13117 translation units must agree on the addresses of the
13118 temporaries. Therefore the temporaries must be given a consistent name
13119 and vague linkage. The mangled name of a temporary is the name of the
13120 non-temporary object in whose initializer they appear, prefixed with
13121 GR and suffixed with a sequence number mangled using the usual rules
13122 for a seq-id. Temporaries are numbered with a pre-order, depth-first,
13123 left-to-right walk of the complete initializer. */
13124 copy_linkage (var, decl);
13126 tree name = mangle_ref_init_variable (decl);
13127 DECL_NAME (var) = name;
13128 SET_DECL_ASSEMBLER_NAME (var, name);
13130 else
13131 /* Create a new cleanup level if necessary. */
13132 maybe_push_cleanup_level (type);
13134 return pushdecl (var);
13137 /* EXPR is the initializer for a variable DECL of reference or
13138 std::initializer_list type. Create, push and return a new VAR_DECL
13139 for the initializer so that it will live as long as DECL. Any
13140 cleanup for the new variable is returned through CLEANUP, and the
13141 code to initialize the new variable is returned through INITP. */
13143 static tree
13144 set_up_extended_ref_temp (tree decl, tree expr, vec<tree, va_gc> **cleanups,
13145 tree *initp, tree *cond_guard)
13147 tree init;
13148 tree type;
13149 tree var;
13151 /* Create the temporary variable. */
13152 type = TREE_TYPE (expr);
13153 var = make_temporary_var_for_ref_to_temp (decl, type);
13154 layout_decl (var, 0);
13155 /* If the rvalue is the result of a function call it will be
13156 a TARGET_EXPR. If it is some other construct (such as a
13157 member access expression where the underlying object is
13158 itself the result of a function call), turn it into a
13159 TARGET_EXPR here. It is important that EXPR be a
13160 TARGET_EXPR below since otherwise the INIT_EXPR will
13161 attempt to make a bitwise copy of EXPR to initialize
13162 VAR. */
13163 if (TREE_CODE (expr) != TARGET_EXPR)
13164 expr = get_target_expr (expr);
13165 else if (TREE_ADDRESSABLE (expr))
13166 TREE_ADDRESSABLE (var) = 1;
13168 if (TREE_CODE (decl) == FIELD_DECL
13169 && extra_warnings && !warning_suppressed_p (decl))
13171 warning (OPT_Wextra, "a temporary bound to %qD only persists "
13172 "until the constructor exits", decl);
13173 suppress_warning (decl);
13176 /* Recursively extend temps in this initializer. */
13177 TARGET_EXPR_INITIAL (expr)
13178 = extend_ref_init_temps (decl, TARGET_EXPR_INITIAL (expr), cleanups,
13179 cond_guard);
13181 /* Any reference temp has a non-trivial initializer. */
13182 DECL_NONTRIVIALLY_INITIALIZED_P (var) = true;
13184 /* If the initializer is constant, put it in DECL_INITIAL so we get
13185 static initialization and use in constant expressions. */
13186 init = maybe_constant_init (expr);
13187 /* As in store_init_value. */
13188 init = cp_fully_fold (init);
13189 if (TREE_CONSTANT (init))
13191 if (literal_type_p (type) && CP_TYPE_CONST_NON_VOLATILE_P (type))
13193 /* 5.19 says that a constant expression can include an
13194 lvalue-rvalue conversion applied to "a glvalue of literal type
13195 that refers to a non-volatile temporary object initialized
13196 with a constant expression". Rather than try to communicate
13197 that this VAR_DECL is a temporary, just mark it constexpr. */
13198 DECL_DECLARED_CONSTEXPR_P (var) = true;
13199 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var) = true;
13200 TREE_CONSTANT (var) = true;
13201 TREE_READONLY (var) = true;
13203 DECL_INITIAL (var) = init;
13204 init = NULL_TREE;
13206 else
13207 /* Create the INIT_EXPR that will initialize the temporary
13208 variable. */
13209 init = split_nonconstant_init (var, expr);
13210 if (at_function_scope_p ())
13212 add_decl_expr (var);
13214 if (TREE_STATIC (var))
13215 init = add_stmt_to_compound (init, register_dtor_fn (var));
13216 else
13218 tree cleanup = cxx_maybe_build_cleanup (var, tf_warning_or_error);
13219 if (cleanup)
13221 if (cond_guard && cleanup != error_mark_node)
13223 if (*cond_guard == NULL_TREE)
13225 *cond_guard = build_local_temp (boolean_type_node);
13226 add_decl_expr (*cond_guard);
13227 tree set = cp_build_modify_expr (UNKNOWN_LOCATION,
13228 *cond_guard, NOP_EXPR,
13229 boolean_false_node,
13230 tf_warning_or_error);
13231 finish_expr_stmt (set);
13233 cleanup = build3 (COND_EXPR, void_type_node,
13234 *cond_guard, cleanup, NULL_TREE);
13236 vec_safe_push (*cleanups, cleanup);
13240 /* We must be careful to destroy the temporary only
13241 after its initialization has taken place. If the
13242 initialization throws an exception, then the
13243 destructor should not be run. We cannot simply
13244 transform INIT into something like:
13246 (INIT, ({ CLEANUP_STMT; }))
13248 because emit_local_var always treats the
13249 initializer as a full-expression. Thus, the
13250 destructor would run too early; it would run at the
13251 end of initializing the reference variable, rather
13252 than at the end of the block enclosing the
13253 reference variable.
13255 The solution is to pass back a cleanup expression
13256 which the caller is responsible for attaching to
13257 the statement tree. */
13259 else
13261 rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
13262 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
13264 if (CP_DECL_THREAD_LOCAL_P (var))
13265 tls_aggregates = tree_cons (NULL_TREE, var,
13266 tls_aggregates);
13267 else
13268 static_aggregates = tree_cons (NULL_TREE, var,
13269 static_aggregates);
13271 else
13272 /* Check whether the dtor is callable. */
13273 cxx_maybe_build_cleanup (var, tf_warning_or_error);
13275 /* Avoid -Wunused-variable warning (c++/38958). */
13276 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
13277 && VAR_P (decl))
13278 TREE_USED (decl) = DECL_READ_P (decl) = true;
13280 *initp = init;
13281 return var;
13284 /* Convert EXPR to the indicated reference TYPE, in a way suitable for
13285 initializing a variable of that TYPE. */
13287 tree
13288 initialize_reference (tree type, tree expr,
13289 int flags, tsubst_flags_t complain)
13291 conversion *conv;
13292 void *p;
13293 location_t loc = cp_expr_loc_or_input_loc (expr);
13295 if (type == error_mark_node || error_operand_p (expr))
13296 return error_mark_node;
13298 /* Get the high-water mark for the CONVERSION_OBSTACK. */
13299 p = conversion_obstack_alloc (0);
13301 conv = reference_binding (type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
13302 flags, complain);
13303 /* If this conversion failed, we're in C++20, and we have something like
13304 A& a(b) where A is an aggregate, try again, this time as A& a{b}. */
13305 if ((!conv || conv->bad_p)
13306 && (flags & LOOKUP_AGGREGATE_PAREN_INIT))
13308 tree e = build_constructor_single (init_list_type_node, NULL_TREE, expr);
13309 CONSTRUCTOR_IS_DIRECT_INIT (e) = true;
13310 CONSTRUCTOR_IS_PAREN_INIT (e) = true;
13311 conversion *c = reference_binding (type, TREE_TYPE (e), e,
13312 /*c_cast_p=*/false, flags, complain);
13313 /* If this worked, use it. */
13314 if (c && !c->bad_p)
13315 expr = e, conv = c;
13317 if (!conv || conv->bad_p)
13319 if (complain & tf_error)
13321 if (conv)
13322 convert_like (conv, expr, complain);
13323 else if (!CP_TYPE_CONST_P (TREE_TYPE (type))
13324 && !TYPE_REF_IS_RVALUE (type)
13325 && !lvalue_p (expr))
13326 error_at (loc, "invalid initialization of non-const reference of "
13327 "type %qH from an rvalue of type %qI",
13328 type, TREE_TYPE (expr));
13329 else
13330 error_at (loc, "invalid initialization of reference of type "
13331 "%qH from expression of type %qI", type,
13332 TREE_TYPE (expr));
13334 return error_mark_node;
13337 if (conv->kind == ck_ref_bind)
13338 /* Perform the conversion. */
13339 expr = convert_like (conv, expr, complain);
13340 else if (conv->kind == ck_ambig)
13341 /* We gave an error in build_user_type_conversion_1. */
13342 expr = error_mark_node;
13343 else
13344 gcc_unreachable ();
13346 /* Free all the conversions we allocated. */
13347 obstack_free (&conversion_obstack, p);
13349 return expr;
13352 /* If *P is an xvalue expression, prevent temporary lifetime extension if it
13353 gets used to initialize a reference. */
13355 static tree
13356 prevent_lifetime_extension (tree t)
13358 tree *p = &t;
13359 while (TREE_CODE (*p) == COMPOUND_EXPR)
13360 p = &TREE_OPERAND (*p, 1);
13361 while (handled_component_p (*p))
13362 p = &TREE_OPERAND (*p, 0);
13363 /* Change a TARGET_EXPR from prvalue to xvalue. */
13364 if (TREE_CODE (*p) == TARGET_EXPR)
13365 *p = build2 (COMPOUND_EXPR, TREE_TYPE (*p), *p,
13366 move (TARGET_EXPR_SLOT (*p)));
13367 return t;
13370 /* Subroutine of extend_ref_init_temps. Possibly extend one initializer,
13371 which is bound either to a reference or a std::initializer_list. */
13373 static tree
13374 extend_ref_init_temps_1 (tree decl, tree init, vec<tree, va_gc> **cleanups,
13375 tree *cond_guard)
13377 tree sub = init;
13378 tree *p;
13379 STRIP_NOPS (sub);
13380 if (TREE_CODE (sub) == COMPOUND_EXPR)
13382 TREE_OPERAND (sub, 1)
13383 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
13384 cond_guard);
13385 return init;
13387 if (TREE_CODE (sub) == COND_EXPR)
13389 tree cur_cond_guard = NULL_TREE;
13390 if (TREE_OPERAND (sub, 1))
13391 TREE_OPERAND (sub, 1)
13392 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
13393 &cur_cond_guard);
13394 if (cur_cond_guard)
13396 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
13397 NOP_EXPR, boolean_true_node,
13398 tf_warning_or_error);
13399 TREE_OPERAND (sub, 1)
13400 = cp_build_compound_expr (set, TREE_OPERAND (sub, 1),
13401 tf_warning_or_error);
13403 cur_cond_guard = NULL_TREE;
13404 if (TREE_OPERAND (sub, 2))
13405 TREE_OPERAND (sub, 2)
13406 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 2), cleanups,
13407 &cur_cond_guard);
13408 if (cur_cond_guard)
13410 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
13411 NOP_EXPR, boolean_true_node,
13412 tf_warning_or_error);
13413 TREE_OPERAND (sub, 2)
13414 = cp_build_compound_expr (set, TREE_OPERAND (sub, 2),
13415 tf_warning_or_error);
13417 return init;
13419 if (TREE_CODE (sub) != ADDR_EXPR)
13420 return init;
13421 /* Deal with binding to a subobject. */
13422 for (p = &TREE_OPERAND (sub, 0);
13423 TREE_CODE (*p) == COMPONENT_REF || TREE_CODE (*p) == ARRAY_REF; )
13424 p = &TREE_OPERAND (*p, 0);
13425 if (TREE_CODE (*p) == TARGET_EXPR)
13427 tree subinit = NULL_TREE;
13428 *p = set_up_extended_ref_temp (decl, *p, cleanups, &subinit, cond_guard);
13429 recompute_tree_invariant_for_addr_expr (sub);
13430 if (init != sub)
13431 init = fold_convert (TREE_TYPE (init), sub);
13432 if (subinit)
13433 init = build2 (COMPOUND_EXPR, TREE_TYPE (init), subinit, init);
13435 return init;
13438 /* INIT is part of the initializer for DECL. If there are any
13439 reference or initializer lists being initialized, extend their
13440 lifetime to match that of DECL. */
13442 tree
13443 extend_ref_init_temps (tree decl, tree init, vec<tree, va_gc> **cleanups,
13444 tree *cond_guard)
13446 tree type = TREE_TYPE (init);
13447 if (processing_template_decl)
13448 return init;
13449 if (TYPE_REF_P (type))
13450 init = extend_ref_init_temps_1 (decl, init, cleanups, cond_guard);
13451 else
13453 tree ctor = init;
13454 if (TREE_CODE (ctor) == TARGET_EXPR)
13455 ctor = TARGET_EXPR_INITIAL (ctor);
13456 if (TREE_CODE (ctor) == CONSTRUCTOR)
13458 /* [dcl.init] When initializing an aggregate from a parenthesized list
13459 of values... a temporary object bound to a reference does not have
13460 its lifetime extended. */
13461 if (CONSTRUCTOR_IS_PAREN_INIT (ctor))
13462 return init;
13464 if (is_std_init_list (type))
13466 /* The temporary array underlying a std::initializer_list
13467 is handled like a reference temporary. */
13468 tree array = CONSTRUCTOR_ELT (ctor, 0)->value;
13469 array = extend_ref_init_temps_1 (decl, array, cleanups,
13470 cond_guard);
13471 CONSTRUCTOR_ELT (ctor, 0)->value = array;
13473 else
13475 unsigned i;
13476 constructor_elt *p;
13477 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
13478 FOR_EACH_VEC_SAFE_ELT (elts, i, p)
13479 p->value = extend_ref_init_temps (decl, p->value, cleanups,
13480 cond_guard);
13482 recompute_constructor_flags (ctor);
13483 if (decl_maybe_constant_var_p (decl) && TREE_CONSTANT (ctor))
13484 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
13488 return init;
13491 /* Returns true iff an initializer for TYPE could contain temporaries that
13492 need to be extended because they are bound to references or
13493 std::initializer_list. */
13495 bool
13496 type_has_extended_temps (tree type)
13498 type = strip_array_types (type);
13499 if (TYPE_REF_P (type))
13500 return true;
13501 if (CLASS_TYPE_P (type))
13503 if (is_std_init_list (type))
13504 return true;
13505 for (tree f = next_aggregate_field (TYPE_FIELDS (type));
13506 f; f = next_aggregate_field (DECL_CHAIN (f)))
13507 if (type_has_extended_temps (TREE_TYPE (f)))
13508 return true;
13510 return false;
13513 /* Returns true iff TYPE is some variant of std::initializer_list. */
13515 bool
13516 is_std_init_list (tree type)
13518 if (!TYPE_P (type))
13519 return false;
13520 if (cxx_dialect == cxx98)
13521 return false;
13522 /* Look through typedefs. */
13523 type = TYPE_MAIN_VARIANT (type);
13524 return (CLASS_TYPE_P (type)
13525 && CP_TYPE_CONTEXT (type) == std_node
13526 && init_list_identifier == DECL_NAME (TYPE_NAME (type)));
13529 /* Returns true iff DECL is a list constructor: i.e. a constructor which
13530 will accept an argument list of a single std::initializer_list<T>. */
13532 bool
13533 is_list_ctor (tree decl)
13535 tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
13536 tree arg;
13538 if (!args || args == void_list_node)
13539 return false;
13541 arg = non_reference (TREE_VALUE (args));
13542 if (!is_std_init_list (arg))
13543 return false;
13545 args = TREE_CHAIN (args);
13547 if (args && args != void_list_node && !TREE_PURPOSE (args))
13548 /* There are more non-defaulted parms. */
13549 return false;
13551 return true;
13554 #include "gt-cp-call.h"