doc: Remove i?86-*-linux* installation note from 2003
[official-gcc.git] / gcc / cp / call.cc
blob309ab01d12d3cd92b2473f42e763a18a0b3b5210
1 /* Functions related to invoking -*- C++ -*- methods and overloaded functions.
2 Copyright (C) 1987-2024 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 "decl.h"
45 #include "c-family/c-type-mismatch.h"
46 #include "tristate.h"
47 #include "tree-pretty-print-markup.h"
49 /* The various kinds of conversion. */
51 enum conversion_kind {
52 ck_identity,
53 ck_lvalue,
54 ck_fnptr,
55 ck_qual,
56 ck_std,
57 ck_ptr,
58 ck_pmem,
59 ck_base,
60 ck_ref_bind,
61 ck_user,
62 ck_ambig,
63 ck_list,
64 ck_aggr,
65 ck_rvalue,
66 /* When LOOKUP_SHORTCUT_BAD_CONVS is set, we may return a conversion of
67 this kind whenever we know the true conversion is either bad or outright
68 invalid, but we don't want to attempt to compute the bad conversion (for
69 sake of avoiding unnecessary instantiation). bad_p should always be set
70 for these. */
71 ck_deferred_bad,
74 /* The rank of the conversion. Order of the enumerals matters; better
75 conversions should come earlier in the list. */
77 enum conversion_rank {
78 cr_identity,
79 cr_exact,
80 cr_promotion,
81 cr_std,
82 cr_pbool,
83 cr_user,
84 cr_ellipsis,
85 cr_bad
88 /* An implicit conversion sequence, in the sense of [over.best.ics].
89 The first conversion to be performed is at the end of the chain.
90 That conversion is always a cr_identity conversion. */
92 struct conversion {
93 /* The kind of conversion represented by this step. */
94 conversion_kind kind;
95 /* The rank of this conversion. */
96 conversion_rank rank;
97 BOOL_BITFIELD user_conv_p : 1;
98 BOOL_BITFIELD ellipsis_p : 1;
99 BOOL_BITFIELD this_p : 1;
100 /* True if this conversion would be permitted with a bending of
101 language standards, e.g. disregarding pointer qualifiers or
102 converting integers to pointers. */
103 BOOL_BITFIELD bad_p : 1;
104 /* If KIND is ck_ref_bind or ck_base, true to indicate that a
105 temporary should be created to hold the result of the
106 conversion. If KIND is ck_ambig or ck_user, true means force
107 copy-initialization. */
108 BOOL_BITFIELD need_temporary_p : 1;
109 /* If KIND is ck_ptr or ck_pmem, true to indicate that a conversion
110 from a pointer-to-derived to pointer-to-base is being performed. */
111 BOOL_BITFIELD base_p : 1;
112 /* If KIND is ck_ref_bind, true when either an lvalue reference is
113 being bound to an lvalue expression or an rvalue reference is
114 being bound to an rvalue expression. If KIND is ck_rvalue or ck_base,
115 true when we are treating an lvalue as an rvalue (12.8p33). If
116 ck_identity, we will be binding a reference directly or decaying to
117 a pointer. */
118 BOOL_BITFIELD rvaluedness_matches_p: 1;
119 BOOL_BITFIELD check_narrowing: 1;
120 /* Whether check_narrowing should only check TREE_CONSTANTs; used
121 in build_converted_constant_expr. */
122 BOOL_BITFIELD check_narrowing_const_only: 1;
123 /* True if this conversion is taking place in a copy-initialization context
124 and we should only consider converting constructors. Only set in
125 ck_base and ck_rvalue. */
126 BOOL_BITFIELD copy_init_p : 1;
127 /* The type of the expression resulting from the conversion. */
128 tree type;
129 union {
130 /* The next conversion in the chain. Since the conversions are
131 arranged from outermost to innermost, the NEXT conversion will
132 actually be performed before this conversion. This variant is
133 used only when KIND is neither ck_identity, ck_aggr, ck_ambig nor
134 ck_list. Please use the next_conversion function instead
135 of using this field directly. */
136 conversion *next;
137 /* The expression at the beginning of the conversion chain. This
138 variant is used only if KIND is ck_identity, ck_aggr, or ck_ambig.
139 You can use conv_get_original_expr to get this expression. */
140 tree expr;
141 /* The array of conversions for an initializer_list, so this
142 variant is used only when KIN D is ck_list. */
143 conversion **list;
144 } u;
145 /* The function candidate corresponding to this conversion
146 sequence. This field is only used if KIND is ck_user. */
147 struct z_candidate *cand;
150 #define CONVERSION_RANK(NODE) \
151 ((NODE)->bad_p ? cr_bad \
152 : (NODE)->ellipsis_p ? cr_ellipsis \
153 : (NODE)->user_conv_p ? cr_user \
154 : (NODE)->rank)
156 #define BAD_CONVERSION_RANK(NODE) \
157 ((NODE)->ellipsis_p ? cr_ellipsis \
158 : (NODE)->user_conv_p ? cr_user \
159 : (NODE)->rank)
161 static struct obstack conversion_obstack;
162 static bool conversion_obstack_initialized;
163 struct rejection_reason;
165 static struct z_candidate * tourney (struct z_candidate *, tsubst_flags_t);
166 static int equal_functions (tree, tree);
167 static int joust (struct z_candidate *, struct z_candidate *, bool,
168 tsubst_flags_t);
169 static int compare_ics (conversion *, conversion *);
170 static void maybe_warn_class_memaccess (location_t, tree,
171 const vec<tree, va_gc> *);
172 static tree build_over_call (struct z_candidate *, int, tsubst_flags_t);
173 static tree convert_like (conversion *, tree, tsubst_flags_t);
174 static tree convert_like_with_context (conversion *, tree, tree, int,
175 tsubst_flags_t);
176 static void op_error (const op_location_t &, enum tree_code, enum tree_code,
177 tree, tree, tree, bool);
178 static struct z_candidate *build_user_type_conversion_1 (tree, tree, int,
179 tsubst_flags_t);
180 static void print_z_candidate (location_t, const char *, struct z_candidate *);
181 static void print_z_candidates (location_t, struct z_candidate *,
182 tristate = tristate::unknown ());
183 static tree build_this (tree);
184 static struct z_candidate *splice_viable (struct z_candidate *, bool, bool *);
185 static bool any_strictly_viable (struct z_candidate *);
186 static struct z_candidate *add_template_candidate
187 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
188 tree, tree, tree, int, unification_kind_t, bool, tsubst_flags_t);
189 static struct z_candidate *add_template_candidate_real
190 (struct z_candidate **, tree, tree, tree, tree, const vec<tree, va_gc> *,
191 tree, tree, tree, int, tree, unification_kind_t, bool, tsubst_flags_t);
192 static bool is_complete (tree);
193 static struct z_candidate *add_conv_candidate
194 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, tree,
195 tree, tsubst_flags_t);
196 static struct z_candidate *add_function_candidate
197 (struct z_candidate **, tree, tree, tree, const vec<tree, va_gc> *, tree,
198 tree, int, conversion**, bool, tsubst_flags_t);
199 static conversion *implicit_conversion (tree, tree, tree, bool, int,
200 tsubst_flags_t);
201 static conversion *reference_binding (tree, tree, tree, bool, int,
202 tsubst_flags_t);
203 static conversion *build_conv (conversion_kind, tree, conversion *);
204 static conversion *build_list_conv (tree, tree, int, tsubst_flags_t);
205 static conversion *next_conversion (conversion *);
206 static bool is_subseq (conversion *, conversion *);
207 static conversion *maybe_handle_ref_bind (conversion **);
208 static void maybe_handle_implicit_object (conversion **);
209 static struct z_candidate *add_candidate
210 (struct z_candidate **, tree, tree, const vec<tree, va_gc> *, size_t,
211 conversion **, tree, tree, int, struct rejection_reason *, int);
212 static tree source_type (conversion *);
213 static void add_warning (struct z_candidate *, struct z_candidate *);
214 static conversion *direct_reference_binding (tree, conversion *);
215 static bool promoted_arithmetic_type_p (tree);
216 static conversion *conditional_conversion (tree, tree, tsubst_flags_t);
217 static char *name_as_c_string (tree, tree, bool *);
218 static tree prep_operand (tree);
219 static void add_candidates (tree, tree, const vec<tree, va_gc> *, tree, tree,
220 bool, tree, tree, int, struct z_candidate **,
221 tsubst_flags_t);
222 static conversion *merge_conversion_sequences (conversion *, conversion *);
223 static tree build_temp (tree, tree, int, diagnostic_t *, tsubst_flags_t);
224 static conversion *build_identity_conv (tree, tree);
225 static inline bool conv_binds_to_array_of_unknown_bound (conversion *);
226 static bool conv_is_prvalue (conversion *);
227 static tree prevent_lifetime_extension (tree);
229 /* Returns nonzero iff the destructor name specified in NAME matches BASETYPE.
230 NAME can take many forms... */
232 bool
233 check_dtor_name (tree basetype, tree name)
235 /* Just accept something we've already complained about. */
236 if (name == error_mark_node)
237 return true;
239 if (TREE_CODE (name) == TYPE_DECL)
240 name = TREE_TYPE (name);
241 else if (TYPE_P (name))
242 /* OK */;
243 else if (identifier_p (name))
245 if ((MAYBE_CLASS_TYPE_P (basetype)
246 || TREE_CODE (basetype) == ENUMERAL_TYPE)
247 && name == constructor_name (basetype))
248 return true;
250 /* Otherwise lookup the name, it could be an unrelated typedef
251 of the correct type. */
252 name = lookup_name (name, LOOK_want::TYPE);
253 if (!name)
254 return false;
255 name = TREE_TYPE (name);
256 if (name == error_mark_node)
257 return false;
259 else
261 /* In the case of:
263 template <class T> struct S { ~S(); };
264 int i;
265 i.~S();
267 NAME will be a class template. */
268 gcc_assert (DECL_CLASS_TEMPLATE_P (name));
269 return false;
272 return same_type_p (TYPE_MAIN_VARIANT (basetype), TYPE_MAIN_VARIANT (name));
275 /* We want the address of a function or method. We avoid creating a
276 pointer-to-member function. */
278 tree
279 build_addr_func (tree function, tsubst_flags_t complain)
281 tree type = TREE_TYPE (function);
283 /* We have to do these by hand to avoid real pointer to member
284 functions. */
285 if (TREE_CODE (type) == METHOD_TYPE)
287 if (TREE_CODE (function) == OFFSET_REF)
289 tree object = build_address (TREE_OPERAND (function, 0));
290 return get_member_function_from_ptrfunc (&object,
291 TREE_OPERAND (function, 1),
292 complain);
294 function = build_address (function);
296 else if (TREE_CODE (function) == FUNCTION_DECL
297 && DECL_IMMEDIATE_FUNCTION_P (function))
298 function = build_address (function);
299 else
300 function = decay_conversion (function, complain, /*reject_builtin=*/false);
302 return function;
305 /* Build a CALL_EXPR, we can handle FUNCTION_TYPEs, METHOD_TYPEs, or
306 POINTER_TYPE to those. Note, pointer to member function types
307 (TYPE_PTRMEMFUNC_P) must be handled by our callers. There are
308 two variants. build_call_a is the primitive taking an array of
309 arguments, while build_call_n is a wrapper that handles varargs. */
311 tree
312 build_call_n (tree function, int n, ...)
314 if (n == 0)
315 return build_call_a (function, 0, NULL);
316 else
318 tree *argarray = XALLOCAVEC (tree, n);
319 va_list ap;
320 int i;
322 va_start (ap, n);
323 for (i = 0; i < n; i++)
324 argarray[i] = va_arg (ap, tree);
325 va_end (ap);
326 return build_call_a (function, n, argarray);
330 /* Update various flags in cfun and the call itself based on what is being
331 called. Split out of build_call_a so that bot_manip can use it too. */
333 void
334 set_flags_from_callee (tree call)
336 /* Handle both CALL_EXPRs and AGGR_INIT_EXPRs. */
337 tree decl = cp_get_callee_fndecl_nofold (call);
339 /* We check both the decl and the type; a function may be known not to
340 throw without being declared throw(). */
341 bool nothrow = decl && TREE_NOTHROW (decl);
342 tree callee = cp_get_callee (call);
343 if (callee)
344 nothrow |= TYPE_NOTHROW_P (TREE_TYPE (TREE_TYPE (callee)));
345 else if (TREE_CODE (call) == CALL_EXPR
346 && internal_fn_flags (CALL_EXPR_IFN (call)) & ECF_NOTHROW)
347 nothrow = true;
349 if (cfun && cp_function_chain && !cp_unevaluated_operand)
351 if (!nothrow && at_function_scope_p ())
352 cp_function_chain->can_throw = 1;
354 if (decl && TREE_THIS_VOLATILE (decl))
355 current_function_returns_abnormally = 1;
358 TREE_NOTHROW (call) = nothrow;
361 tree
362 build_call_a (tree function, int n, tree *argarray)
364 tree decl;
365 tree result_type;
366 tree fntype;
367 int i;
369 function = build_addr_func (function, tf_warning_or_error);
371 gcc_assert (TYPE_PTR_P (TREE_TYPE (function)));
372 fntype = TREE_TYPE (TREE_TYPE (function));
373 gcc_assert (FUNC_OR_METHOD_TYPE_P (fntype));
374 result_type = TREE_TYPE (fntype);
375 /* An rvalue has no cv-qualifiers. */
376 if (SCALAR_TYPE_P (result_type) || VOID_TYPE_P (result_type))
377 result_type = cv_unqualified (result_type);
379 function = build_call_array_loc (input_location,
380 result_type, function, n, argarray);
381 set_flags_from_callee (function);
383 decl = get_callee_fndecl (function);
385 if (decl && !TREE_USED (decl))
387 /* We invoke build_call directly for several library
388 functions. These may have been declared normally if
389 we're building libgcc, so we can't just check
390 DECL_ARTIFICIAL. */
391 gcc_assert (DECL_ARTIFICIAL (decl)
392 || !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)),
393 "__", 2));
394 mark_used (decl);
397 require_complete_eh_spec_types (fntype, decl);
399 TREE_HAS_CONSTRUCTOR (function) = (decl && DECL_CONSTRUCTOR_P (decl));
401 /* Don't pass empty class objects by value. This is useful
402 for tags in STL, which are used to control overload resolution.
403 We don't need to handle other cases of copying empty classes. */
404 if (!decl || !fndecl_built_in_p (decl))
405 for (i = 0; i < n; i++)
407 tree arg = CALL_EXPR_ARG (function, i);
408 if (is_empty_class (TREE_TYPE (arg))
409 && simple_empty_class_p (TREE_TYPE (arg), arg, INIT_EXPR))
411 while (TREE_CODE (arg) == TARGET_EXPR)
412 /* We're disconnecting the initializer from its target,
413 don't create a temporary. */
414 arg = TARGET_EXPR_INITIAL (arg);
415 tree t = build0 (EMPTY_CLASS_EXPR, TREE_TYPE (arg));
416 arg = build2 (COMPOUND_EXPR, TREE_TYPE (t), arg, t);
417 CALL_EXPR_ARG (function, i) = arg;
421 return function;
424 /* New overloading code. */
426 struct z_candidate;
428 struct candidate_warning {
429 z_candidate *loser;
430 candidate_warning *next;
433 /* Information for providing diagnostics about why overloading failed. */
435 enum rejection_reason_code {
436 rr_none,
437 rr_arity,
438 rr_explicit_conversion,
439 rr_template_conversion,
440 rr_arg_conversion,
441 rr_bad_arg_conversion,
442 rr_template_unification,
443 rr_invalid_copy,
444 rr_inherited_ctor,
445 rr_constraint_failure,
446 rr_ignored,
449 struct conversion_info {
450 /* The index of the argument, 0-based. */
451 int n_arg;
452 /* The actual argument or its type. */
453 tree from;
454 /* The type of the parameter. */
455 tree to_type;
456 /* The location of the argument. */
457 location_t loc;
460 struct rejection_reason {
461 enum rejection_reason_code code;
462 union {
463 /* Information about an arity mismatch. */
464 struct {
465 /* The expected number of arguments. */
466 int expected;
467 /* The actual number of arguments in the call. */
468 int actual;
469 /* Whether EXPECTED should be treated as a lower bound. */
470 bool least_p;
471 } arity;
472 /* Information about an argument conversion mismatch. */
473 struct conversion_info conversion;
474 /* Same, but for bad argument conversions. */
475 struct conversion_info bad_conversion;
476 /* Information about template unification failures. These are the
477 parameters passed to fn_type_unification. */
478 struct {
479 tree tmpl;
480 tree explicit_targs;
481 int num_targs;
482 const tree *args;
483 unsigned int nargs;
484 tree return_type;
485 unification_kind_t strict;
486 int flags;
487 } template_unification;
488 /* Information about template instantiation failures. These are the
489 parameters passed to instantiate_template. */
490 struct {
491 tree tmpl;
492 tree targs;
493 } template_instantiation;
494 } u;
497 struct z_candidate {
498 /* The FUNCTION_DECL that will be called if this candidate is
499 selected by overload resolution. */
500 tree fn;
501 /* If not NULL_TREE, the first argument to use when calling this
502 function. */
503 tree first_arg;
504 /* The rest of the arguments to use when calling this function. If
505 there are no further arguments this may be NULL or it may be an
506 empty vector. */
507 const vec<tree, va_gc> *args;
508 /* The implicit conversion sequences for each of the arguments to
509 FN. */
510 conversion **convs;
511 /* The number of implicit conversion sequences. */
512 size_t num_convs;
513 /* If FN is a user-defined conversion, the standard conversion
514 sequence from the type returned by FN to the desired destination
515 type. */
516 conversion *second_conv;
517 struct rejection_reason *reason;
518 /* If FN is a member function, the binfo indicating the path used to
519 qualify the name of FN at the call site. This path is used to
520 determine whether or not FN is accessible if it is selected by
521 overload resolution. The DECL_CONTEXT of FN will always be a
522 (possibly improper) base of this binfo. */
523 tree access_path;
524 /* If FN is a non-static member function, the binfo indicating the
525 subobject to which the `this' pointer should be converted if FN
526 is selected by overload resolution. The type pointed to by
527 the `this' pointer must correspond to the most derived class
528 indicated by the CONVERSION_PATH. */
529 tree conversion_path;
530 tree template_decl;
531 tree explicit_targs;
532 candidate_warning *warnings;
533 z_candidate *next;
534 int viable;
536 /* The flags active in add_candidate. */
537 int flags;
539 bool rewritten () const { return (flags & LOOKUP_REWRITTEN); }
540 bool reversed () const { return (flags & LOOKUP_REVERSED); }
543 /* Returns true iff T is a null pointer constant in the sense of
544 [conv.ptr]. */
546 bool
547 null_ptr_cst_p (tree t)
549 tree type = TREE_TYPE (t);
551 /* [conv.ptr]
553 A null pointer constant is an integer literal ([lex.icon]) with value
554 zero or a prvalue of type std::nullptr_t. */
555 if (NULLPTR_TYPE_P (type))
556 return true;
558 if (cxx_dialect >= cxx11)
560 STRIP_ANY_LOCATION_WRAPPER (t);
562 /* Core issue 903 says only literal 0 is a null pointer constant. */
563 if (TREE_CODE (t) == INTEGER_CST
564 && !TREE_OVERFLOW (t)
565 && TREE_CODE (type) == INTEGER_TYPE
566 && integer_zerop (t)
567 && !char_type_p (type))
568 return true;
570 else if (CP_INTEGRAL_TYPE_P (type))
572 t = fold_non_dependent_expr (t, tf_none);
573 STRIP_NOPS (t);
574 if (integer_zerop (t) && !TREE_OVERFLOW (t))
575 return true;
578 return false;
581 /* Returns true iff T is a null member pointer value (4.11). */
583 bool
584 null_member_pointer_value_p (tree t)
586 tree type = TREE_TYPE (t);
587 if (!type)
588 return false;
589 else if (TYPE_PTRMEMFUNC_P (type))
590 return (TREE_CODE (t) == CONSTRUCTOR
591 && CONSTRUCTOR_NELTS (t)
592 && integer_zerop (CONSTRUCTOR_ELT (t, 0)->value));
593 else if (TYPE_PTRDATAMEM_P (type))
594 return integer_all_onesp (t);
595 else
596 return false;
599 /* Returns nonzero if PARMLIST consists of only default parms,
600 ellipsis, and/or undeduced parameter packs. */
602 bool
603 sufficient_parms_p (const_tree parmlist)
605 for (; parmlist && parmlist != void_list_node;
606 parmlist = TREE_CHAIN (parmlist))
607 if (!TREE_PURPOSE (parmlist)
608 && !PACK_EXPANSION_P (TREE_VALUE (parmlist)))
609 return false;
610 return true;
613 /* Allocate N bytes of memory from the conversion obstack. The memory
614 is zeroed before being returned. */
616 static void *
617 conversion_obstack_alloc (size_t n)
619 void *p;
620 if (!conversion_obstack_initialized)
622 gcc_obstack_init (&conversion_obstack);
623 conversion_obstack_initialized = true;
625 p = obstack_alloc (&conversion_obstack, n);
626 memset (p, 0, n);
627 return p;
630 /* RAII class to discard anything added to conversion_obstack. */
632 struct conversion_obstack_sentinel
634 void *p;
635 conversion_obstack_sentinel (): p (conversion_obstack_alloc (0)) {}
636 ~conversion_obstack_sentinel () { obstack_free (&conversion_obstack, p); }
639 /* Allocate rejection reasons. */
641 static struct rejection_reason *
642 alloc_rejection (enum rejection_reason_code code)
644 struct rejection_reason *p;
645 p = (struct rejection_reason *) conversion_obstack_alloc (sizeof *p);
646 p->code = code;
647 return p;
650 static struct rejection_reason *
651 arity_rejection (tree first_arg, int expected, int actual, bool least_p = false)
653 struct rejection_reason *r = alloc_rejection (rr_arity);
654 int adjust = first_arg != NULL_TREE;
655 r->u.arity.expected = expected - adjust;
656 r->u.arity.actual = actual - adjust;
657 r->u.arity.least_p = least_p;
658 return r;
661 static struct rejection_reason *
662 arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
663 location_t loc)
665 struct rejection_reason *r = alloc_rejection (rr_arg_conversion);
666 int adjust = first_arg != NULL_TREE;
667 r->u.conversion.n_arg = n_arg - adjust;
668 r->u.conversion.from = from;
669 r->u.conversion.to_type = to;
670 r->u.conversion.loc = loc;
671 return r;
674 static struct rejection_reason *
675 bad_arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
676 location_t loc)
678 struct rejection_reason *r = alloc_rejection (rr_bad_arg_conversion);
679 int adjust = first_arg != NULL_TREE;
680 r->u.bad_conversion.n_arg = n_arg - adjust;
681 r->u.bad_conversion.from = from;
682 r->u.bad_conversion.to_type = to;
683 r->u.bad_conversion.loc = loc;
684 return r;
687 static struct rejection_reason *
688 explicit_conversion_rejection (tree from, tree to)
690 struct rejection_reason *r = alloc_rejection (rr_explicit_conversion);
691 r->u.conversion.n_arg = 0;
692 r->u.conversion.from = from;
693 r->u.conversion.to_type = to;
694 r->u.conversion.loc = UNKNOWN_LOCATION;
695 return r;
698 static struct rejection_reason *
699 template_conversion_rejection (tree from, tree to)
701 struct rejection_reason *r = alloc_rejection (rr_template_conversion);
702 r->u.conversion.n_arg = 0;
703 r->u.conversion.from = from;
704 r->u.conversion.to_type = to;
705 r->u.conversion.loc = UNKNOWN_LOCATION;
706 return r;
709 static struct rejection_reason *
710 template_unification_rejection (tree tmpl, tree explicit_targs, tree targs,
711 const tree *args, unsigned int nargs,
712 tree return_type, unification_kind_t strict,
713 int flags)
715 size_t args_n_bytes = sizeof (*args) * nargs;
716 tree *args1 = (tree *) conversion_obstack_alloc (args_n_bytes);
717 struct rejection_reason *r = alloc_rejection (rr_template_unification);
718 r->u.template_unification.tmpl = tmpl;
719 r->u.template_unification.explicit_targs = explicit_targs;
720 r->u.template_unification.num_targs = TREE_VEC_LENGTH (targs);
721 /* Copy args to our own storage. */
722 memcpy (args1, args, args_n_bytes);
723 r->u.template_unification.args = args1;
724 r->u.template_unification.nargs = nargs;
725 r->u.template_unification.return_type = return_type;
726 r->u.template_unification.strict = strict;
727 r->u.template_unification.flags = flags;
728 return r;
731 static struct rejection_reason *
732 template_unification_error_rejection (void)
734 return alloc_rejection (rr_template_unification);
737 static struct rejection_reason *
738 invalid_copy_with_fn_template_rejection (void)
740 struct rejection_reason *r = alloc_rejection (rr_invalid_copy);
741 return r;
744 static struct rejection_reason *
745 inherited_ctor_rejection (void)
747 struct rejection_reason *r = alloc_rejection (rr_inherited_ctor);
748 return r;
751 /* Build a constraint failure record. */
753 static struct rejection_reason *
754 constraint_failure (void)
756 struct rejection_reason *r = alloc_rejection (rr_constraint_failure);
757 return r;
760 /* Dynamically allocate a conversion. */
762 static conversion *
763 alloc_conversion (conversion_kind kind)
765 conversion *c;
766 c = (conversion *) conversion_obstack_alloc (sizeof (conversion));
767 c->kind = kind;
768 return c;
771 /* Make sure that all memory on the conversion obstack has been
772 freed. */
774 void
775 validate_conversion_obstack (void)
777 if (conversion_obstack_initialized)
778 gcc_assert ((obstack_next_free (&conversion_obstack)
779 == obstack_base (&conversion_obstack)));
782 /* Dynamically allocate an array of N conversions. */
784 static conversion **
785 alloc_conversions (size_t n)
787 return (conversion **) conversion_obstack_alloc (n * sizeof (conversion *));
790 /* True iff the active member of conversion::u for code CODE is NEXT. */
792 static inline bool
793 has_next (conversion_kind code)
795 return !(code == ck_identity
796 || code == ck_ambig
797 || code == ck_list
798 || code == ck_aggr
799 || code == ck_deferred_bad);
802 static conversion *
803 build_conv (conversion_kind code, tree type, conversion *from)
805 conversion *t;
806 conversion_rank rank = CONVERSION_RANK (from);
808 /* Only call this function for conversions that use u.next. */
809 gcc_assert (from == NULL || has_next (code));
811 /* Note that the caller is responsible for filling in t->cand for
812 user-defined conversions. */
813 t = alloc_conversion (code);
814 t->type = type;
815 t->u.next = from;
817 switch (code)
819 case ck_ptr:
820 case ck_pmem:
821 case ck_base:
822 case ck_std:
823 if (rank < cr_std)
824 rank = cr_std;
825 break;
827 case ck_qual:
828 case ck_fnptr:
829 if (rank < cr_exact)
830 rank = cr_exact;
831 break;
833 default:
834 break;
836 t->rank = rank;
837 t->user_conv_p = (code == ck_user || from->user_conv_p);
838 t->bad_p = from->bad_p;
839 t->base_p = false;
840 return t;
843 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
844 specialization of std::initializer_list<T>, if such a conversion is
845 possible. */
847 static conversion *
848 build_list_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
850 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (type), 0);
851 unsigned len = CONSTRUCTOR_NELTS (ctor);
852 conversion **subconvs = alloc_conversions (len);
853 conversion *t;
854 unsigned i;
855 tree val;
857 /* Within a list-initialization we can have more user-defined
858 conversions. */
859 flags &= ~LOOKUP_NO_CONVERSION;
860 /* But no narrowing conversions. */
861 flags |= LOOKUP_NO_NARROWING;
863 /* Can't make an array of these types. */
864 if (TYPE_REF_P (elttype)
865 || TREE_CODE (elttype) == FUNCTION_TYPE
866 || VOID_TYPE_P (elttype))
867 return NULL;
869 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
871 conversion *sub
872 = implicit_conversion (elttype, TREE_TYPE (val), val,
873 false, flags, complain);
874 if (sub == NULL)
875 return NULL;
877 subconvs[i] = sub;
880 t = alloc_conversion (ck_list);
881 t->type = type;
882 t->u.list = subconvs;
883 t->rank = cr_exact;
885 for (i = 0; i < len; ++i)
887 conversion *sub = subconvs[i];
888 if (sub->rank > t->rank)
889 t->rank = sub->rank;
890 if (sub->user_conv_p)
891 t->user_conv_p = true;
892 if (sub->bad_p)
893 t->bad_p = true;
896 return t;
899 /* Return the next conversion of the conversion chain (if applicable),
900 or NULL otherwise. Please use this function instead of directly
901 accessing fields of struct conversion. */
903 static conversion *
904 next_conversion (conversion *conv)
906 if (conv == NULL
907 || !has_next (conv->kind))
908 return NULL;
909 return conv->u.next;
912 /* Strip to the first ck_user, ck_ambig, ck_list, ck_aggr or ck_identity
913 encountered. */
915 static conversion *
916 strip_standard_conversion (conversion *conv)
918 while (conv
919 && conv->kind != ck_user
920 && has_next (conv->kind))
921 conv = next_conversion (conv);
922 return conv;
925 /* Subroutine of build_aggr_conv: check whether FROM is a valid aggregate
926 initializer for array type ATYPE. */
928 static bool
929 can_convert_array (tree atype, tree from, int flags, tsubst_flags_t complain)
931 tree elttype = TREE_TYPE (atype);
932 unsigned i;
934 if (TREE_CODE (from) == CONSTRUCTOR)
936 for (i = 0; i < CONSTRUCTOR_NELTS (from); ++i)
938 tree val = CONSTRUCTOR_ELT (from, i)->value;
939 bool ok;
940 if (TREE_CODE (elttype) == ARRAY_TYPE)
941 ok = can_convert_array (elttype, val, flags, complain);
942 else
943 ok = can_convert_arg (elttype, TREE_TYPE (val), val, flags,
944 complain);
945 if (!ok)
946 return false;
948 return true;
951 if (char_type_p (TYPE_MAIN_VARIANT (elttype))
952 && TREE_CODE (tree_strip_any_location_wrapper (from)) == STRING_CST)
953 return array_string_literal_compatible_p (atype, from);
955 /* No other valid way to aggregate initialize an array. */
956 return false;
959 /* Helper for build_aggr_conv. Return true if FIELD is in PSET, or if
960 FIELD has ANON_AGGR_TYPE_P and any initializable field in there recursively
961 is in PSET. */
963 static bool
964 field_in_pset (hash_set<tree, true> &pset, tree field)
966 if (pset.contains (field))
967 return true;
968 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
969 for (field = TYPE_FIELDS (TREE_TYPE (field));
970 field; field = DECL_CHAIN (field))
972 field = next_aggregate_field (field);
973 if (field == NULL_TREE)
974 break;
975 if (field_in_pset (pset, field))
976 return true;
978 return false;
981 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
982 aggregate class, if such a conversion is possible. */
984 static conversion *
985 build_aggr_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
987 unsigned HOST_WIDE_INT i = 0;
988 conversion *c;
989 tree field = next_aggregate_field (TYPE_FIELDS (type));
990 tree empty_ctor = NULL_TREE;
991 hash_set<tree, true> pset;
993 /* We already called reshape_init in implicit_conversion, but it might not
994 have done anything in the case of parenthesized aggr init. */
996 /* The conversions within the init-list aren't affected by the enclosing
997 context; they're always simple copy-initialization. */
998 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1000 /* For designated initializers, verify that each initializer is convertible
1001 to corresponding TREE_TYPE (ce->index) and mark those FIELD_DECLs as
1002 visited. In the following loop then ignore already visited
1003 FIELD_DECLs. */
1004 tree idx, val;
1005 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, idx, val)
1007 if (!idx)
1008 break;
1010 gcc_checking_assert (TREE_CODE (idx) == FIELD_DECL);
1012 tree ftype = TREE_TYPE (idx);
1013 bool ok;
1015 if (TREE_CODE (ftype) == ARRAY_TYPE)
1016 ok = can_convert_array (ftype, val, flags, complain);
1017 else
1018 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1019 complain);
1021 if (!ok)
1022 return NULL;
1024 /* For unions, there should be just one initializer. */
1025 if (TREE_CODE (type) == UNION_TYPE)
1027 field = NULL_TREE;
1028 i = 1;
1029 break;
1031 pset.add (idx);
1034 for (; field; field = next_aggregate_field (DECL_CHAIN (field)))
1036 tree ftype = TREE_TYPE (field);
1037 bool ok;
1039 if (!pset.is_empty () && field_in_pset (pset, field))
1040 continue;
1041 if (i < CONSTRUCTOR_NELTS (ctor))
1043 constructor_elt *ce = CONSTRUCTOR_ELT (ctor, i);
1044 gcc_checking_assert (!ce->index);
1045 val = ce->value;
1046 ++i;
1048 else if (DECL_INITIAL (field))
1049 val = get_nsdmi (field, /*ctor*/false, complain);
1050 else if (TYPE_REF_P (ftype))
1051 /* Value-initialization of reference is ill-formed. */
1052 return NULL;
1053 else
1055 if (empty_ctor == NULL_TREE)
1056 empty_ctor = build_constructor (init_list_type_node, NULL);
1057 val = empty_ctor;
1060 if (TREE_CODE (ftype) == ARRAY_TYPE)
1061 ok = can_convert_array (ftype, val, flags, complain);
1062 else
1063 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1064 complain);
1066 if (!ok)
1067 return NULL;
1069 if (TREE_CODE (type) == UNION_TYPE)
1070 break;
1073 if (i < CONSTRUCTOR_NELTS (ctor))
1074 return NULL;
1076 c = alloc_conversion (ck_aggr);
1077 c->type = type;
1078 c->rank = cr_exact;
1079 c->user_conv_p = true;
1080 c->check_narrowing = true;
1081 c->u.expr = ctor;
1082 return c;
1085 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
1086 array type, if such a conversion is possible. */
1088 static conversion *
1089 build_array_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
1091 conversion *c;
1092 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1093 tree elttype = TREE_TYPE (type);
1094 bool bad = false;
1095 bool user = false;
1096 enum conversion_rank rank = cr_exact;
1098 /* We might need to propagate the size from the element to the array. */
1099 complete_type (type);
1101 if (TYPE_DOMAIN (type)
1102 && !variably_modified_type_p (TYPE_DOMAIN (type), NULL_TREE))
1104 unsigned HOST_WIDE_INT alen = tree_to_uhwi (array_type_nelts_top (type));
1105 if (alen < len)
1106 return NULL;
1109 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1111 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1113 conversion *sub
1114 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1115 false, flags, complain);
1116 if (sub == NULL)
1117 return NULL;
1119 if (sub->rank > rank)
1120 rank = sub->rank;
1121 if (sub->user_conv_p)
1122 user = true;
1123 if (sub->bad_p)
1124 bad = true;
1127 c = alloc_conversion (ck_aggr);
1128 c->type = type;
1129 c->rank = rank;
1130 c->user_conv_p = user;
1131 c->bad_p = bad;
1132 c->u.expr = ctor;
1133 return c;
1136 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
1137 complex type, if such a conversion is possible. */
1139 static conversion *
1140 build_complex_conv (tree type, tree ctor, int flags,
1141 tsubst_flags_t complain)
1143 conversion *c;
1144 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1145 tree elttype = TREE_TYPE (type);
1146 bool bad = false;
1147 bool user = false;
1148 enum conversion_rank rank = cr_exact;
1150 if (len != 2)
1151 return NULL;
1153 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1155 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1157 conversion *sub
1158 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1159 false, flags, complain);
1160 if (sub == NULL)
1161 return NULL;
1163 if (sub->rank > rank)
1164 rank = sub->rank;
1165 if (sub->user_conv_p)
1166 user = true;
1167 if (sub->bad_p)
1168 bad = true;
1171 c = alloc_conversion (ck_aggr);
1172 c->type = type;
1173 c->rank = rank;
1174 c->user_conv_p = user;
1175 c->bad_p = bad;
1176 c->u.expr = ctor;
1177 return c;
1180 /* Build a representation of the identity conversion from EXPR to
1181 itself. The TYPE should match the type of EXPR, if EXPR is non-NULL. */
1183 static conversion *
1184 build_identity_conv (tree type, tree expr)
1186 conversion *c;
1188 c = alloc_conversion (ck_identity);
1189 c->type = type;
1190 c->u.expr = expr;
1192 return c;
1195 /* Converting from EXPR to TYPE was ambiguous in the sense that there
1196 were multiple user-defined conversions to accomplish the job.
1197 Build a conversion that indicates that ambiguity. */
1199 static conversion *
1200 build_ambiguous_conv (tree type, tree expr)
1202 conversion *c;
1204 c = alloc_conversion (ck_ambig);
1205 c->type = type;
1206 c->u.expr = expr;
1208 return c;
1211 tree
1212 strip_top_quals (tree t)
1214 if (TREE_CODE (t) == ARRAY_TYPE)
1215 return t;
1216 return cp_build_qualified_type (t, 0);
1219 /* Returns the standard conversion path (see [conv]) from type FROM to type
1220 TO, if any. For proper handling of null pointer constants, you must
1221 also pass the expression EXPR to convert from. If C_CAST_P is true,
1222 this conversion is coming from a C-style cast. */
1224 static conversion *
1225 standard_conversion (tree to, tree from, tree expr, bool c_cast_p,
1226 int flags, tsubst_flags_t complain)
1228 enum tree_code fcode, tcode;
1229 conversion *conv;
1230 bool fromref = false;
1231 tree qualified_to;
1233 to = non_reference (to);
1234 if (TYPE_REF_P (from))
1236 fromref = true;
1237 from = TREE_TYPE (from);
1239 qualified_to = to;
1240 to = strip_top_quals (to);
1241 from = strip_top_quals (from);
1243 if (expr && type_unknown_p (expr))
1245 if (TYPE_PTRFN_P (to) || TYPE_PTRMEMFUNC_P (to))
1247 tsubst_flags_t tflags = tf_conv;
1248 expr = instantiate_type (to, expr, tflags);
1249 if (expr == error_mark_node)
1250 return NULL;
1251 from = TREE_TYPE (expr);
1253 else if (TREE_CODE (to) == BOOLEAN_TYPE)
1255 /* Necessary for eg, TEMPLATE_ID_EXPRs (c++/50961). */
1256 expr = resolve_nondeduced_context (expr, complain);
1257 from = TREE_TYPE (expr);
1261 fcode = TREE_CODE (from);
1262 tcode = TREE_CODE (to);
1264 conv = build_identity_conv (from, expr);
1265 if (fcode == FUNCTION_TYPE || fcode == ARRAY_TYPE)
1267 from = type_decays_to (from);
1268 fcode = TREE_CODE (from);
1269 /* Tell convert_like that we're using the address. */
1270 conv->rvaluedness_matches_p = true;
1271 conv = build_conv (ck_lvalue, from, conv);
1273 /* Wrapping a ck_rvalue around a class prvalue (as a result of using
1274 obvalue_p) seems odd, since it's already a prvalue, but that's how we
1275 express the copy constructor call required by copy-initialization. */
1276 else if (fromref || (expr && obvalue_p (expr)))
1278 if (expr)
1280 tree bitfield_type;
1281 bitfield_type = is_bitfield_expr_with_lowered_type (expr);
1282 if (bitfield_type)
1284 from = strip_top_quals (bitfield_type);
1285 fcode = TREE_CODE (from);
1288 conv = build_conv (ck_rvalue, from, conv);
1289 /* If we're performing copy-initialization, remember to skip
1290 explicit constructors. */
1291 if (flags & LOOKUP_ONLYCONVERTING)
1292 conv->copy_init_p = true;
1295 /* Allow conversion between `__complex__' data types. */
1296 if (tcode == COMPLEX_TYPE && fcode == COMPLEX_TYPE)
1298 /* The standard conversion sequence to convert FROM to TO is
1299 the standard conversion sequence to perform componentwise
1300 conversion. */
1301 conversion *part_conv = standard_conversion
1302 (TREE_TYPE (to), TREE_TYPE (from), NULL_TREE, c_cast_p, flags,
1303 complain);
1305 if (!part_conv)
1306 conv = NULL;
1307 else if (part_conv->kind == ck_identity)
1308 /* Leave conv alone. */;
1309 else
1311 conv = build_conv (part_conv->kind, to, conv);
1312 conv->rank = part_conv->rank;
1315 return conv;
1318 if (same_type_p (from, to))
1320 if (CLASS_TYPE_P (to) && conv->kind == ck_rvalue)
1321 conv->type = qualified_to;
1322 return conv;
1325 /* [conv.ptr]
1326 A null pointer constant can be converted to a pointer type; ... A
1327 null pointer constant of integral type can be converted to an
1328 rvalue of type std::nullptr_t. */
1329 if ((tcode == POINTER_TYPE || TYPE_PTRMEM_P (to)
1330 || NULLPTR_TYPE_P (to))
1331 && ((expr && null_ptr_cst_p (expr))
1332 || NULLPTR_TYPE_P (from)))
1333 conv = build_conv (ck_std, to, conv);
1334 else if ((tcode == INTEGER_TYPE && fcode == POINTER_TYPE)
1335 || (tcode == POINTER_TYPE && fcode == INTEGER_TYPE))
1337 /* For backwards brain damage compatibility, allow interconversion of
1338 pointers and integers with a pedwarn. */
1339 conv = build_conv (ck_std, to, conv);
1340 conv->bad_p = true;
1342 else if (UNSCOPED_ENUM_P (to) && fcode == INTEGER_TYPE)
1344 /* For backwards brain damage compatibility, allow interconversion of
1345 enums and integers with a pedwarn. */
1346 conv = build_conv (ck_std, to, conv);
1347 conv->bad_p = true;
1349 else if ((tcode == POINTER_TYPE && fcode == POINTER_TYPE)
1350 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from)))
1352 tree to_pointee;
1353 tree from_pointee;
1355 if (tcode == POINTER_TYPE)
1357 to_pointee = TREE_TYPE (to);
1358 from_pointee = TREE_TYPE (from);
1360 /* Since this is the target of a pointer, it can't have function
1361 qualifiers, so any TYPE_QUALS must be for attributes const or
1362 noreturn. Strip them. */
1363 if (TREE_CODE (to_pointee) == FUNCTION_TYPE
1364 && TYPE_QUALS (to_pointee))
1365 to_pointee = build_qualified_type (to_pointee, TYPE_UNQUALIFIED);
1366 if (TREE_CODE (from_pointee) == FUNCTION_TYPE
1367 && TYPE_QUALS (from_pointee))
1368 from_pointee = build_qualified_type (from_pointee, TYPE_UNQUALIFIED);
1370 else
1372 to_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (to);
1373 from_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (from);
1376 if (tcode == POINTER_TYPE
1377 && same_type_ignoring_top_level_qualifiers_p (from_pointee,
1378 to_pointee))
1380 else if (VOID_TYPE_P (to_pointee)
1381 && !TYPE_PTRDATAMEM_P (from)
1382 && TREE_CODE (from_pointee) != FUNCTION_TYPE)
1384 tree nfrom = TREE_TYPE (from);
1385 /* Don't try to apply restrict to void. */
1386 int quals = cp_type_quals (nfrom) & ~TYPE_QUAL_RESTRICT;
1387 from_pointee = cp_build_qualified_type (void_type_node, quals);
1388 from = build_pointer_type (from_pointee);
1389 conv = build_conv (ck_ptr, from, conv);
1391 else if (TYPE_PTRDATAMEM_P (from))
1393 tree fbase = TYPE_PTRMEM_CLASS_TYPE (from);
1394 tree tbase = TYPE_PTRMEM_CLASS_TYPE (to);
1396 if (same_type_p (fbase, tbase))
1397 /* No base conversion needed. */;
1398 else if (DERIVED_FROM_P (fbase, tbase)
1399 && (same_type_ignoring_top_level_qualifiers_p
1400 (from_pointee, to_pointee)))
1402 from = build_ptrmem_type (tbase, from_pointee);
1403 conv = build_conv (ck_pmem, from, conv);
1405 else
1406 return NULL;
1408 else if (CLASS_TYPE_P (from_pointee)
1409 && CLASS_TYPE_P (to_pointee)
1410 /* [conv.ptr]
1412 An rvalue of type "pointer to cv D," where D is a
1413 class type, can be converted to an rvalue of type
1414 "pointer to cv B," where B is a base class (clause
1415 _class.derived_) of D. If B is an inaccessible
1416 (clause _class.access_) or ambiguous
1417 (_class.member.lookup_) base class of D, a program
1418 that necessitates this conversion is ill-formed.
1419 Therefore, we use DERIVED_FROM_P, and do not check
1420 access or uniqueness. */
1421 && DERIVED_FROM_P (to_pointee, from_pointee))
1423 from_pointee
1424 = cp_build_qualified_type (to_pointee,
1425 cp_type_quals (from_pointee));
1426 from = build_pointer_type (from_pointee);
1427 conv = build_conv (ck_ptr, from, conv);
1428 conv->base_p = true;
1431 if (same_type_p (from, to))
1432 /* OK */;
1433 else if (c_cast_p && comp_ptr_ttypes_const (to, from, bounds_either))
1434 /* In a C-style cast, we ignore CV-qualification because we
1435 are allowed to perform a static_cast followed by a
1436 const_cast. */
1437 conv = build_conv (ck_qual, to, conv);
1438 else if (!c_cast_p && comp_ptr_ttypes (to_pointee, from_pointee))
1439 conv = build_conv (ck_qual, to, conv);
1440 else if (expr && string_conv_p (to, expr, 0))
1441 /* converting from string constant to char *. */
1442 conv = build_conv (ck_qual, to, conv);
1443 else if (fnptr_conv_p (to, from))
1444 conv = build_conv (ck_fnptr, to, conv);
1445 /* Allow conversions among compatible ObjC pointer types (base
1446 conversions have been already handled above). */
1447 else if (c_dialect_objc ()
1448 && objc_compare_types (to, from, -4, NULL_TREE))
1449 conv = build_conv (ck_ptr, to, conv);
1450 else if (ptr_reasonably_similar (to_pointee, from_pointee))
1452 conv = build_conv (ck_ptr, to, conv);
1453 conv->bad_p = true;
1455 else
1456 return NULL;
1458 from = to;
1460 else if (TYPE_PTRMEMFUNC_P (to) && TYPE_PTRMEMFUNC_P (from))
1462 tree fromfn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (from));
1463 tree tofn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (to));
1464 tree fbase = class_of_this_parm (fromfn);
1465 tree tbase = class_of_this_parm (tofn);
1467 /* If FBASE and TBASE are equivalent but incomplete, DERIVED_FROM_P
1468 yields false. But a pointer to member of incomplete class is OK. */
1469 if (!same_type_p (fbase, tbase) && !DERIVED_FROM_P (fbase, tbase))
1470 return NULL;
1472 tree fstat = static_fn_type (fromfn);
1473 tree tstat = static_fn_type (tofn);
1474 if (same_type_p (tstat, fstat)
1475 || fnptr_conv_p (tstat, fstat))
1476 /* OK */;
1477 else
1478 return NULL;
1480 if (!same_type_p (fbase, tbase))
1482 from = build_memfn_type (fstat,
1483 tbase,
1484 cp_type_quals (tbase),
1485 type_memfn_rqual (tofn));
1486 from = build_ptrmemfunc_type (build_pointer_type (from));
1487 conv = build_conv (ck_pmem, from, conv);
1488 conv->base_p = true;
1490 if (fnptr_conv_p (tstat, fstat))
1491 conv = build_conv (ck_fnptr, to, conv);
1493 else if (tcode == BOOLEAN_TYPE)
1495 /* [conv.bool]
1497 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer
1498 to member type can be converted to a prvalue of type bool. ...
1499 For direct-initialization (8.5 [dcl.init]), a prvalue of type
1500 std::nullptr_t can be converted to a prvalue of type bool; */
1501 if (ARITHMETIC_TYPE_P (from)
1502 || UNSCOPED_ENUM_P (from)
1503 || fcode == POINTER_TYPE
1504 || TYPE_PTRMEM_P (from)
1505 || NULLPTR_TYPE_P (from))
1507 conv = build_conv (ck_std, to, conv);
1508 if (fcode == POINTER_TYPE
1509 || TYPE_PTRDATAMEM_P (from)
1510 || (TYPE_PTRMEMFUNC_P (from)
1511 && conv->rank < cr_pbool)
1512 || NULLPTR_TYPE_P (from))
1513 conv->rank = cr_pbool;
1514 if (NULLPTR_TYPE_P (from) && (flags & LOOKUP_ONLYCONVERTING))
1515 conv->bad_p = true;
1516 if (flags & LOOKUP_NO_NARROWING)
1517 conv->check_narrowing = true;
1518 return conv;
1521 return NULL;
1523 /* We don't check for ENUMERAL_TYPE here because there are no standard
1524 conversions to enum type. */
1525 /* As an extension, allow conversion to complex type. */
1526 else if (ARITHMETIC_TYPE_P (to))
1528 if (! (INTEGRAL_CODE_P (fcode)
1529 || (fcode == REAL_TYPE && !(flags & LOOKUP_NO_NON_INTEGRAL)))
1530 || SCOPED_ENUM_P (from))
1531 return NULL;
1533 /* If we're parsing an enum with no fixed underlying type, we're
1534 dealing with an incomplete type, which renders the conversion
1535 ill-formed. */
1536 if (!COMPLETE_TYPE_P (from))
1537 return NULL;
1539 conv = build_conv (ck_std, to, conv);
1541 tree underlying_type = NULL_TREE;
1542 if (TREE_CODE (from) == ENUMERAL_TYPE
1543 && ENUM_FIXED_UNDERLYING_TYPE_P (from))
1544 underlying_type = ENUM_UNDERLYING_TYPE (from);
1546 /* Give this a better rank if it's a promotion.
1548 To handle CWG 1601, also bump the rank if we are converting
1549 an enumeration with a fixed underlying type to the underlying
1550 type. */
1551 if ((same_type_p (to, type_promotes_to (from))
1552 || (underlying_type && same_type_p (to, underlying_type)))
1553 && next_conversion (conv)->rank <= cr_promotion)
1554 conv->rank = cr_promotion;
1556 /* A prvalue of floating-point type can be converted to a prvalue of
1557 another floating-point type with a greater or equal conversion
1558 rank ([conv.rank]). A prvalue of standard floating-point type can
1559 be converted to a prvalue of another standard floating-point type.
1560 For backwards compatibility with handling __float128 and other
1561 non-standard floating point types, allow all implicit floating
1562 point conversions if neither type is extended floating-point
1563 type and if at least one of them is, fail if they have unordered
1564 conversion rank or from has higher conversion rank. */
1565 if (fcode == REAL_TYPE
1566 && tcode == REAL_TYPE
1567 && (extended_float_type_p (from)
1568 || extended_float_type_p (to))
1569 && cp_compare_floating_point_conversion_ranks (from, to) >= 2)
1570 conv->bad_p = true;
1572 else if (fcode == VECTOR_TYPE && tcode == VECTOR_TYPE
1573 && vector_types_convertible_p (from, to, false))
1574 return build_conv (ck_std, to, conv);
1575 else if (MAYBE_CLASS_TYPE_P (to) && MAYBE_CLASS_TYPE_P (from)
1576 && is_properly_derived_from (from, to))
1578 if (conv->kind == ck_rvalue)
1579 conv = next_conversion (conv);
1580 conv = build_conv (ck_base, to, conv);
1581 /* The derived-to-base conversion indicates the initialization
1582 of a parameter with base type from an object of a derived
1583 type. A temporary object is created to hold the result of
1584 the conversion unless we're binding directly to a reference. */
1585 conv->need_temporary_p = !(flags & LOOKUP_NO_TEMP_BIND);
1586 /* If we're performing copy-initialization, remember to skip
1587 explicit constructors. */
1588 if (flags & LOOKUP_ONLYCONVERTING)
1589 conv->copy_init_p = true;
1591 else
1592 return NULL;
1594 if (flags & LOOKUP_NO_NARROWING)
1595 conv->check_narrowing = true;
1597 return conv;
1600 /* Returns nonzero if T1 is reference-related to T2.
1602 This is considered when a reference to T1 is initialized by a T2. */
1604 bool
1605 reference_related_p (tree t1, tree t2)
1607 if (t1 == error_mark_node || t2 == error_mark_node)
1608 return false;
1610 t1 = TYPE_MAIN_VARIANT (t1);
1611 t2 = TYPE_MAIN_VARIANT (t2);
1613 /* [dcl.init.ref]
1615 Given types "cv1 T1" and "cv2 T2," "cv1 T1" is reference-related
1616 to "cv2 T2" if T1 is similar to T2, or T1 is a base class of T2. */
1617 return (similar_type_p (t1, t2)
1618 || (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
1619 && DERIVED_FROM_P (t1, t2)));
1622 /* Returns nonzero if T1 is reference-compatible with T2. */
1624 bool
1625 reference_compatible_p (tree t1, tree t2)
1627 /* [dcl.init.ref]
1629 "cv1 T1" is reference compatible with "cv2 T2" if
1630 a prvalue of type "pointer to cv2 T2" can be converted to the type
1631 "pointer to cv1 T1" via a standard conversion sequence. */
1632 tree ptype1 = build_pointer_type (t1);
1633 tree ptype2 = build_pointer_type (t2);
1634 conversion *conv = standard_conversion (ptype1, ptype2, NULL_TREE,
1635 /*c_cast_p=*/false, 0, tf_none);
1636 if (!conv || conv->bad_p)
1637 return false;
1638 return true;
1641 /* Return true if converting FROM to TO would involve a qualification
1642 conversion. */
1644 static bool
1645 involves_qualification_conversion_p (tree to, tree from)
1647 /* If we're not convering a pointer to another one, we won't get
1648 a qualification conversion. */
1649 if (!((TYPE_PTR_P (to) && TYPE_PTR_P (from))
1650 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from))))
1651 return false;
1653 conversion *conv = standard_conversion (to, from, NULL_TREE,
1654 /*c_cast_p=*/false, 0, tf_none);
1655 for (conversion *t = conv; t; t = next_conversion (t))
1656 if (t->kind == ck_qual)
1657 return true;
1659 return false;
1662 /* A reference of the indicated TYPE is being bound directly to the
1663 expression represented by the implicit conversion sequence CONV.
1664 Return a conversion sequence for this binding. */
1666 static conversion *
1667 direct_reference_binding (tree type, conversion *conv)
1669 tree t;
1671 gcc_assert (TYPE_REF_P (type));
1672 gcc_assert (!TYPE_REF_P (conv->type));
1674 t = TREE_TYPE (type);
1676 if (conv->kind == ck_identity)
1677 /* Mark the identity conv as to not decay to rvalue. */
1678 conv->rvaluedness_matches_p = true;
1680 /* [over.ics.rank]
1682 When a parameter of reference type binds directly
1683 (_dcl.init.ref_) to an argument expression, the implicit
1684 conversion sequence is the identity conversion, unless the
1685 argument expression has a type that is a derived class of the
1686 parameter type, in which case the implicit conversion sequence is
1687 a derived-to-base Conversion.
1689 If the parameter binds directly to the result of applying a
1690 conversion function to the argument expression, the implicit
1691 conversion sequence is a user-defined conversion sequence
1692 (_over.ics.user_), with the second standard conversion sequence
1693 either an identity conversion or, if the conversion function
1694 returns an entity of a type that is a derived class of the
1695 parameter type, a derived-to-base conversion. */
1696 if (is_properly_derived_from (conv->type, t))
1698 /* Represent the derived-to-base conversion. */
1699 conv = build_conv (ck_base, t, conv);
1700 /* We will actually be binding to the base-class subobject in
1701 the derived class, so we mark this conversion appropriately.
1702 That way, convert_like knows not to generate a temporary. */
1703 conv->need_temporary_p = false;
1705 else if (involves_qualification_conversion_p (t, conv->type))
1706 /* Represent the qualification conversion. After DR 2352
1707 #1 and #2 were indistinguishable conversion sequences:
1709 void f(int*); // #1
1710 void f(const int* const &); // #2
1711 void g(int* p) { f(p); }
1713 because the types "int *" and "const int *const" are
1714 reference-related and we were binding both directly and they
1715 had the same rank. To break it up, we add a ck_qual under the
1716 ck_ref_bind so that conversion sequence ranking chooses #1.
1718 We strip_top_quals here which is also what standard_conversion
1719 does. Failure to do so would confuse comp_cv_qual_signature
1720 into thinking that in
1722 void f(const int * const &); // #1
1723 void f(const int *); // #2
1724 int *x;
1725 f(x);
1727 #2 is a better match than #1 even though they're ambiguous (97296). */
1728 conv = build_conv (ck_qual, strip_top_quals (t), conv);
1730 return build_conv (ck_ref_bind, type, conv);
1733 /* Returns the conversion path from type FROM to reference type TO for
1734 purposes of reference binding. For lvalue binding, either pass a
1735 reference type to FROM or an lvalue expression to EXPR. If the
1736 reference will be bound to a temporary, NEED_TEMPORARY_P is set for
1737 the conversion returned. If C_CAST_P is true, this
1738 conversion is coming from a C-style cast. */
1740 static conversion *
1741 reference_binding (tree rto, tree rfrom, tree expr, bool c_cast_p, int flags,
1742 tsubst_flags_t complain)
1744 conversion *conv = NULL;
1745 conversion *bad_direct_conv = nullptr;
1746 tree to = TREE_TYPE (rto);
1747 tree from = rfrom;
1748 tree tfrom;
1749 bool related_p;
1750 bool compatible_p;
1751 cp_lvalue_kind gl_kind;
1752 bool is_lvalue;
1754 if (TREE_CODE (to) == FUNCTION_TYPE && expr && type_unknown_p (expr))
1756 expr = instantiate_type (to, expr, tf_none);
1757 if (expr == error_mark_node)
1758 return NULL;
1759 from = TREE_TYPE (expr);
1762 bool copy_list_init = false;
1763 bool single_list_conv = false;
1764 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1766 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
1767 /* DR 1288: Otherwise, if the initializer list has a single element
1768 of type E and ... [T's] referenced type is reference-related to E,
1769 the object or reference is initialized from that element...
1771 ??? With P0388R4, we should bind 't' directly to U{}:
1772 using U = A[2];
1773 A (&&t)[] = {U{}};
1774 because A[] and A[2] are reference-related. But we don't do it
1775 because grok_reference_init has deduced the array size (to 1), and
1776 A[1] and A[2] aren't reference-related. */
1777 if (CONSTRUCTOR_NELTS (expr) == 1
1778 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
1780 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
1781 if (error_operand_p (elt))
1782 return NULL;
1783 tree etype = TREE_TYPE (elt);
1784 if (reference_related_p (to, etype))
1786 expr = elt;
1787 from = etype;
1788 goto skip;
1790 else if (CLASS_TYPE_P (etype) && TYPE_HAS_CONVERSION (etype))
1791 /* CWG1996: jason's proposed drafting adds "or initializing T from E
1792 would bind directly". We check that in the direct binding with
1793 conversion code below. */
1794 single_list_conv = true;
1796 /* Otherwise, if T is a reference type, a prvalue temporary of the type
1797 referenced by T is copy-list-initialized, and the reference is bound
1798 to that temporary. */
1799 copy_list_init = true;
1800 skip:;
1803 if (TYPE_REF_P (from))
1805 from = TREE_TYPE (from);
1806 if (!TYPE_REF_IS_RVALUE (rfrom)
1807 || TREE_CODE (from) == FUNCTION_TYPE)
1808 gl_kind = clk_ordinary;
1809 else
1810 gl_kind = clk_rvalueref;
1812 else if (expr)
1813 gl_kind = lvalue_kind (expr);
1814 else if (CLASS_TYPE_P (from)
1815 || TREE_CODE (from) == ARRAY_TYPE)
1816 gl_kind = clk_class;
1817 else
1818 gl_kind = clk_none;
1820 /* Don't allow a class prvalue when LOOKUP_NO_TEMP_BIND. */
1821 if ((flags & LOOKUP_NO_TEMP_BIND)
1822 && (gl_kind & clk_class))
1823 gl_kind = clk_none;
1825 /* Same mask as real_lvalue_p. */
1826 is_lvalue = gl_kind && !(gl_kind & (clk_rvalueref|clk_class));
1828 tfrom = from;
1829 if ((gl_kind & clk_bitfield) != 0)
1830 tfrom = unlowered_expr_type (expr);
1832 /* Figure out whether or not the types are reference-related and
1833 reference compatible. We have to do this after stripping
1834 references from FROM. */
1835 related_p = reference_related_p (to, tfrom);
1836 /* If this is a C cast, first convert to an appropriately qualified
1837 type, so that we can later do a const_cast to the desired type. */
1838 if (related_p && c_cast_p
1839 && !at_least_as_qualified_p (to, tfrom))
1840 to = cp_build_qualified_type (to, cp_type_quals (tfrom));
1841 compatible_p = reference_compatible_p (to, tfrom);
1843 /* Directly bind reference when target expression's type is compatible with
1844 the reference and expression is an lvalue. In DR391, the wording in
1845 [8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
1846 const and rvalue references to rvalues of compatible class type.
1847 We should also do direct bindings for non-class xvalues. */
1848 if ((related_p || compatible_p) && gl_kind)
1850 /* [dcl.init.ref]
1852 If the initializer expression
1854 -- is an lvalue (but not an lvalue for a bit-field), and "cv1 T1"
1855 is reference-compatible with "cv2 T2,"
1857 the reference is bound directly to the initializer expression
1858 lvalue.
1860 [...]
1861 If the initializer expression is an rvalue, with T2 a class type,
1862 and "cv1 T1" is reference-compatible with "cv2 T2", the reference
1863 is bound to the object represented by the rvalue or to a sub-object
1864 within that object. */
1866 conv = build_identity_conv (tfrom, expr);
1867 conv = direct_reference_binding (rto, conv);
1869 if (TYPE_REF_P (rfrom))
1870 /* Handle rvalue reference to function properly. */
1871 conv->rvaluedness_matches_p
1872 = (TYPE_REF_IS_RVALUE (rto) == TYPE_REF_IS_RVALUE (rfrom));
1873 else
1874 conv->rvaluedness_matches_p
1875 = (TYPE_REF_IS_RVALUE (rto) == !is_lvalue);
1877 if ((gl_kind & clk_bitfield) != 0
1878 || ((gl_kind & clk_packed) != 0 && !TYPE_PACKED (to)))
1879 /* For the purposes of overload resolution, we ignore the fact
1880 this expression is a bitfield or packed field. (In particular,
1881 [over.ics.ref] says specifically that a function with a
1882 non-const reference parameter is viable even if the
1883 argument is a bitfield.)
1885 However, when we actually call the function we must create
1886 a temporary to which to bind the reference. If the
1887 reference is volatile, or isn't const, then we cannot make
1888 a temporary, so we just issue an error when the conversion
1889 actually occurs. */
1890 conv->need_temporary_p = true;
1892 /* Don't allow binding of lvalues (other than function lvalues) to
1893 rvalue references. */
1894 if (is_lvalue && TYPE_REF_IS_RVALUE (rto)
1895 && TREE_CODE (to) != FUNCTION_TYPE)
1896 conv->bad_p = true;
1898 /* Nor the reverse. */
1899 if (!is_lvalue && !TYPE_REF_IS_RVALUE (rto)
1900 /* Unless it's really a C++20 lvalue being treated as an xvalue.
1901 But in C++23, such an expression is just an xvalue, not a special
1902 lvalue, so the binding is once again ill-formed. */
1903 && !(cxx_dialect <= cxx20
1904 && (gl_kind & clk_implicit_rval))
1905 && (!CP_TYPE_CONST_NON_VOLATILE_P (to)
1906 || (flags & LOOKUP_NO_RVAL_BIND))
1907 && TREE_CODE (to) != FUNCTION_TYPE)
1908 conv->bad_p = true;
1910 if (!compatible_p)
1911 conv->bad_p = true;
1913 return conv;
1915 /* [class.conv.fct] A conversion function is never used to convert a
1916 (possibly cv-qualified) object to the (possibly cv-qualified) same
1917 object type (or a reference to it), to a (possibly cv-qualified) base
1918 class of that type (or a reference to it).... */
1919 else if (!related_p
1920 && !(flags & LOOKUP_NO_CONVERSION)
1921 && (CLASS_TYPE_P (from) || single_list_conv))
1923 tree rexpr = expr;
1924 if (single_list_conv)
1925 rexpr = CONSTRUCTOR_ELT (expr, 0)->value;
1927 /* [dcl.init.ref]
1929 If the initializer expression
1931 -- has a class type (i.e., T2 is a class type) can be
1932 implicitly converted to an lvalue of type "cv3 T3," where
1933 "cv1 T1" is reference-compatible with "cv3 T3". (this
1934 conversion is selected by enumerating the applicable
1935 conversion functions (_over.match.ref_) and choosing the
1936 best one through overload resolution. (_over.match_).
1938 the reference is bound to the lvalue result of the conversion
1939 in the second case. */
1940 z_candidate *cand = build_user_type_conversion_1 (rto, rexpr, flags,
1941 complain);
1942 if (cand)
1944 if (!cand->second_conv->bad_p)
1945 return cand->second_conv;
1947 /* Direct reference binding wasn't successful and yielded a bad
1948 conversion. Proceed with trying to go through a temporary
1949 instead, and if that also fails then we'll return this bad
1950 conversion rather than no conversion for sake of better
1951 diagnostics. */
1952 bad_direct_conv = cand->second_conv;
1956 /* From this point on, we conceptually need temporaries, even if we
1957 elide them. Only the cases above are "direct bindings". */
1958 if (flags & LOOKUP_NO_TEMP_BIND)
1959 return bad_direct_conv ? bad_direct_conv : nullptr;
1961 /* [over.ics.rank]
1963 When a parameter of reference type is not bound directly to an
1964 argument expression, the conversion sequence is the one required
1965 to convert the argument expression to the underlying type of the
1966 reference according to _over.best.ics_. Conceptually, this
1967 conversion sequence corresponds to copy-initializing a temporary
1968 of the underlying type with the argument expression. Any
1969 difference in top-level cv-qualification is subsumed by the
1970 initialization itself and does not constitute a conversion. */
1972 bool maybe_valid_p = true;
1974 /* [dcl.init.ref]
1976 Otherwise, the reference shall be an lvalue reference to a
1977 non-volatile const type, or the reference shall be an rvalue
1978 reference. */
1979 if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto))
1980 maybe_valid_p = false;
1982 /* [dcl.init.ref]
1984 Otherwise, a temporary of type "cv1 T1" is created and
1985 initialized from the initializer expression using the rules for a
1986 non-reference copy initialization. If T1 is reference-related to
1987 T2, cv1 must be the same cv-qualification as, or greater
1988 cv-qualification than, cv2; otherwise, the program is ill-formed. */
1989 if (related_p && !at_least_as_qualified_p (to, from))
1990 maybe_valid_p = false;
1992 /* We try below to treat an invalid reference binding as a bad conversion
1993 to improve diagnostics, but doing so may cause otherwise unnecessary
1994 instantiations that can lead to a hard error. So during the first pass
1995 of overload resolution wherein we shortcut bad conversions, instead just
1996 produce a special conversion indicating a second pass is necessary if
1997 there's no strictly viable candidate. */
1998 if (!maybe_valid_p && (flags & LOOKUP_SHORTCUT_BAD_CONVS))
2000 if (bad_direct_conv)
2001 return bad_direct_conv;
2003 conv = alloc_conversion (ck_deferred_bad);
2004 conv->bad_p = true;
2005 return conv;
2008 /* We're generating a temporary now, but don't bind any more in the
2009 conversion (specifically, don't slice the temporary returned by a
2010 conversion operator). */
2011 flags |= LOOKUP_NO_TEMP_BIND;
2013 /* Core issue 899: When [copy-]initializing a temporary to be bound
2014 to the first parameter of a copy constructor (12.8) called with
2015 a single argument in the context of direct-initialization,
2016 explicit conversion functions are also considered.
2018 So don't set LOOKUP_ONLYCONVERTING in that case. */
2019 if (!(flags & LOOKUP_COPY_PARM))
2020 flags |= LOOKUP_ONLYCONVERTING;
2022 if (!conv)
2023 conv = implicit_conversion (to, from, expr, c_cast_p,
2024 flags, complain);
2025 if (!conv)
2026 return bad_direct_conv ? bad_direct_conv : nullptr;
2028 if (conv->user_conv_p)
2030 if (copy_list_init)
2031 /* Remember this was copy-list-initialization. */
2032 conv->need_temporary_p = true;
2034 /* If initializing the temporary used a conversion function,
2035 recalculate the second conversion sequence. */
2036 for (conversion *t = conv; t; t = next_conversion (t))
2037 if (t->kind == ck_user
2038 && c_cast_p && !maybe_valid_p)
2040 if (complain & tf_warning)
2041 warning (OPT_Wcast_user_defined,
2042 "casting %qT to %qT does not use %qD",
2043 from, rto, t->cand->fn);
2044 /* Don't let recalculation try to make this valid. */
2045 break;
2047 else if (t->kind == ck_user
2048 && DECL_CONV_FN_P (t->cand->fn))
2050 tree ftype = TREE_TYPE (TREE_TYPE (t->cand->fn));
2051 /* A prvalue of non-class type is cv-unqualified. */
2052 if (!TYPE_REF_P (ftype) && !CLASS_TYPE_P (ftype))
2053 ftype = cv_unqualified (ftype);
2054 int sflags = (flags|LOOKUP_NO_CONVERSION)&~LOOKUP_NO_TEMP_BIND;
2055 conversion *new_second
2056 = reference_binding (rto, ftype, NULL_TREE, c_cast_p,
2057 sflags, complain);
2058 if (!new_second)
2059 return bad_direct_conv ? bad_direct_conv : nullptr;
2060 conv = merge_conversion_sequences (t, new_second);
2061 gcc_assert (maybe_valid_p || conv->bad_p);
2062 return conv;
2066 conv = build_conv (ck_ref_bind, rto, conv);
2067 /* This reference binding, unlike those above, requires the
2068 creation of a temporary. */
2069 conv->need_temporary_p = true;
2070 conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
2071 conv->bad_p |= !maybe_valid_p;
2073 return conv;
2076 /* Returns the implicit conversion sequence (see [over.ics]) from type
2077 FROM to type TO. The optional expression EXPR may affect the
2078 conversion. FLAGS are the usual overloading flags. If C_CAST_P is
2079 true, this conversion is coming from a C-style cast. */
2081 static conversion *
2082 implicit_conversion (tree to, tree from, tree expr, bool c_cast_p,
2083 int flags, tsubst_flags_t complain)
2085 conversion *conv;
2087 if (from == error_mark_node || to == error_mark_node
2088 || expr == error_mark_node)
2089 return NULL;
2091 /* Other flags only apply to the primary function in overload
2092 resolution, or after we've chosen one. */
2093 flags &= (LOOKUP_ONLYCONVERTING|LOOKUP_NO_CONVERSION|LOOKUP_COPY_PARM
2094 |LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND|LOOKUP_NO_NARROWING
2095 |LOOKUP_PROTECT|LOOKUP_NO_NON_INTEGRAL|LOOKUP_SHORTCUT_BAD_CONVS);
2097 /* FIXME: actually we don't want warnings either, but we can't just
2098 have 'complain &= ~(tf_warning|tf_error)' because it would cause
2099 the regression of, eg, g++.old-deja/g++.benjamin/16077.C.
2100 We really ought not to issue that warning until we've committed
2101 to that conversion. */
2102 complain &= ~tf_error;
2104 /* Call reshape_init early to remove redundant braces. */
2105 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr) && CLASS_TYPE_P (to))
2107 to = complete_type (to);
2108 if (!COMPLETE_TYPE_P (to))
2109 return nullptr;
2110 if (!CLASSTYPE_NON_AGGREGATE (to))
2112 expr = reshape_init (to, expr, complain);
2113 if (expr == error_mark_node)
2114 return nullptr;
2115 from = TREE_TYPE (expr);
2119 if (TYPE_REF_P (to))
2120 conv = reference_binding (to, from, expr, c_cast_p, flags, complain);
2121 else
2122 conv = standard_conversion (to, from, expr, c_cast_p, flags, complain);
2124 if (conv)
2125 return conv;
2127 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
2129 if (is_std_init_list (to) && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2130 return build_list_conv (to, expr, flags, complain);
2132 /* As an extension, allow list-initialization of _Complex. */
2133 if (TREE_CODE (to) == COMPLEX_TYPE
2134 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2136 conv = build_complex_conv (to, expr, flags, complain);
2137 if (conv)
2138 return conv;
2141 /* Allow conversion from an initializer-list with one element to a
2142 scalar type. */
2143 if (SCALAR_TYPE_P (to))
2145 int nelts = CONSTRUCTOR_NELTS (expr);
2146 tree elt;
2148 if (nelts == 0)
2149 elt = build_value_init (to, tf_none);
2150 else if (nelts == 1 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2151 elt = CONSTRUCTOR_ELT (expr, 0)->value;
2152 else
2153 elt = error_mark_node;
2155 conv = implicit_conversion (to, TREE_TYPE (elt), elt,
2156 c_cast_p, flags, complain);
2157 if (conv)
2159 conv->check_narrowing = true;
2160 if (BRACE_ENCLOSED_INITIALIZER_P (elt))
2161 /* Too many levels of braces, i.e. '{{1}}'. */
2162 conv->bad_p = true;
2163 return conv;
2166 else if (TREE_CODE (to) == ARRAY_TYPE)
2167 return build_array_conv (to, expr, flags, complain);
2170 if (expr != NULL_TREE
2171 && (MAYBE_CLASS_TYPE_P (from)
2172 || MAYBE_CLASS_TYPE_P (to))
2173 && (flags & LOOKUP_NO_CONVERSION) == 0)
2175 struct z_candidate *cand;
2177 if (CLASS_TYPE_P (to)
2178 && BRACE_ENCLOSED_INITIALIZER_P (expr)
2179 && !CLASSTYPE_NON_AGGREGATE (complete_type (to)))
2180 return build_aggr_conv (to, expr, flags, complain);
2182 cand = build_user_type_conversion_1 (to, expr, flags, complain);
2183 if (cand)
2185 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
2186 && CONSTRUCTOR_NELTS (expr) == 1
2187 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
2188 && !is_list_ctor (cand->fn))
2190 /* "If C is not an initializer-list constructor and the
2191 initializer list has a single element of type cv U, where U is
2192 X or a class derived from X, the implicit conversion sequence
2193 has Exact Match rank if U is X, or Conversion rank if U is
2194 derived from X." */
2195 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
2196 tree elttype = TREE_TYPE (elt);
2197 if (reference_related_p (to, elttype))
2198 return implicit_conversion (to, elttype, elt,
2199 c_cast_p, flags, complain);
2201 conv = cand->second_conv;
2204 /* We used to try to bind a reference to a temporary here, but that
2205 is now handled after the recursive call to this function at the end
2206 of reference_binding. */
2207 return conv;
2210 return NULL;
2213 /* Like implicit_conversion, but return NULL if the conversion is bad.
2215 This is not static so that check_non_deducible_conversion can call it within
2216 add_template_candidate_real as part of overload resolution; it should not be
2217 called outside of overload resolution. */
2219 conversion *
2220 good_conversion (tree to, tree from, tree expr,
2221 int flags, tsubst_flags_t complain)
2223 conversion *c = implicit_conversion (to, from, expr, /*cast*/false,
2224 flags, complain);
2225 if (c && c->bad_p)
2226 c = NULL;
2227 return c;
2230 /* Add a new entry to the list of candidates. Used by the add_*_candidate
2231 functions. ARGS will not be changed until a single candidate is
2232 selected. */
2234 static struct z_candidate *
2235 add_candidate (struct z_candidate **candidates,
2236 tree fn, tree first_arg, const vec<tree, va_gc> *args,
2237 size_t num_convs, conversion **convs,
2238 tree access_path, tree conversion_path,
2239 int viable, struct rejection_reason *reason,
2240 int flags)
2242 struct z_candidate *cand = (struct z_candidate *)
2243 conversion_obstack_alloc (sizeof (struct z_candidate));
2245 cand->fn = fn;
2246 cand->first_arg = first_arg;
2247 cand->args = args;
2248 cand->convs = convs;
2249 cand->num_convs = num_convs;
2250 cand->access_path = access_path;
2251 cand->conversion_path = conversion_path;
2252 cand->viable = viable;
2253 cand->reason = reason;
2254 cand->next = *candidates;
2255 cand->flags = flags;
2256 *candidates = cand;
2258 if (convs && cand->reversed ())
2259 /* Swap the conversions for comparison in joust; we'll swap them back
2260 before build_over_call. */
2261 std::swap (convs[0], convs[1]);
2263 return cand;
2266 /* FN is a function from the overload set that we outright didn't even
2267 consider (for some reason); add it to the list as an non-viable "ignored"
2268 candidate. */
2270 static z_candidate *
2271 add_ignored_candidate (z_candidate **candidates, tree fn)
2273 /* No need to dynamically allocate these. */
2274 static const rejection_reason reason_ignored = { rr_ignored, {} };
2276 struct z_candidate *cand = (struct z_candidate *)
2277 conversion_obstack_alloc (sizeof (struct z_candidate));
2279 cand->fn = fn;
2280 cand->reason = const_cast<rejection_reason *> (&reason_ignored);
2281 cand->next = *candidates;
2282 *candidates = cand;
2284 return cand;
2287 /* True iff CAND is a candidate added by add_ignored_candidate. */
2289 static bool
2290 ignored_candidate_p (const z_candidate *cand)
2292 return cand->reason && cand->reason->code == rr_ignored;
2295 /* Return the number of remaining arguments in the parameter list
2296 beginning with ARG. */
2299 remaining_arguments (tree arg)
2301 int n;
2303 for (n = 0; arg != NULL_TREE && arg != void_list_node;
2304 arg = TREE_CHAIN (arg))
2305 n++;
2307 return n;
2310 /* [over.match.copy]: When initializing a temporary object (12.2) to be bound
2311 to the first parameter of a constructor where the parameter is of type
2312 "reference to possibly cv-qualified T" and the constructor is called with a
2313 single argument in the context of direct-initialization of an object of type
2314 "cv2 T", explicit conversion functions are also considered.
2316 So set LOOKUP_COPY_PARM to let reference_binding know that
2317 it's being called in that context. */
2320 conv_flags (int i, int nargs, tree fn, tree arg, int flags)
2322 int lflags = flags;
2323 tree t;
2324 if (i == 0 && nargs == 1 && DECL_CONSTRUCTOR_P (fn)
2325 && (t = FUNCTION_FIRST_USER_PARMTYPE (fn))
2326 && (same_type_ignoring_top_level_qualifiers_p
2327 (non_reference (TREE_VALUE (t)), DECL_CONTEXT (fn))))
2329 if (!(flags & LOOKUP_ONLYCONVERTING))
2330 lflags |= LOOKUP_COPY_PARM;
2331 if ((flags & LOOKUP_LIST_INIT_CTOR)
2332 && BRACE_ENCLOSED_INITIALIZER_P (arg))
2333 lflags |= LOOKUP_NO_CONVERSION;
2335 else
2336 lflags |= LOOKUP_ONLYCONVERTING;
2338 return lflags;
2341 /* Build an appropriate 'this' conversion for the method FN and class
2342 type CTYPE from the value ARG (having type ARGTYPE) to the type PARMTYPE.
2343 This function modifies PARMTYPE, ARGTYPE and ARG. */
2345 static conversion *
2346 build_this_conversion (tree fn, tree ctype,
2347 tree& parmtype, tree& argtype, tree& arg,
2348 int flags, tsubst_flags_t complain)
2350 gcc_assert (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
2351 && !DECL_CONSTRUCTOR_P (fn));
2353 /* The type of the implicit object parameter ('this') for
2354 overload resolution is not always the same as for the
2355 function itself; conversion functions are considered to
2356 be members of the class being converted, and functions
2357 introduced by a using-declaration are considered to be
2358 members of the class that uses them.
2360 Since build_over_call ignores the ICS for the `this'
2361 parameter, we can just change the parm type. */
2362 parmtype = cp_build_qualified_type (ctype,
2363 cp_type_quals (TREE_TYPE (parmtype)));
2364 bool this_p = true;
2365 if (FUNCTION_REF_QUALIFIED (TREE_TYPE (fn)))
2367 /* If the function has a ref-qualifier, the implicit
2368 object parameter has reference type. */
2369 bool rv = FUNCTION_RVALUE_QUALIFIED (TREE_TYPE (fn));
2370 parmtype = cp_build_reference_type (parmtype, rv);
2371 /* The special handling of 'this' conversions in compare_ics
2372 does not apply if there is a ref-qualifier. */
2373 this_p = false;
2375 else
2377 parmtype = build_pointer_type (parmtype);
2378 /* We don't use build_this here because we don't want to
2379 capture the object argument until we've chosen a
2380 non-static member function. */
2381 arg = build_address (arg);
2382 argtype = lvalue_type (arg);
2384 flags |= LOOKUP_ONLYCONVERTING;
2385 conversion *t = implicit_conversion (parmtype, argtype, arg,
2386 /*c_cast_p=*/false, flags, complain);
2387 t->this_p = this_p;
2388 return t;
2391 /* Create an overload candidate for the function or method FN called
2392 with the argument list FIRST_ARG/ARGS and add it to CANDIDATES.
2393 FLAGS is passed on to implicit_conversion.
2395 This does not change ARGS.
2397 CTYPE, if non-NULL, is the type we want to pretend this function
2398 comes from for purposes of overload resolution.
2400 SHORTCUT_BAD_CONVS controls how we handle "bad" argument conversions.
2401 If true, we stop computing conversions upon seeing the first bad
2402 conversion. This is used by add_candidates to avoid computing
2403 more conversions than necessary in the presence of a strictly viable
2404 candidate, while preserving the defacto behavior of overload resolution
2405 when it turns out there are only non-strictly viable candidates. */
2407 static struct z_candidate *
2408 add_function_candidate (struct z_candidate **candidates,
2409 tree fn, tree ctype, tree first_arg,
2410 const vec<tree, va_gc> *args, tree access_path,
2411 tree conversion_path, int flags,
2412 conversion **convs,
2413 bool shortcut_bad_convs,
2414 tsubst_flags_t complain)
2416 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
2417 int i, len;
2418 tree parmnode;
2419 tree orig_first_arg = first_arg;
2420 int skip;
2421 int viable = 1;
2422 struct rejection_reason *reason = NULL;
2424 /* The `this', `in_chrg' and VTT arguments to constructors are not
2425 considered in overload resolution. */
2426 if (DECL_CONSTRUCTOR_P (fn))
2428 if (ctor_omit_inherited_parms (fn))
2429 /* Bring back parameters omitted from an inherited ctor. */
2430 parmlist = FUNCTION_FIRST_USER_PARMTYPE (DECL_ORIGIN (fn));
2431 else
2432 parmlist = skip_artificial_parms_for (fn, parmlist);
2433 skip = num_artificial_parms_for (fn);
2434 if (skip > 0 && first_arg != NULL_TREE)
2436 --skip;
2437 first_arg = NULL_TREE;
2440 else
2441 skip = 0;
2443 len = vec_safe_length (args) - skip + (first_arg != NULL_TREE ? 1 : 0);
2444 if (!convs)
2445 convs = alloc_conversions (len);
2447 /* 13.3.2 - Viable functions [over.match.viable]
2448 First, to be a viable function, a candidate function shall have enough
2449 parameters to agree in number with the arguments in the list.
2451 We need to check this first; otherwise, checking the ICSes might cause
2452 us to produce an ill-formed template instantiation. */
2454 parmnode = parmlist;
2455 for (i = 0; i < len; ++i)
2457 if (parmnode == NULL_TREE || parmnode == void_list_node)
2458 break;
2459 parmnode = TREE_CHAIN (parmnode);
2462 if ((i < len && parmnode)
2463 || !sufficient_parms_p (parmnode))
2465 int remaining = remaining_arguments (parmnode);
2466 viable = 0;
2467 reason = arity_rejection (first_arg, i + remaining, len);
2470 /* An inherited constructor (12.6.3 [class.inhctor.init]) that has a first
2471 parameter of type "reference to cv C" (including such a constructor
2472 instantiated from a template) is excluded from the set of candidate
2473 functions when used to construct an object of type D with an argument list
2474 containing a single argument if C is reference-related to D. */
2475 if (viable && len == 1 && parmlist && DECL_CONSTRUCTOR_P (fn)
2476 && flag_new_inheriting_ctors
2477 && DECL_INHERITED_CTOR (fn))
2479 tree ptype = non_reference (TREE_VALUE (parmlist));
2480 tree dtype = DECL_CONTEXT (fn);
2481 tree btype = DECL_INHERITED_CTOR_BASE (fn);
2482 if (reference_related_p (ptype, dtype)
2483 && reference_related_p (btype, ptype))
2485 viable = false;
2486 reason = inherited_ctor_rejection ();
2490 /* Second, for a function to be viable, its constraints must be
2491 satisfied. */
2492 if (flag_concepts && viable && !constraints_satisfied_p (fn))
2494 reason = constraint_failure ();
2495 viable = false;
2498 /* When looking for a function from a subobject from an implicit
2499 copy/move constructor/operator=, don't consider anything that takes (a
2500 reference to) an unrelated type. See c++/44909 and core 1092. */
2501 if (viable && parmlist && (flags & LOOKUP_DEFAULTED))
2503 if (DECL_CONSTRUCTOR_P (fn))
2504 i = 1;
2505 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
2506 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR))
2507 i = 2;
2508 else
2509 i = 0;
2510 if (i && len == i)
2512 parmnode = chain_index (i-1, parmlist);
2513 if (!reference_related_p (non_reference (TREE_VALUE (parmnode)),
2514 ctype))
2515 viable = 0;
2518 /* This only applies at the top level. */
2519 flags &= ~LOOKUP_DEFAULTED;
2522 if (! viable)
2523 goto out;
2525 if (shortcut_bad_convs)
2526 flags |= LOOKUP_SHORTCUT_BAD_CONVS;
2527 else
2528 flags &= ~LOOKUP_SHORTCUT_BAD_CONVS;
2530 /* Third, for F to be a viable function, there shall exist for each
2531 argument an implicit conversion sequence that converts that argument
2532 to the corresponding parameter of F. */
2534 parmnode = parmlist;
2536 for (i = 0; i < len; ++i)
2538 tree argtype, to_type;
2539 tree arg;
2541 if (parmnode == void_list_node)
2542 break;
2544 if (convs[i])
2546 /* Already set during deduction. */
2547 parmnode = TREE_CHAIN (parmnode);
2548 continue;
2551 if (i == 0 && first_arg != NULL_TREE)
2552 arg = first_arg;
2553 else
2554 arg = CONST_CAST_TREE (
2555 (*args)[i + skip - (first_arg != NULL_TREE ? 1 : 0)]);
2556 argtype = lvalue_type (arg);
2558 conversion *t;
2559 if (parmnode)
2561 tree parmtype = TREE_VALUE (parmnode);
2562 if (i == 0
2563 && DECL_IOBJ_MEMBER_FUNCTION_P (fn)
2564 && !DECL_CONSTRUCTOR_P (fn))
2565 t = build_this_conversion (fn, ctype, parmtype, argtype, arg,
2566 flags, complain);
2567 else
2569 int lflags = conv_flags (i, len-skip, fn, arg, flags);
2570 t = implicit_conversion (parmtype, argtype, arg,
2571 /*c_cast_p=*/false, lflags, complain);
2573 to_type = parmtype;
2574 parmnode = TREE_CHAIN (parmnode);
2576 else
2578 t = build_identity_conv (argtype, arg);
2579 t->ellipsis_p = true;
2580 to_type = argtype;
2583 convs[i] = t;
2584 if (! t)
2586 viable = 0;
2587 reason = arg_conversion_rejection (first_arg, i, argtype, to_type,
2588 EXPR_LOCATION (arg));
2589 break;
2592 if (t->bad_p)
2594 viable = -1;
2595 reason = bad_arg_conversion_rejection (first_arg, i, arg, to_type,
2596 EXPR_LOCATION (arg));
2597 if (shortcut_bad_convs)
2598 break;
2602 out:
2603 return add_candidate (candidates, fn, orig_first_arg, args, len, convs,
2604 access_path, conversion_path, viable, reason, flags);
2607 /* Create an overload candidate for the conversion function FN which will
2608 be invoked for expression OBJ, producing a pointer-to-function which
2609 will in turn be called with the argument list FIRST_ARG/ARGLIST,
2610 and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
2611 passed on to implicit_conversion.
2613 Actually, we don't really care about FN; we care about the type it
2614 converts to. There may be multiple conversion functions that will
2615 convert to that type, and we rely on build_user_type_conversion_1 to
2616 choose the best one; so when we create our candidate, we record the type
2617 instead of the function. */
2619 static struct z_candidate *
2620 add_conv_candidate (struct z_candidate **candidates, tree fn, tree obj,
2621 const vec<tree, va_gc> *arglist,
2622 tree access_path, tree conversion_path,
2623 tsubst_flags_t complain)
2625 tree totype = TREE_TYPE (TREE_TYPE (fn));
2626 int i, len, viable, flags;
2627 tree parmlist, parmnode;
2628 conversion **convs;
2629 struct rejection_reason *reason;
2631 for (parmlist = totype; TREE_CODE (parmlist) != FUNCTION_TYPE; )
2632 parmlist = TREE_TYPE (parmlist);
2633 parmlist = TYPE_ARG_TYPES (parmlist);
2635 len = vec_safe_length (arglist) + 1;
2636 convs = alloc_conversions (len);
2637 parmnode = parmlist;
2638 viable = 1;
2639 flags = LOOKUP_IMPLICIT;
2640 reason = NULL;
2642 /* Don't bother looking up the same type twice. */
2643 if (*candidates && (*candidates)->fn == totype)
2644 return NULL;
2646 if (!constraints_satisfied_p (fn))
2648 reason = constraint_failure ();
2649 viable = 0;
2650 return add_candidate (candidates, fn, obj, arglist, len, convs,
2651 access_path, conversion_path, viable, reason, flags);
2654 for (i = 0; i < len; ++i)
2656 tree arg, argtype, convert_type = NULL_TREE;
2657 conversion *t;
2659 if (i == 0)
2660 arg = obj;
2661 else
2662 arg = (*arglist)[i - 1];
2663 argtype = lvalue_type (arg);
2665 if (i == 0)
2667 t = build_identity_conv (argtype, NULL_TREE);
2668 t = build_conv (ck_user, totype, t);
2669 /* Leave the 'cand' field null; we'll figure out the conversion in
2670 convert_like if this candidate is chosen. */
2671 convert_type = totype;
2673 else if (parmnode == void_list_node)
2674 break;
2675 else if (parmnode)
2677 t = implicit_conversion (TREE_VALUE (parmnode), argtype, arg,
2678 /*c_cast_p=*/false, flags, complain);
2679 convert_type = TREE_VALUE (parmnode);
2681 else
2683 t = build_identity_conv (argtype, arg);
2684 t->ellipsis_p = true;
2685 convert_type = argtype;
2688 convs[i] = t;
2689 if (! t)
2690 break;
2692 if (t->bad_p)
2694 viable = -1;
2695 reason = bad_arg_conversion_rejection (NULL_TREE, i, arg, convert_type,
2696 EXPR_LOCATION (arg));
2699 if (i == 0)
2700 continue;
2702 if (parmnode)
2703 parmnode = TREE_CHAIN (parmnode);
2706 if (i < len
2707 || ! sufficient_parms_p (parmnode))
2709 int remaining = remaining_arguments (parmnode);
2710 viable = 0;
2711 reason = arity_rejection (NULL_TREE, i + remaining, len);
2714 return add_candidate (candidates, totype, obj, arglist, len, convs,
2715 access_path, conversion_path, viable, reason, flags);
2718 static void
2719 build_builtin_candidate (struct z_candidate **candidates, tree fnname,
2720 tree type1, tree type2, const vec<tree,va_gc> &args,
2721 tree *argtypes, int flags, tsubst_flags_t complain)
2723 conversion *t;
2724 conversion **convs;
2725 size_t num_convs;
2726 int viable = 1;
2727 tree types[2];
2728 struct rejection_reason *reason = NULL;
2730 types[0] = type1;
2731 types[1] = type2;
2733 num_convs = args.length ();
2734 convs = alloc_conversions (num_convs);
2736 /* TRUTH_*_EXPR do "contextual conversion to bool", which means explicit
2737 conversion ops are allowed. We handle that here by just checking for
2738 boolean_type_node because other operators don't ask for it. COND_EXPR
2739 also does contextual conversion to bool for the first operand, but we
2740 handle that in build_conditional_expr, and type1 here is operand 2. */
2741 if (type1 != boolean_type_node)
2742 flags |= LOOKUP_ONLYCONVERTING;
2744 for (unsigned i = 0; i < 2 && i < num_convs; ++i)
2746 t = implicit_conversion (types[i], argtypes[i], args[i],
2747 /*c_cast_p=*/false, flags, complain);
2748 if (! t)
2750 viable = 0;
2751 /* We need something for printing the candidate. */
2752 t = build_identity_conv (types[i], NULL_TREE);
2753 reason = arg_conversion_rejection (NULL_TREE, i, argtypes[i],
2754 types[i], EXPR_LOCATION (args[i]));
2756 else if (t->bad_p)
2758 viable = 0;
2759 reason = bad_arg_conversion_rejection (NULL_TREE, i, args[i],
2760 types[i],
2761 EXPR_LOCATION (args[i]));
2763 convs[i] = t;
2766 /* For COND_EXPR we rearranged the arguments; undo that now. */
2767 if (num_convs == 3)
2769 convs[2] = convs[1];
2770 convs[1] = convs[0];
2771 t = implicit_conversion (boolean_type_node, argtypes[2], args[2],
2772 /*c_cast_p=*/false, flags,
2773 complain);
2774 if (t)
2775 convs[0] = t;
2776 else
2778 viable = 0;
2779 reason = arg_conversion_rejection (NULL_TREE, 0, argtypes[2],
2780 boolean_type_node,
2781 EXPR_LOCATION (args[2]));
2785 add_candidate (candidates, fnname, /*first_arg=*/NULL_TREE, /*args=*/NULL,
2786 num_convs, convs,
2787 /*access_path=*/NULL_TREE,
2788 /*conversion_path=*/NULL_TREE,
2789 viable, reason, flags);
2792 static bool
2793 is_complete (tree t)
2795 return COMPLETE_TYPE_P (complete_type (t));
2798 /* Returns nonzero if TYPE is a promoted arithmetic type. */
2800 static bool
2801 promoted_arithmetic_type_p (tree type)
2803 /* [over.built]
2805 In this section, the term promoted integral type is used to refer
2806 to those integral types which are preserved by integral promotion
2807 (including e.g. int and long but excluding e.g. char).
2808 Similarly, the term promoted arithmetic type refers to promoted
2809 integral types plus floating types. */
2810 return ((CP_INTEGRAL_TYPE_P (type)
2811 && same_type_p (type_promotes_to (type), type))
2812 || SCALAR_FLOAT_TYPE_P (type));
2815 /* Create any builtin operator overload candidates for the operator in
2816 question given the converted operand types TYPE1 and TYPE2. The other
2817 args are passed through from add_builtin_candidates to
2818 build_builtin_candidate.
2820 TYPE1 and TYPE2 may not be permissible, and we must filter them.
2821 If CODE is requires candidates operands of the same type of the kind
2822 of which TYPE1 and TYPE2 are, we add both candidates
2823 CODE (TYPE1, TYPE1) and CODE (TYPE2, TYPE2). */
2825 static void
2826 add_builtin_candidate (struct z_candidate **candidates, enum tree_code code,
2827 enum tree_code code2, tree fnname, tree type1,
2828 tree type2, vec<tree,va_gc> &args, tree *argtypes,
2829 int flags, tsubst_flags_t complain)
2831 switch (code)
2833 case POSTINCREMENT_EXPR:
2834 case POSTDECREMENT_EXPR:
2835 args[1] = integer_zero_node;
2836 type2 = integer_type_node;
2837 break;
2838 default:
2839 break;
2842 switch (code)
2845 /* 4 For every pair (T, VQ), where T is an arithmetic type other than bool,
2846 and VQ is either volatile or empty, there exist candidate operator
2847 functions of the form
2848 VQ T& operator++(VQ T&);
2849 T operator++(VQ T&, int);
2850 5 For every pair (T, VQ), where T is an arithmetic type other than bool,
2851 and VQ is either volatile or empty, there exist candidate operator
2852 functions of the form
2853 VQ T& operator--(VQ T&);
2854 T operator--(VQ T&, int);
2855 6 For every pair (T, VQ), where T is a cv-qualified or cv-unqualified object
2856 type, and VQ is either volatile or empty, there exist candidate operator
2857 functions of the form
2858 T*VQ& operator++(T*VQ&);
2859 T*VQ& operator--(T*VQ&);
2860 T* operator++(T*VQ&, int);
2861 T* operator--(T*VQ&, int); */
2863 case POSTDECREMENT_EXPR:
2864 case PREDECREMENT_EXPR:
2865 if (TREE_CODE (type1) == BOOLEAN_TYPE)
2866 return;
2867 /* FALLTHRU */
2868 case POSTINCREMENT_EXPR:
2869 case PREINCREMENT_EXPR:
2870 /* P0002R1, Remove deprecated operator++(bool) added "other than bool"
2871 to p4. */
2872 if (TREE_CODE (type1) == BOOLEAN_TYPE && cxx_dialect >= cxx17)
2873 return;
2874 if (ARITHMETIC_TYPE_P (type1) || TYPE_PTROB_P (type1))
2876 type1 = build_reference_type (type1);
2877 break;
2879 return;
2881 /* 7 For every cv-qualified or cv-unqualified object type T, there
2882 exist candidate operator functions of the form
2884 T& operator*(T*);
2887 8 For every function type T that does not have cv-qualifiers or
2888 a ref-qualifier, there exist candidate operator functions of the form
2889 T& operator*(T*); */
2891 case INDIRECT_REF:
2892 if (TYPE_PTR_P (type1)
2893 && (TYPE_PTROB_P (type1)
2894 || TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE))
2895 break;
2896 return;
2898 /* 9 For every type T, there exist candidate operator functions of the form
2899 T* operator+(T*);
2901 10 For every floating-point or promoted integral type T, there exist
2902 candidate operator functions of the form
2903 T operator+(T);
2904 T operator-(T); */
2906 case UNARY_PLUS_EXPR: /* unary + */
2907 if (TYPE_PTR_P (type1))
2908 break;
2909 /* FALLTHRU */
2910 case NEGATE_EXPR:
2911 if (ARITHMETIC_TYPE_P (type1))
2912 break;
2913 return;
2915 /* 11 For every promoted integral type T, there exist candidate operator
2916 functions of the form
2917 T operator~(T); */
2919 case BIT_NOT_EXPR:
2920 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1))
2921 break;
2922 return;
2924 /* 12 For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, C1
2925 is the same type as C2 or is a derived class of C2, and T is an object
2926 type or a function type there exist candidate operator functions of the
2927 form
2928 CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
2929 where CV12 is the union of CV1 and CV2. */
2931 case MEMBER_REF:
2932 if (TYPE_PTR_P (type1) && TYPE_PTRMEM_P (type2))
2934 tree c1 = TREE_TYPE (type1);
2935 tree c2 = TYPE_PTRMEM_CLASS_TYPE (type2);
2937 if (CLASS_TYPE_P (c1) && DERIVED_FROM_P (c2, c1)
2938 && (TYPE_PTRMEMFUNC_P (type2)
2939 || is_complete (TYPE_PTRMEM_POINTED_TO_TYPE (type2))))
2940 break;
2942 return;
2944 /* 13 For every pair of types L and R, where each of L and R is a floating-point
2945 or promoted integral type, there exist candidate operator functions of the
2946 form
2947 LR operator*(L, R);
2948 LR operator/(L, R);
2949 LR operator+(L, R);
2950 LR operator-(L, R);
2951 bool operator<(L, R);
2952 bool operator>(L, R);
2953 bool operator<=(L, R);
2954 bool operator>=(L, R);
2955 bool operator==(L, R);
2956 bool operator!=(L, R);
2957 where LR is the result of the usual arithmetic conversions between
2958 types L and R.
2960 14 For every integral type T there exists a candidate operator function of
2961 the form
2963 std::strong_ordering operator<=>(T, T);
2965 15 For every pair of floating-point types L and R, there exists a candidate
2966 operator function of the form
2968 std::partial_ordering operator<=>(L, R);
2970 16 For every cv-qualified or cv-unqualified object type T there exist
2971 candidate operator functions of the form
2972 T* operator+(T*, std::ptrdiff_t);
2973 T& operator[](T*, std::ptrdiff_t);
2974 T* operator-(T*, std::ptrdiff_t);
2975 T* operator+(std::ptrdiff_t, T*);
2976 T& operator[](std::ptrdiff_t, T*);
2978 17 For every T, where T is a pointer to object type, there exist candidate
2979 operator functions of the form
2980 std::ptrdiff_t operator-(T, T);
2982 18 For every T, where T is an enumeration type or a pointer type, there
2983 exist candidate operator functions of the form
2984 bool operator<(T, T);
2985 bool operator>(T, T);
2986 bool operator<=(T, T);
2987 bool operator>=(T, T);
2988 bool operator==(T, T);
2989 bool operator!=(T, T);
2990 R operator<=>(T, T);
2992 where R is the result type specified in [expr.spaceship].
2994 19 For every T, where T is a pointer-to-member type or std::nullptr_t,
2995 there exist candidate operator functions of the form
2996 bool operator==(T, T);
2997 bool operator!=(T, T); */
2999 case MINUS_EXPR:
3000 if (TYPE_PTROB_P (type1) && TYPE_PTROB_P (type2))
3001 break;
3002 if (TYPE_PTROB_P (type1)
3003 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3005 type2 = ptrdiff_type_node;
3006 break;
3008 /* FALLTHRU */
3009 case MULT_EXPR:
3010 case TRUNC_DIV_EXPR:
3011 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3012 break;
3013 return;
3015 /* This isn't exactly what's specified above for operator<=>, but it's
3016 close enough. In particular, we don't care about the return type
3017 specified above; it doesn't participate in overload resolution and it
3018 doesn't affect the semantics of the built-in operator. */
3019 case SPACESHIP_EXPR:
3020 case EQ_EXPR:
3021 case NE_EXPR:
3022 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3023 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2)))
3024 break;
3025 if (NULLPTR_TYPE_P (type1) && NULLPTR_TYPE_P (type2))
3026 break;
3027 if (TYPE_PTRMEM_P (type1) && null_ptr_cst_p (args[1]))
3029 type2 = type1;
3030 break;
3032 if (TYPE_PTRMEM_P (type2) && null_ptr_cst_p (args[0]))
3034 type1 = type2;
3035 break;
3037 /* Fall through. */
3038 case LT_EXPR:
3039 case GT_EXPR:
3040 case LE_EXPR:
3041 case GE_EXPR:
3042 case MAX_EXPR:
3043 case MIN_EXPR:
3044 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3045 break;
3046 if (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3047 break;
3048 if (TREE_CODE (type1) == ENUMERAL_TYPE
3049 && TREE_CODE (type2) == ENUMERAL_TYPE)
3050 break;
3051 if (TYPE_PTR_P (type1)
3052 && null_ptr_cst_p (args[1]))
3054 type2 = type1;
3055 break;
3057 if (null_ptr_cst_p (args[0])
3058 && TYPE_PTR_P (type2))
3060 type1 = type2;
3061 break;
3063 return;
3065 case PLUS_EXPR:
3066 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3067 break;
3068 /* FALLTHRU */
3069 case ARRAY_REF:
3070 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && TYPE_PTROB_P (type2))
3072 type1 = ptrdiff_type_node;
3073 break;
3075 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3077 type2 = ptrdiff_type_node;
3078 break;
3080 return;
3082 /* 18For every pair of promoted integral types L and R, there exist candi-
3083 date operator functions of the form
3084 LR operator%(L, R);
3085 LR operator&(L, R);
3086 LR operator^(L, R);
3087 LR operator|(L, R);
3088 L operator<<(L, R);
3089 L operator>>(L, R);
3090 where LR is the result of the usual arithmetic conversions between
3091 types L and R. */
3093 case TRUNC_MOD_EXPR:
3094 case BIT_AND_EXPR:
3095 case BIT_IOR_EXPR:
3096 case BIT_XOR_EXPR:
3097 case LSHIFT_EXPR:
3098 case RSHIFT_EXPR:
3099 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3100 break;
3101 return;
3103 /* 19For every triple L, VQ, R), where L is an arithmetic or enumeration
3104 type, VQ is either volatile or empty, and R is a promoted arithmetic
3105 type, there exist candidate operator functions of the form
3106 VQ L& operator=(VQ L&, R);
3107 VQ L& operator*=(VQ L&, R);
3108 VQ L& operator/=(VQ L&, R);
3109 VQ L& operator+=(VQ L&, R);
3110 VQ L& operator-=(VQ L&, R);
3112 20For every pair T, VQ), where T is any type and VQ is either volatile
3113 or empty, there exist candidate operator functions of the form
3114 T*VQ& operator=(T*VQ&, T*);
3116 21For every pair T, VQ), where T is a pointer to member type and VQ is
3117 either volatile or empty, there exist candidate operator functions of
3118 the form
3119 VQ T& operator=(VQ T&, T);
3121 22For every triple T, VQ, I), where T is a cv-qualified or cv-
3122 unqualified complete object type, VQ is either volatile or empty, and
3123 I is a promoted integral type, there exist candidate operator func-
3124 tions of the form
3125 T*VQ& operator+=(T*VQ&, I);
3126 T*VQ& operator-=(T*VQ&, I);
3128 23For every triple L, VQ, R), where L is an integral or enumeration
3129 type, VQ is either volatile or empty, and R is a promoted integral
3130 type, there exist candidate operator functions of the form
3132 VQ L& operator%=(VQ L&, R);
3133 VQ L& operator<<=(VQ L&, R);
3134 VQ L& operator>>=(VQ L&, R);
3135 VQ L& operator&=(VQ L&, R);
3136 VQ L& operator^=(VQ L&, R);
3137 VQ L& operator|=(VQ L&, R); */
3139 case MODIFY_EXPR:
3140 switch (code2)
3142 case PLUS_EXPR:
3143 case MINUS_EXPR:
3144 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3146 type2 = ptrdiff_type_node;
3147 break;
3149 /* FALLTHRU */
3150 case MULT_EXPR:
3151 case TRUNC_DIV_EXPR:
3152 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3153 break;
3154 return;
3156 case TRUNC_MOD_EXPR:
3157 case BIT_AND_EXPR:
3158 case BIT_IOR_EXPR:
3159 case BIT_XOR_EXPR:
3160 case LSHIFT_EXPR:
3161 case RSHIFT_EXPR:
3162 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3163 break;
3164 return;
3166 case NOP_EXPR:
3167 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3168 break;
3169 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3170 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3171 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3172 || ((TYPE_PTRMEMFUNC_P (type1)
3173 || TYPE_PTR_P (type1))
3174 && null_ptr_cst_p (args[1])))
3176 type2 = type1;
3177 break;
3179 return;
3181 default:
3182 gcc_unreachable ();
3184 type1 = build_reference_type (type1);
3185 break;
3187 case COND_EXPR:
3188 /* [over.built]
3190 For every pair of promoted arithmetic types L and R, there
3191 exist candidate operator functions of the form
3193 LR operator?(bool, L, R);
3195 where LR is the result of the usual arithmetic conversions
3196 between types L and R.
3198 For every type T, where T is a pointer or pointer-to-member
3199 type, there exist candidate operator functions of the form T
3200 operator?(bool, T, T); */
3202 if (promoted_arithmetic_type_p (type1)
3203 && promoted_arithmetic_type_p (type2))
3204 /* That's OK. */
3205 break;
3207 /* Otherwise, the types should be pointers. */
3208 if (!TYPE_PTR_OR_PTRMEM_P (type1) || !TYPE_PTR_OR_PTRMEM_P (type2))
3209 return;
3211 /* We don't check that the two types are the same; the logic
3212 below will actually create two candidates; one in which both
3213 parameter types are TYPE1, and one in which both parameter
3214 types are TYPE2. */
3215 break;
3217 case REALPART_EXPR:
3218 case IMAGPART_EXPR:
3219 if (ARITHMETIC_TYPE_P (type1))
3220 break;
3221 return;
3223 default:
3224 gcc_unreachable ();
3227 /* Make sure we don't create builtin candidates with dependent types. */
3228 bool u1 = uses_template_parms (type1);
3229 bool u2 = type2 ? uses_template_parms (type2) : false;
3230 if (u1 || u2)
3232 /* Try to recover if one of the types is non-dependent. But if
3233 there's only one type, there's nothing we can do. */
3234 if (!type2)
3235 return;
3236 /* And we lose if both are dependent. */
3237 if (u1 && u2)
3238 return;
3239 /* Or if they have different forms. */
3240 if (TREE_CODE (type1) != TREE_CODE (type2))
3241 return;
3243 if (u1 && !u2)
3244 type1 = type2;
3245 else if (u2 && !u1)
3246 type2 = type1;
3249 /* If we're dealing with two pointer types or two enumeral types,
3250 we need candidates for both of them. */
3251 if (type2 && !same_type_p (type1, type2)
3252 && TREE_CODE (type1) == TREE_CODE (type2)
3253 && (TYPE_REF_P (type1)
3254 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3255 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3256 || TYPE_PTRMEMFUNC_P (type1)
3257 || MAYBE_CLASS_TYPE_P (type1)
3258 || TREE_CODE (type1) == ENUMERAL_TYPE))
3260 if (TYPE_PTR_OR_PTRMEM_P (type1))
3262 tree cptype = composite_pointer_type (input_location,
3263 type1, type2,
3264 error_mark_node,
3265 error_mark_node,
3266 CPO_CONVERSION,
3267 tf_none);
3268 if (cptype != error_mark_node)
3270 build_builtin_candidate
3271 (candidates, fnname, cptype, cptype, args, argtypes,
3272 flags, complain);
3273 return;
3277 build_builtin_candidate
3278 (candidates, fnname, type1, type1, args, argtypes, flags, complain);
3279 build_builtin_candidate
3280 (candidates, fnname, type2, type2, args, argtypes, flags, complain);
3281 return;
3284 build_builtin_candidate
3285 (candidates, fnname, type1, type2, args, argtypes, flags, complain);
3288 tree
3289 type_decays_to (tree type)
3291 if (TREE_CODE (type) == ARRAY_TYPE)
3292 return build_pointer_type (TREE_TYPE (type));
3293 if (TREE_CODE (type) == FUNCTION_TYPE)
3294 return build_pointer_type (type);
3295 return type;
3298 /* There are three conditions of builtin candidates:
3300 1) bool-taking candidates. These are the same regardless of the input.
3301 2) pointer-pair taking candidates. These are generated for each type
3302 one of the input types converts to.
3303 3) arithmetic candidates. According to the standard, we should generate
3304 all of these, but I'm trying not to...
3306 Here we generate a superset of the possible candidates for this particular
3307 case. That is a subset of the full set the standard defines, plus some
3308 other cases which the standard disallows. add_builtin_candidate will
3309 filter out the invalid set. */
3311 static void
3312 add_builtin_candidates (struct z_candidate **candidates, enum tree_code code,
3313 enum tree_code code2, tree fnname,
3314 vec<tree, va_gc> *argv,
3315 int flags, tsubst_flags_t complain)
3317 int ref1;
3318 int enum_p = 0;
3319 tree type, argtypes[3], t;
3320 /* TYPES[i] is the set of possible builtin-operator parameter types
3321 we will consider for the Ith argument. */
3322 vec<tree, va_gc> *types[2];
3323 unsigned ix;
3324 vec<tree, va_gc> &args = *argv;
3325 unsigned len = args.length ();
3327 for (unsigned i = 0; i < len; ++i)
3329 if (args[i])
3330 argtypes[i] = unlowered_expr_type (args[i]);
3331 else
3332 argtypes[i] = NULL_TREE;
3335 switch (code)
3337 /* 4 For every pair T, VQ), where T is an arithmetic or enumeration type,
3338 and VQ is either volatile or empty, there exist candidate operator
3339 functions of the form
3340 VQ T& operator++(VQ T&); */
3342 case POSTINCREMENT_EXPR:
3343 case PREINCREMENT_EXPR:
3344 case POSTDECREMENT_EXPR:
3345 case PREDECREMENT_EXPR:
3346 case MODIFY_EXPR:
3347 ref1 = 1;
3348 break;
3350 /* 24There also exist candidate operator functions of the form
3351 bool operator!(bool);
3352 bool operator&&(bool, bool);
3353 bool operator||(bool, bool); */
3355 case TRUTH_NOT_EXPR:
3356 build_builtin_candidate
3357 (candidates, fnname, boolean_type_node,
3358 NULL_TREE, args, argtypes, flags, complain);
3359 return;
3361 case TRUTH_ORIF_EXPR:
3362 case TRUTH_ANDIF_EXPR:
3363 build_builtin_candidate
3364 (candidates, fnname, boolean_type_node,
3365 boolean_type_node, args, argtypes, flags, complain);
3366 return;
3368 case ADDR_EXPR:
3369 case COMPOUND_EXPR:
3370 case COMPONENT_REF:
3371 case CO_AWAIT_EXPR:
3372 return;
3374 case COND_EXPR:
3375 case EQ_EXPR:
3376 case NE_EXPR:
3377 case LT_EXPR:
3378 case LE_EXPR:
3379 case GT_EXPR:
3380 case GE_EXPR:
3381 case SPACESHIP_EXPR:
3382 enum_p = 1;
3383 /* Fall through. */
3385 default:
3386 ref1 = 0;
3389 types[0] = make_tree_vector ();
3390 types[1] = make_tree_vector ();
3392 if (len == 3)
3393 len = 2;
3394 for (unsigned i = 0; i < len; ++i)
3396 if (MAYBE_CLASS_TYPE_P (argtypes[i]))
3398 tree convs;
3400 if (i == 0 && code == MODIFY_EXPR && code2 == NOP_EXPR)
3401 return;
3403 convs = lookup_conversions (argtypes[i]);
3405 if (code == COND_EXPR)
3407 if (lvalue_p (args[i]))
3408 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3410 vec_safe_push (types[i], TYPE_MAIN_VARIANT (argtypes[i]));
3413 else if (! convs)
3414 return;
3416 for (; convs; convs = TREE_CHAIN (convs))
3418 type = TREE_TYPE (convs);
3420 if (i == 0 && ref1
3421 && (!TYPE_REF_P (type)
3422 || CP_TYPE_CONST_P (TREE_TYPE (type))))
3423 continue;
3425 if (code == COND_EXPR && TYPE_REF_P (type))
3426 vec_safe_push (types[i], type);
3428 type = non_reference (type);
3429 if (i != 0 || ! ref1)
3431 type = cv_unqualified (type_decays_to (type));
3432 if (enum_p && TREE_CODE (type) == ENUMERAL_TYPE)
3433 vec_safe_push (types[i], type);
3434 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3435 type = type_promotes_to (type);
3438 if (! vec_member (type, types[i]))
3439 vec_safe_push (types[i], type);
3442 else
3444 if (code == COND_EXPR && lvalue_p (args[i]))
3445 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3446 type = non_reference (argtypes[i]);
3447 if (i != 0 || ! ref1)
3449 type = cv_unqualified (type_decays_to (type));
3450 if (enum_p && UNSCOPED_ENUM_P (type))
3451 vec_safe_push (types[i], type);
3452 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3453 type = type_promotes_to (type);
3455 vec_safe_push (types[i], type);
3459 /* Run through the possible parameter types of both arguments,
3460 creating candidates with those parameter types. */
3461 FOR_EACH_VEC_ELT_REVERSE (*(types[0]), ix, t)
3463 unsigned jx;
3464 tree u;
3466 if (!types[1]->is_empty ())
3467 FOR_EACH_VEC_ELT_REVERSE (*(types[1]), jx, u)
3468 add_builtin_candidate
3469 (candidates, code, code2, fnname, t,
3470 u, args, argtypes, flags, complain);
3471 else
3472 add_builtin_candidate
3473 (candidates, code, code2, fnname, t,
3474 NULL_TREE, args, argtypes, flags, complain);
3477 release_tree_vector (types[0]);
3478 release_tree_vector (types[1]);
3482 /* If TMPL can be successfully instantiated as indicated by
3483 EXPLICIT_TARGS and ARGLIST, adds the instantiation to CANDIDATES.
3485 TMPL is the template. EXPLICIT_TARGS are any explicit template
3486 arguments. ARGLIST is the arguments provided at the call-site.
3487 This does not change ARGLIST. The RETURN_TYPE is the desired type
3488 for conversion operators. If OBJ is NULL_TREE, FLAGS and CTYPE are
3489 as for add_function_candidate. If an OBJ is supplied, FLAGS and
3490 CTYPE are ignored, and OBJ is as for add_conv_candidate.
3492 SHORTCUT_BAD_CONVS is as in add_function_candidate. */
3494 static struct z_candidate*
3495 add_template_candidate_real (struct z_candidate **candidates, tree tmpl,
3496 tree ctype, tree explicit_targs, tree first_arg,
3497 const vec<tree, va_gc> *arglist, tree return_type,
3498 tree access_path, tree conversion_path,
3499 int flags, tree obj, unification_kind_t strict,
3500 bool shortcut_bad_convs, tsubst_flags_t complain)
3502 int ntparms = DECL_NTPARMS (tmpl);
3503 tree targs = make_tree_vec (ntparms);
3504 unsigned int len = vec_safe_length (arglist);
3505 unsigned int nargs = (first_arg == NULL_TREE ? 0 : 1) + len;
3506 unsigned int skip_without_in_chrg = 0;
3507 tree first_arg_without_in_chrg = first_arg;
3508 tree *args_without_in_chrg;
3509 unsigned int nargs_without_in_chrg;
3510 unsigned int ia, ix;
3511 tree arg;
3512 struct z_candidate *cand;
3513 tree fn;
3514 struct rejection_reason *reason = NULL;
3515 int errs;
3516 conversion **convs = NULL;
3518 /* We don't do deduction on the in-charge parameter, the VTT
3519 parameter or 'this'. */
3520 if (DECL_IOBJ_MEMBER_FUNCTION_P (tmpl))
3522 if (first_arg_without_in_chrg != NULL_TREE)
3523 first_arg_without_in_chrg = NULL_TREE;
3524 else if (return_type && strict == DEDUCE_CALL)
3525 /* We're deducing for a call to the result of a template conversion
3526 function, so the args don't contain 'this'; leave them alone. */;
3527 else
3528 ++skip_without_in_chrg;
3531 if ((DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (tmpl)
3532 || DECL_BASE_CONSTRUCTOR_P (tmpl))
3533 && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (tmpl)))
3535 if (first_arg_without_in_chrg != NULL_TREE)
3536 first_arg_without_in_chrg = NULL_TREE;
3537 else
3538 ++skip_without_in_chrg;
3541 if (len < skip_without_in_chrg)
3542 return add_ignored_candidate (candidates, tmpl);
3544 if (DECL_CONSTRUCTOR_P (tmpl) && nargs == 2
3545 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (first_arg),
3546 TREE_TYPE ((*arglist)[0])))
3548 /* 12.8/6 says, "A declaration of a constructor for a class X is
3549 ill-formed if its first parameter is of type (optionally cv-qualified)
3550 X and either there are no other parameters or else all other
3551 parameters have default arguments. A member function template is never
3552 instantiated to produce such a constructor signature."
3554 So if we're trying to copy an object of the containing class, don't
3555 consider a template constructor that has a first parameter type that
3556 is just a template parameter, as we would deduce a signature that we
3557 would then reject in the code below. */
3558 if (tree firstparm = FUNCTION_FIRST_USER_PARMTYPE (tmpl))
3560 firstparm = TREE_VALUE (firstparm);
3561 if (PACK_EXPANSION_P (firstparm))
3562 firstparm = PACK_EXPANSION_PATTERN (firstparm);
3563 if (TREE_CODE (firstparm) == TEMPLATE_TYPE_PARM)
3565 gcc_assert (!explicit_targs);
3566 reason = invalid_copy_with_fn_template_rejection ();
3567 goto fail;
3572 nargs_without_in_chrg = ((first_arg_without_in_chrg != NULL_TREE ? 1 : 0)
3573 + (len - skip_without_in_chrg));
3574 args_without_in_chrg = XALLOCAVEC (tree, nargs_without_in_chrg);
3575 ia = 0;
3576 if (first_arg_without_in_chrg != NULL_TREE)
3578 args_without_in_chrg[ia] = first_arg_without_in_chrg;
3579 ++ia;
3581 for (ix = skip_without_in_chrg;
3582 vec_safe_iterate (arglist, ix, &arg);
3583 ++ix)
3585 args_without_in_chrg[ia] = arg;
3586 ++ia;
3588 gcc_assert (ia == nargs_without_in_chrg);
3590 if (!obj)
3592 /* Check that there's no obvious arity mismatch before proceeding with
3593 deduction. This avoids substituting explicit template arguments
3594 into the template or e.g. derived-to-base parm/arg unification
3595 (which could result in an error outside the immediate context) when
3596 the resulting candidate would be unviable anyway. */
3597 int min_arity = 0, max_arity = 0;
3598 tree parms = TYPE_ARG_TYPES (TREE_TYPE (tmpl));
3599 parms = skip_artificial_parms_for (tmpl, parms);
3600 for (; parms != void_list_node; parms = TREE_CHAIN (parms))
3602 if (!parms || PACK_EXPANSION_P (TREE_VALUE (parms)))
3604 max_arity = -1;
3605 break;
3607 if (TREE_PURPOSE (parms))
3608 /* A parameter with a default argument. */
3609 ++max_arity;
3610 else
3611 ++min_arity, ++max_arity;
3613 if (ia < (unsigned)min_arity)
3615 /* Too few arguments. */
3616 reason = arity_rejection (NULL_TREE, min_arity, ia,
3617 /*least_p=*/(max_arity == -1));
3618 goto fail;
3620 else if (max_arity != -1 && ia > (unsigned)max_arity)
3622 /* Too many arguments. */
3623 reason = arity_rejection (NULL_TREE, max_arity, ia);
3624 goto fail;
3627 convs = alloc_conversions (nargs);
3629 if (shortcut_bad_convs
3630 && DECL_IOBJ_MEMBER_FUNCTION_P (tmpl)
3631 && !DECL_CONSTRUCTOR_P (tmpl))
3633 /* Check the 'this' conversion before proceeding with deduction.
3634 This is effectively an extension of the DR 1391 resolution
3635 that we perform in check_non_deducible_conversions, though it's
3636 convenient to do this extra check here instead of there. */
3637 tree parmtype = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (tmpl)));
3638 tree argtype = lvalue_type (first_arg);
3639 tree arg = first_arg;
3640 conversion *t = build_this_conversion (tmpl, ctype,
3641 parmtype, argtype, arg,
3642 flags, complain);
3643 convs[0] = t;
3644 if (t->bad_p)
3646 reason = bad_arg_conversion_rejection (first_arg, 0,
3647 arg, parmtype,
3648 EXPR_LOCATION (arg));
3649 goto fail;
3654 errs = errorcount+sorrycount;
3655 fn = fn_type_unification (tmpl, explicit_targs, targs,
3656 args_without_in_chrg,
3657 nargs_without_in_chrg,
3658 return_type, strict, flags, convs,
3659 false, complain & tf_decltype);
3661 if (fn == error_mark_node)
3663 /* Don't repeat unification later if it already resulted in errors. */
3664 if (errorcount+sorrycount == errs)
3665 reason = template_unification_rejection (tmpl, explicit_targs,
3666 targs, args_without_in_chrg,
3667 nargs_without_in_chrg,
3668 return_type, strict, flags);
3669 else
3670 reason = template_unification_error_rejection ();
3671 goto fail;
3674 /* Now the explicit specifier might have been deduced; check if this
3675 declaration is explicit. If it is and we're ignoring non-converting
3676 constructors, don't add this function to the set of candidates. */
3677 if (((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
3678 == LOOKUP_ONLYCONVERTING)
3679 && DECL_NONCONVERTING_P (fn))
3680 return add_ignored_candidate (candidates, fn);
3682 if (DECL_CONSTRUCTOR_P (fn) && nargs == 2)
3684 tree arg_types = FUNCTION_FIRST_USER_PARMTYPE (fn);
3685 if (arg_types && same_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (arg_types)),
3686 ctype))
3688 /* We're trying to produce a constructor with a prohibited signature,
3689 as discussed above; handle here any cases we didn't catch then,
3690 such as X(X<T>). */
3691 reason = invalid_copy_with_fn_template_rejection ();
3692 goto fail;
3696 if (obj != NULL_TREE)
3697 /* Aha, this is a conversion function. */
3698 cand = add_conv_candidate (candidates, fn, obj, arglist,
3699 access_path, conversion_path, complain);
3700 else
3701 cand = add_function_candidate (candidates, fn, ctype,
3702 first_arg, arglist, access_path,
3703 conversion_path, flags, convs,
3704 shortcut_bad_convs, complain);
3705 if (DECL_TI_TEMPLATE (fn) != tmpl)
3706 /* This situation can occur if a member template of a template
3707 class is specialized. Then, instantiate_template might return
3708 an instantiation of the specialization, in which case the
3709 DECL_TI_TEMPLATE field will point at the original
3710 specialization. For example:
3712 template <class T> struct S { template <class U> void f(U);
3713 template <> void f(int) {}; };
3714 S<double> sd;
3715 sd.f(3);
3717 Here, TMPL will be template <class U> S<double>::f(U).
3718 And, instantiate template will give us the specialization
3719 template <> S<double>::f(int). But, the DECL_TI_TEMPLATE field
3720 for this will point at template <class T> template <> S<T>::f(int),
3721 so that we can find the definition. For the purposes of
3722 overload resolution, however, we want the original TMPL. */
3723 cand->template_decl = build_template_info (tmpl, targs);
3724 else
3725 cand->template_decl = DECL_TEMPLATE_INFO (fn);
3726 cand->explicit_targs = explicit_targs;
3728 return cand;
3729 fail:
3730 int viable = (reason->code == rr_bad_arg_conversion ? -1 : 0);
3731 return add_candidate (candidates, tmpl, first_arg, arglist, nargs, convs,
3732 access_path, conversion_path, viable, reason, flags);
3736 static struct z_candidate *
3737 add_template_candidate (struct z_candidate **candidates, tree tmpl, tree ctype,
3738 tree explicit_targs, tree first_arg,
3739 const vec<tree, va_gc> *arglist, tree return_type,
3740 tree access_path, tree conversion_path, int flags,
3741 unification_kind_t strict, bool shortcut_bad_convs,
3742 tsubst_flags_t complain)
3744 return
3745 add_template_candidate_real (candidates, tmpl, ctype,
3746 explicit_targs, first_arg, arglist,
3747 return_type, access_path, conversion_path,
3748 flags, NULL_TREE, strict, shortcut_bad_convs,
3749 complain);
3752 /* Create an overload candidate for the conversion function template TMPL,
3753 returning RETURN_TYPE, which will be invoked for expression OBJ to produce a
3754 pointer-to-function which will in turn be called with the argument list
3755 ARGLIST, and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
3756 passed on to implicit_conversion. */
3758 static struct z_candidate *
3759 add_template_conv_candidate (struct z_candidate **candidates, tree tmpl,
3760 tree obj,
3761 const vec<tree, va_gc> *arglist,
3762 tree return_type, tree access_path,
3763 tree conversion_path, tsubst_flags_t complain)
3765 return
3766 add_template_candidate_real (candidates, tmpl, NULL_TREE, NULL_TREE,
3767 NULL_TREE, arglist, return_type, access_path,
3768 conversion_path, 0, obj, DEDUCE_CALL,
3769 /*shortcut_bad_convs=*/false, complain);
3772 /* The CANDS are the set of candidates that were considered for
3773 overload resolution. Sort CANDS so that the strictly viable
3774 candidates appear first, followed by non-strictly viable candidates,
3775 followed by non-viable candidates. Returns the first candidate
3776 in this sorted list. If any of the candidates were viable, set
3777 *ANY_VIABLE_P to true. STRICT_P is true if a candidate should be
3778 considered viable only if it is strictly viable when setting
3779 *ANY_VIABLE_P. */
3781 static struct z_candidate*
3782 splice_viable (struct z_candidate *cands,
3783 bool strict_p,
3784 bool *any_viable_p)
3786 z_candidate *strictly_viable = nullptr;
3787 z_candidate **strictly_viable_tail = &strictly_viable;
3789 z_candidate *non_strictly_viable = nullptr;
3790 z_candidate **non_strictly_viable_tail = &non_strictly_viable;
3792 z_candidate *non_viable = nullptr;
3793 z_candidate **non_viable_tail = &non_viable;
3795 z_candidate *non_viable_ignored = nullptr;
3796 z_candidate **non_viable_ignored_tail = &non_viable_ignored;
3798 /* Be strict inside templates, since build_over_call won't actually
3799 do the conversions to get pedwarns. */
3800 if (processing_template_decl)
3801 strict_p = true;
3803 for (z_candidate *cand = cands; cand; cand = cand->next)
3805 if (!strict_p
3806 && (cand->viable == 1 || TREE_CODE (cand->fn) == TEMPLATE_DECL))
3807 /* Be strict in the presence of a viable candidate. Also if
3808 there are template candidates, so that we get deduction errors
3809 for them instead of silently preferring a bad conversion. */
3810 strict_p = true;
3812 /* Move this candidate to the appropriate list according to
3813 its viability. */
3814 auto& tail = (cand->viable == 1 ? strictly_viable_tail
3815 : cand->viable == -1 ? non_strictly_viable_tail
3816 : ignored_candidate_p (cand) ? non_viable_ignored_tail
3817 : non_viable_tail);
3818 *tail = cand;
3819 tail = &cand->next;
3822 *any_viable_p = (strictly_viable != nullptr
3823 || (!strict_p && non_strictly_viable != nullptr));
3825 /* Combine the lists. */
3826 *non_viable_ignored_tail = nullptr;
3827 *non_viable_tail = non_viable_ignored;
3828 *non_strictly_viable_tail = non_viable;
3829 *strictly_viable_tail = non_strictly_viable;
3831 return strictly_viable;
3834 static bool
3835 any_strictly_viable (struct z_candidate *cands)
3837 for (; cands; cands = cands->next)
3838 if (cands->viable == 1)
3839 return true;
3840 return false;
3843 /* OBJ is being used in an expression like "OBJ.f (...)". In other
3844 words, it is about to become the "this" pointer for a member
3845 function call. Take the address of the object. */
3847 static tree
3848 build_this (tree obj)
3850 /* In a template, we are only concerned about the type of the
3851 expression, so we can take a shortcut. */
3852 if (processing_template_decl)
3853 return build_address (obj);
3855 return cp_build_addr_expr (obj, tf_warning_or_error);
3858 /* Returns true iff functions are equivalent. Equivalent functions are
3859 not '==' only if one is a function-local extern function or if
3860 both are extern "C". */
3862 static inline int
3863 equal_functions (tree fn1, tree fn2)
3865 if (TREE_CODE (fn1) != TREE_CODE (fn2))
3866 return 0;
3867 if (TREE_CODE (fn1) == TEMPLATE_DECL)
3868 return fn1 == fn2;
3869 if (DECL_LOCAL_DECL_P (fn1) || DECL_LOCAL_DECL_P (fn2)
3870 || DECL_EXTERN_C_FUNCTION_P (fn1))
3871 return decls_match (fn1, fn2);
3872 return fn1 == fn2;
3875 /* Print information about a candidate FN being rejected due to INFO. */
3877 static void
3878 print_conversion_rejection (location_t loc, struct conversion_info *info,
3879 tree fn)
3881 tree from = info->from;
3882 if (!TYPE_P (from))
3883 from = lvalue_type (from);
3884 if (info->n_arg == -1)
3886 /* Conversion of implicit `this' argument failed. */
3887 if (!TYPE_P (info->from))
3888 /* A bad conversion for 'this' must be discarding cv-quals. */
3889 inform (loc, " passing %qT as %<this%> "
3890 "argument discards qualifiers",
3891 from);
3892 else
3893 inform (loc, " no known conversion for implicit "
3894 "%<this%> parameter from %qH to %qI",
3895 from, info->to_type);
3897 else if (!TYPE_P (info->from))
3899 if (info->n_arg >= 0)
3900 inform (loc, " conversion of argument %d would be ill-formed:",
3901 info->n_arg + 1);
3902 iloc_sentinel ils = loc;
3903 perform_implicit_conversion (info->to_type, info->from,
3904 tf_warning_or_error);
3906 else if (info->n_arg == -2)
3907 /* Conversion of conversion function return value failed. */
3908 inform (loc, " no known conversion from %qH to %qI",
3909 from, info->to_type);
3910 else
3912 if (TREE_CODE (fn) == FUNCTION_DECL)
3913 loc = get_fndecl_argument_location (fn, info->n_arg);
3914 inform (loc, " no known conversion for argument %d from %qH to %qI",
3915 info->n_arg + 1, from, info->to_type);
3919 /* Print information about a candidate with WANT parameters and we found
3920 HAVE. */
3922 static void
3923 print_arity_information (location_t loc, unsigned int have, unsigned int want,
3924 bool least_p)
3926 if (least_p)
3927 inform_n (loc, want,
3928 " candidate expects at least %d argument, %d provided",
3929 " candidate expects at least %d arguments, %d provided",
3930 want, have);
3931 else
3932 inform_n (loc, want,
3933 " candidate expects %d argument, %d provided",
3934 " candidate expects %d arguments, %d provided",
3935 want, have);
3938 /* Print information about one overload candidate CANDIDATE. MSGSTR
3939 is the text to print before the candidate itself.
3941 NOTE: Unlike most diagnostic functions in GCC, MSGSTR is expected
3942 to have been run through gettext by the caller. This wart makes
3943 life simpler in print_z_candidates and for the translators. */
3945 static void
3946 print_z_candidate (location_t loc, const char *msgstr,
3947 struct z_candidate *candidate)
3949 const char *msg = (msgstr == NULL
3950 ? ""
3951 : ACONCAT ((_(msgstr), " ", NULL)));
3952 tree fn = candidate->fn;
3953 if (flag_new_inheriting_ctors)
3954 fn = strip_inheriting_ctors (fn);
3955 location_t cloc = location_of (fn);
3957 if (identifier_p (fn))
3959 cloc = loc;
3960 if (candidate->num_convs == 3)
3961 inform (cloc, "%s%<%D(%T, %T, %T)%> (built-in)", msg, fn,
3962 candidate->convs[0]->type,
3963 candidate->convs[1]->type,
3964 candidate->convs[2]->type);
3965 else if (candidate->num_convs == 2)
3966 inform (cloc, "%s%<%D(%T, %T)%> (built-in)", msg, fn,
3967 candidate->convs[0]->type,
3968 candidate->convs[1]->type);
3969 else
3970 inform (cloc, "%s%<%D(%T)%> (built-in)", msg, fn,
3971 candidate->convs[0]->type);
3973 else if (TYPE_P (fn))
3974 inform (cloc, "%s%qT (conversion)", msg, fn);
3975 else if (candidate->viable == -1)
3976 inform (cloc, "%s%#qD (near match)", msg, fn);
3977 else if (ignored_candidate_p (candidate))
3978 inform (cloc, "%s%#qD (ignored)", msg, fn);
3979 else if (DECL_DELETED_FN (fn))
3980 inform (cloc, "%s%#qD (deleted)", msg, fn);
3981 else if (candidate->reversed ())
3982 inform (cloc, "%s%#qD (reversed)", msg, fn);
3983 else if (candidate->rewritten ())
3984 inform (cloc, "%s%#qD (rewritten)", msg, fn);
3985 else
3986 inform (cloc, "%s%#qD", msg, fn);
3987 if (fn != candidate->fn)
3989 cloc = location_of (candidate->fn);
3990 inform (cloc, " inherited here");
3992 /* Give the user some information about why this candidate failed. */
3993 if (candidate->reason != NULL)
3995 struct rejection_reason *r = candidate->reason;
3997 switch (r->code)
3999 case rr_arity:
4000 print_arity_information (cloc, r->u.arity.actual,
4001 r->u.arity.expected,
4002 r->u.arity.least_p);
4003 break;
4004 case rr_arg_conversion:
4005 print_conversion_rejection (cloc, &r->u.conversion, fn);
4006 break;
4007 case rr_bad_arg_conversion:
4008 print_conversion_rejection (cloc, &r->u.bad_conversion, fn);
4009 break;
4010 case rr_explicit_conversion:
4011 inform (cloc, " return type %qT of explicit conversion function "
4012 "cannot be converted to %qT with a qualification "
4013 "conversion", r->u.conversion.from,
4014 r->u.conversion.to_type);
4015 break;
4016 case rr_template_conversion:
4017 inform (cloc, " conversion from return type %qT of template "
4018 "conversion function specialization to %qT is not an "
4019 "exact match", r->u.conversion.from,
4020 r->u.conversion.to_type);
4021 break;
4022 case rr_template_unification:
4023 /* We use template_unification_error_rejection if unification caused
4024 actual non-SFINAE errors, in which case we don't need to repeat
4025 them here. */
4026 if (r->u.template_unification.tmpl == NULL_TREE)
4028 inform (cloc, " substitution of deduced template arguments "
4029 "resulted in errors seen above");
4030 break;
4032 /* Re-run template unification with diagnostics. */
4033 inform (cloc, " template argument deduction/substitution failed:");
4034 fn_type_unification (r->u.template_unification.tmpl,
4035 r->u.template_unification.explicit_targs,
4036 (make_tree_vec
4037 (r->u.template_unification.num_targs)),
4038 r->u.template_unification.args,
4039 r->u.template_unification.nargs,
4040 r->u.template_unification.return_type,
4041 r->u.template_unification.strict,
4042 r->u.template_unification.flags,
4043 NULL, true, false);
4044 break;
4045 case rr_invalid_copy:
4046 inform (cloc,
4047 " a constructor taking a single argument of its own "
4048 "class type is invalid");
4049 break;
4050 case rr_constraint_failure:
4051 diagnose_constraints (cloc, fn, NULL_TREE);
4052 break;
4053 case rr_inherited_ctor:
4054 inform (cloc, " an inherited constructor is not a candidate for "
4055 "initialization from an expression of the same or derived "
4056 "type");
4057 break;
4058 case rr_ignored:
4059 break;
4060 case rr_none:
4061 default:
4062 /* This candidate didn't have any issues or we failed to
4063 handle a particular code. Either way... */
4064 gcc_unreachable ();
4069 /* Print information about each overload candidate in CANDIDATES,
4070 which is assumed to have gone through splice_viable and tourney
4071 (if splice_viable succeeded). */
4073 static void
4074 print_z_candidates (location_t loc, struct z_candidate *candidates,
4075 tristate only_viable_p /* = tristate::unknown () */)
4077 struct z_candidate *cand1;
4078 struct z_candidate **cand2;
4080 if (!candidates)
4081 return;
4083 /* Remove non-viable deleted candidates. */
4084 cand1 = candidates;
4085 for (cand2 = &cand1; *cand2; )
4087 if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
4088 && !(*cand2)->viable
4089 && DECL_DELETED_FN ((*cand2)->fn))
4090 *cand2 = (*cand2)->next;
4091 else
4092 cand2 = &(*cand2)->next;
4094 /* ...if there are any non-deleted ones. */
4095 if (cand1)
4096 candidates = cand1;
4098 /* There may be duplicates in the set of candidates. We put off
4099 checking this condition as long as possible, since we have no way
4100 to eliminate duplicates from a set of functions in less than n^2
4101 time. Now we are about to emit an error message, so it is more
4102 permissible to go slowly. */
4103 for (cand1 = candidates; cand1; cand1 = cand1->next)
4105 tree fn = cand1->fn;
4106 /* Skip builtin candidates and conversion functions. */
4107 if (!DECL_P (fn))
4108 continue;
4109 cand2 = &cand1->next;
4110 while (*cand2)
4112 if (DECL_P ((*cand2)->fn)
4113 && equal_functions (fn, (*cand2)->fn))
4114 *cand2 = (*cand2)->next;
4115 else
4116 cand2 = &(*cand2)->next;
4120 /* Unless otherwise specified, if there's a (strictly) viable candidate
4121 then we assume we're being called as part of diagnosing ambiguity, in
4122 which case we want to print only viable candidates since non-viable
4123 candidates couldn't have contributed to the ambiguity. */
4124 if (only_viable_p.is_unknown ())
4125 only_viable_p = candidates->viable == 1;
4127 for (; candidates; candidates = candidates->next)
4129 if (only_viable_p.is_true () && candidates->viable != 1)
4130 break;
4131 if (ignored_candidate_p (candidates) && !flag_diagnostics_all_candidates)
4133 inform (loc, "some candidates omitted; "
4134 "use %<-fdiagnostics-all-candidates%> to display them");
4135 break;
4137 print_z_candidate (loc, N_("candidate:"), candidates);
4141 /* USER_SEQ is a user-defined conversion sequence, beginning with a
4142 USER_CONV. STD_SEQ is the standard conversion sequence applied to
4143 the result of the conversion function to convert it to the final
4144 desired type. Merge the two sequences into a single sequence,
4145 and return the merged sequence. */
4147 static conversion *
4148 merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
4150 conversion **t;
4151 bool bad = user_seq->bad_p;
4153 gcc_assert (user_seq->kind == ck_user);
4155 /* Find the end of the second conversion sequence. */
4156 for (t = &std_seq; (*t)->kind != ck_identity; t = &((*t)->u.next))
4158 /* The entire sequence is a user-conversion sequence. */
4159 (*t)->user_conv_p = true;
4160 if (bad)
4161 (*t)->bad_p = true;
4164 if ((*t)->rvaluedness_matches_p)
4165 /* We're binding a reference directly to the result of the conversion.
4166 build_user_type_conversion_1 stripped the REFERENCE_TYPE from the return
4167 type, but we want it back. */
4168 user_seq->type = TREE_TYPE (TREE_TYPE (user_seq->cand->fn));
4170 /* Replace the identity conversion with the user conversion
4171 sequence. */
4172 *t = user_seq;
4174 return std_seq;
4177 /* Handle overload resolution for initializing an object of class type from
4178 an initializer list. First we look for a suitable constructor that
4179 takes a std::initializer_list; if we don't find one, we then look for a
4180 non-list constructor.
4182 Parameters are as for add_candidates, except that the arguments are in
4183 the form of a CONSTRUCTOR (the initializer list) rather than a vector, and
4184 the RETURN_TYPE parameter is replaced by TOTYPE, the desired type. */
4186 static void
4187 add_list_candidates (tree fns, tree first_arg,
4188 const vec<tree, va_gc> *args, tree totype,
4189 tree explicit_targs, bool template_only,
4190 tree conversion_path, tree access_path,
4191 int flags,
4192 struct z_candidate **candidates,
4193 tsubst_flags_t complain)
4195 gcc_assert (*candidates == NULL);
4197 /* We're looking for a ctor for list-initialization. */
4198 flags |= LOOKUP_LIST_INIT_CTOR;
4199 /* And we don't allow narrowing conversions. We also use this flag to
4200 avoid the copy constructor call for copy-list-initialization. */
4201 flags |= LOOKUP_NO_NARROWING;
4203 unsigned nart = num_artificial_parms_for (OVL_FIRST (fns)) - 1;
4204 tree init_list = (*args)[nart];
4206 /* Always use the default constructor if the list is empty (DR 990). */
4207 if (CONSTRUCTOR_NELTS (init_list) == 0
4208 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
4210 else if (CONSTRUCTOR_IS_DESIGNATED_INIT (init_list)
4211 && !CP_AGGREGATE_TYPE_P (totype))
4213 if (complain & tf_error)
4214 error ("designated initializers cannot be used with a "
4215 "non-aggregate type %qT", totype);
4216 return;
4218 /* If the class has a list ctor, try passing the list as a single
4219 argument first, but only consider list ctors. */
4220 else if (TYPE_HAS_LIST_CTOR (totype))
4222 flags |= LOOKUP_LIST_ONLY;
4223 add_candidates (fns, first_arg, args, NULL_TREE,
4224 explicit_targs, template_only, conversion_path,
4225 access_path, flags, candidates, complain);
4226 if (any_strictly_viable (*candidates))
4227 return;
4230 /* Expand the CONSTRUCTOR into a new argument vec. */
4231 vec<tree, va_gc> *new_args;
4232 vec_alloc (new_args, nart + CONSTRUCTOR_NELTS (init_list));
4233 for (unsigned i = 0; i < nart; ++i)
4234 new_args->quick_push ((*args)[i]);
4235 for (unsigned i = 0; i < CONSTRUCTOR_NELTS (init_list); ++i)
4236 new_args->quick_push (CONSTRUCTOR_ELT (init_list, i)->value);
4238 /* We aren't looking for list-ctors anymore. */
4239 flags &= ~LOOKUP_LIST_ONLY;
4240 /* We allow more user-defined conversions within an init-list. */
4241 flags &= ~LOOKUP_NO_CONVERSION;
4243 add_candidates (fns, first_arg, new_args, NULL_TREE,
4244 explicit_targs, template_only, conversion_path,
4245 access_path, flags, candidates, complain);
4248 /* Given C(std::initializer_list<A>), return A. */
4250 static tree
4251 list_ctor_element_type (tree fn)
4253 gcc_checking_assert (is_list_ctor (fn));
4255 tree parm = FUNCTION_FIRST_USER_PARMTYPE (fn);
4256 parm = non_reference (TREE_VALUE (parm));
4257 return TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
4260 /* If EXPR is a braced-init-list where the elements all decay to the same type,
4261 return that type. */
4263 static tree
4264 braced_init_element_type (tree expr)
4266 if (TREE_CODE (expr) == CONSTRUCTOR
4267 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
4268 return TREE_TYPE (TREE_TYPE (expr));
4269 if (!BRACE_ENCLOSED_INITIALIZER_P (expr))
4270 return NULL_TREE;
4272 tree elttype = NULL_TREE;
4273 for (constructor_elt &e: CONSTRUCTOR_ELTS (expr))
4275 tree type = TREE_TYPE (e.value);
4276 type = type_decays_to (type);
4277 if (!elttype)
4278 elttype = type;
4279 else if (!same_type_p (type, elttype))
4280 return NULL_TREE;
4282 return elttype;
4285 /* True iff EXPR contains any temporaries with non-trivial destruction.
4287 ??? Also ignore classes with non-trivial but no-op destruction other than
4288 std::allocator? */
4290 static bool
4291 has_non_trivial_temporaries (tree expr)
4293 auto_vec<tree*> temps;
4294 cp_walk_tree_without_duplicates (&expr, find_temps_r, &temps);
4295 for (tree *p : temps)
4297 tree t = TREE_TYPE (*p);
4298 if (!TYPE_HAS_TRIVIAL_DESTRUCTOR (t)
4299 && !is_std_allocator (t))
4300 return true;
4302 return false;
4305 /* We're initializing an array of ELTTYPE from INIT. If it seems useful,
4306 return INIT as an array (of its own type) so the caller can initialize the
4307 target array in a loop. */
4309 static tree
4310 maybe_init_list_as_array (tree elttype, tree init)
4312 /* Only do this if the array can go in rodata but not once converted. */
4313 if (!TYPE_NON_AGGREGATE_CLASS (elttype))
4314 return NULL_TREE;
4315 tree init_elttype = braced_init_element_type (init);
4316 if (!init_elttype || !SCALAR_TYPE_P (init_elttype) || !TREE_CONSTANT (init))
4317 return NULL_TREE;
4319 /* Check with a stub expression to weed out special cases, and check whether
4320 we call the same function for direct-init as copy-list-init. */
4321 conversion_obstack_sentinel cos;
4322 init_elttype = cp_build_qualified_type (init_elttype, TYPE_QUAL_CONST);
4323 tree arg = build_stub_object (init_elttype);
4324 conversion *c = implicit_conversion (elttype, init_elttype, arg, false,
4325 LOOKUP_NORMAL, tf_none);
4326 if (c && c->kind == ck_rvalue)
4327 c = next_conversion (c);
4328 if (!c || c->kind != ck_user)
4329 return NULL_TREE;
4330 /* Check that we actually can perform the conversion. */
4331 if (convert_like (c, arg, tf_none) == error_mark_node)
4332 /* Let the normal code give the error. */
4333 return NULL_TREE;
4335 tree first = CONSTRUCTOR_ELT (init, 0)->value;
4336 conversion *fc = implicit_conversion (elttype, init_elttype, first, false,
4337 LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING,
4338 tf_none);
4339 if (fc && fc->kind == ck_rvalue)
4340 fc = next_conversion (fc);
4341 if (!fc || fc->kind != ck_user || fc->cand->fn != c->cand->fn)
4342 return NULL_TREE;
4343 first = convert_like (fc, first, tf_none);
4344 if (first == error_mark_node)
4345 /* Let the normal code give the error. */
4346 return NULL_TREE;
4348 /* Don't do this if the conversion would be constant. */
4349 first = maybe_constant_init (first);
4350 if (TREE_CONSTANT (first))
4351 return NULL_TREE;
4353 /* We can't do this if the conversion creates temporaries that need
4354 to live until the whole array is initialized. */
4355 if (has_non_trivial_temporaries (first))
4356 return NULL_TREE;
4358 /* We can't do this if copying from the initializer_list would be
4359 ill-formed. */
4360 tree copy_argtypes = make_tree_vec (1);
4361 TREE_VEC_ELT (copy_argtypes, 0)
4362 = cp_build_qualified_type (elttype, TYPE_QUAL_CONST);
4363 if (!is_xible (INIT_EXPR, elttype, copy_argtypes))
4364 return NULL_TREE;
4366 tree arr = build_array_of_n_type (init_elttype, CONSTRUCTOR_NELTS (init));
4367 arr = finish_compound_literal (arr, init, tf_none);
4368 DECL_MERGEABLE (TARGET_EXPR_SLOT (arr)) = true;
4369 return arr;
4372 /* If we were going to call e.g. vector(initializer_list<string>) starting
4373 with a list of string-literals (which is inefficient, see PR105838),
4374 instead build an array of const char* and pass it to the range constructor.
4375 But only do this for standard library types, where we can assume the
4376 transformation makes sense.
4378 Really the container classes should have initializer_list<U> constructors to
4379 get the same effect more simply; this is working around that lack. */
4381 static tree
4382 maybe_init_list_as_range (tree fn, tree expr)
4384 if (!processing_template_decl
4385 && BRACE_ENCLOSED_INITIALIZER_P (expr)
4386 && is_list_ctor (fn)
4387 && decl_in_std_namespace_p (fn))
4389 tree to = list_ctor_element_type (fn);
4390 if (tree init = maybe_init_list_as_array (to, expr))
4392 tree begin = decay_conversion (TARGET_EXPR_SLOT (init), tf_none);
4393 tree nelts = array_type_nelts_top (TREE_TYPE (init));
4394 tree end = cp_build_binary_op (input_location, PLUS_EXPR, begin,
4395 nelts, tf_none);
4396 begin = cp_build_compound_expr (init, begin, tf_none);
4397 return build_constructor_va (init_list_type_node, 2,
4398 NULL_TREE, begin, NULL_TREE, end);
4402 return NULL_TREE;
4405 /* Returns the best overload candidate to perform the requested
4406 conversion. This function is used for three the overloading situations
4407 described in [over.match.copy], [over.match.conv], and [over.match.ref].
4408 If TOTYPE is a REFERENCE_TYPE, we're trying to find a direct binding as
4409 per [dcl.init.ref], so we ignore temporary bindings. */
4411 static struct z_candidate *
4412 build_user_type_conversion_1 (tree totype, tree expr, int flags,
4413 tsubst_flags_t complain)
4415 struct z_candidate *candidates, *cand;
4416 tree fromtype;
4417 tree ctors = NULL_TREE;
4418 tree conv_fns = NULL_TREE;
4419 conversion *conv = NULL;
4420 tree first_arg = NULL_TREE;
4421 vec<tree, va_gc> *args = NULL;
4422 bool any_viable_p;
4423 int convflags;
4425 if (!expr)
4426 return NULL;
4428 fromtype = TREE_TYPE (expr);
4430 /* We represent conversion within a hierarchy using RVALUE_CONV and
4431 BASE_CONV, as specified by [over.best.ics]; these become plain
4432 constructor calls, as specified in [dcl.init]. */
4433 gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
4434 || !DERIVED_FROM_P (totype, fromtype));
4436 if (CLASS_TYPE_P (totype))
4437 /* Use lookup_fnfields_slot instead of lookup_fnfields to avoid
4438 creating a garbage BASELINK; constructors can't be inherited. */
4439 ctors = get_class_binding (totype, complete_ctor_identifier);
4441 tree to_nonref = non_reference (totype);
4442 if (MAYBE_CLASS_TYPE_P (fromtype))
4444 if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
4445 (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
4446 && DERIVED_FROM_P (to_nonref, fromtype)))
4448 /* [class.conv.fct] A conversion function is never used to
4449 convert a (possibly cv-qualified) object to the (possibly
4450 cv-qualified) same object type (or a reference to it), to a
4451 (possibly cv-qualified) base class of that type (or a
4452 reference to it)... */
4454 else
4455 conv_fns = lookup_conversions (fromtype);
4458 candidates = 0;
4459 flags |= LOOKUP_NO_CONVERSION;
4460 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4461 flags |= LOOKUP_NO_NARROWING;
4462 /* Prevent add_candidates from treating a non-strictly viable candidate
4463 as unviable. */
4464 complain |= tf_conv;
4466 /* It's OK to bind a temporary for converting constructor arguments, but
4467 not in converting the return value of a conversion operator. */
4468 convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION
4469 | (flags & LOOKUP_NO_NARROWING));
4470 flags &= ~LOOKUP_NO_TEMP_BIND;
4472 if (ctors)
4474 int ctorflags = flags;
4476 first_arg = build_dummy_object (totype);
4478 /* We should never try to call the abstract or base constructor
4479 from here. */
4480 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_FIRST (ctors))
4481 && !DECL_HAS_VTT_PARM_P (OVL_FIRST (ctors)));
4483 args = make_tree_vector_single (expr);
4484 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4486 /* List-initialization. */
4487 add_list_candidates (ctors, first_arg, args, totype, NULL_TREE,
4488 false, TYPE_BINFO (totype), TYPE_BINFO (totype),
4489 ctorflags, &candidates, complain);
4491 else
4493 add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
4494 TYPE_BINFO (totype), TYPE_BINFO (totype),
4495 ctorflags, &candidates, complain);
4498 for (cand = candidates; cand; cand = cand->next)
4500 cand->second_conv = build_identity_conv (totype, NULL_TREE);
4502 /* If totype isn't a reference, and LOOKUP_ONLYCONVERTING is
4503 set, then this is copy-initialization. In that case, "The
4504 result of the call is then used to direct-initialize the
4505 object that is the destination of the copy-initialization."
4506 [dcl.init]
4508 We represent this in the conversion sequence with an
4509 rvalue conversion, which means a constructor call. */
4510 if (!TYPE_REF_P (totype)
4511 && cxx_dialect < cxx17
4512 && (flags & LOOKUP_ONLYCONVERTING)
4513 && !(convflags & LOOKUP_NO_TEMP_BIND))
4514 cand->second_conv
4515 = build_conv (ck_rvalue, totype, cand->second_conv);
4519 if (conv_fns)
4521 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4522 first_arg = CONSTRUCTOR_ELT (expr, 0)->value;
4523 else
4524 first_arg = expr;
4527 for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
4529 tree conversion_path = TREE_PURPOSE (conv_fns);
4530 struct z_candidate *old_candidates;
4532 /* If LOOKUP_NO_CONVERSION, don't consider a conversion function that
4533 would need an addional user-defined conversion, i.e. if the return
4534 type differs in class-ness from the desired type. So we avoid
4535 considering operator bool when calling a copy constructor.
4537 This optimization avoids the failure in PR97600, and is allowed by
4538 [temp.inst]/9: "If the function selected by overload resolution can be
4539 determined without instantiating a class template definition, it is
4540 unspecified whether that instantiation actually takes place." */
4541 tree convtype = non_reference (TREE_TYPE (conv_fns));
4542 if ((flags & LOOKUP_NO_CONVERSION)
4543 && !WILDCARD_TYPE_P (convtype)
4544 && (CLASS_TYPE_P (to_nonref)
4545 != CLASS_TYPE_P (convtype)))
4546 continue;
4548 /* If we are called to convert to a reference type, we are trying to
4549 find a direct binding, so don't even consider temporaries. If
4550 we don't find a direct binding, the caller will try again to
4551 look for a temporary binding. */
4552 if (TYPE_REF_P (totype))
4553 convflags |= LOOKUP_NO_TEMP_BIND;
4555 old_candidates = candidates;
4556 add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
4557 NULL_TREE, false,
4558 conversion_path, TYPE_BINFO (fromtype),
4559 flags, &candidates, complain);
4561 for (cand = candidates; cand != old_candidates; cand = cand->next)
4563 if (cand->viable == 0)
4564 /* Already rejected, don't change to -1. */
4565 continue;
4567 tree rettype = TREE_TYPE (TREE_TYPE (cand->fn));
4568 conversion *ics
4569 = implicit_conversion (totype,
4570 rettype,
4572 /*c_cast_p=*/false, convflags,
4573 complain);
4575 /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
4576 copy-initialization. In that case, "The result of the
4577 call is then used to direct-initialize the object that is
4578 the destination of the copy-initialization." [dcl.init]
4580 We represent this in the conversion sequence with an
4581 rvalue conversion, which means a constructor call. But
4582 don't add a second rvalue conversion if there's already
4583 one there. Which there really shouldn't be, but it's
4584 harmless since we'd add it here anyway. */
4585 if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
4586 && !(convflags & LOOKUP_NO_TEMP_BIND))
4587 ics = build_conv (ck_rvalue, totype, ics);
4589 cand->second_conv = ics;
4591 if (!ics)
4593 cand->viable = 0;
4594 cand->reason = arg_conversion_rejection (NULL_TREE, -2,
4595 rettype, totype,
4596 EXPR_LOCATION (expr));
4598 else if (TYPE_REF_P (totype) && !ics->rvaluedness_matches_p
4599 /* Limit this to non-templates for now (PR90546). */
4600 && !cand->template_decl
4601 && TREE_CODE (TREE_TYPE (totype)) != FUNCTION_TYPE)
4603 /* If we are called to convert to a reference type, we are trying
4604 to find a direct binding per [over.match.ref], so rvaluedness
4605 must match for non-functions. */
4606 cand->viable = 0;
4608 else if (DECL_NONCONVERTING_P (cand->fn)
4609 && ics->rank > cr_exact)
4611 /* 13.3.1.5: For direct-initialization, those explicit
4612 conversion functions that are not hidden within S and
4613 yield type T or a type that can be converted to type T
4614 with a qualification conversion (4.4) are also candidate
4615 functions. */
4616 /* 13.3.1.6 doesn't have a parallel restriction, but it should;
4617 I've raised this issue with the committee. --jason 9/2011 */
4618 cand->viable = -1;
4619 cand->reason = explicit_conversion_rejection (rettype, totype);
4621 else if (cand->viable == 1 && ics->bad_p)
4623 cand->viable = -1;
4624 cand->reason
4625 = bad_arg_conversion_rejection (NULL_TREE, -2,
4626 rettype, totype,
4627 EXPR_LOCATION (expr));
4629 else if (primary_template_specialization_p (cand->fn)
4630 && ics->rank > cr_exact)
4632 /* 13.3.3.1.2: If the user-defined conversion is specified by
4633 a specialization of a conversion function template, the
4634 second standard conversion sequence shall have exact match
4635 rank. */
4636 cand->viable = -1;
4637 cand->reason = template_conversion_rejection (rettype, totype);
4642 candidates = splice_viable (candidates, false, &any_viable_p);
4643 if (!any_viable_p)
4645 if (args)
4646 release_tree_vector (args);
4647 return NULL;
4650 cand = tourney (candidates, complain);
4651 if (cand == NULL)
4653 if (complain & tf_error)
4655 auto_diagnostic_group d;
4656 error_at (cp_expr_loc_or_input_loc (expr),
4657 "conversion from %qH to %qI is ambiguous",
4658 fromtype, totype);
4659 print_z_candidates (location_of (expr), candidates);
4662 cand = candidates; /* any one will do */
4663 cand->second_conv = build_ambiguous_conv (totype, expr);
4664 cand->second_conv->user_conv_p = true;
4665 if (!any_strictly_viable (candidates))
4666 cand->second_conv->bad_p = true;
4667 if (flags & LOOKUP_ONLYCONVERTING)
4668 cand->second_conv->need_temporary_p = true;
4669 /* If there are viable candidates, don't set ICS_BAD_FLAG; an
4670 ambiguous conversion is no worse than another user-defined
4671 conversion. */
4673 return cand;
4676 /* Maybe pass { } as iterators instead of an initializer_list. */
4677 if (tree iters = maybe_init_list_as_range (cand->fn, expr))
4678 if (z_candidate *cand2
4679 = build_user_type_conversion_1 (totype, iters, flags, tf_none))
4680 if (cand2->viable == 1 && !is_list_ctor (cand2->fn))
4682 cand = cand2;
4683 expr = iters;
4686 tree convtype;
4687 if (!DECL_CONSTRUCTOR_P (cand->fn))
4688 convtype = non_reference (TREE_TYPE (TREE_TYPE (cand->fn)));
4689 else if (cand->second_conv->kind == ck_rvalue)
4690 /* DR 5: [in the first step of copy-initialization]...if the function
4691 is a constructor, the call initializes a temporary of the
4692 cv-unqualified version of the destination type. */
4693 convtype = cv_unqualified (totype);
4694 else
4695 convtype = totype;
4696 /* Build the user conversion sequence. */
4697 conv = build_conv
4698 (ck_user,
4699 convtype,
4700 build_identity_conv (TREE_TYPE (expr), expr));
4701 conv->cand = cand;
4702 if (cand->viable == -1)
4703 conv->bad_p = true;
4705 /* Remember that this was a list-initialization. */
4706 if (flags & LOOKUP_NO_NARROWING)
4707 conv->check_narrowing = true;
4709 /* Combine it with the second conversion sequence. */
4710 cand->second_conv = merge_conversion_sequences (conv,
4711 cand->second_conv);
4713 return cand;
4716 /* Wrapper for above. */
4718 tree
4719 build_user_type_conversion (tree totype, tree expr, int flags,
4720 tsubst_flags_t complain)
4722 struct z_candidate *cand;
4723 tree ret;
4725 auto_cond_timevar tv (TV_OVERLOAD);
4727 conversion_obstack_sentinel cos;
4729 cand = build_user_type_conversion_1 (totype, expr, flags, complain);
4731 if (cand)
4733 if (cand->second_conv->kind == ck_ambig)
4734 ret = error_mark_node;
4735 else
4737 expr = convert_like (cand->second_conv, expr, complain);
4738 ret = convert_from_reference (expr);
4741 else
4742 ret = NULL_TREE;
4744 return ret;
4747 /* Give a helpful diagnostic when implicit_conversion fails. */
4749 static void
4750 implicit_conversion_error (location_t loc, tree type, tree expr)
4752 tsubst_flags_t complain = tf_warning_or_error;
4754 /* If expr has unknown type, then it is an overloaded function.
4755 Call instantiate_type to get good error messages. */
4756 if (TREE_TYPE (expr) == unknown_type_node)
4757 instantiate_type (type, expr, complain);
4758 else if (invalid_nonstatic_memfn_p (loc, expr, complain))
4759 /* We gave an error. */;
4760 else if (BRACE_ENCLOSED_INITIALIZER_P (expr)
4761 && CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
4762 && !CP_AGGREGATE_TYPE_P (type))
4763 error_at (loc, "designated initializers cannot be used with a "
4764 "non-aggregate type %qT", type);
4765 else
4767 range_label_for_type_mismatch label (TREE_TYPE (expr), type);
4768 gcc_rich_location rich_loc (loc, &label,
4769 highlight_colors::percent_h);
4770 error_at (&rich_loc, "could not convert %qE from %qH to %qI",
4771 expr, TREE_TYPE (expr), type);
4775 /* Worker for build_converted_constant_expr. */
4777 static tree
4778 build_converted_constant_expr_internal (tree type, tree expr,
4779 int flags, tsubst_flags_t complain)
4781 conversion *conv;
4782 tree t;
4783 location_t loc = cp_expr_loc_or_input_loc (expr);
4785 if (error_operand_p (expr))
4786 return error_mark_node;
4788 conversion_obstack_sentinel cos;
4790 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
4791 /*c_cast_p=*/false, flags, complain);
4793 /* A converted constant expression of type T is an expression, implicitly
4794 converted to type T, where the converted expression is a constant
4795 expression and the implicit conversion sequence contains only
4797 * user-defined conversions,
4798 * lvalue-to-rvalue conversions (7.1),
4799 * array-to-pointer conversions (7.2),
4800 * function-to-pointer conversions (7.3),
4801 * qualification conversions (7.5),
4802 * integral promotions (7.6),
4803 * integral conversions (7.8) other than narrowing conversions (11.6.4),
4804 * null pointer conversions (7.11) from std::nullptr_t,
4805 * null member pointer conversions (7.12) from std::nullptr_t, and
4806 * function pointer conversions (7.13),
4808 and where the reference binding (if any) binds directly. */
4810 for (conversion *c = conv;
4811 c && c->kind != ck_identity;
4812 c = next_conversion (c))
4814 switch (c->kind)
4816 /* A conversion function is OK. If it isn't constexpr, we'll
4817 complain later that the argument isn't constant. */
4818 case ck_user:
4819 /* List-initialization is OK. */
4820 case ck_aggr:
4821 /* The lvalue-to-rvalue conversion is OK. */
4822 case ck_rvalue:
4823 /* Array-to-pointer and function-to-pointer. */
4824 case ck_lvalue:
4825 /* Function pointer conversions. */
4826 case ck_fnptr:
4827 /* Qualification conversions. */
4828 case ck_qual:
4829 break;
4831 case ck_ref_bind:
4832 if (c->need_temporary_p)
4834 if (complain & tf_error)
4835 error_at (loc, "initializing %qH with %qI in converted "
4836 "constant expression does not bind directly",
4837 type, next_conversion (c)->type);
4838 conv = NULL;
4840 break;
4842 case ck_base:
4843 case ck_pmem:
4844 case ck_ptr:
4845 case ck_std:
4846 t = next_conversion (c)->type;
4847 if (INTEGRAL_OR_ENUMERATION_TYPE_P (t)
4848 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4849 /* Integral promotion or conversion. */
4850 break;
4851 if (NULLPTR_TYPE_P (t))
4852 /* Conversion from nullptr to pointer or pointer-to-member. */
4853 break;
4855 if (complain & tf_error)
4856 error_at (loc, "conversion from %qH to %qI in a "
4857 "converted constant expression", t, type);
4858 /* fall through. */
4860 default:
4861 conv = NULL;
4862 break;
4866 /* Avoid confusing convert_nontype_argument by introducing
4867 a redundant conversion to the same reference type. */
4868 if (conv && conv->kind == ck_ref_bind
4869 && REFERENCE_REF_P (expr))
4871 tree ref = TREE_OPERAND (expr, 0);
4872 if (same_type_p (type, TREE_TYPE (ref)))
4873 return ref;
4876 if (conv)
4878 /* Don't copy a class in a template. */
4879 if (CLASS_TYPE_P (type) && conv->kind == ck_rvalue
4880 && processing_template_decl)
4881 conv = next_conversion (conv);
4883 /* Issuing conversion warnings for value-dependent expressions is
4884 likely too noisy. */
4885 warning_sentinel w (warn_conversion);
4886 conv->check_narrowing = true;
4887 conv->check_narrowing_const_only = true;
4888 expr = convert_like (conv, expr, complain);
4890 else
4892 if (complain & tf_error)
4893 implicit_conversion_error (loc, type, expr);
4894 expr = error_mark_node;
4897 return expr;
4900 /* Subroutine of convert_nontype_argument.
4902 EXPR is an expression used in a context that requires a converted
4903 constant-expression, such as a template non-type parameter. Do any
4904 necessary conversions (that are permitted for converted
4905 constant-expressions) to convert it to the desired type.
4907 This function doesn't consider explicit conversion functions. If
4908 you mean to use "a contextually converted constant expression of type
4909 bool", use build_converted_constant_bool_expr.
4911 If conversion is successful, returns the converted expression;
4912 otherwise, returns error_mark_node. */
4914 tree
4915 build_converted_constant_expr (tree type, tree expr, tsubst_flags_t complain)
4917 return build_converted_constant_expr_internal (type, expr, LOOKUP_IMPLICIT,
4918 complain);
4921 /* Used to create "a contextually converted constant expression of type
4922 bool". This differs from build_converted_constant_expr in that it
4923 also considers explicit conversion functions. */
4925 tree
4926 build_converted_constant_bool_expr (tree expr, tsubst_flags_t complain)
4928 return build_converted_constant_expr_internal (boolean_type_node, expr,
4929 LOOKUP_NORMAL, complain);
4932 /* Do any initial processing on the arguments to a function call. */
4934 vec<tree, va_gc> *
4935 resolve_args (vec<tree, va_gc> *args, tsubst_flags_t complain)
4937 unsigned int ix;
4938 tree arg;
4940 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
4942 if (error_operand_p (arg))
4943 return NULL;
4944 else if (VOID_TYPE_P (TREE_TYPE (arg)))
4946 if (complain & tf_error)
4947 error_at (cp_expr_loc_or_input_loc (arg),
4948 "invalid use of void expression");
4949 return NULL;
4951 else if (invalid_nonstatic_memfn_p (EXPR_LOCATION (arg), arg, complain))
4952 return NULL;
4954 /* Force auto deduction now. Omit tf_warning to avoid redundant
4955 deprecated warning on deprecated-14.C. */
4956 if (!mark_single_function (arg, complain & ~tf_warning))
4957 return NULL;
4959 return args;
4962 /* Perform overload resolution on FN, which is called with the ARGS.
4964 Return the candidate function selected by overload resolution, or
4965 NULL if the event that overload resolution failed. In the case
4966 that overload resolution fails, *CANDIDATES will be the set of
4967 candidates considered, and ANY_VIABLE_P will be set to true or
4968 false to indicate whether or not any of the candidates were
4969 viable.
4971 The ARGS should already have gone through RESOLVE_ARGS before this
4972 function is called. */
4974 static struct z_candidate *
4975 perform_overload_resolution (tree fn,
4976 const vec<tree, va_gc> *args,
4977 struct z_candidate **candidates,
4978 bool *any_viable_p, tsubst_flags_t complain)
4980 struct z_candidate *cand;
4981 tree explicit_targs;
4982 int template_only;
4984 auto_cond_timevar tv (TV_OVERLOAD);
4986 explicit_targs = NULL_TREE;
4987 template_only = 0;
4989 *candidates = NULL;
4990 *any_viable_p = true;
4992 /* Check FN. */
4993 gcc_assert (OVL_P (fn) || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
4995 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
4997 explicit_targs = TREE_OPERAND (fn, 1);
4998 fn = TREE_OPERAND (fn, 0);
4999 template_only = 1;
5002 /* Add the various candidate functions. */
5003 add_candidates (fn, NULL_TREE, args, NULL_TREE,
5004 explicit_targs, template_only,
5005 /*conversion_path=*/NULL_TREE,
5006 /*access_path=*/NULL_TREE,
5007 LOOKUP_NORMAL,
5008 candidates, complain);
5010 *candidates = splice_viable (*candidates, false, any_viable_p);
5011 if (*any_viable_p)
5012 cand = tourney (*candidates, complain);
5013 else
5014 cand = NULL;
5016 return cand;
5019 /* Print an error message about being unable to build a call to FN with
5020 ARGS. ANY_VIABLE_P indicates whether any candidate functions could
5021 be located; CANDIDATES is a possibly empty list of such
5022 functions. */
5024 static void
5025 print_error_for_call_failure (tree fn, const vec<tree, va_gc> *args,
5026 struct z_candidate *candidates)
5028 tree targs = NULL_TREE;
5029 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
5031 targs = TREE_OPERAND (fn, 1);
5032 fn = TREE_OPERAND (fn, 0);
5034 tree name = OVL_NAME (fn);
5035 location_t loc = location_of (name);
5036 if (targs)
5037 name = lookup_template_function (name, targs);
5039 auto_diagnostic_group d;
5040 if (!any_strictly_viable (candidates))
5041 error_at (loc, "no matching function for call to %<%D(%A)%>",
5042 name, build_tree_list_vec (args));
5043 else
5044 error_at (loc, "call of overloaded %<%D(%A)%> is ambiguous",
5045 name, build_tree_list_vec (args));
5046 if (candidates)
5047 print_z_candidates (loc, candidates);
5050 /* Perform overload resolution on the set of deduction guides DGUIDES
5051 using ARGS. Returns the selected deduction guide, or error_mark_node
5052 if overload resolution fails. */
5054 tree
5055 perform_dguide_overload_resolution (tree dguides, const vec<tree, va_gc> *args,
5056 tsubst_flags_t complain)
5058 z_candidate *candidates;
5059 bool any_viable_p;
5060 tree result;
5062 gcc_assert (deduction_guide_p (OVL_FIRST (dguides)));
5064 conversion_obstack_sentinel cos;
5066 z_candidate *cand = perform_overload_resolution (dguides, args, &candidates,
5067 &any_viable_p, complain);
5068 if (!cand)
5070 if (complain & tf_error)
5071 print_error_for_call_failure (dguides, args, candidates);
5072 result = error_mark_node;
5074 else
5075 result = cand->fn;
5077 return result;
5080 /* Return an expression for a call to FN (a namespace-scope function,
5081 or a static member function) with the ARGS. This may change
5082 ARGS. */
5084 tree
5085 build_new_function_call (tree fn, vec<tree, va_gc> **args,
5086 tsubst_flags_t complain)
5088 struct z_candidate *candidates, *cand;
5089 bool any_viable_p;
5090 tree result;
5092 if (args != NULL && *args != NULL)
5094 *args = resolve_args (*args, complain);
5095 if (*args == NULL)
5096 return error_mark_node;
5099 if (flag_tm)
5100 tm_malloc_replacement (fn);
5102 conversion_obstack_sentinel cos;
5104 cand = perform_overload_resolution (fn, *args, &candidates, &any_viable_p,
5105 complain);
5107 if (!cand)
5109 if (complain & tf_error)
5111 // If there is a single (non-viable) function candidate,
5112 // let the error be diagnosed by cp_build_function_call_vec.
5113 if (!any_viable_p && candidates && ! candidates->next
5114 && TREE_CODE (candidates->fn) == FUNCTION_DECL
5115 /* A template-id callee consisting of a single (ignored)
5116 non-template candidate needs to be diagnosed the
5117 ordinary way. */
5118 && (TREE_CODE (fn) != TEMPLATE_ID_EXPR
5119 || candidates->template_decl))
5120 return cp_build_function_call_vec (candidates->fn, args, complain);
5122 // Otherwise, emit notes for non-viable candidates.
5123 print_error_for_call_failure (fn, *args, candidates);
5125 result = error_mark_node;
5127 else
5129 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5132 if (flag_coroutines
5133 && result
5134 && TREE_CODE (result) == CALL_EXPR
5135 && DECL_BUILT_IN_CLASS (TREE_OPERAND (CALL_EXPR_FN (result), 0))
5136 == BUILT_IN_NORMAL)
5137 result = coro_validate_builtin_call (result);
5139 return result;
5142 /* Build a call to a global operator new. FNNAME is the name of the
5143 operator (either "operator new" or "operator new[]") and ARGS are
5144 the arguments provided. This may change ARGS. *SIZE points to the
5145 total number of bytes required by the allocation, and is updated if
5146 that is changed here. *COOKIE_SIZE is non-NULL if a cookie should
5147 be used. If this function determines that no cookie should be
5148 used, after all, *COOKIE_SIZE is set to NULL_TREE. If SIZE_CHECK
5149 is not NULL_TREE, it is evaluated before calculating the final
5150 array size, and if it fails, the array size is replaced with
5151 (size_t)-1 (usually triggering a std::bad_alloc exception). If FN
5152 is non-NULL, it will be set, upon return, to the allocation
5153 function called. */
5155 tree
5156 build_operator_new_call (tree fnname, vec<tree, va_gc> **args,
5157 tree *size, tree *cookie_size,
5158 tree align_arg, tree size_check,
5159 tree *fn, tsubst_flags_t complain)
5161 tree original_size = *size;
5162 tree fns;
5163 struct z_candidate *candidates;
5164 struct z_candidate *cand = NULL;
5165 bool any_viable_p;
5167 if (fn)
5168 *fn = NULL_TREE;
5169 /* Set to (size_t)-1 if the size check fails. */
5170 if (size_check != NULL_TREE)
5172 tree errval = TYPE_MAX_VALUE (sizetype);
5173 if (cxx_dialect >= cxx11 && flag_exceptions)
5174 errval = throw_bad_array_new_length ();
5175 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5176 original_size, errval);
5178 vec_safe_insert (*args, 0, *size);
5179 *args = resolve_args (*args, complain);
5180 if (*args == NULL)
5181 return error_mark_node;
5183 conversion_obstack_sentinel cos;
5185 /* Based on:
5187 [expr.new]
5189 If this lookup fails to find the name, or if the allocated type
5190 is not a class type, the allocation function's name is looked
5191 up in the global scope.
5193 we disregard block-scope declarations of "operator new". */
5194 fns = lookup_qualified_name (global_namespace, fnname);
5196 if (align_arg)
5198 vec<tree, va_gc>* align_args
5199 = vec_copy_and_insert (*args, align_arg, 1);
5200 cand = perform_overload_resolution (fns, align_args, &candidates,
5201 &any_viable_p, tf_none);
5202 if (cand)
5203 *args = align_args;
5204 /* If no aligned allocation function matches, try again without the
5205 alignment. */
5208 /* Figure out what function is being called. */
5209 if (!cand)
5210 cand = perform_overload_resolution (fns, *args, &candidates, &any_viable_p,
5211 complain);
5213 /* If no suitable function could be found, issue an error message
5214 and give up. */
5215 if (!cand)
5217 if (complain & tf_error)
5218 print_error_for_call_failure (fns, *args, candidates);
5219 return error_mark_node;
5222 /* If a cookie is required, add some extra space. Whether
5223 or not a cookie is required cannot be determined until
5224 after we know which function was called. */
5225 if (*cookie_size)
5227 bool use_cookie = true;
5228 tree arg_types;
5230 arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
5231 /* Skip the size_t parameter. */
5232 arg_types = TREE_CHAIN (arg_types);
5233 /* Check the remaining parameters (if any). */
5234 if (arg_types
5235 && TREE_CHAIN (arg_types) == void_list_node
5236 && same_type_p (TREE_VALUE (arg_types),
5237 ptr_type_node))
5238 use_cookie = false;
5239 /* If we need a cookie, adjust the number of bytes allocated. */
5240 if (use_cookie)
5242 /* Update the total size. */
5243 *size = size_binop (PLUS_EXPR, original_size, *cookie_size);
5244 if (size_check)
5246 /* Set to (size_t)-1 if the size check fails. */
5247 gcc_assert (size_check != NULL_TREE);
5248 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5249 *size, TYPE_MAX_VALUE (sizetype));
5251 /* Update the argument list to reflect the adjusted size. */
5252 (**args)[0] = *size;
5254 else
5255 *cookie_size = NULL_TREE;
5258 /* Tell our caller which function we decided to call. */
5259 if (fn)
5260 *fn = cand->fn;
5262 /* Build the CALL_EXPR. */
5263 tree ret = build_over_call (cand, LOOKUP_NORMAL, complain);
5265 /* Set this flag for all callers of this function. In addition to
5266 new-expressions, this is called for allocating coroutine state; treat
5267 that as an implicit new-expression. */
5268 tree call = extract_call_expr (ret);
5269 if (TREE_CODE (call) == CALL_EXPR)
5270 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
5272 return ret;
5275 /* Evaluate side-effects from OBJ before evaluating call
5276 to FN in RESULT expression.
5277 This is for expressions of the form `obj->fn(...)'
5278 where `fn' turns out to be a static member function and
5279 `obj' needs to be evaluated. `fn' could be also static operator[]
5280 or static operator(), in which cases the source expression
5281 would be `obj[...]' or `obj(...)'. */
5283 tree
5284 keep_unused_object_arg (tree result, tree obj, tree fn)
5286 if (result == NULL_TREE
5287 || result == error_mark_node
5288 || DECL_OBJECT_MEMBER_FUNCTION_P (fn)
5289 || !TREE_SIDE_EFFECTS (obj))
5290 return result;
5292 /* But avoid the implicit lvalue-rvalue conversion when `obj' is
5293 volatile. */
5294 tree a = obj;
5295 if (TREE_THIS_VOLATILE (a))
5296 a = build_this (a);
5297 if (TREE_SIDE_EFFECTS (a))
5298 return cp_build_compound_expr (a, result, tf_error);
5299 return result;
5302 /* Build a new call to operator(). This may change ARGS. */
5304 tree
5305 build_op_call (tree obj, vec<tree, va_gc> **args, tsubst_flags_t complain)
5307 struct z_candidate *candidates = 0, *cand;
5308 tree fns, convs, first_mem_arg = NULL_TREE;
5309 bool any_viable_p;
5310 tree result = NULL_TREE;
5312 auto_cond_timevar tv (TV_OVERLOAD);
5314 obj = mark_lvalue_use (obj);
5316 if (error_operand_p (obj))
5317 return error_mark_node;
5319 tree type = TREE_TYPE (obj);
5321 obj = prep_operand (obj);
5323 if (TYPE_PTRMEMFUNC_P (type))
5325 if (complain & tf_error)
5326 /* It's no good looking for an overloaded operator() on a
5327 pointer-to-member-function. */
5328 error ("pointer-to-member function %qE cannot be called without "
5329 "an object; consider using %<.*%> or %<->*%>", obj);
5330 return error_mark_node;
5333 if (TYPE_BINFO (type))
5335 fns = lookup_fnfields (TYPE_BINFO (type), call_op_identifier, 1, complain);
5336 if (fns == error_mark_node)
5337 return error_mark_node;
5339 else
5340 fns = NULL_TREE;
5342 if (args != NULL && *args != NULL)
5344 *args = resolve_args (*args, complain);
5345 if (*args == NULL)
5346 return error_mark_node;
5349 conversion_obstack_sentinel cos;
5351 if (fns)
5353 first_mem_arg = obj;
5355 add_candidates (BASELINK_FUNCTIONS (fns),
5356 first_mem_arg, *args, NULL_TREE,
5357 NULL_TREE, false,
5358 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
5359 LOOKUP_NORMAL, &candidates, complain);
5362 bool any_call_ops = candidates != nullptr;
5364 convs = lookup_conversions (type);
5366 for (; convs; convs = TREE_CHAIN (convs))
5368 tree totype = TREE_TYPE (convs);
5370 if (TYPE_PTRFN_P (totype)
5371 || TYPE_REFFN_P (totype)
5372 || (TYPE_REF_P (totype)
5373 && TYPE_PTRFN_P (TREE_TYPE (totype))))
5374 for (tree fn : ovl_range (TREE_VALUE (convs)))
5376 if (DECL_NONCONVERTING_P (fn))
5377 continue;
5379 if (TREE_CODE (fn) == TEMPLATE_DECL)
5381 /* Making this work broke PR 71117 and 85118, so until the
5382 committee resolves core issue 2189, let's disable this
5383 candidate if there are any call operators. */
5384 if (any_call_ops)
5385 continue;
5387 add_template_conv_candidate
5388 (&candidates, fn, obj, *args, totype,
5389 /*access_path=*/NULL_TREE,
5390 /*conversion_path=*/NULL_TREE, complain);
5392 else
5393 add_conv_candidate (&candidates, fn, obj,
5394 *args, /*conversion_path=*/NULL_TREE,
5395 /*access_path=*/NULL_TREE, complain);
5399 /* Be strict here because if we choose a bad conversion candidate, the
5400 errors we get won't mention the call context. */
5401 candidates = splice_viable (candidates, true, &any_viable_p);
5402 if (!any_viable_p)
5404 if (complain & tf_error)
5406 auto_diagnostic_group d;
5407 error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
5408 build_tree_list_vec (*args));
5409 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5411 result = error_mark_node;
5413 else
5415 cand = tourney (candidates, complain);
5416 if (cand == 0)
5418 if (complain & tf_error)
5420 auto_diagnostic_group d;
5421 error ("call of %<(%T) (%A)%> is ambiguous",
5422 TREE_TYPE (obj), build_tree_list_vec (*args));
5423 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5425 result = error_mark_node;
5427 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
5428 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
5429 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, CALL_EXPR))
5431 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5432 /* In an expression of the form `a()' where cand->fn
5433 which is operator() turns out to be a static member function,
5434 `a' is none-the-less evaluated. */
5435 result = keep_unused_object_arg (result, obj, cand->fn);
5437 else
5439 if (TREE_CODE (cand->fn) == FUNCTION_DECL)
5440 obj = convert_like_with_context (cand->convs[0], obj, cand->fn,
5441 -1, complain);
5442 else
5444 gcc_checking_assert (TYPE_P (cand->fn));
5445 obj = convert_like (cand->convs[0], obj, complain);
5447 obj = convert_from_reference (obj);
5448 result = cp_build_function_call_vec (obj, args, complain);
5452 return result;
5455 /* Subroutine for preparing format strings suitable for the error
5456 function. It concatenates a prefix (controlled by MATCH), ERRMSG,
5457 and SUFFIX. */
5459 static const char *
5460 concat_op_error_string (bool match, const char *errmsg, const char *suffix)
5462 return concat (match
5463 ? G_("ambiguous overload for ")
5464 : G_("no match for "),
5465 errmsg, suffix, nullptr);
5468 /* Called by op_error to prepare format strings suitable for the error
5469 function. It concatenates a prefix (controlled by MATCH), ERRMSG,
5470 and a suffix (controlled by NTYPES). */
5472 static const char *
5473 op_error_string (const char *errmsg, int ntypes, bool match)
5475 const char *suffix;
5476 if (ntypes == 3)
5477 suffix = G_(" (operand types are %qT, %qT, and %qT)");
5478 else if (ntypes == 2)
5479 suffix = G_(" (operand types are %qT and %qT)");
5480 else
5481 suffix = G_(" (operand type is %qT)");
5482 return concat_op_error_string (match, errmsg, suffix);
5485 /* Similar to op_error_string, but a special-case for binary ops that
5486 use %e for the args, rather than %qT. */
5488 static const char *
5489 binop_error_string (const char *errmsg, bool match)
5491 return concat_op_error_string (match, errmsg,
5492 G_(" (operand types are %e and %e)"));
5495 static void
5496 op_error (const op_location_t &loc,
5497 enum tree_code code, enum tree_code code2,
5498 tree arg1, tree arg2, tree arg3, bool match)
5500 bool assop = code == MODIFY_EXPR;
5501 const char *opname = OVL_OP_INFO (assop, assop ? code2 : code)->name;
5503 switch (code)
5505 case COND_EXPR:
5506 if (flag_diagnostics_show_caret)
5507 error_at (loc, op_error_string (G_("ternary %<operator?:%>"),
5508 3, match),
5509 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5510 else
5511 error_at (loc, op_error_string (G_("ternary %<operator?:%> "
5512 "in %<%E ? %E : %E%>"), 3, match),
5513 arg1, arg2, arg3,
5514 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5515 break;
5517 case POSTINCREMENT_EXPR:
5518 case POSTDECREMENT_EXPR:
5519 if (flag_diagnostics_show_caret)
5520 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5521 opname, TREE_TYPE (arg1));
5522 else
5523 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E%s%>"),
5524 1, match),
5525 opname, arg1, opname, TREE_TYPE (arg1));
5526 break;
5528 case ARRAY_REF:
5529 if (flag_diagnostics_show_caret)
5530 error_at (loc, op_error_string (G_("%<operator[]%>"), 2, match),
5531 TREE_TYPE (arg1), TREE_TYPE (arg2));
5532 else
5533 error_at (loc, op_error_string (G_("%<operator[]%> in %<%E[%E]%>"),
5534 2, match),
5535 arg1, arg2, TREE_TYPE (arg1), TREE_TYPE (arg2));
5536 break;
5538 case REALPART_EXPR:
5539 case IMAGPART_EXPR:
5540 if (flag_diagnostics_show_caret)
5541 error_at (loc, op_error_string (G_("%qs"), 1, match),
5542 opname, TREE_TYPE (arg1));
5543 else
5544 error_at (loc, op_error_string (G_("%qs in %<%s %E%>"), 1, match),
5545 opname, opname, arg1, TREE_TYPE (arg1));
5546 break;
5548 case CO_AWAIT_EXPR:
5549 if (flag_diagnostics_show_caret)
5550 error_at (loc, op_error_string (G_("%<operator %s%>"), 1, match),
5551 opname, TREE_TYPE (arg1));
5552 else
5553 error_at (loc, op_error_string (G_("%<operator %s%> in %<%s%E%>"),
5554 1, match),
5555 opname, opname, arg1, TREE_TYPE (arg1));
5556 break;
5558 default:
5559 if (arg2)
5560 if (flag_diagnostics_show_caret)
5562 binary_op_rich_location richloc (loc, arg1, arg2, true);
5563 pp_markup::element_quoted_type element_0
5564 (TREE_TYPE (arg1), highlight_colors::lhs);
5565 pp_markup::element_quoted_type element_1
5566 (TREE_TYPE (arg2), highlight_colors::rhs);
5567 error_at (&richloc,
5568 binop_error_string (G_("%<operator%s%>"), match),
5569 opname, &element_0, &element_1);
5571 else
5572 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E %s %E%>"),
5573 2, match),
5574 opname, arg1, opname, arg2,
5575 TREE_TYPE (arg1), TREE_TYPE (arg2));
5576 else
5577 if (flag_diagnostics_show_caret)
5578 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5579 opname, TREE_TYPE (arg1));
5580 else
5581 error_at (loc, op_error_string (G_("%<operator%s%> in %<%s%E%>"),
5582 1, match),
5583 opname, opname, arg1, TREE_TYPE (arg1));
5584 break;
5588 /* Return the implicit conversion sequence that could be used to
5589 convert E1 to E2 in [expr.cond]. */
5591 static conversion *
5592 conditional_conversion (tree e1, tree e2, tsubst_flags_t complain)
5594 tree t1 = non_reference (TREE_TYPE (e1));
5595 tree t2 = non_reference (TREE_TYPE (e2));
5596 conversion *conv;
5597 bool good_base;
5599 /* [expr.cond]
5601 If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5602 implicitly converted (clause _conv_) to the type "lvalue reference to
5603 T2", subject to the constraint that in the conversion the
5604 reference must bind directly (_dcl.init.ref_) to an lvalue.
5606 If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5607 implicitly converted to the type "rvalue reference to T2", subject to
5608 the constraint that the reference must bind directly. */
5609 if (glvalue_p (e2))
5611 tree rtype = cp_build_reference_type (t2, !lvalue_p (e2));
5612 conv = implicit_conversion (rtype,
5615 /*c_cast_p=*/false,
5616 LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND
5617 |LOOKUP_ONLYCONVERTING,
5618 complain);
5619 if (conv && !conv->bad_p)
5620 return conv;
5623 /* If E2 is a prvalue or if neither of the conversions above can be done
5624 and at least one of the operands has (possibly cv-qualified) class
5625 type: */
5626 if (!CLASS_TYPE_P (t1) && !CLASS_TYPE_P (t2))
5627 return NULL;
5629 /* [expr.cond]
5631 If E1 and E2 have class type, and the underlying class types are
5632 the same or one is a base class of the other: E1 can be converted
5633 to match E2 if the class of T2 is the same type as, or a base
5634 class of, the class of T1, and the cv-qualification of T2 is the
5635 same cv-qualification as, or a greater cv-qualification than, the
5636 cv-qualification of T1. If the conversion is applied, E1 is
5637 changed to an rvalue of type T2 that still refers to the original
5638 source class object (or the appropriate subobject thereof). */
5639 if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
5640 && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
5642 if (good_base && at_least_as_qualified_p (t2, t1))
5644 conv = build_identity_conv (t1, e1);
5645 if (!same_type_p (TYPE_MAIN_VARIANT (t1),
5646 TYPE_MAIN_VARIANT (t2)))
5647 conv = build_conv (ck_base, t2, conv);
5648 else
5649 conv = build_conv (ck_rvalue, t2, conv);
5650 return conv;
5652 else
5653 return NULL;
5655 else
5656 /* [expr.cond]
5658 Otherwise: E1 can be converted to match E2 if E1 can be implicitly
5659 converted to the type that expression E2 would have if E2 were
5660 converted to an rvalue (or the type it has, if E2 is an rvalue). */
5661 return implicit_conversion (t2, t1, e1, /*c_cast_p=*/false,
5662 LOOKUP_IMPLICIT, complain);
5665 /* Implement [expr.cond]. ARG1, ARG2, and ARG3 are the three
5666 arguments to the conditional expression. */
5668 tree
5669 build_conditional_expr (const op_location_t &loc,
5670 tree arg1, tree arg2, tree arg3,
5671 tsubst_flags_t complain)
5673 tree arg2_type;
5674 tree arg3_type;
5675 tree result = NULL_TREE;
5676 tree result_type = NULL_TREE;
5677 tree semantic_result_type = NULL_TREE;
5678 bool is_glvalue = true;
5679 struct z_candidate *candidates = 0;
5680 struct z_candidate *cand;
5681 tree orig_arg2, orig_arg3;
5683 auto_cond_timevar tv (TV_OVERLOAD);
5685 /* As a G++ extension, the second argument to the conditional can be
5686 omitted. (So that `a ? : c' is roughly equivalent to `a ? a :
5687 c'.) If the second operand is omitted, make sure it is
5688 calculated only once. */
5689 if (!arg2)
5691 if (complain & tf_error)
5692 pedwarn (loc, OPT_Wpedantic,
5693 "ISO C++ forbids omitting the middle term of "
5694 "a %<?:%> expression");
5696 if ((complain & tf_warning) && !truth_value_p (TREE_CODE (arg1)))
5697 warn_for_omitted_condop (loc, arg1);
5699 /* Make sure that lvalues remain lvalues. See g++.oliva/ext1.C. */
5700 if (glvalue_p (arg1))
5702 arg1 = cp_stabilize_reference (arg1);
5703 arg2 = arg1 = prevent_lifetime_extension (arg1);
5705 else if (TREE_CODE (arg1) == TARGET_EXPR)
5706 /* arg1 can't be a prvalue result of the conditional
5707 expression, since it needs to be materialized for the
5708 conversion to bool, so treat it as an xvalue in arg2. */
5709 arg2 = move (TARGET_EXPR_SLOT (arg1));
5710 else if (TREE_CODE (arg1) == EXCESS_PRECISION_EXPR)
5711 arg2 = arg1 = build1 (EXCESS_PRECISION_EXPR, TREE_TYPE (arg1),
5712 cp_save_expr (TREE_OPERAND (arg1, 0)));
5713 else
5714 arg2 = arg1 = cp_save_expr (arg1);
5717 /* If something has already gone wrong, just pass that fact up the
5718 tree. */
5719 if (error_operand_p (arg1)
5720 || error_operand_p (arg2)
5721 || error_operand_p (arg3))
5722 return error_mark_node;
5724 conversion_obstack_sentinel cos;
5726 orig_arg2 = arg2;
5727 orig_arg3 = arg3;
5729 if (gnu_vector_type_p (TREE_TYPE (arg1))
5730 && VECTOR_INTEGER_TYPE_P (TREE_TYPE (arg1)))
5732 tree arg1_type = TREE_TYPE (arg1);
5734 /* If arg1 is another cond_expr choosing between -1 and 0,
5735 then we can use its comparison. It may help to avoid
5736 additional comparison, produce more accurate diagnostics
5737 and enables folding. */
5738 if (TREE_CODE (arg1) == VEC_COND_EXPR
5739 && integer_minus_onep (TREE_OPERAND (arg1, 1))
5740 && integer_zerop (TREE_OPERAND (arg1, 2)))
5741 arg1 = TREE_OPERAND (arg1, 0);
5743 arg1 = force_rvalue (arg1, complain);
5744 arg2 = force_rvalue (arg2, complain);
5745 arg3 = force_rvalue (arg3, complain);
5747 /* force_rvalue can return error_mark on valid arguments. */
5748 if (error_operand_p (arg1)
5749 || error_operand_p (arg2)
5750 || error_operand_p (arg3))
5751 return error_mark_node;
5753 arg2_type = TREE_TYPE (arg2);
5754 arg3_type = TREE_TYPE (arg3);
5756 if (!VECTOR_TYPE_P (arg2_type)
5757 && !VECTOR_TYPE_P (arg3_type))
5759 /* Rely on the error messages of the scalar version. */
5760 tree scal = build_conditional_expr (loc, integer_one_node,
5761 orig_arg2, orig_arg3, complain);
5762 if (scal == error_mark_node)
5763 return error_mark_node;
5764 tree stype = TREE_TYPE (scal);
5765 tree ctype = TREE_TYPE (arg1_type);
5766 if (TYPE_SIZE (stype) != TYPE_SIZE (ctype)
5767 || (!INTEGRAL_TYPE_P (stype) && !SCALAR_FLOAT_TYPE_P (stype)))
5769 if (complain & tf_error)
5770 error_at (loc, "inferred scalar type %qT is not an integer or "
5771 "floating-point type of the same size as %qT", stype,
5772 COMPARISON_CLASS_P (arg1)
5773 ? TREE_TYPE (TREE_TYPE (TREE_OPERAND (arg1, 0)))
5774 : ctype);
5775 return error_mark_node;
5778 tree vtype = build_opaque_vector_type (stype,
5779 TYPE_VECTOR_SUBPARTS (arg1_type));
5780 /* We could pass complain & tf_warning to unsafe_conversion_p,
5781 but the warnings (like Wsign-conversion) have already been
5782 given by the scalar build_conditional_expr_1. We still check
5783 unsafe_conversion_p to forbid truncating long long -> float. */
5784 if (unsafe_conversion_p (stype, arg2, NULL_TREE, false))
5786 if (complain & tf_error)
5787 error_at (loc, "conversion of scalar %qH to vector %qI "
5788 "involves truncation", arg2_type, vtype);
5789 return error_mark_node;
5791 if (unsafe_conversion_p (stype, arg3, NULL_TREE, false))
5793 if (complain & tf_error)
5794 error_at (loc, "conversion of scalar %qH to vector %qI "
5795 "involves truncation", arg3_type, vtype);
5796 return error_mark_node;
5799 arg2 = cp_convert (stype, arg2, complain);
5800 arg2 = save_expr (arg2);
5801 arg2 = build_vector_from_val (vtype, arg2);
5802 arg2_type = vtype;
5803 arg3 = cp_convert (stype, arg3, complain);
5804 arg3 = save_expr (arg3);
5805 arg3 = build_vector_from_val (vtype, arg3);
5806 arg3_type = vtype;
5809 if ((gnu_vector_type_p (arg2_type) && !VECTOR_TYPE_P (arg3_type))
5810 || (gnu_vector_type_p (arg3_type) && !VECTOR_TYPE_P (arg2_type)))
5812 enum stv_conv convert_flag =
5813 scalar_to_vector (loc, VEC_COND_EXPR, arg2, arg3,
5814 complain & tf_error);
5816 switch (convert_flag)
5818 case stv_error:
5819 return error_mark_node;
5820 case stv_firstarg:
5822 arg2 = save_expr (arg2);
5823 arg2 = convert (TREE_TYPE (arg3_type), arg2);
5824 arg2 = build_vector_from_val (arg3_type, arg2);
5825 arg2_type = TREE_TYPE (arg2);
5826 break;
5828 case stv_secondarg:
5830 arg3 = save_expr (arg3);
5831 arg3 = convert (TREE_TYPE (arg2_type), arg3);
5832 arg3 = build_vector_from_val (arg2_type, arg3);
5833 arg3_type = TREE_TYPE (arg3);
5834 break;
5836 default:
5837 break;
5841 if (!gnu_vector_type_p (arg2_type)
5842 || !gnu_vector_type_p (arg3_type)
5843 || !same_type_p (arg2_type, arg3_type)
5844 || maybe_ne (TYPE_VECTOR_SUBPARTS (arg1_type),
5845 TYPE_VECTOR_SUBPARTS (arg2_type))
5846 || TYPE_SIZE (arg1_type) != TYPE_SIZE (arg2_type))
5848 if (complain & tf_error)
5849 error_at (loc,
5850 "incompatible vector types in conditional expression: "
5851 "%qT, %qT and %qT", TREE_TYPE (arg1),
5852 TREE_TYPE (orig_arg2), TREE_TYPE (orig_arg3));
5853 return error_mark_node;
5856 if (!COMPARISON_CLASS_P (arg1))
5858 tree cmp_type = truth_type_for (arg1_type);
5859 arg1 = build2 (NE_EXPR, cmp_type, arg1, build_zero_cst (arg1_type));
5861 return build3_loc (loc, VEC_COND_EXPR, arg2_type, arg1, arg2, arg3);
5864 /* [expr.cond]
5866 The first expression is implicitly converted to bool (clause
5867 _conv_). */
5868 arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
5869 LOOKUP_NORMAL);
5870 if (error_operand_p (arg1))
5871 return error_mark_node;
5873 arg2_type = unlowered_expr_type (arg2);
5874 arg3_type = unlowered_expr_type (arg3);
5876 if ((TREE_CODE (arg2) == EXCESS_PRECISION_EXPR
5877 || TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
5878 && (TREE_CODE (arg2_type) == INTEGER_TYPE
5879 || SCALAR_FLOAT_TYPE_P (arg2_type)
5880 || TREE_CODE (arg2_type) == COMPLEX_TYPE)
5881 && (TREE_CODE (arg3_type) == INTEGER_TYPE
5882 || SCALAR_FLOAT_TYPE_P (arg3_type)
5883 || TREE_CODE (arg3_type) == COMPLEX_TYPE))
5885 semantic_result_type
5886 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
5887 if (semantic_result_type == error_mark_node)
5889 tree t1 = arg2_type;
5890 tree t2 = arg3_type;
5891 if (TREE_CODE (t1) == COMPLEX_TYPE)
5892 t1 = TREE_TYPE (t1);
5893 if (TREE_CODE (t2) == COMPLEX_TYPE)
5894 t2 = TREE_TYPE (t2);
5895 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
5896 && SCALAR_FLOAT_TYPE_P (t2)
5897 && (extended_float_type_p (t1)
5898 || extended_float_type_p (t2))
5899 && cp_compare_floating_point_conversion_ranks
5900 (t1, t2) == 3);
5901 if (complain & tf_error)
5902 error_at (loc, "operands to %<?:%> of types %qT and %qT "
5903 "have unordered conversion rank",
5904 arg2_type, arg3_type);
5905 return error_mark_node;
5907 if (TREE_CODE (arg2) == EXCESS_PRECISION_EXPR)
5909 arg2 = TREE_OPERAND (arg2, 0);
5910 arg2_type = TREE_TYPE (arg2);
5912 if (TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
5914 arg3 = TREE_OPERAND (arg3, 0);
5915 arg3_type = TREE_TYPE (arg3);
5919 /* [expr.cond]
5921 If either the second or the third operand has type (possibly
5922 cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
5923 array-to-pointer (_conv.array_), and function-to-pointer
5924 (_conv.func_) standard conversions are performed on the second
5925 and third operands. */
5926 if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
5928 /* 'void' won't help in resolving an overloaded expression on the
5929 other side, so require it to resolve by itself. */
5930 if (arg2_type == unknown_type_node)
5932 arg2 = resolve_nondeduced_context_or_error (arg2, complain);
5933 arg2_type = TREE_TYPE (arg2);
5935 if (arg3_type == unknown_type_node)
5937 arg3 = resolve_nondeduced_context_or_error (arg3, complain);
5938 arg3_type = TREE_TYPE (arg3);
5941 /* [expr.cond]
5943 One of the following shall hold:
5945 --The second or the third operand (but not both) is a
5946 throw-expression (_except.throw_); the result is of the type
5947 and value category of the other.
5949 --Both the second and the third operands have type void; the
5950 result is of type void and is a prvalue. */
5951 if (TREE_CODE (arg2) == THROW_EXPR
5952 && TREE_CODE (arg3) != THROW_EXPR)
5954 result_type = arg3_type;
5955 is_glvalue = glvalue_p (arg3);
5957 else if (TREE_CODE (arg2) != THROW_EXPR
5958 && TREE_CODE (arg3) == THROW_EXPR)
5960 result_type = arg2_type;
5961 is_glvalue = glvalue_p (arg2);
5963 else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
5965 result_type = void_type_node;
5966 is_glvalue = false;
5968 else
5970 if (complain & tf_error)
5972 if (VOID_TYPE_P (arg2_type))
5973 error_at (cp_expr_loc_or_loc (arg3, loc),
5974 "second operand to the conditional operator "
5975 "is of type %<void%>, but the third operand is "
5976 "neither a throw-expression nor of type %<void%>");
5977 else
5978 error_at (cp_expr_loc_or_loc (arg2, loc),
5979 "third operand to the conditional operator "
5980 "is of type %<void%>, but the second operand is "
5981 "neither a throw-expression nor of type %<void%>");
5983 return error_mark_node;
5986 goto valid_operands;
5988 /* [expr.cond]
5990 Otherwise, if the second and third operand have different types,
5991 and either has (possibly cv-qualified) class type, or if both are
5992 glvalues of the same value category and the same type except for
5993 cv-qualification, an attempt is made to convert each of those operands
5994 to the type of the other. */
5995 else if (!same_type_p (arg2_type, arg3_type)
5996 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)
5997 || (same_type_ignoring_top_level_qualifiers_p (arg2_type,
5998 arg3_type)
5999 && glvalue_p (arg2) && glvalue_p (arg3)
6000 && lvalue_p (arg2) == lvalue_p (arg3))))
6002 conversion *conv2;
6003 conversion *conv3;
6004 bool converted = false;
6006 conv2 = conditional_conversion (arg2, arg3, complain);
6007 conv3 = conditional_conversion (arg3, arg2, complain);
6009 /* [expr.cond]
6011 If both can be converted, or one can be converted but the
6012 conversion is ambiguous, the program is ill-formed. If
6013 neither can be converted, the operands are left unchanged and
6014 further checking is performed as described below. If exactly
6015 one conversion is possible, that conversion is applied to the
6016 chosen operand and the converted operand is used in place of
6017 the original operand for the remainder of this section. */
6018 if ((conv2 && !conv2->bad_p
6019 && conv3 && !conv3->bad_p)
6020 || (conv2 && conv2->kind == ck_ambig)
6021 || (conv3 && conv3->kind == ck_ambig))
6023 if (complain & tf_error)
6025 error_at (loc, "operands to %<?:%> have different types "
6026 "%qT and %qT",
6027 arg2_type, arg3_type);
6028 if (conv2 && !conv2->bad_p && conv3 && !conv3->bad_p)
6029 inform (loc, " and each type can be converted to the other");
6030 else if (conv2 && conv2->kind == ck_ambig)
6031 convert_like (conv2, arg2, complain);
6032 else
6033 convert_like (conv3, arg3, complain);
6035 result = error_mark_node;
6037 else if (conv2 && !conv2->bad_p)
6039 arg2 = convert_like (conv2, arg2, complain);
6040 arg2 = convert_from_reference (arg2);
6041 arg2_type = TREE_TYPE (arg2);
6042 /* Even if CONV2 is a valid conversion, the result of the
6043 conversion may be invalid. For example, if ARG3 has type
6044 "volatile X", and X does not have a copy constructor
6045 accepting a "volatile X&", then even if ARG2 can be
6046 converted to X, the conversion will fail. */
6047 if (error_operand_p (arg2))
6048 result = error_mark_node;
6049 converted = true;
6051 else if (conv3 && !conv3->bad_p)
6053 arg3 = convert_like (conv3, arg3, complain);
6054 arg3 = convert_from_reference (arg3);
6055 arg3_type = TREE_TYPE (arg3);
6056 if (error_operand_p (arg3))
6057 result = error_mark_node;
6058 converted = true;
6061 if (result)
6062 return result;
6064 /* If, after the conversion, both operands have class type,
6065 treat the cv-qualification of both operands as if it were the
6066 union of the cv-qualification of the operands.
6068 The standard is not clear about what to do in this
6069 circumstance. For example, if the first operand has type
6070 "const X" and the second operand has a user-defined
6071 conversion to "volatile X", what is the type of the second
6072 operand after this step? Making it be "const X" (matching
6073 the first operand) seems wrong, as that discards the
6074 qualification without actually performing a copy. Leaving it
6075 as "volatile X" seems wrong as that will result in the
6076 conditional expression failing altogether, even though,
6077 according to this step, the one operand could be converted to
6078 the type of the other. */
6079 if (converted
6080 && CLASS_TYPE_P (arg2_type)
6081 && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
6082 arg2_type = arg3_type =
6083 cp_build_qualified_type (arg2_type,
6084 cp_type_quals (arg2_type)
6085 | cp_type_quals (arg3_type));
6088 /* [expr.cond]
6090 If the second and third operands are glvalues of the same value
6091 category and have the same type, the result is of that type and
6092 value category. */
6093 if (((lvalue_p (arg2) && lvalue_p (arg3))
6094 || (xvalue_p (arg2) && xvalue_p (arg3)))
6095 && same_type_p (arg2_type, arg3_type))
6097 result_type = arg2_type;
6098 goto valid_operands;
6101 /* [expr.cond]
6103 Otherwise, the result is an rvalue. If the second and third
6104 operand do not have the same type, and either has (possibly
6105 cv-qualified) class type, overload resolution is used to
6106 determine the conversions (if any) to be applied to the operands
6107 (_over.match.oper_, _over.built_). */
6108 is_glvalue = false;
6109 if (!same_type_p (arg2_type, arg3_type)
6110 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
6112 releasing_vec args;
6113 conversion *conv;
6114 bool any_viable_p;
6116 /* Rearrange the arguments so that add_builtin_candidate only has
6117 to know about two args. In build_builtin_candidate, the
6118 arguments are unscrambled. */
6119 args->quick_push (arg2);
6120 args->quick_push (arg3);
6121 args->quick_push (arg1);
6122 add_builtin_candidates (&candidates,
6123 COND_EXPR,
6124 NOP_EXPR,
6125 ovl_op_identifier (false, COND_EXPR),
6126 args,
6127 LOOKUP_NORMAL, complain);
6129 /* [expr.cond]
6131 If the overload resolution fails, the program is
6132 ill-formed. */
6133 candidates = splice_viable (candidates, false, &any_viable_p);
6134 if (!any_viable_p)
6136 if (complain & tf_error)
6137 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6138 arg2_type, arg3_type);
6139 return error_mark_node;
6141 cand = tourney (candidates, complain);
6142 if (!cand)
6144 if (complain & tf_error)
6146 auto_diagnostic_group d;
6147 op_error (loc, COND_EXPR, NOP_EXPR, arg1, arg2, arg3, false);
6148 print_z_candidates (loc, candidates);
6150 return error_mark_node;
6153 /* [expr.cond]
6155 Otherwise, the conversions thus determined are applied, and
6156 the converted operands are used in place of the original
6157 operands for the remainder of this section. */
6158 conv = cand->convs[0];
6159 arg1 = convert_like (conv, arg1, complain);
6160 conv = cand->convs[1];
6161 arg2 = convert_like (conv, arg2, complain);
6162 arg2_type = TREE_TYPE (arg2);
6163 conv = cand->convs[2];
6164 arg3 = convert_like (conv, arg3, complain);
6165 arg3_type = TREE_TYPE (arg3);
6168 /* [expr.cond]
6170 Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
6171 and function-to-pointer (_conv.func_) standard conversions are
6172 performed on the second and third operands.
6174 We need to force the lvalue-to-rvalue conversion here for class types,
6175 so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
6176 that isn't wrapped with a TARGET_EXPR plays havoc with exception
6177 regions. */
6179 arg2 = force_rvalue (arg2, complain);
6180 if (!CLASS_TYPE_P (arg2_type))
6181 arg2_type = TREE_TYPE (arg2);
6183 arg3 = force_rvalue (arg3, complain);
6184 if (!CLASS_TYPE_P (arg3_type))
6185 arg3_type = TREE_TYPE (arg3);
6187 if (arg2 == error_mark_node || arg3 == error_mark_node)
6188 return error_mark_node;
6190 /* [expr.cond]
6192 After those conversions, one of the following shall hold:
6194 --The second and third operands have the same type; the result is of
6195 that type. */
6196 if (same_type_p (arg2_type, arg3_type))
6197 result_type = arg2_type;
6198 /* [expr.cond]
6200 --The second and third operands have arithmetic or enumeration
6201 type; the usual arithmetic conversions are performed to bring
6202 them to a common type, and the result is of that type. */
6203 else if ((ARITHMETIC_TYPE_P (arg2_type)
6204 || UNSCOPED_ENUM_P (arg2_type))
6205 && (ARITHMETIC_TYPE_P (arg3_type)
6206 || UNSCOPED_ENUM_P (arg3_type)))
6208 /* A conditional expression between a floating-point
6209 type and an integer type should convert the integer type to
6210 the evaluation format of the floating-point type, with
6211 possible excess precision. */
6212 tree eptype2 = arg2_type;
6213 tree eptype3 = arg3_type;
6214 tree eptype;
6215 if (ANY_INTEGRAL_TYPE_P (arg2_type)
6216 && (eptype = excess_precision_type (arg3_type)) != NULL_TREE)
6218 eptype3 = eptype;
6219 if (!semantic_result_type)
6220 semantic_result_type
6221 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6223 else if (ANY_INTEGRAL_TYPE_P (arg3_type)
6224 && (eptype = excess_precision_type (arg2_type)) != NULL_TREE)
6226 eptype2 = eptype;
6227 if (!semantic_result_type)
6228 semantic_result_type
6229 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6231 result_type = type_after_usual_arithmetic_conversions (eptype2,
6232 eptype3);
6233 if (result_type == error_mark_node)
6235 tree t1 = eptype2;
6236 tree t2 = eptype3;
6237 if (TREE_CODE (t1) == COMPLEX_TYPE)
6238 t1 = TREE_TYPE (t1);
6239 if (TREE_CODE (t2) == COMPLEX_TYPE)
6240 t2 = TREE_TYPE (t2);
6241 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6242 && SCALAR_FLOAT_TYPE_P (t2)
6243 && (extended_float_type_p (t1)
6244 || extended_float_type_p (t2))
6245 && cp_compare_floating_point_conversion_ranks
6246 (t1, t2) == 3);
6247 if (complain & tf_error)
6248 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6249 "have unordered conversion rank",
6250 eptype2, eptype3);
6251 return error_mark_node;
6253 if (semantic_result_type == error_mark_node)
6255 tree t1 = arg2_type;
6256 tree t2 = arg3_type;
6257 if (TREE_CODE (t1) == COMPLEX_TYPE)
6258 t1 = TREE_TYPE (t1);
6259 if (TREE_CODE (t2) == COMPLEX_TYPE)
6260 t2 = TREE_TYPE (t2);
6261 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6262 && SCALAR_FLOAT_TYPE_P (t2)
6263 && (extended_float_type_p (t1)
6264 || extended_float_type_p (t2))
6265 && cp_compare_floating_point_conversion_ranks
6266 (t1, t2) == 3);
6267 if (complain & tf_error)
6268 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6269 "have unordered conversion rank",
6270 arg2_type, arg3_type);
6271 return error_mark_node;
6274 if (complain & tf_warning)
6275 do_warn_double_promotion (result_type, arg2_type, arg3_type,
6276 "implicit conversion from %qH to %qI to "
6277 "match other result of conditional",
6278 loc);
6280 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
6281 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
6283 tree stripped_orig_arg2 = tree_strip_any_location_wrapper (orig_arg2);
6284 tree stripped_orig_arg3 = tree_strip_any_location_wrapper (orig_arg3);
6285 if (TREE_CODE (stripped_orig_arg2) == CONST_DECL
6286 && TREE_CODE (stripped_orig_arg3) == CONST_DECL
6287 && (DECL_CONTEXT (stripped_orig_arg2)
6288 == DECL_CONTEXT (stripped_orig_arg3)))
6289 /* Two enumerators from the same enumeration can have different
6290 types when the enumeration is still being defined. */;
6291 else if (complain & (cxx_dialect >= cxx26
6292 ? tf_warning_or_error : tf_warning))
6293 emit_diagnostic (cxx_dialect >= cxx26 ? DK_PEDWARN : DK_WARNING,
6294 loc, OPT_Wenum_compare, "enumerated mismatch "
6295 "in conditional expression: %qT vs %qT",
6296 arg2_type, arg3_type);
6297 else if (cxx_dialect >= cxx26)
6298 return error_mark_node;
6300 else if ((((complain & (cxx_dialect >= cxx26
6301 ? tf_warning_or_error : tf_warning))
6302 && warn_deprecated_enum_float_conv)
6303 || (cxx_dialect >= cxx26
6304 && (complain & tf_warning_or_error) == 0))
6305 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6306 && SCALAR_FLOAT_TYPE_P (arg3_type))
6307 || (SCALAR_FLOAT_TYPE_P (arg2_type)
6308 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)))
6310 if (cxx_dialect >= cxx26 && (complain & tf_warning_or_error) == 0)
6311 return error_mark_node;
6312 if (cxx_dialect >= cxx26 && TREE_CODE (arg2_type) == ENUMERAL_TYPE)
6313 pedwarn (loc, OPT_Wdeprecated_enum_float_conversion,
6314 "conditional expression between enumeration type "
6315 "%qT and floating-point type %qT", arg2_type, arg3_type);
6316 else if (cxx_dialect >= cxx26)
6317 pedwarn (loc, OPT_Wdeprecated_enum_float_conversion,
6318 "conditional expression between floating-point type "
6319 "%qT and enumeration type %qT", arg2_type, arg3_type);
6320 else if (TREE_CODE (arg2_type) == ENUMERAL_TYPE)
6321 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6322 "conditional expression between enumeration type "
6323 "%qT and floating-point type %qT is deprecated",
6324 arg2_type, arg3_type);
6325 else
6326 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6327 "conditional expression between floating-point "
6328 "type %qT and enumeration type %qT is deprecated",
6329 arg2_type, arg3_type);
6331 else if ((extra_warnings || warn_enum_conversion)
6332 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6333 && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
6334 || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
6335 && !same_type_p (arg2_type,
6336 type_promotes_to (arg3_type)))))
6338 if (complain & tf_warning)
6340 enum opt_code opt = (warn_enum_conversion
6341 ? OPT_Wenum_conversion
6342 : OPT_Wextra);
6343 warning_at (loc, opt, "enumerated and "
6344 "non-enumerated type in conditional expression");
6348 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6349 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6351 /* [expr.cond]
6353 --The second and third operands have pointer type, or one has
6354 pointer type and the other is a null pointer constant; pointer
6355 conversions (_conv.ptr_) and qualification conversions
6356 (_conv.qual_) are performed to bring them to their composite
6357 pointer type (_expr.rel_). The result is of the composite
6358 pointer type.
6360 --The second and third operands have pointer to member type, or
6361 one has pointer to member type and the other is a null pointer
6362 constant; pointer to member conversions (_conv.mem_) and
6363 qualification conversions (_conv.qual_) are performed to bring
6364 them to a common type, whose cv-qualification shall match the
6365 cv-qualification of either the second or the third operand.
6366 The result is of the common type. */
6367 else if ((null_ptr_cst_p (arg2)
6368 && TYPE_PTR_OR_PTRMEM_P (arg3_type))
6369 || (null_ptr_cst_p (arg3)
6370 && TYPE_PTR_OR_PTRMEM_P (arg2_type))
6371 || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
6372 || (TYPE_PTRDATAMEM_P (arg2_type) && TYPE_PTRDATAMEM_P (arg3_type))
6373 || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
6375 result_type = composite_pointer_type (loc,
6376 arg2_type, arg3_type, arg2,
6377 arg3, CPO_CONDITIONAL_EXPR,
6378 complain);
6379 if (result_type == error_mark_node)
6380 return error_mark_node;
6381 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6382 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6385 if (!result_type)
6387 if (complain & tf_error)
6388 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6389 arg2_type, arg3_type);
6390 return error_mark_node;
6393 if (arg2 == error_mark_node || arg3 == error_mark_node)
6394 return error_mark_node;
6396 valid_operands:
6397 if (processing_template_decl && is_glvalue)
6399 /* Let lvalue_kind know this was a glvalue. */
6400 tree arg = (result_type == arg2_type ? arg2 : arg3);
6401 result_type = cp_build_reference_type (result_type, xvalue_p (arg));
6404 result = build3_loc (loc, COND_EXPR, result_type, arg1, arg2, arg3);
6406 /* If the ARG2 and ARG3 are the same and don't have side-effects,
6407 warn here, because the COND_EXPR will be turned into ARG2. */
6408 if (warn_duplicated_branches
6409 && (complain & tf_warning)
6410 && (arg2 == arg3 || operand_equal_p (arg2, arg3,
6411 OEP_ADDRESS_OF_SAME_FIELD)))
6412 warning_at (EXPR_LOCATION (result), OPT_Wduplicated_branches,
6413 "this condition has identical branches");
6415 /* We can't use result_type below, as fold might have returned a
6416 throw_expr. */
6418 if (!is_glvalue)
6420 /* Expand both sides into the same slot, hopefully the target of
6421 the ?: expression. We used to check for TARGET_EXPRs here,
6422 but now we sometimes wrap them in NOP_EXPRs so the test would
6423 fail. */
6424 if (CLASS_TYPE_P (TREE_TYPE (result)))
6426 result = get_target_expr (result, complain);
6427 /* Tell gimplify_modify_expr_rhs not to strip this in
6428 assignment context: we want both arms to initialize
6429 the same temporary. */
6430 TARGET_EXPR_NO_ELIDE (result) = true;
6432 /* If this expression is an rvalue, but might be mistaken for an
6433 lvalue, we must add a NON_LVALUE_EXPR. */
6434 result = rvalue (result);
6435 if (semantic_result_type)
6436 result = build1 (EXCESS_PRECISION_EXPR, semantic_result_type,
6437 result);
6439 else
6441 result = force_paren_expr (result);
6442 gcc_assert (semantic_result_type == NULL_TREE);
6445 return result;
6448 /* OPERAND is an operand to an expression. Perform necessary steps
6449 required before using it. If OPERAND is NULL_TREE, NULL_TREE is
6450 returned. */
6452 static tree
6453 prep_operand (tree operand)
6455 if (operand)
6457 if (CLASS_TYPE_P (TREE_TYPE (operand))
6458 && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
6459 /* Make sure the template type is instantiated now. */
6460 instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
6463 return operand;
6466 /* True iff CONV represents a conversion sequence which no other can be better
6467 than under [over.ics.rank]: in other words, a "conversion" to the exact same
6468 type (including binding to a reference to the same type). This is stronger
6469 than the standard's "identity" category, which also includes reference
6470 bindings that add cv-qualifiers or change rvalueness. */
6472 static bool
6473 perfect_conversion_p (conversion *conv)
6475 if (CONVERSION_RANK (conv) != cr_identity)
6476 return false;
6477 if (conv->kind == ck_ref_bind)
6479 if (!conv->rvaluedness_matches_p)
6480 return false;
6481 if (!same_type_p (TREE_TYPE (conv->type),
6482 next_conversion (conv)->type))
6483 return false;
6485 if (conv->check_narrowing)
6486 /* Brace elision is imperfect. */
6487 return false;
6488 return true;
6491 /* True if CAND represents a perfect match, i.e. all perfect conversions, so no
6492 other candidate can be a better match. Since the template/non-template
6493 tiebreaker comes immediately after the conversion comparison in
6494 [over.match.best], a perfect non-template candidate is better than all
6495 templates. */
6497 static bool
6498 perfect_candidate_p (z_candidate *cand)
6500 if (cand->viable < 1)
6501 return false;
6502 /* CWG1402 makes an implicitly deleted move op worse than other
6503 candidates. */
6504 if (DECL_DELETED_FN (cand->fn) && DECL_DEFAULTED_FN (cand->fn)
6505 && move_fn_p (cand->fn))
6506 return false;
6507 int len = cand->num_convs;
6508 for (int i = 0; i < len; ++i)
6509 if (!perfect_conversion_p (cand->convs[i]))
6510 return false;
6511 if (conversion *conv = cand->second_conv)
6512 if (!perfect_conversion_p (conv))
6513 return false;
6514 return true;
6517 /* True iff one of CAND's argument conversions is missing. */
6519 static bool
6520 missing_conversion_p (const z_candidate *cand)
6522 for (unsigned i = 0; i < cand->num_convs; ++i)
6524 conversion *conv = cand->convs[i];
6525 if (!conv)
6526 return true;
6527 if (conv->kind == ck_deferred_bad)
6529 /* We don't know whether this conversion is outright invalid or
6530 just bad, so conservatively assume it's missing. */
6531 gcc_checking_assert (conv->bad_p);
6532 return true;
6535 return false;
6538 /* Add each of the viable functions in FNS (a FUNCTION_DECL or
6539 OVERLOAD) to the CANDIDATES, returning an updated list of
6540 CANDIDATES. The ARGS are the arguments provided to the call;
6541 if FIRST_ARG is non-null it is the implicit object argument,
6542 otherwise the first element of ARGS is used if needed. The
6543 EXPLICIT_TARGS are explicit template arguments provided.
6544 TEMPLATE_ONLY is true if only template functions should be
6545 considered. CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
6546 add_function_candidate. */
6548 static void
6549 add_candidates (tree fns, tree first_arg, const vec<tree, va_gc> *args,
6550 tree return_type,
6551 tree explicit_targs, bool template_only,
6552 tree conversion_path, tree access_path,
6553 int flags,
6554 struct z_candidate **candidates,
6555 tsubst_flags_t complain)
6557 tree ctype;
6558 const vec<tree, va_gc> *non_static_args;
6559 bool check_list_ctor = false;
6560 bool check_converting = false;
6561 unification_kind_t strict;
6562 tree ne_fns = NULL_TREE;
6564 if (!fns)
6565 return;
6567 /* Precalculate special handling of constructors and conversion ops. */
6568 tree fn = OVL_FIRST (fns);
6569 if (DECL_CONV_FN_P (fn))
6571 check_list_ctor = false;
6572 check_converting = (flags & LOOKUP_ONLYCONVERTING) != 0;
6573 if (flags & LOOKUP_NO_CONVERSION)
6574 /* We're doing return_type(x). */
6575 strict = DEDUCE_CONV;
6576 else
6577 /* We're doing x.operator return_type(). */
6578 strict = DEDUCE_EXACT;
6579 /* [over.match.funcs] For conversion functions, the function
6580 is considered to be a member of the class of the implicit
6581 object argument for the purpose of defining the type of
6582 the implicit object parameter. */
6583 ctype = TYPE_MAIN_VARIANT (TREE_TYPE (first_arg));
6585 else
6587 if (DECL_CONSTRUCTOR_P (fn))
6589 check_list_ctor = (flags & LOOKUP_LIST_ONLY) != 0;
6590 /* For list-initialization we consider explicit constructors
6591 and complain if one is chosen. */
6592 check_converting
6593 = ((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
6594 == LOOKUP_ONLYCONVERTING);
6596 strict = DEDUCE_CALL;
6597 ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
6600 /* P2468: Check if operator== is a rewrite target with first operand
6601 (*args)[0]; for now just do the lookups. */
6602 if ((flags & (LOOKUP_REWRITTEN | LOOKUP_REVERSED))
6603 && DECL_OVERLOADED_OPERATOR_IS (fn, EQ_EXPR))
6605 tree ne_name = ovl_op_identifier (false, NE_EXPR);
6606 if (DECL_CLASS_SCOPE_P (fn))
6608 ne_fns = lookup_fnfields (TREE_TYPE ((*args)[0]), ne_name,
6609 1, tf_none);
6610 if (ne_fns == error_mark_node || ne_fns == NULL_TREE)
6611 ne_fns = NULL_TREE;
6612 else
6613 ne_fns = BASELINK_FUNCTIONS (ne_fns);
6615 else
6617 tree context = decl_namespace_context (fn);
6618 ne_fns = lookup_qualified_name (context, ne_name, LOOK_want::NORMAL,
6619 /*complain*/false);
6620 if (ne_fns == error_mark_node
6621 || !is_overloaded_fn (ne_fns))
6622 ne_fns = NULL_TREE;
6626 if (first_arg)
6627 non_static_args = args;
6628 else
6629 /* Delay creating the implicit this parameter until it is needed. */
6630 non_static_args = NULL;
6632 bool seen_strictly_viable = any_strictly_viable (*candidates);
6633 /* If there's a non-template perfect match, we don't need to consider
6634 templates. So check non-templates first. This optimization is only
6635 really needed for the defaulted copy constructor of tuple and the like
6636 (96926), but it seems like we might as well enable it more generally. */
6637 bool seen_perfect = false;
6638 enum { templates, non_templates, either } which = either;
6639 if (template_only)
6640 which = templates;
6641 else /*if (flags & LOOKUP_DEFAULTED)*/
6642 which = non_templates;
6644 /* Template candidates that we'll potentially ignore if the
6645 perfect candidate optimization succeeds. */
6646 z_candidate *ignored_template_cands = nullptr;
6648 /* During overload resolution, we first consider each function under the
6649 assumption that we'll eventually find a strictly viable candidate.
6650 This allows us to circumvent our defacto behavior when checking
6651 argument conversions and shortcut consideration of the candidate
6652 upon encountering the first bad conversion. If this assumption
6653 turns out to be false, and all candidates end up being non-strictly
6654 viable, then we reconsider such candidates under the defacto behavior.
6655 This trick is important for pruning member function overloads according
6656 to their const/ref-qualifiers (since all 'this' conversions are at
6657 worst bad) without breaking -fpermissive. */
6658 z_candidate *bad_cands = nullptr;
6659 bool shortcut_bad_convs = true;
6661 again:
6662 for (tree fn : lkp_range (fns))
6664 if (which == templates && TREE_CODE (fn) != TEMPLATE_DECL)
6666 if (template_only)
6667 add_ignored_candidate (candidates, fn);
6668 continue;
6670 if (which == non_templates && TREE_CODE (fn) == TEMPLATE_DECL)
6672 add_ignored_candidate (&ignored_template_cands, fn);
6673 continue;
6675 if ((check_converting && DECL_NONCONVERTING_P (fn))
6676 || (check_list_ctor && !is_list_ctor (fn)))
6678 add_ignored_candidate (candidates, fn);
6679 continue;
6682 tree fn_first_arg = NULL_TREE;
6683 const vec<tree, va_gc> *fn_args = args;
6685 if (DECL_OBJECT_MEMBER_FUNCTION_P (fn))
6687 /* Figure out where the object arg comes from. If this
6688 function is a non-static member and we didn't get an
6689 implicit object argument, move it out of args. */
6690 if (first_arg == NULL_TREE)
6692 unsigned int ix;
6693 tree arg;
6694 vec<tree, va_gc> *tempvec;
6695 vec_alloc (tempvec, args->length () - 1);
6696 for (ix = 1; args->iterate (ix, &arg); ++ix)
6697 tempvec->quick_push (arg);
6698 non_static_args = tempvec;
6699 first_arg = (*args)[0];
6702 fn_first_arg = first_arg;
6703 fn_args = non_static_args;
6706 /* Don't bother reversing an operator with two identical parameters. */
6707 else if (vec_safe_length (args) == 2 && (flags & LOOKUP_REVERSED))
6709 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
6710 if (same_type_p (TREE_VALUE (parmlist),
6711 TREE_VALUE (TREE_CHAIN (parmlist))))
6712 continue;
6715 /* When considering reversed operator==, if there's a corresponding
6716 operator!= in the same scope, it's not a rewrite target. */
6717 if (ne_fns)
6719 bool found = false;
6720 for (lkp_iterator ne (ne_fns); !found && ne; ++ne)
6721 if (0 && !ne.using_p ()
6722 && DECL_NAMESPACE_SCOPE_P (fn)
6723 && DECL_CONTEXT (*ne) != DECL_CONTEXT (fn))
6724 /* ??? This kludge excludes inline namespace members for the H
6725 test in spaceship-eq15.C, but I don't see why we would want
6726 that behavior. Asked Core 2022-11-04. Disabling for now. */;
6727 else if (fns_correspond (fn, *ne))
6729 found = true;
6730 break;
6732 if (found)
6733 continue;
6736 if (TREE_CODE (fn) == TEMPLATE_DECL)
6737 add_template_candidate (candidates,
6739 ctype,
6740 explicit_targs,
6741 fn_first_arg,
6742 fn_args,
6743 return_type,
6744 access_path,
6745 conversion_path,
6746 flags,
6747 strict,
6748 shortcut_bad_convs,
6749 complain);
6750 else
6752 add_function_candidate (candidates,
6754 ctype,
6755 fn_first_arg,
6756 fn_args,
6757 access_path,
6758 conversion_path,
6759 flags,
6760 NULL,
6761 shortcut_bad_convs,
6762 complain);
6763 if (perfect_candidate_p (*candidates))
6764 seen_perfect = true;
6767 z_candidate *cand = *candidates;
6768 if (cand->viable == 1)
6769 seen_strictly_viable = true;
6771 if (cand->viable == -1
6772 && shortcut_bad_convs
6773 && (missing_conversion_p (cand)
6774 || TREE_CODE (cand->fn) == TEMPLATE_DECL))
6776 /* This candidate has been tentatively marked non-strictly viable,
6777 and we didn't compute all argument conversions for it (having
6778 stopped at the first bad conversion). Move it to BAD_CANDS to
6779 to fully reconsider later if we don't find any strictly viable
6780 candidates. */
6781 if (complain & (tf_error | tf_conv))
6783 *candidates = cand->next;
6784 cand->next = bad_cands;
6785 bad_cands = cand;
6787 else
6788 /* But if we're in a SFINAE context, just mark this candidate as
6789 unviable outright and avoid potentially reconsidering it.
6790 This is safe to do because in a SFINAE context, performing a bad
6791 conversion is always an error (even with -fpermissive), so a
6792 non-strictly viable candidate is effectively unviable anyway. */
6793 cand->viable = 0;
6796 if (which == non_templates && !seen_perfect)
6798 which = templates;
6799 ignored_template_cands = nullptr;
6800 goto again;
6802 else if (which == templates
6803 && !seen_strictly_viable
6804 && shortcut_bad_convs
6805 && bad_cands)
6807 /* None of the candidates are strictly viable, so consider again those
6808 functions in BAD_CANDS, this time without shortcutting bad conversions
6809 so that all their argument conversions are computed. */
6810 which = either;
6811 fns = NULL_TREE;
6812 for (z_candidate *cand = bad_cands; cand; cand = cand->next)
6814 tree fn = cand->fn;
6815 if (tree ti = cand->template_decl)
6816 fn = TI_TEMPLATE (ti);
6817 fns = ovl_make (fn, fns);
6819 shortcut_bad_convs = false;
6820 bad_cands = nullptr;
6821 goto again;
6824 if (complain & tf_error)
6826 /* Remember any omitted candidates; we may want to print all candidates
6827 as part of overload resolution failure diagnostics. */
6828 for (z_candidate *omitted_cands : { ignored_template_cands, bad_cands })
6830 z_candidate **omitted_cands_tail = &omitted_cands;
6831 while (*omitted_cands_tail)
6832 omitted_cands_tail = &(*omitted_cands_tail)->next;
6833 *omitted_cands_tail = *candidates;
6834 *candidates = omitted_cands;
6839 /* Returns 1 if P0145R2 says that the LHS of operator CODE is evaluated first,
6840 -1 if the RHS is evaluated first, or 0 if the order is unspecified. */
6842 static int
6843 op_is_ordered (tree_code code)
6845 switch (code)
6847 // 5. b @= a
6848 case MODIFY_EXPR:
6849 return (flag_strong_eval_order > 1 ? -1 : 0);
6851 // 6. a[b]
6852 case ARRAY_REF:
6853 return (flag_strong_eval_order > 1 ? 1 : 0);
6855 // 1. a.b
6856 // Not overloadable (yet).
6857 // 2. a->b
6858 // Only one argument.
6859 // 3. a->*b
6860 case MEMBER_REF:
6861 // 7. a << b
6862 case LSHIFT_EXPR:
6863 // 8. a >> b
6864 case RSHIFT_EXPR:
6865 // a && b
6866 // Predates P0145R3.
6867 case TRUTH_ANDIF_EXPR:
6868 // a || b
6869 // Predates P0145R3.
6870 case TRUTH_ORIF_EXPR:
6871 // a , b
6872 // Predates P0145R3.
6873 case COMPOUND_EXPR:
6874 return (flag_strong_eval_order ? 1 : 0);
6876 default:
6877 return 0;
6881 /* Subroutine of build_new_op: Add to CANDIDATES all candidates for the
6882 operator indicated by CODE/CODE2. This function calls itself recursively to
6883 handle C++20 rewritten comparison operator candidates. Returns NULL_TREE
6884 upon success, and error_mark_node if something went wrong that prevented
6885 us from performing overload resolution (e.g. ambiguous member name lookup).
6887 LOOKUPS, if non-NULL, is the set of pertinent namespace-scope operator
6888 overloads to consider. This parameter is used when instantiating a
6889 dependent operator expression and has the same structure as
6890 DEPENDENT_OPERATOR_TYPE_SAVED_LOOKUPS. */
6892 static tree
6893 add_operator_candidates (z_candidate **candidates,
6894 tree_code code, tree_code code2,
6895 vec<tree, va_gc> *arglist, tree lookups,
6896 int flags, tsubst_flags_t complain)
6898 z_candidate *start_candidates = *candidates;
6899 bool ismodop = code2 != ERROR_MARK;
6900 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
6902 /* LOOKUP_REWRITTEN is set when we're looking for the == or <=> operator to
6903 rewrite from, and also when we're looking for the e.g. < operator to use
6904 on the result of <=>. In the latter case, we don't want the flag set in
6905 the candidate, we just want to suppress looking for rewrites. */
6906 bool rewritten = (flags & LOOKUP_REWRITTEN);
6907 if (rewritten && code != EQ_EXPR && code != SPACESHIP_EXPR)
6908 flags &= ~LOOKUP_REWRITTEN;
6910 bool memonly = false;
6911 switch (code)
6913 /* =, ->, [], () must be non-static member functions. */
6914 case MODIFY_EXPR:
6915 if (code2 != NOP_EXPR)
6916 break;
6917 /* FALLTHRU */
6918 case COMPONENT_REF:
6919 case ARRAY_REF:
6920 memonly = true;
6921 break;
6923 default:
6924 break;
6927 /* Add namespace-scope operators to the list of functions to
6928 consider. */
6929 if (!memonly)
6931 tree fns;
6932 if (!lookups)
6933 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
6934 /* If LOOKUPS is non-NULL, then we're instantiating a dependent operator
6935 expression, and LOOKUPS is the result of stage 1 name lookup. */
6936 else if (tree found = purpose_member (fnname, lookups))
6937 fns = TREE_VALUE (found);
6938 else
6939 fns = NULL_TREE;
6940 fns = lookup_arg_dependent (fnname, fns, arglist);
6941 add_candidates (fns, NULL_TREE, arglist, NULL_TREE,
6942 NULL_TREE, false, NULL_TREE, NULL_TREE,
6943 flags, candidates, complain);
6946 /* Add class-member operators to the candidate set. */
6947 tree arg1_type = TREE_TYPE ((*arglist)[0]);
6948 unsigned nargs = arglist->length () > 1 ? 2 : 1;
6949 tree arg2_type = nargs > 1 ? TREE_TYPE ((*arglist)[1]) : NULL_TREE;
6950 if (CLASS_TYPE_P (arg1_type))
6952 tree fns = lookup_fnfields (arg1_type, fnname, 1, complain);
6953 if (fns == error_mark_node)
6954 return error_mark_node;
6955 if (fns)
6957 if (code == ARRAY_REF)
6959 vec<tree,va_gc> *restlist = make_tree_vector ();
6960 for (unsigned i = 1; i < nargs; ++i)
6961 vec_safe_push (restlist, (*arglist)[i]);
6962 z_candidate *save_cand = *candidates;
6963 add_candidates (BASELINK_FUNCTIONS (fns),
6964 (*arglist)[0], restlist, NULL_TREE,
6965 NULL_TREE, false,
6966 BASELINK_BINFO (fns),
6967 BASELINK_ACCESS_BINFO (fns),
6968 flags, candidates, complain);
6969 /* Release the vec if we didn't add a candidate that uses it. */
6970 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
6971 if (c->args == restlist)
6973 restlist = NULL;
6974 break;
6976 release_tree_vector (restlist);
6978 else
6979 add_candidates (BASELINK_FUNCTIONS (fns),
6980 NULL_TREE, arglist, NULL_TREE,
6981 NULL_TREE, false,
6982 BASELINK_BINFO (fns),
6983 BASELINK_ACCESS_BINFO (fns),
6984 flags, candidates, complain);
6987 /* Per [over.match.oper]3.2, if no operand has a class type, then
6988 only non-member functions that have type T1 or reference to
6989 cv-qualified-opt T1 for the first argument, if the first argument
6990 has an enumeration type, or T2 or reference to cv-qualified-opt
6991 T2 for the second argument, if the second argument has an
6992 enumeration type. Filter out those that don't match. */
6993 else if (! arg2_type || ! CLASS_TYPE_P (arg2_type))
6995 struct z_candidate **candp, **next;
6997 for (candp = candidates; *candp != start_candidates; candp = next)
6999 unsigned i;
7000 z_candidate *cand = *candp;
7001 next = &cand->next;
7003 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
7005 for (i = 0; i < nargs; ++i)
7007 tree parmtype = TREE_VALUE (parmlist);
7008 tree argtype = unlowered_expr_type ((*arglist)[i]);
7010 if (TYPE_REF_P (parmtype))
7011 parmtype = TREE_TYPE (parmtype);
7012 if (TREE_CODE (argtype) == ENUMERAL_TYPE
7013 && (same_type_ignoring_top_level_qualifiers_p
7014 (argtype, parmtype)))
7015 break;
7017 parmlist = TREE_CHAIN (parmlist);
7020 /* No argument has an appropriate type, so remove this
7021 candidate function from the list. */
7022 if (i == nargs)
7024 *candp = cand->next;
7025 next = candp;
7030 if (!rewritten)
7032 /* The standard says to rewrite built-in candidates, too,
7033 but there's no point. */
7034 add_builtin_candidates (candidates, code, code2, fnname, arglist,
7035 flags, complain);
7037 /* Maybe add C++20 rewritten comparison candidates. */
7038 tree_code rewrite_code = ERROR_MARK;
7039 if (cxx_dialect >= cxx20
7040 && nargs == 2
7041 && (OVERLOAD_TYPE_P (arg1_type) || OVERLOAD_TYPE_P (arg2_type)))
7042 switch (code)
7044 case LT_EXPR:
7045 case LE_EXPR:
7046 case GT_EXPR:
7047 case GE_EXPR:
7048 case SPACESHIP_EXPR:
7049 rewrite_code = SPACESHIP_EXPR;
7050 break;
7052 case NE_EXPR:
7053 case EQ_EXPR:
7054 rewrite_code = EQ_EXPR;
7055 break;
7057 default:;
7060 if (rewrite_code)
7062 tree r;
7063 flags |= LOOKUP_REWRITTEN;
7064 if (rewrite_code != code)
7066 /* Add rewritten candidates in same order. */
7067 r = add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
7068 arglist, lookups, flags, complain);
7069 if (r == error_mark_node)
7070 return error_mark_node;
7073 z_candidate *save_cand = *candidates;
7075 /* Add rewritten candidates in reverse order. */
7076 flags |= LOOKUP_REVERSED;
7077 vec<tree,va_gc> *revlist = make_tree_vector ();
7078 revlist->quick_push ((*arglist)[1]);
7079 revlist->quick_push ((*arglist)[0]);
7080 r = add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
7081 revlist, lookups, flags, complain);
7082 if (r == error_mark_node)
7083 return error_mark_node;
7085 /* Release the vec if we didn't add a candidate that uses it. */
7086 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
7087 if (c->args == revlist)
7089 revlist = NULL;
7090 break;
7092 release_tree_vector (revlist);
7096 return NULL_TREE;
7099 tree
7100 build_new_op (const op_location_t &loc, enum tree_code code, int flags,
7101 tree arg1, tree arg2, tree arg3, tree lookups,
7102 tree *overload, tsubst_flags_t complain)
7104 struct z_candidate *candidates = 0, *cand;
7105 releasing_vec arglist;
7106 tree result = NULL_TREE;
7107 bool result_valid_p = false;
7108 enum tree_code code2 = ERROR_MARK;
7109 enum tree_code code_orig_arg1 = ERROR_MARK;
7110 enum tree_code code_orig_arg2 = ERROR_MARK;
7111 bool strict_p;
7112 bool any_viable_p;
7114 auto_cond_timevar tv (TV_OVERLOAD);
7116 if (error_operand_p (arg1)
7117 || error_operand_p (arg2)
7118 || error_operand_p (arg3))
7119 return error_mark_node;
7121 conversion_obstack_sentinel cos;
7123 bool ismodop = code == MODIFY_EXPR;
7124 if (ismodop)
7126 code2 = TREE_CODE (arg3);
7127 arg3 = NULL_TREE;
7130 tree arg1_type = unlowered_expr_type (arg1);
7131 tree arg2_type = arg2 ? unlowered_expr_type (arg2) : NULL_TREE;
7133 arg1 = prep_operand (arg1);
7135 switch (code)
7137 case NEW_EXPR:
7138 case VEC_NEW_EXPR:
7139 case VEC_DELETE_EXPR:
7140 case DELETE_EXPR:
7141 /* Use build_operator_new_call and build_op_delete_call instead. */
7142 gcc_unreachable ();
7144 case CALL_EXPR:
7145 /* Use build_op_call instead. */
7146 gcc_unreachable ();
7148 case TRUTH_ORIF_EXPR:
7149 case TRUTH_ANDIF_EXPR:
7150 case TRUTH_AND_EXPR:
7151 case TRUTH_OR_EXPR:
7152 /* These are saved for the sake of warn_logical_operator. */
7153 code_orig_arg1 = TREE_CODE (arg1);
7154 code_orig_arg2 = TREE_CODE (arg2);
7155 break;
7156 case GT_EXPR:
7157 case LT_EXPR:
7158 case GE_EXPR:
7159 case LE_EXPR:
7160 case EQ_EXPR:
7161 case NE_EXPR:
7162 /* These are saved for the sake of maybe_warn_bool_compare. */
7163 code_orig_arg1 = TREE_CODE (arg1_type);
7164 code_orig_arg2 = TREE_CODE (arg2_type);
7165 break;
7167 default:
7168 break;
7171 arg2 = prep_operand (arg2);
7172 arg3 = prep_operand (arg3);
7174 if (code == COND_EXPR)
7175 /* Use build_conditional_expr instead. */
7176 gcc_unreachable ();
7177 else if (! OVERLOAD_TYPE_P (arg1_type)
7178 && (! arg2 || ! OVERLOAD_TYPE_P (arg2_type)))
7179 goto builtin;
7181 if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
7183 arg2 = integer_zero_node;
7184 arg2_type = integer_type_node;
7187 arglist->quick_push (arg1);
7188 if (arg2 != NULL_TREE)
7189 arglist->quick_push (arg2);
7190 if (arg3 != NULL_TREE)
7191 arglist->quick_push (arg3);
7193 result = add_operator_candidates (&candidates, code, code2, arglist,
7194 lookups, flags, complain);
7195 if (result == error_mark_node)
7196 return error_mark_node;
7198 switch (code)
7200 case COMPOUND_EXPR:
7201 case ADDR_EXPR:
7202 /* For these, the built-in candidates set is empty
7203 [over.match.oper]/3. We don't want non-strict matches
7204 because exact matches are always possible with built-in
7205 operators. The built-in candidate set for COMPONENT_REF
7206 would be empty too, but since there are no such built-in
7207 operators, we accept non-strict matches for them. */
7208 strict_p = true;
7209 break;
7211 default:
7212 strict_p = false;
7213 break;
7216 candidates = splice_viable (candidates, strict_p, &any_viable_p);
7217 if (!any_viable_p)
7219 switch (code)
7221 case POSTINCREMENT_EXPR:
7222 case POSTDECREMENT_EXPR:
7223 /* Don't try anything fancy if we're not allowed to produce
7224 errors. */
7225 if (!(complain & tf_error))
7226 return error_mark_node;
7228 /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
7229 distinguish between prefix and postfix ++ and
7230 operator++() was used for both, so we allow this with
7231 -fpermissive. */
7232 else
7234 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
7235 const char *msg = (flag_permissive)
7236 ? G_("no %<%D(int)%> declared for postfix %qs,"
7237 " trying prefix operator instead")
7238 : G_("no %<%D(int)%> declared for postfix %qs");
7239 permerror (loc, msg, fnname, OVL_OP_INFO (false, code)->name);
7242 if (!flag_permissive)
7243 return error_mark_node;
7245 if (code == POSTINCREMENT_EXPR)
7246 code = PREINCREMENT_EXPR;
7247 else
7248 code = PREDECREMENT_EXPR;
7249 result = build_new_op (loc, code, flags, arg1, NULL_TREE,
7250 NULL_TREE, lookups, overload, complain);
7251 break;
7253 /* The caller will deal with these. */
7254 case ADDR_EXPR:
7255 case COMPOUND_EXPR:
7256 case COMPONENT_REF:
7257 case CO_AWAIT_EXPR:
7258 result = NULL_TREE;
7259 result_valid_p = true;
7260 break;
7262 default:
7263 if (complain & tf_error)
7265 /* If one of the arguments of the operator represents
7266 an invalid use of member function pointer, try to report
7267 a meaningful error ... */
7268 if (invalid_nonstatic_memfn_p (loc, arg1, tf_error)
7269 || invalid_nonstatic_memfn_p (loc, arg2, tf_error)
7270 || invalid_nonstatic_memfn_p (loc, arg3, tf_error))
7271 /* We displayed the error message. */;
7272 else
7274 /* ... Otherwise, report the more generic
7275 "no matching operator found" error */
7276 auto_diagnostic_group d;
7277 op_error (loc, code, code2, arg1, arg2, arg3, false);
7278 print_z_candidates (loc, candidates);
7281 result = error_mark_node;
7282 break;
7285 else
7287 cand = tourney (candidates, complain);
7288 if (cand == 0)
7290 if (complain & tf_error)
7292 auto_diagnostic_group d;
7293 op_error (loc, code, code2, arg1, arg2, arg3, true);
7294 print_z_candidates (loc, candidates);
7296 result = error_mark_node;
7297 if (overload)
7298 *overload = error_mark_node;
7300 else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
7302 if (overload)
7303 *overload = cand->fn;
7305 if (resolve_args (arglist, complain) == NULL)
7306 result = error_mark_node;
7307 else
7309 tsubst_flags_t ocomplain = complain;
7310 if (cand->rewritten ())
7311 /* We'll wrap this call in another one. */
7312 ocomplain &= ~tf_decltype;
7313 if (cand->reversed ())
7315 /* We swapped these in add_candidate, swap them back now. */
7316 std::swap (cand->convs[0], cand->convs[1]);
7317 if (cand->fn == current_function_decl)
7318 warning_at (loc, 0, "in C++20 this comparison calls the "
7319 "current function recursively with reversed "
7320 "arguments");
7322 result = build_over_call (cand, LOOKUP_NORMAL, ocomplain);
7325 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7326 /* There won't be a CALL_EXPR. */;
7327 else if (result && result != error_mark_node)
7329 tree call = extract_call_expr (result);
7330 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7332 /* Specify evaluation order as per P0145R2. */
7333 CALL_EXPR_ORDERED_ARGS (call) = false;
7334 switch (op_is_ordered (code))
7336 case -1:
7337 CALL_EXPR_REVERSE_ARGS (call) = true;
7338 break;
7340 case 1:
7341 CALL_EXPR_ORDERED_ARGS (call) = true;
7342 break;
7344 default:
7345 break;
7349 /* If this was a C++20 rewritten comparison, adjust the result. */
7350 if (cand->rewritten ())
7352 /* FIXME build_min_non_dep_op_overload can't handle rewrites. */
7353 if (overload)
7354 *overload = NULL_TREE;
7355 switch (code)
7357 case EQ_EXPR:
7358 gcc_checking_assert (cand->reversed ());
7359 gcc_fallthrough ();
7360 case NE_EXPR:
7361 if (result == error_mark_node)
7363 /* If a rewritten operator== candidate is selected by
7364 overload resolution for an operator @, its return type
7365 shall be cv bool.... */
7366 else if (TREE_CODE (TREE_TYPE (result)) != BOOLEAN_TYPE)
7368 if (complain & tf_error)
7370 auto_diagnostic_group d;
7371 error_at (loc, "return type of %qD is not %qs",
7372 cand->fn, "bool");
7373 inform (loc, "used as rewritten candidate for "
7374 "comparison of %qT and %qT",
7375 arg1_type, arg2_type);
7377 result = error_mark_node;
7379 else if (code == NE_EXPR)
7380 /* !(y == x) or !(x == y) */
7381 result = build1_loc (loc, TRUTH_NOT_EXPR,
7382 boolean_type_node, result);
7383 break;
7385 /* If a rewritten operator<=> candidate is selected by
7386 overload resolution for an operator @, x @ y is
7387 interpreted as 0 @ (y <=> x) if the selected candidate is
7388 a synthesized candidate with reversed order of parameters,
7389 or (x <=> y) @ 0 otherwise, using the selected rewritten
7390 operator<=> candidate. */
7391 case SPACESHIP_EXPR:
7392 if (!cand->reversed ())
7393 /* We're in the build_new_op call below for an outer
7394 reversed call; we don't need to do anything more. */
7395 break;
7396 gcc_fallthrough ();
7397 case LT_EXPR:
7398 case LE_EXPR:
7399 case GT_EXPR:
7400 case GE_EXPR:
7402 tree lhs = result;
7403 tree rhs = integer_zero_node;
7404 if (cand->reversed ())
7405 std::swap (lhs, rhs);
7406 warning_sentinel ws (warn_zero_as_null_pointer_constant);
7407 result = build_new_op (loc, code,
7408 LOOKUP_NORMAL|LOOKUP_REWRITTEN,
7409 lhs, rhs, NULL_TREE, lookups,
7410 NULL, complain);
7412 break;
7414 default:
7415 gcc_unreachable ();
7419 /* In an expression of the form `a[]' where cand->fn
7420 which is operator[] turns out to be a static member function,
7421 `a' is none-the-less evaluated. */
7422 if (code == ARRAY_REF)
7423 result = keep_unused_object_arg (result, arg1, cand->fn);
7425 else
7427 /* Give any warnings we noticed during overload resolution. */
7428 if (cand->warnings && (complain & tf_warning))
7430 struct candidate_warning *w;
7431 for (w = cand->warnings; w; w = w->next)
7432 joust (cand, w->loser, 1, complain);
7435 /* Check for comparison of different enum types. */
7436 switch (code)
7438 case GT_EXPR:
7439 case LT_EXPR:
7440 case GE_EXPR:
7441 case LE_EXPR:
7442 case EQ_EXPR:
7443 case NE_EXPR:
7444 if (TREE_CODE (arg1_type) == ENUMERAL_TYPE
7445 && TREE_CODE (arg2_type) == ENUMERAL_TYPE
7446 && (TYPE_MAIN_VARIANT (arg1_type)
7447 != TYPE_MAIN_VARIANT (arg2_type)))
7449 if (cxx_dialect >= cxx26
7450 && (complain & tf_warning_or_error) == 0)
7451 result = error_mark_node;
7452 else if (cxx_dialect >= cxx26 || (complain & tf_warning))
7453 emit_diagnostic (cxx_dialect >= cxx26
7454 ? DK_PEDWARN : DK_WARNING,
7455 loc, OPT_Wenum_compare,
7456 "comparison between %q#T and %q#T",
7457 arg1_type, arg2_type);
7459 break;
7460 default:
7461 break;
7464 /* "If a built-in candidate is selected by overload resolution, the
7465 operands of class type are converted to the types of the
7466 corresponding parameters of the selected operation function,
7467 except that the second standard conversion sequence of a
7468 user-defined conversion sequence (12.3.3.1.2) is not applied." */
7469 conversion *conv = cand->convs[0];
7470 if (conv->user_conv_p)
7472 conv = strip_standard_conversion (conv);
7473 arg1 = convert_like (conv, arg1, complain);
7476 if (arg2)
7478 conv = cand->convs[1];
7479 if (conv->user_conv_p)
7481 conv = strip_standard_conversion (conv);
7482 arg2 = convert_like (conv, arg2, complain);
7486 if (arg3)
7488 conv = cand->convs[2];
7489 if (conv->user_conv_p)
7491 conv = strip_standard_conversion (conv);
7492 arg3 = convert_like (conv, arg3, complain);
7498 if (result || result_valid_p)
7499 return result;
7501 builtin:
7502 switch (code)
7504 case MODIFY_EXPR:
7505 return cp_build_modify_expr (loc, arg1, code2, arg2, complain);
7507 case INDIRECT_REF:
7508 return cp_build_indirect_ref (loc, arg1, RO_UNARY_STAR, complain);
7510 case TRUTH_ANDIF_EXPR:
7511 case TRUTH_ORIF_EXPR:
7512 case TRUTH_AND_EXPR:
7513 case TRUTH_OR_EXPR:
7514 if ((complain & tf_warning) && !processing_template_decl)
7515 warn_logical_operator (loc, code, boolean_type_node,
7516 code_orig_arg1, arg1,
7517 code_orig_arg2, arg2);
7518 /* Fall through. */
7519 case GT_EXPR:
7520 case LT_EXPR:
7521 case GE_EXPR:
7522 case LE_EXPR:
7523 case EQ_EXPR:
7524 case NE_EXPR:
7525 if ((complain & tf_warning)
7526 && ((code_orig_arg1 == BOOLEAN_TYPE)
7527 ^ (code_orig_arg2 == BOOLEAN_TYPE)))
7528 maybe_warn_bool_compare (loc, code, arg1, arg2);
7529 if (complain & tf_warning && warn_tautological_compare)
7530 warn_tautological_cmp (loc, code, arg1, arg2);
7531 /* Fall through. */
7532 case SPACESHIP_EXPR:
7533 case PLUS_EXPR:
7534 case MINUS_EXPR:
7535 case MULT_EXPR:
7536 case TRUNC_DIV_EXPR:
7537 case MAX_EXPR:
7538 case MIN_EXPR:
7539 case LSHIFT_EXPR:
7540 case RSHIFT_EXPR:
7541 case TRUNC_MOD_EXPR:
7542 case BIT_AND_EXPR:
7543 case BIT_IOR_EXPR:
7544 case BIT_XOR_EXPR:
7545 return cp_build_binary_op (loc, code, arg1, arg2, complain);
7547 case UNARY_PLUS_EXPR:
7548 case NEGATE_EXPR:
7549 case BIT_NOT_EXPR:
7550 case TRUTH_NOT_EXPR:
7551 case PREINCREMENT_EXPR:
7552 case POSTINCREMENT_EXPR:
7553 case PREDECREMENT_EXPR:
7554 case POSTDECREMENT_EXPR:
7555 case REALPART_EXPR:
7556 case IMAGPART_EXPR:
7557 case ABS_EXPR:
7558 case CO_AWAIT_EXPR:
7559 return cp_build_unary_op (code, arg1, false, complain);
7561 case ARRAY_REF:
7562 return cp_build_array_ref (input_location, arg1, arg2, complain);
7564 case MEMBER_REF:
7565 return build_m_component_ref (cp_build_indirect_ref (loc, arg1,
7566 RO_ARROW_STAR,
7567 complain),
7568 arg2, complain);
7570 /* The caller will deal with these. */
7571 case ADDR_EXPR:
7572 case COMPONENT_REF:
7573 case COMPOUND_EXPR:
7574 return NULL_TREE;
7576 default:
7577 gcc_unreachable ();
7579 return NULL_TREE;
7582 /* Build a new call to operator[]. This may change ARGS. */
7584 tree
7585 build_op_subscript (const op_location_t &loc, tree obj,
7586 vec<tree, va_gc> **args, tree *overload,
7587 tsubst_flags_t complain)
7589 struct z_candidate *candidates = 0, *cand;
7590 tree fns, first_mem_arg = NULL_TREE;
7591 bool any_viable_p;
7592 tree result = NULL_TREE;
7594 auto_cond_timevar tv (TV_OVERLOAD);
7596 obj = mark_lvalue_use (obj);
7598 if (error_operand_p (obj))
7599 return error_mark_node;
7601 tree type = TREE_TYPE (obj);
7603 obj = prep_operand (obj);
7605 if (TYPE_BINFO (type))
7607 fns = lookup_fnfields (TYPE_BINFO (type), ovl_op_identifier (ARRAY_REF),
7608 1, complain);
7609 if (fns == error_mark_node)
7610 return error_mark_node;
7612 else
7613 fns = NULL_TREE;
7615 if (args != NULL && *args != NULL)
7617 *args = resolve_args (*args, complain);
7618 if (*args == NULL)
7619 return error_mark_node;
7622 conversion_obstack_sentinel cos;
7624 if (fns)
7626 first_mem_arg = obj;
7628 add_candidates (BASELINK_FUNCTIONS (fns),
7629 first_mem_arg, *args, NULL_TREE,
7630 NULL_TREE, false,
7631 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
7632 LOOKUP_NORMAL, &candidates, complain);
7635 /* Be strict here because if we choose a bad conversion candidate, the
7636 errors we get won't mention the call context. */
7637 candidates = splice_viable (candidates, true, &any_viable_p);
7638 if (!any_viable_p)
7640 if (complain & tf_error)
7642 auto_diagnostic_group d;
7643 error ("no match for call to %<%T::operator[] (%A)%>",
7644 TREE_TYPE (obj), build_tree_list_vec (*args));
7645 print_z_candidates (loc, candidates);
7647 result = error_mark_node;
7649 else
7651 cand = tourney (candidates, complain);
7652 if (cand == 0)
7654 if (complain & tf_error)
7656 auto_diagnostic_group d;
7657 error ("call of %<%T::operator[] (%A)%> is ambiguous",
7658 TREE_TYPE (obj), build_tree_list_vec (*args));
7659 print_z_candidates (loc, candidates);
7661 result = error_mark_node;
7663 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
7664 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
7665 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, ARRAY_REF))
7667 if (overload)
7668 *overload = cand->fn;
7669 result = build_over_call (cand, LOOKUP_NORMAL, complain);
7670 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7671 /* There won't be a CALL_EXPR. */;
7672 else if (result && result != error_mark_node)
7674 tree call = extract_call_expr (result);
7675 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7677 /* Specify evaluation order as per P0145R2. */
7678 CALL_EXPR_ORDERED_ARGS (call) = op_is_ordered (ARRAY_REF) == 1;
7681 /* In an expression of the form `a[]' where cand->fn
7682 which is operator[] turns out to be a static member function,
7683 `a' is none-the-less evaluated. */
7684 result = keep_unused_object_arg (result, obj, cand->fn);
7686 else
7687 gcc_unreachable ();
7690 return result;
7693 /* CALL was returned by some call-building function; extract the actual
7694 CALL_EXPR from any bits that have been tacked on, e.g. by
7695 convert_from_reference. */
7697 tree
7698 extract_call_expr (tree call)
7700 while (TREE_CODE (call) == COMPOUND_EXPR)
7701 call = TREE_OPERAND (call, 1);
7702 if (REFERENCE_REF_P (call))
7703 call = TREE_OPERAND (call, 0);
7704 if (TREE_CODE (call) == TARGET_EXPR)
7705 call = TARGET_EXPR_INITIAL (call);
7706 if (cxx_dialect >= cxx20)
7707 switch (TREE_CODE (call))
7709 /* C++20 rewritten comparison operators. */
7710 case TRUTH_NOT_EXPR:
7711 call = TREE_OPERAND (call, 0);
7712 break;
7713 case LT_EXPR:
7714 case LE_EXPR:
7715 case GT_EXPR:
7716 case GE_EXPR:
7717 case SPACESHIP_EXPR:
7719 tree op0 = TREE_OPERAND (call, 0);
7720 if (integer_zerop (op0))
7721 call = TREE_OPERAND (call, 1);
7722 else
7723 call = op0;
7725 break;
7726 default:;
7729 if (TREE_CODE (call) != CALL_EXPR
7730 && TREE_CODE (call) != AGGR_INIT_EXPR
7731 && call != error_mark_node)
7732 return NULL_TREE;
7733 return call;
7736 /* Returns true if FN has two parameters, of which the second has type
7737 size_t. */
7739 static bool
7740 second_parm_is_size_t (tree fn)
7742 tree t = FUNCTION_ARG_CHAIN (fn);
7743 if (!t || !same_type_p (TREE_VALUE (t), size_type_node))
7744 return false;
7745 t = TREE_CHAIN (t);
7746 if (t == void_list_node)
7747 return true;
7748 return false;
7751 /* True if T, an allocation function, has std::align_val_t as its second
7752 argument. */
7754 bool
7755 aligned_allocation_fn_p (tree t)
7757 if (!aligned_new_threshold)
7758 return false;
7760 tree a = FUNCTION_ARG_CHAIN (t);
7761 return (a && same_type_p (TREE_VALUE (a), align_type_node));
7764 /* True if T is std::destroying_delete_t. */
7766 static bool
7767 std_destroying_delete_t_p (tree t)
7769 return (TYPE_CONTEXT (t) == std_node
7770 && id_equal (TYPE_IDENTIFIER (t), "destroying_delete_t"));
7773 /* A deallocation function with at least two parameters whose second parameter
7774 type is of type std::destroying_delete_t is a destroying operator delete. A
7775 destroying operator delete shall be a class member function named operator
7776 delete. [ Note: Array deletion cannot use a destroying operator
7777 delete. --end note ] */
7779 tree
7780 destroying_delete_p (tree t)
7782 tree a = TYPE_ARG_TYPES (TREE_TYPE (t));
7783 if (!a || !TREE_CHAIN (a))
7784 return NULL_TREE;
7785 tree type = TREE_VALUE (TREE_CHAIN (a));
7786 return std_destroying_delete_t_p (type) ? type : NULL_TREE;
7789 struct dealloc_info
7791 bool sized;
7792 bool aligned;
7793 tree destroying;
7796 /* Returns true iff T, an element of an OVERLOAD chain, is a usual deallocation
7797 function (3.7.4.2 [basic.stc.dynamic.deallocation]). If so, and DI is
7798 non-null, also set *DI. */
7800 static bool
7801 usual_deallocation_fn_p (tree t, dealloc_info *di)
7803 if (di) *di = dealloc_info();
7805 /* A template instance is never a usual deallocation function,
7806 regardless of its signature. */
7807 if (TREE_CODE (t) == TEMPLATE_DECL
7808 || primary_template_specialization_p (t))
7809 return false;
7811 /* A usual deallocation function is a deallocation function whose parameters
7812 after the first are
7813 - optionally, a parameter of type std::destroying_delete_t, then
7814 - optionally, a parameter of type std::size_t, then
7815 - optionally, a parameter of type std::align_val_t. */
7816 bool global = DECL_NAMESPACE_SCOPE_P (t);
7817 tree chain = FUNCTION_ARG_CHAIN (t);
7818 if (chain && destroying_delete_p (t))
7820 if (di) di->destroying = TREE_VALUE (chain);
7821 chain = TREE_CHAIN (chain);
7823 if (chain
7824 && (!global || flag_sized_deallocation)
7825 && same_type_p (TREE_VALUE (chain), size_type_node))
7827 if (di) di->sized = true;
7828 chain = TREE_CHAIN (chain);
7830 if (chain && aligned_new_threshold
7831 && same_type_p (TREE_VALUE (chain), align_type_node))
7833 if (di) di->aligned = true;
7834 chain = TREE_CHAIN (chain);
7836 return (chain == void_list_node);
7839 /* Just return whether FN is a usual deallocation function. */
7841 bool
7842 usual_deallocation_fn_p (tree fn)
7844 return usual_deallocation_fn_p (fn, NULL);
7847 /* Build a call to operator delete. This has to be handled very specially,
7848 because the restrictions on what signatures match are different from all
7849 other call instances. For a normal delete, only a delete taking (void *)
7850 or (void *, size_t) is accepted. For a placement delete, only an exact
7851 match with the placement new is accepted.
7853 CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
7854 ADDR is the pointer to be deleted.
7855 SIZE is the size of the memory block to be deleted.
7856 GLOBAL_P is true if the delete-expression should not consider
7857 class-specific delete operators.
7858 CORO_P is true if the allocation is for a coroutine, where the two argument
7859 usual deallocation should be chosen in preference to the single argument
7860 version in a class context.
7861 PLACEMENT is the corresponding placement new call, or NULL_TREE.
7863 If this call to "operator delete" is being generated as part to
7864 deallocate memory allocated via a new-expression (as per [expr.new]
7865 which requires that if the initialization throws an exception then
7866 we call a deallocation function), then ALLOC_FN is the allocation
7867 function. */
7869 static tree
7870 build_op_delete_call_1 (enum tree_code code, tree addr, tree size,
7871 bool global_p, bool coro_p, tree placement,
7872 tree alloc_fn, tsubst_flags_t complain)
7874 tree fn = NULL_TREE;
7875 tree fns, fnname, type, t;
7876 dealloc_info di_fn = { };
7878 if (addr == error_mark_node)
7879 return error_mark_node;
7881 type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
7883 fnname = ovl_op_identifier (false, code);
7885 if (CLASS_TYPE_P (type)
7886 && COMPLETE_TYPE_P (complete_type (type))
7887 && !global_p)
7888 /* In [class.free]
7890 If the result of the lookup is ambiguous or inaccessible, or if
7891 the lookup selects a placement deallocation function, the
7892 program is ill-formed.
7894 Therefore, we ask lookup_fnfields to complain about ambiguity. */
7896 fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1, complain);
7897 if (fns == error_mark_node)
7898 return error_mark_node;
7900 else
7901 fns = NULL_TREE;
7903 if (fns == NULL_TREE)
7904 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
7906 /* Strip const and volatile from addr. */
7907 tree oaddr = addr;
7908 addr = cp_convert (ptr_type_node, addr, complain);
7910 tree excluded_destroying = NULL_TREE;
7912 if (placement)
7914 /* "A declaration of a placement deallocation function matches the
7915 declaration of a placement allocation function if it has the same
7916 number of parameters and, after parameter transformations (8.3.5),
7917 all parameter types except the first are identical."
7919 So we build up the function type we want and ask instantiate_type
7920 to get it for us. */
7921 t = FUNCTION_ARG_CHAIN (alloc_fn);
7922 t = tree_cons (NULL_TREE, ptr_type_node, t);
7923 t = build_function_type (void_type_node, t);
7925 fn = instantiate_type (t, fns, tf_none);
7926 if (fn == error_mark_node)
7927 return NULL_TREE;
7929 fn = MAYBE_BASELINK_FUNCTIONS (fn);
7931 /* "If the lookup finds the two-parameter form of a usual deallocation
7932 function (3.7.4.2) and that function, considered as a placement
7933 deallocation function, would have been selected as a match for the
7934 allocation function, the program is ill-formed." */
7935 if (second_parm_is_size_t (fn))
7937 const char *const msg1
7938 = G_("exception cleanup for this placement new selects "
7939 "non-placement %<operator delete%>");
7940 const char *const msg2
7941 = G_("%qD is a usual (non-placement) deallocation "
7942 "function in C++14 (or with %<-fsized-deallocation%>)");
7944 /* But if the class has an operator delete (void *), then that is
7945 the usual deallocation function, so we shouldn't complain
7946 about using the operator delete (void *, size_t). */
7947 if (DECL_CLASS_SCOPE_P (fn))
7948 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7950 if (usual_deallocation_fn_p (elt)
7951 && FUNCTION_ARG_CHAIN (elt) == void_list_node)
7952 goto ok;
7954 /* Before C++14 a two-parameter global deallocation function is
7955 always a placement deallocation function, but warn if
7956 -Wc++14-compat. */
7957 else if (!flag_sized_deallocation)
7959 if (complain & tf_warning)
7961 auto_diagnostic_group d;
7962 if (warning (OPT_Wc__14_compat, msg1))
7963 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7965 goto ok;
7968 if (complain & tf_warning_or_error)
7970 auto_diagnostic_group d;
7971 if (permerror (input_location, msg1))
7973 /* Only mention C++14 for namespace-scope delete. */
7974 if (DECL_NAMESPACE_SCOPE_P (fn))
7975 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
7976 else
7977 inform (DECL_SOURCE_LOCATION (fn),
7978 "%qD is a usual (non-placement) deallocation "
7979 "function", fn);
7982 else
7983 return error_mark_node;
7984 ok:;
7987 else
7988 /* "Any non-placement deallocation function matches a non-placement
7989 allocation function. If the lookup finds a single matching
7990 deallocation function, that function will be called; otherwise, no
7991 deallocation function will be called." */
7992 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
7994 dealloc_info di_elt;
7995 if (usual_deallocation_fn_p (elt, &di_elt))
7997 /* If we're called for an EH cleanup in a new-expression, we can't
7998 use a destroying delete; the exception was thrown before the
7999 object was constructed. */
8000 if (alloc_fn && di_elt.destroying)
8002 excluded_destroying = elt;
8003 continue;
8006 if (!fn)
8008 fn = elt;
8009 di_fn = di_elt;
8010 continue;
8013 /* -- If any of the deallocation functions is a destroying
8014 operator delete, all deallocation functions that are not
8015 destroying operator deletes are eliminated from further
8016 consideration. */
8017 if (di_elt.destroying != di_fn.destroying)
8019 if (di_elt.destroying)
8021 fn = elt;
8022 di_fn = di_elt;
8024 continue;
8027 /* -- If the type has new-extended alignment, a function with a
8028 parameter of type std::align_val_t is preferred; otherwise a
8029 function without such a parameter is preferred. If exactly one
8030 preferred function is found, that function is selected and the
8031 selection process terminates. If more than one preferred
8032 function is found, all non-preferred functions are eliminated
8033 from further consideration. */
8034 if (aligned_new_threshold)
8036 bool want_align = type_has_new_extended_alignment (type);
8037 if (di_elt.aligned != di_fn.aligned)
8039 if (want_align == di_elt.aligned)
8041 fn = elt;
8042 di_fn = di_elt;
8044 continue;
8048 /* -- If the deallocation functions have class scope, the one
8049 without a parameter of type std::size_t is selected. */
8050 bool want_size;
8051 if (DECL_CLASS_SCOPE_P (fn) && !coro_p)
8052 want_size = false;
8054 /* -- If the type is complete and if, for the second alternative
8055 (delete array) only, the operand is a pointer to a class type
8056 with a non-trivial destructor or a (possibly multi-dimensional)
8057 array thereof, the function with a parameter of type std::size_t
8058 is selected.
8060 -- Otherwise, it is unspecified whether a deallocation function
8061 with a parameter of type std::size_t is selected. */
8062 else
8064 want_size = COMPLETE_TYPE_P (type);
8065 if (code == VEC_DELETE_EXPR
8066 && !TYPE_VEC_NEW_USES_COOKIE (type))
8067 /* We need a cookie to determine the array size. */
8068 want_size = false;
8070 gcc_assert (di_fn.sized != di_elt.sized);
8071 if (want_size == di_elt.sized)
8073 fn = elt;
8074 di_fn = di_elt;
8079 /* If we have a matching function, call it. */
8080 if (fn)
8082 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
8084 /* If the FN is a member function, make sure that it is
8085 accessible. */
8086 if (BASELINK_P (fns))
8087 perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn,
8088 complain);
8090 /* Core issue 901: It's ok to new a type with deleted delete. */
8091 if (DECL_DELETED_FN (fn) && alloc_fn)
8092 return NULL_TREE;
8094 tree ret;
8095 if (placement)
8097 /* The placement args might not be suitable for overload
8098 resolution at this point, so build the call directly. */
8099 int nargs = call_expr_nargs (placement);
8100 tree *argarray = XALLOCAVEC (tree, nargs);
8101 int i;
8102 argarray[0] = addr;
8103 for (i = 1; i < nargs; i++)
8104 argarray[i] = CALL_EXPR_ARG (placement, i);
8105 if (!mark_used (fn, complain) && !(complain & tf_error))
8106 return error_mark_node;
8107 ret = build_cxx_call (fn, nargs, argarray, complain);
8109 else
8111 tree destroying = di_fn.destroying;
8112 if (destroying)
8114 /* Strip const and volatile from addr but retain the type of the
8115 object. */
8116 tree rtype = TREE_TYPE (TREE_TYPE (oaddr));
8117 rtype = cv_unqualified (rtype);
8118 rtype = TYPE_POINTER_TO (rtype);
8119 addr = cp_convert (rtype, oaddr, complain);
8120 destroying = build_functional_cast (input_location,
8121 destroying, NULL_TREE,
8122 complain);
8125 releasing_vec args;
8126 args->quick_push (addr);
8127 if (destroying)
8128 args->quick_push (destroying);
8129 if (di_fn.sized)
8130 args->quick_push (size);
8131 if (di_fn.aligned)
8133 tree al = build_int_cst (align_type_node, TYPE_ALIGN_UNIT (type));
8134 args->quick_push (al);
8136 ret = cp_build_function_call_vec (fn, &args, complain);
8139 /* Set this flag for all callers of this function. In addition to
8140 delete-expressions, this is called for deallocating coroutine state;
8141 treat that as an implicit delete-expression. This is also called for
8142 the delete if the constructor throws in a new-expression, and for a
8143 deleting destructor (which implements a delete-expression). */
8144 /* But leave this flag off for destroying delete to avoid wrong
8145 assumptions in the optimizers. */
8146 tree call = extract_call_expr (ret);
8147 if (TREE_CODE (call) == CALL_EXPR && !destroying_delete_p (fn))
8148 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
8150 return ret;
8153 /* If there's only a destroying delete that we can't use because the
8154 object isn't constructed yet, and we used global new, use global
8155 delete as well. */
8156 if (excluded_destroying
8157 && DECL_NAMESPACE_SCOPE_P (alloc_fn))
8158 return build_op_delete_call (code, addr, size, true, placement,
8159 alloc_fn, complain);
8161 /* [expr.new]
8163 If no unambiguous matching deallocation function can be found,
8164 propagating the exception does not cause the object's memory to
8165 be freed. */
8166 if (alloc_fn)
8168 if ((complain & tf_warning)
8169 && !placement)
8171 bool w = warning (0,
8172 "no corresponding deallocation function for %qD",
8173 alloc_fn);
8174 if (w && excluded_destroying)
8175 inform (DECL_SOURCE_LOCATION (excluded_destroying), "destroying "
8176 "delete %qD cannot be used to release the allocated memory"
8177 " if the initialization throws because the object is not "
8178 "constructed yet", excluded_destroying);
8180 return NULL_TREE;
8183 if (complain & tf_error)
8184 error ("no suitable %<operator %s%> for %qT",
8185 OVL_OP_INFO (false, code)->name, type);
8186 return error_mark_node;
8189 /* Arguments as per build_op_delete_call_1 (). */
8191 tree
8192 build_op_delete_call (enum tree_code code, tree addr, tree size, bool global_p,
8193 tree placement, tree alloc_fn, tsubst_flags_t complain)
8195 return build_op_delete_call_1 (code, addr, size, global_p, /*coro_p*/false,
8196 placement, alloc_fn, complain);
8199 /* Arguments as per build_op_delete_call_1 (). */
8201 tree
8202 build_coroutine_op_delete_call (enum tree_code code, tree addr, tree size,
8203 bool global_p, tree placement, tree alloc_fn,
8204 tsubst_flags_t complain)
8206 return build_op_delete_call_1 (code, addr, size, global_p, /*coro_p*/true,
8207 placement, alloc_fn, complain);
8210 /* Issue diagnostics about a disallowed access of DECL, using DIAG_DECL
8211 in the diagnostics.
8213 If ISSUE_ERROR is true, then issue an error about the access, followed
8214 by a note showing the declaration. Otherwise, just show the note.
8216 DIAG_DECL and DIAG_LOCATION will almost always be the same.
8217 DIAG_LOCATION is just another DECL. NO_ACCESS_REASON is an optional
8218 parameter used to specify why DECL wasn't accessible (e.g. ak_private
8219 would be because DECL was private). If not using NO_ACCESS_REASON,
8220 then it must be ak_none, and the access failure reason will be
8221 figured out by looking at the protection of DECL. */
8223 void
8224 complain_about_access (tree decl, tree diag_decl, tree diag_location,
8225 bool issue_error, access_kind no_access_reason)
8227 /* If we have not already figured out why DECL is inaccessible... */
8228 if (no_access_reason == ak_none)
8230 /* Examine the access of DECL to find out why. */
8231 if (TREE_PRIVATE (decl))
8232 no_access_reason = ak_private;
8233 else if (TREE_PROTECTED (decl))
8234 no_access_reason = ak_protected;
8237 /* Now generate an error message depending on calculated access. */
8238 if (no_access_reason == ak_private)
8240 if (issue_error)
8241 error ("%q#D is private within this context", diag_decl);
8242 inform (DECL_SOURCE_LOCATION (diag_location), "declared private here");
8244 else if (no_access_reason == ak_protected)
8246 if (issue_error)
8247 error ("%q#D is protected within this context", diag_decl);
8248 inform (DECL_SOURCE_LOCATION (diag_location), "declared protected here");
8250 /* Couldn't figure out why DECL is inaccesible, so just say it's
8251 inaccessible. */
8252 else
8254 if (issue_error)
8255 error ("%q#D is inaccessible within this context", diag_decl);
8256 inform (DECL_SOURCE_LOCATION (diag_decl), "declared here");
8260 /* Initialize a temporary of type TYPE with EXPR. The FLAGS are a
8261 bitwise or of LOOKUP_* values. If any errors are warnings are
8262 generated, set *DIAGNOSTIC_FN to "error" or "warning",
8263 respectively. If no diagnostics are generated, set *DIAGNOSTIC_FN
8264 to NULL. */
8266 static tree
8267 build_temp (tree expr, tree type, int flags,
8268 diagnostic_t *diagnostic_kind, tsubst_flags_t complain)
8270 int savew, savee;
8272 *diagnostic_kind = DK_UNSPECIFIED;
8274 /* If the source is a packed field, calling the copy constructor will require
8275 binding the field to the reference parameter to the copy constructor, and
8276 we'll end up with an infinite loop. If we can use a bitwise copy, then
8277 do that now. */
8278 if ((lvalue_kind (expr) & clk_packed)
8279 && CLASS_TYPE_P (TREE_TYPE (expr))
8280 && !type_has_nontrivial_copy_init (TREE_TYPE (expr)))
8281 return get_target_expr (expr, complain);
8283 /* In decltype, we might have decided not to wrap this call in a TARGET_EXPR.
8284 But it turns out to be a subexpression, so perform temporary
8285 materialization now. */
8286 if (TREE_CODE (expr) == CALL_EXPR
8287 && CLASS_TYPE_P (type)
8288 && same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
8289 expr = build_cplus_new (type, expr, complain);
8291 savew = warningcount + werrorcount, savee = errorcount;
8292 releasing_vec args (make_tree_vector_single (expr));
8293 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
8294 &args, type, flags, complain);
8295 if (warningcount + werrorcount > savew)
8296 *diagnostic_kind = DK_WARNING;
8297 else if (errorcount > savee)
8298 *diagnostic_kind = DK_ERROR;
8299 return expr;
8302 /* Get any location for EXPR, falling back to input_location.
8304 If the result is in a system header and is the virtual location for
8305 a token coming from the expansion of a macro, unwind it to the
8306 location of the expansion point of the macro (e.g. to avoid the
8307 diagnostic being suppressed for expansions of NULL where "NULL" is
8308 in a system header). */
8310 static location_t
8311 get_location_for_expr_unwinding_for_system_header (tree expr)
8313 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
8314 loc = expansion_point_location_if_in_system_header (loc);
8315 return loc;
8318 /* Perform warnings about peculiar, but valid, conversions from/to NULL.
8319 Also handle a subset of zero as null warnings.
8320 EXPR is implicitly converted to type TOTYPE.
8321 FN and ARGNUM are used for diagnostics. */
8323 static void
8324 conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
8326 /* Issue warnings about peculiar, but valid, uses of NULL. */
8327 if (TREE_CODE (totype) != BOOLEAN_TYPE
8328 && ARITHMETIC_TYPE_P (totype)
8329 && null_node_p (expr))
8331 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8332 if (fn)
8334 auto_diagnostic_group d;
8335 if (warning_at (loc, OPT_Wconversion_null,
8336 "passing NULL to non-pointer argument %P of %qD",
8337 argnum, fn))
8338 inform (get_fndecl_argument_location (fn, argnum),
8339 " declared here");
8341 else
8342 warning_at (loc, OPT_Wconversion_null,
8343 "converting to non-pointer type %qT from NULL", totype);
8346 /* Issue warnings if "false" is converted to a NULL pointer */
8347 else if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
8348 && TYPE_PTR_P (totype))
8350 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8351 if (fn)
8353 auto_diagnostic_group d;
8354 if (warning_at (loc, OPT_Wconversion_null,
8355 "converting %<false%> to pointer type for argument "
8356 "%P of %qD", argnum, fn))
8357 inform (get_fndecl_argument_location (fn, argnum),
8358 " declared here");
8360 else
8361 warning_at (loc, OPT_Wconversion_null,
8362 "converting %<false%> to pointer type %qT", totype);
8364 /* Handle zero as null pointer warnings for cases other
8365 than EQ_EXPR and NE_EXPR */
8366 else if ((TYPE_PTR_OR_PTRMEM_P (totype) || NULLPTR_TYPE_P (totype))
8367 && null_ptr_cst_p (expr))
8369 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8370 maybe_warn_zero_as_null_pointer_constant (expr, loc);
8374 /* We gave a diagnostic during a conversion. If this was in the second
8375 standard conversion sequence of a user-defined conversion sequence, say
8376 which user-defined conversion. */
8378 static void
8379 maybe_print_user_conv_context (conversion *convs)
8381 if (convs->user_conv_p)
8382 for (conversion *t = convs; t; t = next_conversion (t))
8383 if (t->kind == ck_user)
8385 print_z_candidate (0, N_(" after user-defined conversion:"),
8386 t->cand);
8387 break;
8391 /* Locate the parameter with the given index within FNDECL.
8392 ARGNUM is zero based, -1 indicates the `this' argument of a method.
8393 Return the location of the FNDECL itself if there are problems. */
8395 location_t
8396 get_fndecl_argument_location (tree fndecl, int argnum)
8398 /* The locations of implicitly-declared functions are likely to be
8399 more meaningful than those of their parameters. */
8400 if (DECL_ARTIFICIAL (fndecl))
8401 return DECL_SOURCE_LOCATION (fndecl);
8403 int i;
8404 tree param;
8406 /* Locate param by index within DECL_ARGUMENTS (fndecl). */
8407 for (i = 0, param = FUNCTION_FIRST_USER_PARM (fndecl);
8408 i < argnum && param;
8409 i++, param = TREE_CHAIN (param))
8412 /* If something went wrong (e.g. if we have a builtin and thus no arguments),
8413 return the location of FNDECL. */
8414 if (param == NULL)
8415 return DECL_SOURCE_LOCATION (fndecl);
8417 return DECL_SOURCE_LOCATION (param);
8420 /* If FNDECL is non-NULL, issue a note highlighting ARGNUM
8421 within its declaration (or the fndecl itself if something went
8422 wrong). */
8424 void
8425 maybe_inform_about_fndecl_for_bogus_argument_init (tree fn, int argnum,
8426 const char *highlight_color)
8428 if (fn)
8430 gcc_rich_location richloc (get_fndecl_argument_location (fn, argnum));
8431 richloc.set_highlight_color (highlight_color);
8432 inform (&richloc,
8433 " initializing argument %P of %qD", argnum, fn);
8437 /* Maybe warn about C++20 Conversions to arrays of unknown bound. C is
8438 the conversion, EXPR is the expression we're converting. */
8440 static void
8441 maybe_warn_array_conv (location_t loc, conversion *c, tree expr)
8443 if (cxx_dialect >= cxx20)
8444 return;
8446 tree type = TREE_TYPE (expr);
8447 type = strip_pointer_operator (type);
8449 if (TREE_CODE (type) != ARRAY_TYPE
8450 || TYPE_DOMAIN (type) == NULL_TREE)
8451 return;
8453 if (pedantic && conv_binds_to_array_of_unknown_bound (c))
8454 pedwarn (loc, OPT_Wc__20_extensions,
8455 "conversions to arrays of unknown bound "
8456 "are only available with %<-std=c++20%> or %<-std=gnu++20%>");
8459 /* We call this recursively in convert_like_internal. */
8460 static tree convert_like (conversion *, tree, tree, int, bool, bool, bool,
8461 tsubst_flags_t);
8463 /* Perform the conversions in CONVS on the expression EXPR. FN and
8464 ARGNUM are used for diagnostics. ARGNUM is zero based, -1
8465 indicates the `this' argument of a method. INNER is nonzero when
8466 being called to continue a conversion chain. It is negative when a
8467 reference binding will be applied, positive otherwise. If
8468 ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
8469 conversions will be emitted if appropriate. If C_CAST_P is true,
8470 this conversion is coming from a C-style cast; in that case,
8471 conversions to inaccessible bases are permitted. */
8473 static tree
8474 convert_like_internal (conversion *convs, tree expr, tree fn, int argnum,
8475 bool issue_conversion_warnings, bool c_cast_p,
8476 bool nested_p, tsubst_flags_t complain)
8478 tree totype = convs->type;
8479 diagnostic_t diag_kind;
8480 int flags;
8481 location_t loc = cp_expr_loc_or_input_loc (expr);
8483 if (convs->bad_p && !(complain & tf_error))
8484 return error_mark_node;
8486 if (convs->bad_p
8487 && convs->kind != ck_user
8488 && convs->kind != ck_list
8489 && convs->kind != ck_ambig
8490 && (convs->kind != ck_ref_bind
8491 || (convs->user_conv_p && next_conversion (convs)->bad_p))
8492 && (convs->kind != ck_rvalue
8493 || SCALAR_TYPE_P (totype))
8494 && convs->kind != ck_base)
8496 int complained = 0;
8497 conversion *t = convs;
8499 /* Give a helpful error if this is bad because of excess braces. */
8500 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8501 && SCALAR_TYPE_P (totype)
8502 && CONSTRUCTOR_NELTS (expr) > 0
8503 && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
8505 complained = permerror (loc, "too many braces around initializer "
8506 "for %qT", totype);
8507 while (BRACE_ENCLOSED_INITIALIZER_P (expr)
8508 && CONSTRUCTOR_NELTS (expr) == 1)
8509 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8512 /* Give a helpful error if this is bad because a conversion to bool
8513 from std::nullptr_t requires direct-initialization. */
8514 if (NULLPTR_TYPE_P (TREE_TYPE (expr))
8515 && TREE_CODE (totype) == BOOLEAN_TYPE)
8516 complained = permerror (loc, "converting to %qH from %qI requires "
8517 "direct-initialization",
8518 totype, TREE_TYPE (expr));
8520 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (expr))
8521 && SCALAR_FLOAT_TYPE_P (totype)
8522 && (extended_float_type_p (TREE_TYPE (expr))
8523 || extended_float_type_p (totype)))
8524 switch (cp_compare_floating_point_conversion_ranks (TREE_TYPE (expr),
8525 totype))
8527 case 2:
8528 if (pedwarn (loc, OPT_Wnarrowing, "ISO C++ does not allow "
8529 "converting to %qH from %qI with greater "
8530 "conversion rank", totype, TREE_TYPE (expr)))
8531 complained = 1;
8532 else if (!complained)
8533 complained = -1;
8534 break;
8535 case 3:
8536 if (pedwarn (loc, OPT_Wnarrowing, "ISO C++ does not allow "
8537 "converting to %qH from %qI with unordered "
8538 "conversion rank", totype, TREE_TYPE (expr)))
8539 complained = 1;
8540 else if (!complained)
8541 complained = -1;
8542 break;
8543 default:
8544 break;
8547 for (; t ; t = next_conversion (t))
8549 if (t->kind == ck_user && t->cand->reason)
8551 auto_diagnostic_group d;
8552 complained = permerror (loc, "invalid user-defined conversion "
8553 "from %qH to %qI", TREE_TYPE (expr),
8554 totype);
8555 if (complained)
8556 print_z_candidate (loc, N_("candidate is:"), t->cand);
8557 expr = convert_like (t, expr, fn, argnum,
8558 /*issue_conversion_warnings=*/false,
8559 /*c_cast_p=*/false, /*nested_p=*/true,
8560 complain);
8562 else if (t->kind == ck_user || !t->bad_p)
8564 expr = convert_like (t, expr, fn, argnum,
8565 /*issue_conversion_warnings=*/false,
8566 /*c_cast_p=*/false, /*nested_p=*/true,
8567 complain);
8568 if (t->bad_p)
8569 complained = 1;
8570 break;
8572 else if (t->kind == ck_ambig)
8573 return convert_like (t, expr, fn, argnum,
8574 /*issue_conversion_warnings=*/false,
8575 /*c_cast_p=*/false, /*nested_p=*/true,
8576 complain);
8577 else if (t->kind == ck_identity)
8578 break;
8580 if (!complained && expr != error_mark_node)
8582 range_label_for_type_mismatch label (TREE_TYPE (expr), totype);
8583 gcc_rich_location richloc (loc, &label, highlight_colors::percent_h);
8584 complained = permerror (&richloc,
8585 "invalid conversion from %qH to %qI",
8586 TREE_TYPE (expr), totype);
8588 if (convs->kind == ck_ref_bind)
8589 expr = convert_to_reference (totype, expr, CONV_IMPLICIT,
8590 LOOKUP_NORMAL, NULL_TREE,
8591 complain);
8592 else
8593 expr = cp_convert (totype, expr, complain);
8594 if (complained == 1)
8595 maybe_inform_about_fndecl_for_bogus_argument_init
8596 (fn, argnum, highlight_colors::percent_i);
8597 return expr;
8600 if (issue_conversion_warnings && (complain & tf_warning))
8601 conversion_null_warnings (totype, expr, fn, argnum);
8603 switch (convs->kind)
8605 case ck_user:
8607 struct z_candidate *cand = convs->cand;
8609 if (cand == NULL)
8610 /* We chose the surrogate function from add_conv_candidate, now we
8611 actually need to build the conversion. */
8612 cand = build_user_type_conversion_1 (totype, expr,
8613 LOOKUP_NO_CONVERSION, complain);
8615 tree convfn = cand->fn;
8617 /* When converting from an init list we consider explicit
8618 constructors, but actually trying to call one is an error. */
8619 if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn)
8620 && BRACE_ENCLOSED_INITIALIZER_P (expr)
8621 /* Unless this is for direct-list-initialization. */
8622 && (!CONSTRUCTOR_IS_DIRECT_INIT (expr) || convs->need_temporary_p)
8623 /* And in C++98 a default constructor can't be explicit. */
8624 && cxx_dialect >= cxx11)
8626 if (!(complain & tf_error))
8627 return error_mark_node;
8628 location_t loc = location_of (expr);
8629 if (CONSTRUCTOR_NELTS (expr) == 0
8630 && FUNCTION_FIRST_USER_PARMTYPE (convfn) != void_list_node)
8632 auto_diagnostic_group d;
8633 if (pedwarn (loc, 0, "converting to %qT from initializer list "
8634 "would use explicit constructor %qD",
8635 totype, convfn))
8637 inform (DECL_SOURCE_LOCATION (convfn), "%qD declared here",
8638 convfn);
8639 inform (loc, "in C++11 and above a default constructor "
8640 "can be explicit");
8643 else
8645 auto_diagnostic_group d;
8646 error ("converting to %qT from initializer list would use "
8647 "explicit constructor %qD", totype, convfn);
8648 inform (DECL_SOURCE_LOCATION (convfn), "%qD declared here",
8649 convfn);
8653 /* If we're initializing from {}, it's value-initialization. */
8654 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8655 && CONSTRUCTOR_NELTS (expr) == 0
8656 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype)
8657 && !processing_template_decl)
8659 if (abstract_virtuals_error (NULL_TREE, totype, complain))
8660 return error_mark_node;
8661 expr = build_value_init (totype, complain);
8662 expr = get_target_expr (expr, complain);
8663 if (expr != error_mark_node)
8664 TARGET_EXPR_LIST_INIT_P (expr) = true;
8665 return expr;
8668 /* We don't know here whether EXPR is being used as an lvalue or
8669 rvalue, but we know it's read. */
8670 mark_exp_read (expr);
8672 /* Give the conversion call the location of EXPR rather than the
8673 location of the context that caused the conversion. */
8674 iloc_sentinel ils (loc);
8676 /* Pass LOOKUP_NO_CONVERSION so rvalue/base handling knows not to allow
8677 any more UDCs. */
8678 expr = build_over_call (cand, LOOKUP_NORMAL|LOOKUP_NO_CONVERSION,
8679 complain);
8681 /* If this is a constructor or a function returning an aggr type,
8682 we need to build up a TARGET_EXPR. */
8683 if (DECL_CONSTRUCTOR_P (convfn))
8685 expr = build_cplus_new (totype, expr, complain);
8687 /* Remember that this was list-initialization. */
8688 if (convs->check_narrowing && expr != error_mark_node)
8689 TARGET_EXPR_LIST_INIT_P (expr) = true;
8692 return expr;
8694 case ck_identity:
8695 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
8697 int nelts = CONSTRUCTOR_NELTS (expr);
8698 if (nelts == 0)
8699 expr = build_value_init (totype, complain);
8700 else if (nelts == 1)
8701 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8702 else
8703 gcc_unreachable ();
8705 expr = mark_use (expr, /*rvalue_p=*/!convs->rvaluedness_matches_p,
8706 /*read_p=*/true, UNKNOWN_LOCATION,
8707 /*reject_builtin=*/true);
8709 if (type_unknown_p (expr))
8710 expr = instantiate_type (totype, expr, complain);
8711 if (!nested_p && TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
8712 expr = cp_convert (totype, TREE_OPERAND (expr, 0), complain);
8713 if (expr == null_node
8714 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
8715 /* If __null has been converted to an integer type, we do not want to
8716 continue to warn about uses of EXPR as an integer, rather than as a
8717 pointer. */
8718 expr = build_int_cst (totype, 0);
8719 return expr;
8720 case ck_ambig:
8721 /* We leave bad_p off ck_ambig because overload resolution considers
8722 it valid, it just fails when we try to perform it. So we need to
8723 check complain here, too. */
8724 if (complain & tf_error)
8726 /* Call build_user_type_conversion again for the error. */
8727 int flags = (convs->need_temporary_p
8728 ? LOOKUP_IMPLICIT : LOOKUP_NORMAL);
8729 build_user_type_conversion (totype, convs->u.expr, flags, complain);
8730 gcc_assert (seen_error ());
8731 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8733 return error_mark_node;
8735 case ck_list:
8737 /* Conversion to std::initializer_list<T>. */
8738 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
8739 unsigned len = CONSTRUCTOR_NELTS (expr);
8740 tree array;
8742 if (tree init = maybe_init_list_as_array (elttype, expr))
8744 elttype = cp_build_qualified_type
8745 (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
8746 array = build_array_of_n_type (elttype, len);
8747 array = build_vec_init_expr (array, init, complain);
8748 array = get_target_expr (array);
8749 array = cp_build_addr_expr (array, complain);
8751 else if (len)
8753 tree val; unsigned ix;
8755 tree new_ctor = build_constructor (init_list_type_node, NULL);
8757 /* Convert all the elements. */
8758 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
8760 tree sub = convert_like (convs->u.list[ix], val, fn,
8761 argnum, false, false,
8762 /*nested_p=*/true, complain);
8763 if (sub == error_mark_node)
8764 return sub;
8765 if (!BRACE_ENCLOSED_INITIALIZER_P (val)
8766 && !check_narrowing (TREE_TYPE (sub), val, complain))
8767 return error_mark_node;
8768 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor),
8769 NULL_TREE, sub);
8770 if (!TREE_CONSTANT (sub))
8771 TREE_CONSTANT (new_ctor) = false;
8773 /* Build up the array. */
8774 elttype = cp_build_qualified_type
8775 (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
8776 array = build_array_of_n_type (elttype, len);
8777 array = finish_compound_literal (array, new_ctor, complain);
8778 /* This is dubious now, should be blessed by P2752. */
8779 DECL_MERGEABLE (TARGET_EXPR_SLOT (array)) = true;
8780 array = cp_build_addr_expr (array, complain);
8782 else
8783 array = nullptr_node;
8785 array = cp_convert (build_pointer_type (elttype), array, complain);
8786 if (array == error_mark_node)
8787 return error_mark_node;
8789 /* Build up the initializer_list object. Note: fail gracefully
8790 if the object cannot be completed because, for example, no
8791 definition is provided (c++/80956). */
8792 totype = complete_type_or_maybe_complain (totype, NULL_TREE, complain);
8793 if (!totype)
8794 return error_mark_node;
8795 tree field = next_aggregate_field (TYPE_FIELDS (totype));
8796 vec<constructor_elt, va_gc> *vec = NULL;
8797 CONSTRUCTOR_APPEND_ELT (vec, field, array);
8798 field = next_aggregate_field (DECL_CHAIN (field));
8799 CONSTRUCTOR_APPEND_ELT (vec, field, size_int (len));
8800 tree new_ctor = build_constructor (totype, vec);
8801 return get_target_expr (new_ctor, complain);
8804 case ck_aggr:
8805 if (TREE_CODE (totype) == COMPLEX_TYPE)
8807 tree real = CONSTRUCTOR_ELT (expr, 0)->value;
8808 tree imag = CONSTRUCTOR_ELT (expr, 1)->value;
8809 real = perform_implicit_conversion (TREE_TYPE (totype),
8810 real, complain);
8811 imag = perform_implicit_conversion (TREE_TYPE (totype),
8812 imag, complain);
8813 expr = build2 (COMPLEX_EXPR, totype, real, imag);
8814 return expr;
8816 expr = reshape_init (totype, expr, complain);
8817 expr = get_target_expr (digest_init (totype, expr, complain),
8818 complain);
8819 if (expr != error_mark_node)
8820 TARGET_EXPR_LIST_INIT_P (expr) = true;
8821 return expr;
8823 default:
8824 break;
8827 conversion *nc = next_conversion (convs);
8828 if (convs->kind == ck_ref_bind && nc->kind == ck_qual
8829 && !convs->need_temporary_p)
8830 /* direct_reference_binding might have inserted a ck_qual under
8831 this ck_ref_bind for the benefit of conversion sequence ranking.
8832 Don't actually perform that conversion. */
8833 nc = next_conversion (nc);
8835 expr = convert_like (nc, expr, fn, argnum,
8836 convs->kind == ck_ref_bind
8837 ? issue_conversion_warnings : false,
8838 c_cast_p, /*nested_p=*/true, complain & ~tf_no_cleanup);
8839 if (expr == error_mark_node)
8840 return error_mark_node;
8842 switch (convs->kind)
8844 case ck_rvalue:
8845 expr = decay_conversion (expr, complain);
8846 if (expr == error_mark_node)
8848 if (complain & tf_error)
8850 auto_diagnostic_group d;
8851 maybe_print_user_conv_context (convs);
8852 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8854 return error_mark_node;
8857 if (! MAYBE_CLASS_TYPE_P (totype))
8858 return expr;
8860 /* Don't introduce copies when passing arguments along to the inherited
8861 constructor. */
8862 if (current_function_decl
8863 && flag_new_inheriting_ctors
8864 && DECL_INHERITED_CTOR (current_function_decl))
8865 return expr;
8867 if (TREE_CODE (expr) == TARGET_EXPR
8868 && TARGET_EXPR_LIST_INIT_P (expr))
8869 /* Copy-list-initialization doesn't actually involve a copy. */
8870 return expr;
8872 /* Fall through. */
8873 case ck_base:
8874 if (convs->kind == ck_base && !convs->need_temporary_p)
8876 /* We are going to bind a reference directly to a base-class
8877 subobject of EXPR. */
8878 /* Build an expression for `*((base*) &expr)'. */
8879 expr = convert_to_base (expr, totype,
8880 !c_cast_p, /*nonnull=*/true, complain);
8881 return expr;
8884 /* Copy-initialization where the cv-unqualified version of the source
8885 type is the same class as, or a derived class of, the class of the
8886 destination [is treated as direct-initialization]. [dcl.init] */
8887 flags = LOOKUP_NORMAL;
8888 /* This conversion is being done in the context of a user-defined
8889 conversion (i.e. the second step of copy-initialization), so
8890 don't allow any more. */
8891 if (convs->user_conv_p)
8892 flags |= LOOKUP_NO_CONVERSION;
8893 /* We might be performing a conversion of the argument
8894 to the user-defined conversion, i.e., not a conversion of the
8895 result of the user-defined conversion. In which case we skip
8896 explicit constructors. */
8897 if (convs->copy_init_p)
8898 flags |= LOOKUP_ONLYCONVERTING;
8899 expr = build_temp (expr, totype, flags, &diag_kind, complain);
8900 if (diag_kind && complain)
8902 auto_diagnostic_group d;
8903 maybe_print_user_conv_context (convs);
8904 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8907 return build_cplus_new (totype, expr, complain);
8909 case ck_ref_bind:
8911 tree ref_type = totype;
8913 if (convs->bad_p && !next_conversion (convs)->bad_p)
8915 tree extype = TREE_TYPE (expr);
8916 auto_diagnostic_group d;
8917 if (TYPE_REF_IS_RVALUE (ref_type)
8918 && lvalue_p (expr))
8919 error_at (loc, "cannot bind rvalue reference of type %qH to "
8920 "lvalue of type %qI", totype, extype);
8921 else if (!TYPE_REF_IS_RVALUE (ref_type) && !lvalue_p (expr)
8922 && !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (ref_type)))
8924 conversion *next = next_conversion (convs);
8925 if (next->kind == ck_std)
8927 next = next_conversion (next);
8928 error_at (loc, "cannot bind non-const lvalue reference of "
8929 "type %qH to a value of type %qI",
8930 totype, next->type);
8932 else if (!CP_TYPE_CONST_P (TREE_TYPE (ref_type)))
8933 error_at (loc, "cannot bind non-const lvalue reference of "
8934 "type %qH to an rvalue of type %qI", totype, extype);
8935 else // extype is volatile
8936 error_at (loc, "cannot bind lvalue reference of type "
8937 "%qH to an rvalue of type %qI", totype,
8938 extype);
8940 else if (!reference_compatible_p (TREE_TYPE (totype), extype))
8942 /* If we're converting from T[] to T[N], don't talk
8943 about discarding qualifiers. (Converting from T[N] to
8944 T[] is allowed by P0388R4.) */
8945 if (TREE_CODE (extype) == ARRAY_TYPE
8946 && TYPE_DOMAIN (extype) == NULL_TREE
8947 && TREE_CODE (TREE_TYPE (totype)) == ARRAY_TYPE
8948 && TYPE_DOMAIN (TREE_TYPE (totype)) != NULL_TREE)
8949 error_at (loc, "cannot bind reference of type %qH to %qI "
8950 "due to different array bounds", totype, extype);
8951 else
8952 error_at (loc, "binding reference of type %qH to %qI "
8953 "discards qualifiers", totype, extype);
8955 else
8956 gcc_unreachable ();
8957 maybe_print_user_conv_context (convs);
8958 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8960 return error_mark_node;
8962 else if (complain & tf_warning)
8963 maybe_warn_array_conv (loc, convs, expr);
8965 /* If necessary, create a temporary.
8967 VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
8968 that need temporaries, even when their types are reference
8969 compatible with the type of reference being bound, so the
8970 upcoming call to cp_build_addr_expr doesn't fail. */
8971 if (convs->need_temporary_p
8972 || TREE_CODE (expr) == CONSTRUCTOR
8973 || TREE_CODE (expr) == VA_ARG_EXPR)
8975 /* Otherwise, a temporary of type "cv1 T1" is created and
8976 initialized from the initializer expression using the rules
8977 for a non-reference copy-initialization (8.5). */
8979 tree type = TREE_TYPE (ref_type);
8980 cp_lvalue_kind lvalue = lvalue_kind (expr);
8982 gcc_assert (similar_type_p (type, next_conversion (convs)->type));
8983 if (!CP_TYPE_CONST_NON_VOLATILE_P (type)
8984 && !TYPE_REF_IS_RVALUE (ref_type))
8986 /* If the reference is volatile or non-const, we
8987 cannot create a temporary. */
8988 if (complain & tf_error)
8990 if (lvalue & clk_bitfield)
8991 error_at (loc, "cannot bind bit-field %qE to %qT",
8992 expr, ref_type);
8993 else if (lvalue & clk_packed)
8994 error_at (loc, "cannot bind packed field %qE to %qT",
8995 expr, ref_type);
8996 else
8997 error_at (loc, "cannot bind rvalue %qE to %qT",
8998 expr, ref_type);
9000 return error_mark_node;
9002 /* If the source is a packed field, and we must use a copy
9003 constructor, then building the target expr will require
9004 binding the field to the reference parameter to the
9005 copy constructor, and we'll end up with an infinite
9006 loop. If we can use a bitwise copy, then we'll be
9007 OK. */
9008 if ((lvalue & clk_packed)
9009 && CLASS_TYPE_P (type)
9010 && type_has_nontrivial_copy_init (type))
9012 error_at (loc, "cannot bind packed field %qE to %qT",
9013 expr, ref_type);
9014 return error_mark_node;
9016 if (lvalue & clk_bitfield)
9018 expr = convert_bitfield_to_declared_type (expr);
9019 expr = fold_convert (type, expr);
9022 /* Creating &TARGET_EXPR<> in a template would break when
9023 tsubsting the expression, so use an IMPLICIT_CONV_EXPR
9024 instead. This can happen even when there's no class
9025 involved, e.g., when converting an integer to a reference
9026 type. */
9027 if (processing_template_decl)
9028 return build1 (IMPLICIT_CONV_EXPR, totype, expr);
9029 expr = build_target_expr_with_type (expr, type, complain);
9032 /* Take the address of the thing to which we will bind the
9033 reference. */
9034 expr = cp_build_addr_expr (expr, complain);
9035 if (expr == error_mark_node)
9036 return error_mark_node;
9038 /* Convert it to a pointer to the type referred to by the
9039 reference. This will adjust the pointer if a derived to
9040 base conversion is being performed. */
9041 expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
9042 expr, complain);
9043 /* Convert the pointer to the desired reference type. */
9044 return build_nop (ref_type, expr);
9047 case ck_lvalue:
9048 return decay_conversion (expr, complain);
9050 case ck_fnptr:
9051 /* ??? Should the address of a transaction-safe pointer point to the TM
9052 clone, and this conversion look up the primary function? */
9053 return build_nop (totype, expr);
9055 case ck_qual:
9056 /* Warn about deprecated conversion if appropriate. */
9057 if (complain & tf_warning)
9059 string_conv_p (totype, expr, 1);
9060 maybe_warn_array_conv (loc, convs, expr);
9062 break;
9064 case ck_ptr:
9065 if (convs->base_p)
9066 expr = convert_to_base (expr, totype, !c_cast_p,
9067 /*nonnull=*/false, complain);
9068 return build_nop (totype, expr);
9070 case ck_pmem:
9071 return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
9072 c_cast_p, complain);
9074 default:
9075 break;
9078 if (convs->check_narrowing
9079 && !check_narrowing (totype, expr, complain,
9080 convs->check_narrowing_const_only))
9081 return error_mark_node;
9083 warning_sentinel w (warn_zero_as_null_pointer_constant);
9084 if (issue_conversion_warnings)
9085 expr = cp_convert_and_check (totype, expr, complain);
9086 else
9088 if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
9089 expr = TREE_OPERAND (expr, 0);
9090 expr = cp_convert (totype, expr, complain);
9093 return expr;
9096 /* Return true if converting FROM to TO is unsafe in a template. */
9098 static bool
9099 conv_unsafe_in_template_p (tree to, tree from)
9101 /* Converting classes involves TARGET_EXPR. */
9102 if (CLASS_TYPE_P (to) || CLASS_TYPE_P (from))
9103 return true;
9105 /* Converting real to integer produces FIX_TRUNC_EXPR which tsubst
9106 doesn't handle. */
9107 if (SCALAR_FLOAT_TYPE_P (from) && INTEGRAL_OR_ENUMERATION_TYPE_P (to))
9108 return true;
9110 /* Converting integer to real isn't a trivial conversion, either. */
9111 if (INTEGRAL_OR_ENUMERATION_TYPE_P (from) && SCALAR_FLOAT_TYPE_P (to))
9112 return true;
9114 return false;
9117 /* Wrapper for convert_like_internal that handles creating
9118 IMPLICIT_CONV_EXPR. */
9120 static tree
9121 convert_like (conversion *convs, tree expr, tree fn, int argnum,
9122 bool issue_conversion_warnings, bool c_cast_p, bool nested_p,
9123 tsubst_flags_t complain)
9125 /* Creating &TARGET_EXPR<> in a template breaks when substituting,
9126 and creating a CALL_EXPR in a template breaks in finish_call_expr
9127 so use an IMPLICIT_CONV_EXPR for this conversion. We would have
9128 created such codes e.g. when calling a user-defined conversion
9129 function. */
9130 tree conv_expr = NULL_TREE;
9131 if (processing_template_decl
9132 && convs->kind != ck_identity
9133 && conv_unsafe_in_template_p (convs->type, TREE_TYPE (expr)))
9135 conv_expr = build1 (IMPLICIT_CONV_EXPR, convs->type, expr);
9136 if (convs->kind != ck_ref_bind)
9137 conv_expr = convert_from_reference (conv_expr);
9138 if (!convs->bad_p)
9139 return conv_expr;
9140 /* Do the normal processing to give the bad_p errors. But we still
9141 need to return the IMPLICIT_CONV_EXPR, unless we're returning
9142 error_mark_node. */
9144 expr = convert_like_internal (convs, expr, fn, argnum,
9145 issue_conversion_warnings, c_cast_p,
9146 nested_p, complain);
9147 if (expr == error_mark_node)
9148 return error_mark_node;
9149 return conv_expr ? conv_expr : expr;
9152 /* Convenience wrapper for convert_like. */
9154 static inline tree
9155 convert_like (conversion *convs, tree expr, tsubst_flags_t complain)
9157 return convert_like (convs, expr, NULL_TREE, 0,
9158 /*issue_conversion_warnings=*/true,
9159 /*c_cast_p=*/false, /*nested_p=*/false, complain);
9162 /* Convenience wrapper for convert_like. */
9164 static inline tree
9165 convert_like_with_context (conversion *convs, tree expr, tree fn, int argnum,
9166 tsubst_flags_t complain)
9168 return convert_like (convs, expr, fn, argnum,
9169 /*issue_conversion_warnings=*/true,
9170 /*c_cast_p=*/false, /*nested_p=*/false, complain);
9173 /* ARG is being passed to a varargs function. Perform any conversions
9174 required. Return the converted value. */
9176 tree
9177 convert_arg_to_ellipsis (tree arg, tsubst_flags_t complain)
9179 tree arg_type = TREE_TYPE (arg);
9180 location_t loc = cp_expr_loc_or_input_loc (arg);
9182 /* [expr.call]
9184 If the argument has integral or enumeration type that is subject
9185 to the integral promotions (_conv.prom_), or a floating-point
9186 type that is subject to the floating-point promotion
9187 (_conv.fpprom_), the value of the argument is converted to the
9188 promoted type before the call. */
9189 if (SCALAR_FLOAT_TYPE_P (arg_type)
9190 && (TYPE_PRECISION (arg_type)
9191 < TYPE_PRECISION (double_type_node))
9192 && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (arg_type))
9193 && !extended_float_type_p (arg_type))
9195 if ((complain & tf_warning)
9196 && warn_double_promotion && !c_inhibit_evaluation_warnings)
9197 warning_at (loc, OPT_Wdouble_promotion,
9198 "implicit conversion from %qH to %qI when passing "
9199 "argument to function",
9200 arg_type, double_type_node);
9201 if (TREE_CODE (arg) == EXCESS_PRECISION_EXPR)
9202 arg = TREE_OPERAND (arg, 0);
9203 arg = mark_rvalue_use (arg);
9204 arg = convert_to_real_nofold (double_type_node, arg);
9206 else if (NULLPTR_TYPE_P (arg_type))
9208 arg = mark_rvalue_use (arg);
9209 if (TREE_SIDE_EFFECTS (arg))
9211 warning_sentinel w(warn_unused_result);
9212 arg = cp_build_compound_expr (arg, null_pointer_node, complain);
9214 else
9215 arg = null_pointer_node;
9217 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (arg_type))
9219 if (SCOPED_ENUM_P (arg_type))
9221 tree prom = cp_convert (ENUM_UNDERLYING_TYPE (arg_type), arg,
9222 complain);
9223 prom = cp_perform_integral_promotions (prom, complain);
9224 if (abi_version_crosses (6)
9225 && TYPE_MODE (TREE_TYPE (prom)) != TYPE_MODE (arg_type)
9226 && (complain & tf_warning))
9227 warning_at (loc, OPT_Wabi, "scoped enum %qT passed through %<...%>"
9228 " as %qT before %<-fabi-version=6%>, %qT after",
9229 arg_type,
9230 TREE_TYPE (prom), ENUM_UNDERLYING_TYPE (arg_type));
9231 if (!abi_version_at_least (6))
9232 arg = prom;
9234 else
9235 arg = cp_perform_integral_promotions (arg, complain);
9237 else
9238 /* [expr.call]
9240 The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
9241 standard conversions are performed. */
9242 arg = decay_conversion (arg, complain);
9244 arg = require_complete_type (arg, complain);
9245 arg_type = TREE_TYPE (arg);
9247 if (arg != error_mark_node
9248 /* In a template (or ill-formed code), we can have an incomplete type
9249 even after require_complete_type, in which case we don't know
9250 whether it has trivial copy or not. */
9251 && COMPLETE_TYPE_P (arg_type)
9252 && !cp_unevaluated_operand)
9254 /* [expr.call] 5.2.2/7:
9255 Passing a potentially-evaluated argument of class type (Clause 9)
9256 with a non-trivial copy constructor or a non-trivial destructor
9257 with no corresponding parameter is conditionally-supported, with
9258 implementation-defined semantics.
9260 We support it as pass-by-invisible-reference, just like a normal
9261 value parameter.
9263 If the call appears in the context of a sizeof expression,
9264 it is not potentially-evaluated. */
9265 if (type_has_nontrivial_copy_init (arg_type)
9266 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (arg_type))
9268 arg = force_rvalue (arg, complain);
9269 if (complain & tf_warning)
9270 warning (OPT_Wconditionally_supported,
9271 "passing objects of non-trivially-copyable "
9272 "type %q#T through %<...%> is conditionally supported",
9273 arg_type);
9274 return build1 (ADDR_EXPR, build_reference_type (arg_type), arg);
9276 /* Build up a real lvalue-to-rvalue conversion in case the
9277 copy constructor is trivial but not callable. */
9278 else if (CLASS_TYPE_P (arg_type))
9279 force_rvalue (arg, complain);
9283 return arg;
9286 /* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused. */
9288 tree
9289 build_x_va_arg (location_t loc, tree expr, tree type)
9291 if (processing_template_decl)
9293 tree r = build_min (VA_ARG_EXPR, type, expr);
9294 SET_EXPR_LOCATION (r, loc);
9295 return r;
9298 type = complete_type_or_else (type, NULL_TREE);
9300 if (expr == error_mark_node || !type)
9301 return error_mark_node;
9303 expr = mark_lvalue_use (expr);
9305 if (TYPE_REF_P (type))
9307 error ("cannot receive reference type %qT through %<...%>", type);
9308 return error_mark_node;
9311 if (type_has_nontrivial_copy_init (type)
9312 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
9314 /* conditionally-supported behavior [expr.call] 5.2.2/7. Let's treat
9315 it as pass by invisible reference. */
9316 warning_at (loc, OPT_Wconditionally_supported,
9317 "receiving objects of non-trivially-copyable type %q#T "
9318 "through %<...%> is conditionally-supported", type);
9320 tree ref = cp_build_reference_type (type, false);
9321 expr = build_va_arg (loc, expr, ref);
9322 return convert_from_reference (expr);
9325 tree ret = build_va_arg (loc, expr, type);
9326 if (CLASS_TYPE_P (type))
9327 /* Wrap the VA_ARG_EXPR in a TARGET_EXPR now so other code doesn't need to
9328 know how to handle it. */
9329 ret = get_target_expr (ret);
9330 return ret;
9333 /* TYPE has been given to va_arg. Apply the default conversions which
9334 would have happened when passed via ellipsis. Return the promoted
9335 type, or the passed type if there is no change. */
9337 tree
9338 cxx_type_promotes_to (tree type)
9340 tree promote;
9342 /* Perform the array-to-pointer and function-to-pointer
9343 conversions. */
9344 type = type_decays_to (type);
9346 promote = type_promotes_to (type);
9347 if (same_type_p (type, promote))
9348 promote = type;
9350 return promote;
9353 /* ARG is a default argument expression being passed to a parameter of
9354 the indicated TYPE, which is a parameter to FN. PARMNUM is the
9355 zero-based argument number. Do any required conversions. Return
9356 the converted value. */
9358 static GTY(()) vec<tree, va_gc> *default_arg_context;
9359 void
9360 push_defarg_context (tree fn)
9361 { vec_safe_push (default_arg_context, fn); }
9363 void
9364 pop_defarg_context (void)
9365 { default_arg_context->pop (); }
9367 tree
9368 convert_default_arg (tree type, tree arg, tree fn, int parmnum,
9369 tsubst_flags_t complain)
9371 int i;
9372 tree t;
9374 /* See through clones. */
9375 fn = DECL_ORIGIN (fn);
9376 /* And inheriting ctors. */
9377 if (flag_new_inheriting_ctors)
9378 fn = strip_inheriting_ctors (fn);
9380 /* Detect recursion. */
9381 FOR_EACH_VEC_SAFE_ELT (default_arg_context, i, t)
9382 if (t == fn)
9384 if (complain & tf_error)
9385 error ("recursive evaluation of default argument for %q#D", fn);
9386 return error_mark_node;
9389 /* If the ARG is an unparsed default argument expression, the
9390 conversion cannot be performed. */
9391 if (TREE_CODE (arg) == DEFERRED_PARSE)
9393 if (complain & tf_error)
9394 error ("call to %qD uses the default argument for parameter %P, which "
9395 "is not yet defined", fn, parmnum);
9396 return error_mark_node;
9399 push_defarg_context (fn);
9401 if (fn && DECL_TEMPLATE_INFO (fn))
9402 arg = tsubst_default_argument (fn, parmnum, type, arg, complain);
9404 /* Due to:
9406 [dcl.fct.default]
9408 The names in the expression are bound, and the semantic
9409 constraints are checked, at the point where the default
9410 expressions appears.
9412 we must not perform access checks here. */
9413 push_deferring_access_checks (dk_no_check);
9414 /* We must make a copy of ARG, in case subsequent processing
9415 alters any part of it. */
9416 arg = break_out_target_exprs (arg, /*clear location*/true);
9418 arg = convert_for_initialization (0, type, arg, LOOKUP_IMPLICIT,
9419 ICR_DEFAULT_ARGUMENT, fn, parmnum,
9420 complain);
9421 arg = convert_for_arg_passing (type, arg, complain);
9422 pop_deferring_access_checks();
9424 pop_defarg_context ();
9426 return arg;
9429 /* Returns the type which will really be used for passing an argument of
9430 type TYPE. */
9432 tree
9433 type_passed_as (tree type)
9435 /* Pass classes with copy ctors by invisible reference. */
9436 if (TREE_ADDRESSABLE (type))
9437 type = build_reference_type (type);
9438 else if (targetm.calls.promote_prototypes (NULL_TREE)
9439 && INTEGRAL_TYPE_P (type)
9440 && COMPLETE_TYPE_P (type)
9441 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9442 type = integer_type_node;
9444 return type;
9447 /* Actually perform the appropriate conversion. */
9449 tree
9450 convert_for_arg_passing (tree type, tree val, tsubst_flags_t complain)
9452 tree bitfield_type;
9454 /* If VAL is a bitfield, then -- since it has already been converted
9455 to TYPE -- it cannot have a precision greater than TYPE.
9457 If it has a smaller precision, we must widen it here. For
9458 example, passing "int f:3;" to a function expecting an "int" will
9459 not result in any conversion before this point.
9461 If the precision is the same we must not risk widening. For
9462 example, the COMPONENT_REF for a 32-bit "long long" bitfield will
9463 often have type "int", even though the C++ type for the field is
9464 "long long". If the value is being passed to a function
9465 expecting an "int", then no conversions will be required. But,
9466 if we call convert_bitfield_to_declared_type, the bitfield will
9467 be converted to "long long". */
9468 bitfield_type = is_bitfield_expr_with_lowered_type (val);
9469 if (bitfield_type
9470 && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
9471 val = convert_to_integer_nofold (TYPE_MAIN_VARIANT (bitfield_type), val);
9473 if (val == error_mark_node)
9475 /* Pass classes with copy ctors by invisible reference. */
9476 else if (TREE_ADDRESSABLE (type))
9477 val = build1 (ADDR_EXPR, build_reference_type (type), val);
9478 else if (targetm.calls.promote_prototypes (NULL_TREE)
9479 && INTEGRAL_TYPE_P (type)
9480 && COMPLETE_TYPE_P (type)
9481 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9482 val = cp_perform_integral_promotions (val, complain);
9483 if (complain & tf_warning)
9485 if (warn_suggest_attribute_format)
9487 tree rhstype = TREE_TYPE (val);
9488 const enum tree_code coder = TREE_CODE (rhstype);
9489 const enum tree_code codel = TREE_CODE (type);
9490 if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
9491 && coder == codel
9492 && check_missing_format_attribute (type, rhstype))
9493 warning (OPT_Wsuggest_attribute_format,
9494 "argument of function call might be a candidate "
9495 "for a format attribute");
9497 maybe_warn_parm_abi (type, cp_expr_loc_or_input_loc (val));
9500 if (complain & tf_warning)
9501 warn_for_address_of_packed_member (type, val);
9503 /* gimplify_arg elides TARGET_EXPRs that initialize a function argument,
9504 unless the initializer is a CONSTRUCTOR. In that case, we fail to
9505 elide the copy anyway. See that function for more information. */
9506 if (SIMPLE_TARGET_EXPR_P (val)
9507 && TREE_CODE (TARGET_EXPR_INITIAL (val)) != CONSTRUCTOR)
9508 set_target_expr_eliding (val);
9510 return val;
9513 /* Returns non-zero iff FN is a function with magic varargs, i.e. ones for
9514 which just decay_conversion or no conversions at all should be done.
9515 This is true for some builtins which don't act like normal functions.
9516 Return 2 if just decay_conversion and removal of excess precision should
9517 be done, 1 if just decay_conversion. Return 3 for special treatment of
9518 the 3rd argument for __builtin_*_overflow_p. Return 4 for special
9519 treatment of the 1st argument for
9520 __builtin_{clz,ctz,clrsb,ffs,parity,popcount}g. */
9523 magic_varargs_p (tree fn)
9525 if (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
9526 switch (DECL_FUNCTION_CODE (fn))
9528 case BUILT_IN_CLASSIFY_TYPE:
9529 case BUILT_IN_CONSTANT_P:
9530 case BUILT_IN_NEXT_ARG:
9531 case BUILT_IN_VA_START:
9532 return 1;
9534 case BUILT_IN_ADD_OVERFLOW_P:
9535 case BUILT_IN_SUB_OVERFLOW_P:
9536 case BUILT_IN_MUL_OVERFLOW_P:
9537 return 3;
9539 case BUILT_IN_ISFINITE:
9540 case BUILT_IN_ISINF:
9541 case BUILT_IN_ISINF_SIGN:
9542 case BUILT_IN_ISNAN:
9543 case BUILT_IN_ISNORMAL:
9544 case BUILT_IN_FPCLASSIFY:
9545 return 2;
9547 case BUILT_IN_CLZG:
9548 case BUILT_IN_CTZG:
9549 case BUILT_IN_CLRSBG:
9550 case BUILT_IN_FFSG:
9551 case BUILT_IN_PARITYG:
9552 case BUILT_IN_POPCOUNTG:
9553 return 4;
9555 default:
9556 return lookup_attribute ("type generic",
9557 TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
9560 return 0;
9563 /* Returns the decl of the dispatcher function if FN is a function version. */
9565 tree
9566 get_function_version_dispatcher (tree fn)
9568 tree dispatcher_decl = NULL;
9570 if (DECL_LOCAL_DECL_P (fn))
9571 fn = DECL_LOCAL_DECL_ALIAS (fn);
9573 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
9574 && DECL_FUNCTION_VERSIONED (fn));
9576 gcc_assert (targetm.get_function_versions_dispatcher);
9577 dispatcher_decl = targetm.get_function_versions_dispatcher (fn);
9579 if (dispatcher_decl == NULL)
9581 error_at (input_location, "use of multiversioned function "
9582 "without a default");
9583 return NULL;
9586 retrofit_lang_decl (dispatcher_decl);
9587 gcc_assert (dispatcher_decl != NULL);
9588 return dispatcher_decl;
9591 /* fn is a function version dispatcher that is marked used. Mark all the
9592 semantically identical function versions it will dispatch as used. */
9594 void
9595 mark_versions_used (tree fn)
9597 struct cgraph_node *node;
9598 struct cgraph_function_version_info *node_v;
9599 struct cgraph_function_version_info *it_v;
9601 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
9603 node = cgraph_node::get (fn);
9604 if (node == NULL)
9605 return;
9607 gcc_assert (node->dispatcher_function);
9609 node_v = node->function_version ();
9610 if (node_v == NULL)
9611 return;
9613 /* All semantically identical versions are chained. Traverse and mark each
9614 one of them as used. */
9615 it_v = node_v->next;
9616 while (it_v != NULL)
9618 mark_used (it_v->this_node->decl);
9619 it_v = it_v->next;
9623 /* Build a call to "the copy constructor" for the type of A, even if it
9624 wouldn't be selected by normal overload resolution. Used for
9625 diagnostics. */
9627 static tree
9628 call_copy_ctor (tree a, tsubst_flags_t complain)
9630 tree ctype = TYPE_MAIN_VARIANT (TREE_TYPE (a));
9631 tree binfo = TYPE_BINFO (ctype);
9632 tree copy = get_copy_ctor (ctype, complain);
9633 copy = build_baselink (binfo, binfo, copy, NULL_TREE);
9634 tree ob = build_dummy_object (ctype);
9635 releasing_vec args (make_tree_vector_single (a));
9636 tree r = build_new_method_call (ob, copy, &args, NULL_TREE,
9637 LOOKUP_NORMAL, NULL, complain);
9638 return r;
9641 /* Return the base constructor corresponding to COMPLETE_CTOR or NULL_TREE. */
9643 static tree
9644 base_ctor_for (tree complete_ctor)
9646 tree clone;
9647 FOR_EACH_CLONE (clone, DECL_CLONED_FUNCTION (complete_ctor))
9648 if (DECL_BASE_CONSTRUCTOR_P (clone))
9649 return clone;
9650 return NULL_TREE;
9653 /* Try to make EXP suitable to be used as the initializer for a base subobject,
9654 and return whether we were successful. EXP must have already been cleared
9655 by unsafe_copy_elision_p{,_opt}. */
9657 static bool
9658 make_base_init_ok (tree exp)
9660 if (TREE_CODE (exp) == TARGET_EXPR)
9661 exp = TARGET_EXPR_INITIAL (exp);
9662 while (TREE_CODE (exp) == COMPOUND_EXPR)
9663 exp = TREE_OPERAND (exp, 1);
9664 if (TREE_CODE (exp) == COND_EXPR)
9666 bool ret = make_base_init_ok (TREE_OPERAND (exp, 2));
9667 if (tree op1 = TREE_OPERAND (exp, 1))
9669 bool r1 = make_base_init_ok (op1);
9670 /* If unsafe_copy_elision_p was false, the arms should match. */
9671 gcc_assert (r1 == ret);
9673 return ret;
9675 if (TREE_CODE (exp) != AGGR_INIT_EXPR)
9676 /* A trivial copy is OK. */
9677 return true;
9678 if (!AGGR_INIT_VIA_CTOR_P (exp))
9679 /* unsafe_copy_elision_p_opt must have said this is OK. */
9680 return true;
9681 tree fn = cp_get_callee_fndecl_nofold (exp);
9682 if (DECL_BASE_CONSTRUCTOR_P (fn))
9683 return true;
9684 gcc_assert (DECL_COMPLETE_CONSTRUCTOR_P (fn));
9685 fn = base_ctor_for (fn);
9686 if (!fn || DECL_HAS_VTT_PARM_P (fn))
9687 /* The base constructor has more parameters, so we can't just change the
9688 call target. It would be possible to splice in the appropriate
9689 arguments, but probably not worth the complexity. */
9690 return false;
9691 mark_used (fn);
9692 AGGR_INIT_EXPR_FN (exp) = build_address (fn);
9693 return true;
9696 /* Return 2 if T refers to a base, 1 if a potentially-overlapping field,
9697 neither of which can be used for return by invisible reference. We avoid
9698 doing C++17 mandatory copy elision for either of these cases.
9700 This returns non-zero even if the type of T has no tail padding that other
9701 data could be allocated into, because that depends on the particular ABI.
9702 unsafe_copy_elision_p_opt does consider whether there is padding. */
9705 unsafe_return_slot_p (tree t)
9707 /* Check empty bases separately, they don't have fields. */
9708 if (is_empty_base_ref (t))
9709 return 2;
9711 /* A delegating constructor might be used to initialize a base. */
9712 if (current_function_decl
9713 && DECL_CONSTRUCTOR_P (current_function_decl)
9714 && (t == current_class_ref
9715 || tree_strip_nop_conversions (t) == current_class_ptr))
9716 return 2;
9718 STRIP_NOPS (t);
9719 if (TREE_CODE (t) == ADDR_EXPR)
9720 t = TREE_OPERAND (t, 0);
9721 if (TREE_CODE (t) == COMPONENT_REF)
9722 t = TREE_OPERAND (t, 1);
9723 if (TREE_CODE (t) != FIELD_DECL)
9724 return false;
9725 if (!CLASS_TYPE_P (TREE_TYPE (t)))
9726 /* The middle-end will do the right thing for scalar types. */
9727 return false;
9728 if (DECL_FIELD_IS_BASE (t))
9729 return 2;
9730 if (lookup_attribute ("no_unique_address", DECL_ATTRIBUTES (t)))
9731 return 1;
9732 return 0;
9735 /* True IFF EXP is a prvalue that represents return by invisible reference. */
9737 static bool
9738 init_by_return_slot_p (tree exp)
9740 /* Copy elision only happens with a TARGET_EXPR. */
9741 if (TREE_CODE (exp) != TARGET_EXPR)
9742 return false;
9743 tree init = TARGET_EXPR_INITIAL (exp);
9744 /* build_compound_expr pushes COMPOUND_EXPR inside TARGET_EXPR. */
9745 while (TREE_CODE (init) == COMPOUND_EXPR)
9746 init = TREE_OPERAND (init, 1);
9747 if (TREE_CODE (init) == COND_EXPR)
9749 /* We'll end up copying from each of the arms of the COND_EXPR directly
9750 into the target, so look at them. */
9751 if (tree op = TREE_OPERAND (init, 1))
9752 if (init_by_return_slot_p (op))
9753 return true;
9754 return init_by_return_slot_p (TREE_OPERAND (init, 2));
9756 return (TREE_CODE (init) == AGGR_INIT_EXPR
9757 && !AGGR_INIT_VIA_CTOR_P (init));
9760 /* We can't elide a copy from a function returning by value to a
9761 potentially-overlapping subobject, as the callee might clobber tail padding.
9762 Return true iff this could be that case.
9764 Places that use this function (or _opt) to decide to elide a copy should
9765 probably use make_safe_copy_elision instead. */
9767 bool
9768 unsafe_copy_elision_p (tree target, tree exp)
9770 return unsafe_return_slot_p (target) && init_by_return_slot_p (exp);
9773 /* As above, but for optimization allow more cases that are actually safe. */
9775 static bool
9776 unsafe_copy_elision_p_opt (tree target, tree exp)
9778 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (exp));
9779 /* It's safe to elide the copy for a class with no tail padding. */
9780 if (!is_empty_class (type)
9781 && tree_int_cst_equal (TYPE_SIZE (type), CLASSTYPE_SIZE (type)))
9782 return false;
9783 return unsafe_copy_elision_p (target, exp);
9786 /* Try to make EXP suitable to be used as the initializer for TARGET,
9787 and return whether we were successful. */
9789 bool
9790 make_safe_copy_elision (tree target, tree exp)
9792 int uns = unsafe_return_slot_p (target);
9793 if (!uns)
9794 return true;
9795 if (init_by_return_slot_p (exp))
9796 return false;
9797 if (uns == 1)
9798 return true;
9799 return make_base_init_ok (exp);
9802 /* True IFF the result of the conversion C is a prvalue. */
9804 static bool
9805 conv_is_prvalue (conversion *c)
9807 if (c->kind == ck_rvalue)
9808 return true;
9809 if (c->kind == ck_base && c->need_temporary_p)
9810 return true;
9811 if (c->kind == ck_user && !TYPE_REF_P (c->type))
9812 return true;
9813 if (c->kind == ck_identity && c->u.expr
9814 && TREE_CODE (c->u.expr) == TARGET_EXPR)
9815 return true;
9817 return false;
9820 /* True iff C is a conversion that binds a reference to a prvalue. */
9822 static bool
9823 conv_binds_ref_to_prvalue (conversion *c)
9825 if (c->kind != ck_ref_bind)
9826 return false;
9827 if (c->need_temporary_p)
9828 return true;
9830 return conv_is_prvalue (next_conversion (c));
9833 /* True iff EXPR represents a (subobject of a) temporary. */
9835 static bool
9836 expr_represents_temporary_p (tree expr)
9838 while (handled_component_p (expr))
9839 expr = TREE_OPERAND (expr, 0);
9840 return TREE_CODE (expr) == TARGET_EXPR;
9843 /* True iff C is a conversion that binds a reference to a temporary.
9844 This is a superset of conv_binds_ref_to_prvalue: here we're also
9845 interested in xvalues. */
9847 static bool
9848 conv_binds_ref_to_temporary (conversion *c)
9850 if (conv_binds_ref_to_prvalue (c))
9851 return true;
9852 if (c->kind != ck_ref_bind)
9853 return false;
9854 c = next_conversion (c);
9855 /* This is the case for
9856 struct Base {};
9857 struct Derived : Base {};
9858 const Base& b(Derived{});
9859 where we bind 'b' to the Base subobject of a temporary object of type
9860 Derived. The subobject is an xvalue; the whole object is a prvalue.
9862 The ck_base doesn't have to be present for cases like X{}.m. */
9863 if (c->kind == ck_base)
9864 c = next_conversion (c);
9865 if (c->kind == ck_identity && c->u.expr
9866 && expr_represents_temporary_p (c->u.expr))
9867 return true;
9868 return false;
9871 /* Return tristate::TS_TRUE if converting EXPR to a reference type TYPE binds
9872 the reference to a temporary. Return tristate::TS_FALSE if converting
9873 EXPR to a reference type TYPE doesn't bind the reference to a temporary. If
9874 the conversion is invalid or bad, return tristate::TS_UNKNOWN. DIRECT_INIT_P
9875 says whether the conversion should be done in direct- or copy-initialization
9876 context. */
9878 tristate
9879 ref_conv_binds_to_temporary (tree type, tree expr, bool direct_init_p/*=false*/)
9881 gcc_assert (TYPE_REF_P (type));
9883 conversion_obstack_sentinel cos;
9885 const int flags = direct_init_p ? LOOKUP_NORMAL : LOOKUP_IMPLICIT;
9886 conversion *conv = implicit_conversion (type, TREE_TYPE (expr), expr,
9887 /*c_cast_p=*/false, flags, tf_none);
9888 tristate ret (tristate::TS_UNKNOWN);
9889 if (conv && !conv->bad_p)
9890 ret = tristate (conv_binds_ref_to_temporary (conv));
9892 return ret;
9895 /* Call the trivial destructor for INSTANCE, which can be either an lvalue of
9896 class type or a pointer to class type. If NO_PTR_DEREF is true and
9897 INSTANCE has pointer type, clobber the pointer rather than what it points
9898 to. */
9900 tree
9901 build_trivial_dtor_call (tree instance, bool no_ptr_deref)
9903 gcc_assert (!is_dummy_object (instance));
9905 if (!flag_lifetime_dse)
9907 no_clobber:
9908 return fold_convert (void_type_node, instance);
9911 if (INDIRECT_TYPE_P (TREE_TYPE (instance))
9912 && (!no_ptr_deref || TYPE_REF_P (TREE_TYPE (instance))))
9914 if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (instance))))
9915 goto no_clobber;
9916 instance = cp_build_fold_indirect_ref (instance);
9919 /* A trivial destructor should still clobber the object. */
9920 tree clobber = build_clobber (TREE_TYPE (instance), CLOBBER_OBJECT_END);
9921 return build2 (MODIFY_EXPR, void_type_node,
9922 instance, clobber);
9925 /* Return true if in an immediate function context, or an unevaluated operand,
9926 or a default argument/member initializer, or a subexpression of an immediate
9927 invocation. */
9929 bool
9930 in_immediate_context ()
9932 return (cp_unevaluated_operand != 0
9933 || (current_function_decl != NULL_TREE
9934 && DECL_IMMEDIATE_FUNCTION_P (current_function_decl))
9935 /* DR 2631: default args and DMI aren't immediately evaluated.
9936 Return true here so immediate_invocation_p returns false. */
9937 || current_binding_level->kind == sk_function_parms
9938 || current_binding_level->kind == sk_template_parms
9939 || parsing_nsdmi ()
9940 || in_consteval_if_p);
9943 /* Return true if a call to FN with number of arguments NARGS
9944 is an immediate invocation. */
9946 bool
9947 immediate_invocation_p (tree fn)
9949 return (TREE_CODE (fn) == FUNCTION_DECL
9950 && DECL_IMMEDIATE_FUNCTION_P (fn)
9951 && !in_immediate_context ());
9954 /* Subroutine of the various build_*_call functions. Overload resolution
9955 has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
9956 ARGS is a TREE_LIST of the unconverted arguments to the call. FLAGS is a
9957 bitmask of various LOOKUP_* flags which apply to the call itself. */
9959 static tree
9960 build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
9962 tree fn = cand->fn;
9963 const vec<tree, va_gc> *args = cand->args;
9964 tree first_arg = cand->first_arg;
9965 conversion **convs = cand->convs;
9966 tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
9967 int parmlen;
9968 tree val;
9969 int nargs;
9970 tree *argarray;
9971 bool already_used = false;
9973 /* In a template, there is no need to perform all of the work that
9974 is normally done. We are only interested in the type of the call
9975 expression, i.e., the return type of the function. Any semantic
9976 errors will be deferred until the template is instantiated. */
9977 if (processing_template_decl)
9979 if (undeduced_auto_decl (fn))
9980 mark_used (fn, complain);
9981 else
9982 /* Otherwise set TREE_USED for the benefit of -Wunused-function.
9983 See PR80598. */
9984 TREE_USED (fn) = 1;
9986 tree return_type = TREE_TYPE (TREE_TYPE (fn));
9987 tree callee;
9988 if (first_arg == NULL_TREE)
9990 callee = build_addr_func (fn, complain);
9991 if (callee == error_mark_node)
9992 return error_mark_node;
9994 else
9996 callee = build_baselink (cand->conversion_path, cand->access_path,
9997 fn, NULL_TREE);
9998 callee = build_min (COMPONENT_REF, TREE_TYPE (fn),
9999 first_arg, callee, NULL_TREE);
10002 tree expr = build_call_vec (return_type, callee, args);
10003 SET_EXPR_LOCATION (expr, input_location);
10004 if (TREE_THIS_VOLATILE (fn) && cfun)
10005 current_function_returns_abnormally = 1;
10006 if (immediate_invocation_p (fn))
10008 tree obj_arg = NULL_TREE, exprimm = expr;
10009 if (DECL_CONSTRUCTOR_P (fn))
10010 obj_arg = first_arg;
10011 if (obj_arg
10012 && is_dummy_object (obj_arg)
10013 && !type_dependent_expression_p (obj_arg))
10015 exprimm = build_cplus_new (DECL_CONTEXT (fn), expr, complain);
10016 obj_arg = NULL_TREE;
10018 /* Look through *(const T *)&obj. */
10019 else if (obj_arg && INDIRECT_REF_P (obj_arg))
10021 tree addr = TREE_OPERAND (obj_arg, 0);
10022 STRIP_NOPS (addr);
10023 if (TREE_CODE (addr) == ADDR_EXPR)
10025 tree typeo = TREE_TYPE (obj_arg);
10026 tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
10027 if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
10028 obj_arg = TREE_OPERAND (addr, 0);
10031 fold_non_dependent_expr (exprimm, complain,
10032 /*manifestly_const_eval=*/true,
10033 obj_arg);
10035 return convert_from_reference (expr);
10038 /* Give any warnings we noticed during overload resolution. */
10039 if (cand->warnings && (complain & tf_warning))
10041 struct candidate_warning *w;
10042 for (w = cand->warnings; w; w = w->next)
10043 joust (cand, w->loser, 1, complain);
10046 /* Core issue 2327: P0135 doesn't say how to handle the case where the
10047 argument to the copy constructor ends up being a prvalue after
10048 conversion. Let's do the normal processing, but pretend we aren't
10049 actually using the copy constructor. */
10050 bool force_elide = false;
10051 if (cxx_dialect >= cxx17
10052 && cand->num_convs == 1
10053 && DECL_COMPLETE_CONSTRUCTOR_P (fn)
10054 && (DECL_COPY_CONSTRUCTOR_P (fn)
10055 || DECL_MOVE_CONSTRUCTOR_P (fn))
10056 && !unsafe_return_slot_p (first_arg)
10057 && conv_binds_ref_to_prvalue (convs[0]))
10059 force_elide = true;
10060 goto not_really_used;
10063 /* OK, we're actually calling this inherited constructor; set its deletedness
10064 appropriately. We can get away with doing this here because calling is
10065 the only way to refer to a constructor. */
10066 if (DECL_INHERITED_CTOR (fn)
10067 && !deduce_inheriting_ctor (fn))
10069 if (complain & tf_error)
10070 mark_used (fn);
10071 return error_mark_node;
10074 /* Make =delete work with SFINAE. */
10075 if (DECL_DELETED_FN (fn))
10077 if (complain & tf_error)
10079 mark_used (fn);
10080 if (cand->next)
10082 if (flag_diagnostics_all_candidates)
10083 print_z_candidates (input_location, cand, /*only_viable_p=*/false);
10084 else
10085 inform (input_location,
10086 "use %<-fdiagnostics-all-candidates%> to display "
10087 "considered candidates");
10090 return error_mark_node;
10093 if (DECL_FUNCTION_MEMBER_P (fn))
10095 tree access_fn;
10096 /* If FN is a template function, two cases must be considered.
10097 For example:
10099 struct A {
10100 protected:
10101 template <class T> void f();
10103 template <class T> struct B {
10104 protected:
10105 void g();
10107 struct C : A, B<int> {
10108 using A::f; // #1
10109 using B<int>::g; // #2
10112 In case #1 where `A::f' is a member template, DECL_ACCESS is
10113 recorded in the primary template but not in its specialization.
10114 We check access of FN using its primary template.
10116 In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
10117 because it is a member of class template B, DECL_ACCESS is
10118 recorded in the specialization `B<int>::g'. We cannot use its
10119 primary template because `B<T>::g' and `B<int>::g' may have
10120 different access. */
10121 if (DECL_TEMPLATE_INFO (fn)
10122 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
10123 access_fn = DECL_TI_TEMPLATE (fn);
10124 else
10125 access_fn = fn;
10126 if (!perform_or_defer_access_check (cand->access_path, access_fn,
10127 fn, complain))
10128 return error_mark_node;
10131 /* If we're checking for implicit delete, don't bother with argument
10132 conversions. */
10133 if (flags & LOOKUP_SPECULATIVE)
10135 if (cand->viable == 1)
10136 return fn;
10137 else if (!(complain & tf_error))
10138 /* Reject bad conversions now. */
10139 return error_mark_node;
10140 /* else continue to get conversion error. */
10143 not_really_used:
10145 /* N3276 magic doesn't apply to nested calls. */
10146 tsubst_flags_t decltype_flag = (complain & tf_decltype);
10147 complain &= ~tf_decltype;
10148 /* No-Cleanup doesn't apply to nested calls either. */
10149 tsubst_flags_t no_cleanup_complain = complain;
10150 complain &= ~tf_no_cleanup;
10152 /* Find maximum size of vector to hold converted arguments. */
10153 parmlen = list_length (parm);
10154 nargs = vec_safe_length (args) + (first_arg != NULL_TREE ? 1 : 0);
10155 if (parmlen > nargs)
10156 nargs = parmlen;
10157 argarray = XALLOCAVEC (tree, nargs);
10159 in_consteval_if_p_temp_override icip;
10160 /* If the call is immediate function invocation, make sure
10161 taking address of immediate functions is allowed in its arguments. */
10162 if (immediate_invocation_p (STRIP_TEMPLATE (fn)))
10163 in_consteval_if_p = true;
10165 int argarray_size = 0;
10166 unsigned int arg_index = 0;
10167 int conv_index = 0;
10168 int param_index = 0;
10170 auto consume_object_arg = [&arg_index, &first_arg, args]()
10172 if (!first_arg)
10173 return (*args)[arg_index++];
10174 tree object_arg = first_arg;
10175 first_arg = NULL_TREE;
10176 return object_arg;
10179 /* The implicit parameters to a constructor are not considered by overload
10180 resolution, and must be of the proper type. */
10181 if (DECL_CONSTRUCTOR_P (fn))
10183 tree object_arg = consume_object_arg ();
10184 argarray[argarray_size++] = build_this (object_arg);
10185 parm = TREE_CHAIN (parm);
10186 /* We should never try to call the abstract constructor. */
10187 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
10189 if (DECL_HAS_VTT_PARM_P (fn))
10191 argarray[argarray_size++] = (*args)[arg_index];
10192 ++arg_index;
10193 parm = TREE_CHAIN (parm);
10196 /* Bypass access control for 'this' parameter. */
10197 else if (DECL_IOBJ_MEMBER_FUNCTION_P (fn))
10199 tree arg = build_this (consume_object_arg ());
10200 tree argtype = TREE_TYPE (arg);
10202 if (arg == error_mark_node)
10203 return error_mark_node;
10204 if (convs[conv_index++]->bad_p)
10206 if (complain & tf_error)
10208 auto_diagnostic_group d;
10209 if (permerror (input_location, "passing %qT as %<this%> "
10210 "argument discards qualifiers",
10211 TREE_TYPE (argtype)))
10212 inform (DECL_SOURCE_LOCATION (fn), " in call to %qD", fn);
10214 else
10215 return error_mark_node;
10218 /* The class where FN is defined. */
10219 tree ctx = DECL_CONTEXT (fn);
10221 /* See if the function member or the whole class type is declared
10222 final and the call can be devirtualized. */
10223 if (DECL_FINAL_P (fn) || CLASSTYPE_FINAL (ctx))
10224 flags |= LOOKUP_NONVIRTUAL;
10226 /* [class.mfct.non-static]: If a non-static member function of a class
10227 X is called for an object that is not of type X, or of a type
10228 derived from X, the behavior is undefined.
10230 So we can assume that anything passed as 'this' is non-null, and
10231 optimize accordingly. */
10232 /* Check that the base class is accessible. */
10233 if (!accessible_base_p (TREE_TYPE (argtype),
10234 BINFO_TYPE (cand->conversion_path), true))
10236 if (complain & tf_error)
10237 error ("%qT is not an accessible base of %qT",
10238 BINFO_TYPE (cand->conversion_path),
10239 TREE_TYPE (argtype));
10240 else
10241 return error_mark_node;
10243 /* If fn was found by a using declaration, the conversion path
10244 will be to the derived class, not the base declaring fn. We
10245 must convert to the base. */
10246 tree base_binfo = cand->conversion_path;
10247 if (BINFO_TYPE (base_binfo) != ctx)
10249 base_binfo = lookup_base (base_binfo, ctx, ba_unique, NULL, complain);
10250 if (base_binfo == error_mark_node)
10251 return error_mark_node;
10254 /* If we know the dynamic type of the object, look up the final overrider
10255 in the BINFO. */
10256 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0
10257 && resolves_to_fixed_type_p (arg))
10259 tree ov = lookup_vfn_in_binfo (DECL_VINDEX (fn), base_binfo);
10261 /* And unwind base_binfo to match. If we don't find the type we're
10262 looking for in BINFO_INHERITANCE_CHAIN, we're looking at diamond
10263 inheritance; for now do a normal virtual call in that case. */
10264 tree octx = DECL_CONTEXT (ov);
10265 tree obinfo = base_binfo;
10266 while (obinfo && !SAME_BINFO_TYPE_P (BINFO_TYPE (obinfo), octx))
10267 obinfo = BINFO_INHERITANCE_CHAIN (obinfo);
10268 if (obinfo)
10270 fn = ov;
10271 base_binfo = obinfo;
10272 flags |= LOOKUP_NONVIRTUAL;
10276 tree converted_arg = build_base_path (PLUS_EXPR, arg,
10277 base_binfo, 1, complain);
10279 argarray[argarray_size++] = converted_arg;
10280 parm = TREE_CHAIN (parm);
10283 auto handle_arg = [fn, flags](tree type,
10284 tree arg,
10285 int const param_index,
10286 conversion *conv,
10287 tsubst_flags_t const arg_complain)
10289 /* Set user_conv_p on the argument conversions, so rvalue/base handling
10290 knows not to allow any more UDCs. This needs to happen after we
10291 process cand->warnings. */
10292 if (flags & LOOKUP_NO_CONVERSION)
10293 conv->user_conv_p = true;
10295 if (arg_complain & tf_warning)
10296 maybe_warn_pessimizing_move (arg, type, /*return_p=*/false);
10298 tree val = convert_like_with_context (conv, arg, fn,
10299 param_index, arg_complain);
10300 val = convert_for_arg_passing (type, val, arg_complain);
10301 return val;
10304 if (DECL_XOBJ_MEMBER_FUNCTION_P (fn))
10306 gcc_assert (cand->num_convs > 0);
10307 tree object_arg = consume_object_arg ();
10308 val = handle_arg (TREE_VALUE (parm),
10309 object_arg,
10310 param_index++,
10311 convs[conv_index++],
10312 complain);
10314 if (val == error_mark_node)
10315 return error_mark_node;
10316 else
10317 argarray[argarray_size++] = val;
10318 parm = TREE_CHAIN (parm);
10321 gcc_assert (first_arg == NULL_TREE);
10322 for (; arg_index < vec_safe_length (args) && parm;
10323 parm = TREE_CHAIN (parm), ++arg_index, ++param_index, ++conv_index)
10325 tree current_arg = (*args)[arg_index];
10327 /* If the argument is NULL and used to (implicitly) instantiate a
10328 template function (and bind one of the template arguments to
10329 the type of 'long int'), we don't want to warn about passing NULL
10330 to non-pointer argument.
10331 For example, if we have this template function:
10333 template<typename T> void func(T x) {}
10335 we want to warn (when -Wconversion is enabled) in this case:
10337 void foo() {
10338 func<int>(NULL);
10341 but not in this case:
10343 void foo() {
10344 func(NULL);
10347 bool const conversion_warning = !(null_node_p (current_arg)
10348 && DECL_TEMPLATE_INFO (fn)
10349 && cand->template_decl
10350 && !cand->explicit_targs);
10352 tsubst_flags_t const arg_complain
10353 = conversion_warning ? complain : complain & ~tf_warning;
10355 val = handle_arg (TREE_VALUE (parm),
10356 current_arg,
10357 param_index,
10358 convs[conv_index],
10359 arg_complain);
10361 if (val == error_mark_node)
10362 return error_mark_node;
10363 else
10364 argarray[argarray_size++] = val;
10367 /* Default arguments */
10368 for (; parm && parm != void_list_node;
10369 parm = TREE_CHAIN (parm), param_index++)
10371 if (TREE_VALUE (parm) == error_mark_node)
10372 return error_mark_node;
10373 val = convert_default_arg (TREE_VALUE (parm),
10374 TREE_PURPOSE (parm),
10375 fn, param_index,
10376 complain);
10377 if (val == error_mark_node)
10378 return error_mark_node;
10379 argarray[argarray_size++] = val;
10382 /* Ellipsis */
10383 int magic = magic_varargs_p (fn);
10384 for (; arg_index < vec_safe_length (args); ++arg_index)
10386 tree a = (*args)[arg_index];
10387 if ((magic == 3 && arg_index == 2) || (magic == 4 && arg_index == 0))
10389 /* Do no conversions for certain magic varargs. */
10390 a = mark_type_use (a);
10391 if (TREE_CODE (a) == FUNCTION_DECL && reject_gcc_builtin (a))
10392 return error_mark_node;
10394 else if (magic != 0)
10396 /* Don't truncate excess precision to the semantic type. */
10397 if (magic == 1 && TREE_CODE (a) == EXCESS_PRECISION_EXPR)
10398 a = TREE_OPERAND (a, 0);
10399 /* For other magic varargs only do decay_conversion. */
10400 a = decay_conversion (a, complain);
10402 else if (DECL_CONSTRUCTOR_P (fn)
10403 && vec_safe_length (args) == 1
10404 && same_type_ignoring_top_level_qualifiers_p (DECL_CONTEXT (fn),
10405 TREE_TYPE (a)))
10407 /* Avoid infinite recursion trying to call A(...). */
10408 if (complain & tf_error)
10409 /* Try to call the actual copy constructor for a good error. */
10410 call_copy_ctor (a, complain);
10411 return error_mark_node;
10413 else
10414 a = convert_arg_to_ellipsis (a, complain);
10415 if (a == error_mark_node)
10416 return error_mark_node;
10417 argarray[argarray_size++] = a;
10420 gcc_assert (argarray_size <= nargs);
10421 nargs = argarray_size;
10422 icip.reset ();
10424 /* Avoid performing argument transformation if warnings are disabled.
10425 When tf_warning is set and at least one of the warnings is active
10426 the check_function_arguments function might warn about something. */
10428 bool warned_p = false;
10429 if ((complain & tf_warning)
10430 && (warn_nonnull
10431 || warn_format
10432 || warn_suggest_attribute_format
10433 || warn_restrict))
10435 tree *fargs = (!nargs ? argarray
10436 : (tree *) alloca (nargs * sizeof (tree)));
10437 for (int j = 0; j < nargs; j++)
10439 /* For -Wformat undo the implicit passing by hidden reference
10440 done by convert_arg_to_ellipsis. */
10441 if (TREE_CODE (argarray[j]) == ADDR_EXPR
10442 && TYPE_REF_P (TREE_TYPE (argarray[j])))
10443 fargs[j] = TREE_OPERAND (argarray[j], 0);
10444 else
10445 fargs[j] = argarray[j];
10448 warned_p = check_function_arguments (input_location, fn, TREE_TYPE (fn),
10449 nargs, fargs, NULL,
10450 cp_comp_parm_types);
10453 if (DECL_INHERITED_CTOR (fn))
10455 /* Check for passing ellipsis arguments to an inherited constructor. We
10456 could handle this by open-coding the inherited constructor rather than
10457 defining it, but let's not bother now. */
10458 if (!cp_unevaluated_operand
10459 && cand->num_convs
10460 && cand->convs[cand->num_convs-1]->ellipsis_p)
10462 if (complain & tf_error)
10464 sorry ("passing arguments to ellipsis of inherited constructor "
10465 "%qD", cand->fn);
10466 inform (DECL_SOURCE_LOCATION (cand->fn), "declared here");
10468 return error_mark_node;
10471 /* A base constructor inheriting from a virtual base doesn't get the
10472 inherited arguments, just this and __vtt. */
10473 if (ctor_omit_inherited_parms (fn))
10474 nargs = 2;
10477 /* Avoid actually calling copy constructors and copy assignment operators,
10478 if possible. */
10480 if (!force_elide
10481 && (!flag_elide_constructors
10482 /* It's unsafe to elide the operation when handling
10483 a noexcept-expression, it may evaluate to the wrong
10484 value (c++/53025, c++/96090). */
10485 || cp_noexcept_operand != 0))
10486 /* Do things the hard way. */;
10487 else if (cand->num_convs == 1
10488 && (DECL_COPY_CONSTRUCTOR_P (fn)
10489 || DECL_MOVE_CONSTRUCTOR_P (fn)))
10491 tree targ;
10492 tree arg = argarray[num_artificial_parms_for (fn)];
10493 tree fa = argarray[0];
10494 bool trivial = trivial_fn_p (fn);
10496 /* Pull out the real argument, disregarding const-correctness. */
10497 targ = arg;
10498 /* Strip the reference binding for the constructor parameter. */
10499 if (CONVERT_EXPR_P (targ)
10500 && TYPE_REF_P (TREE_TYPE (targ)))
10501 targ = TREE_OPERAND (targ, 0);
10502 /* But don't strip any other reference bindings; binding a temporary to a
10503 reference prevents copy elision. */
10504 while ((CONVERT_EXPR_P (targ)
10505 && !TYPE_REF_P (TREE_TYPE (targ)))
10506 || TREE_CODE (targ) == NON_LVALUE_EXPR)
10507 targ = TREE_OPERAND (targ, 0);
10508 if (TREE_CODE (targ) == ADDR_EXPR)
10510 targ = TREE_OPERAND (targ, 0);
10511 if (!same_type_ignoring_top_level_qualifiers_p
10512 (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
10513 targ = NULL_TREE;
10515 else
10516 targ = NULL_TREE;
10518 if (targ)
10519 arg = targ;
10520 else
10521 arg = cp_build_fold_indirect_ref (arg);
10523 /* In C++17 we shouldn't be copying a TARGET_EXPR except into a
10524 potentially-overlapping subobject. */
10525 if (CHECKING_P && cxx_dialect >= cxx17)
10526 gcc_assert (TREE_CODE (arg) != TARGET_EXPR
10527 || force_elide
10528 /* It's from binding the ref parm to a packed field. */
10529 || convs[0]->need_temporary_p
10530 || seen_error ()
10531 /* See unsafe_copy_elision_p. */
10532 || unsafe_return_slot_p (fa));
10534 bool unsafe = unsafe_copy_elision_p_opt (fa, arg);
10535 bool eliding_temp = (TREE_CODE (arg) == TARGET_EXPR && !unsafe);
10537 /* [class.copy]: the copy constructor is implicitly defined even if the
10538 implementation elided its use. But don't warn about deprecation when
10539 eliding a temporary, as then no copy is actually performed. */
10540 warning_sentinel s (warn_deprecated_copy, eliding_temp);
10541 if (force_elide)
10542 /* The language says this isn't called. */;
10543 else if (!trivial)
10545 if (!mark_used (fn, complain) && !(complain & tf_error))
10546 return error_mark_node;
10547 already_used = true;
10549 else
10550 cp_handle_deprecated_or_unavailable (fn, complain);
10552 if (eliding_temp && DECL_BASE_CONSTRUCTOR_P (fn)
10553 && !make_base_init_ok (arg))
10554 unsafe = true;
10556 /* If we're creating a temp and we already have one, don't create a
10557 new one. If we're not creating a temp but we get one, use
10558 INIT_EXPR to collapse the temp into our target. Otherwise, if the
10559 ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
10560 temp or an INIT_EXPR otherwise. */
10561 if (is_dummy_object (fa))
10563 if (TREE_CODE (arg) == TARGET_EXPR)
10564 return arg;
10565 else if (trivial)
10566 return force_target_expr (DECL_CONTEXT (fn), arg, complain);
10568 else if ((trivial || TREE_CODE (arg) == TARGET_EXPR)
10569 && !unsafe)
10571 tree to = cp_build_fold_indirect_ref (fa);
10572 val = cp_build_init_expr (to, arg);
10573 return val;
10576 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
10577 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR)
10578 && trivial_fn_p (fn))
10580 tree to = cp_build_fold_indirect_ref (argarray[0]);
10581 tree type = TREE_TYPE (to);
10582 tree as_base = CLASSTYPE_AS_BASE (type);
10583 tree arg = argarray[1];
10584 location_t loc = cp_expr_loc_or_input_loc (arg);
10586 if (is_really_empty_class (type, /*ignore_vptr*/true))
10588 /* Avoid copying empty classes, but ensure op= returns an lvalue even
10589 if the object argument isn't one. This isn't needed in other cases
10590 since MODIFY_EXPR is always considered an lvalue. */
10591 to = cp_build_addr_expr (to, tf_none);
10592 to = cp_build_indirect_ref (input_location, to, RO_ARROW, complain);
10593 val = build2 (COMPOUND_EXPR, type, arg, to);
10594 suppress_warning (val, OPT_Wunused);
10596 else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
10598 if (is_std_init_list (type)
10599 && conv_binds_ref_to_prvalue (convs[1]))
10600 warning_at (loc, OPT_Winit_list_lifetime,
10601 "assignment from temporary %<initializer_list%> does "
10602 "not extend the lifetime of the underlying array");
10603 arg = cp_build_fold_indirect_ref (arg);
10604 val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
10606 else
10608 /* We must only copy the non-tail padding parts. */
10609 tree arg0, arg2, t;
10610 tree array_type, alias_set;
10612 arg2 = TYPE_SIZE_UNIT (as_base);
10613 to = cp_stabilize_reference (to);
10614 arg0 = cp_build_addr_expr (to, complain);
10616 array_type = build_array_type (unsigned_char_type_node,
10617 build_index_type
10618 (size_binop (MINUS_EXPR,
10619 arg2, size_int (1))));
10620 alias_set = build_int_cst (build_pointer_type (type), 0);
10621 t = build2 (MODIFY_EXPR, void_type_node,
10622 build2 (MEM_REF, array_type, arg0, alias_set),
10623 build2 (MEM_REF, array_type, arg, alias_set));
10624 val = build2 (COMPOUND_EXPR, TREE_TYPE (to), t, to);
10625 suppress_warning (val, OPT_Wunused);
10628 cp_handle_deprecated_or_unavailable (fn, complain);
10630 return val;
10632 else if (trivial_fn_p (fn))
10634 if (DECL_DESTRUCTOR_P (fn))
10635 return build_trivial_dtor_call (argarray[0]);
10636 else if (default_ctor_p (fn))
10638 if (is_dummy_object (argarray[0]))
10639 return force_target_expr (DECL_CONTEXT (fn), void_node,
10640 no_cleanup_complain);
10641 else
10642 return cp_build_fold_indirect_ref (argarray[0]);
10646 gcc_assert (!force_elide);
10648 if (!already_used
10649 && !mark_used (fn, complain))
10650 return error_mark_node;
10652 /* Warn if the built-in writes to an object of a non-trivial type. */
10653 if (warn_class_memaccess
10654 && vec_safe_length (args) >= 2
10655 && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
10656 maybe_warn_class_memaccess (input_location, fn, args);
10658 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
10660 tree t;
10661 tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
10662 DECL_CONTEXT (fn),
10663 ba_any, NULL, complain);
10664 gcc_assert (binfo && binfo != error_mark_node);
10666 argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1,
10667 complain);
10668 if (TREE_SIDE_EFFECTS (argarray[0]))
10669 argarray[0] = save_expr (argarray[0]);
10670 t = build_pointer_type (TREE_TYPE (fn));
10671 fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
10672 TREE_TYPE (fn) = t;
10674 else
10676 /* If FN is marked deprecated or unavailable, then we've already
10677 issued a diagnostic from mark_used above, so avoid redundantly
10678 issuing another one from build_addr_func. */
10679 auto w = make_temp_override (deprecated_state,
10680 UNAVAILABLE_DEPRECATED_SUPPRESS);
10682 fn = build_addr_func (fn, complain);
10683 if (fn == error_mark_node)
10684 return error_mark_node;
10686 /* We're actually invoking the function. (Immediate functions get an
10687 & when invoking it even though the user didn't use &.) */
10688 ADDR_EXPR_DENOTES_CALL_P (fn) = true;
10691 tree call = build_cxx_call (fn, nargs, argarray, complain|decltype_flag);
10692 if (call == error_mark_node)
10693 return call;
10694 if (cand->flags & LOOKUP_LIST_INIT_CTOR)
10696 tree c = extract_call_expr (call);
10697 /* build_new_op will clear this when appropriate. */
10698 CALL_EXPR_ORDERED_ARGS (c) = true;
10700 if (warned_p)
10702 tree c = extract_call_expr (call);
10703 if (TREE_CODE (c) == CALL_EXPR)
10704 suppress_warning (c /* Suppress all warnings. */);
10707 return call;
10710 namespace
10713 /* Return the DECL of the first non-static subobject of class TYPE
10714 that satisfies the predicate PRED or null if none can be found. */
10716 template <class Predicate>
10717 tree
10718 first_non_static_field (tree type, Predicate pred)
10720 if (!type || !CLASS_TYPE_P (type))
10721 return NULL_TREE;
10723 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
10725 if (TREE_CODE (field) != FIELD_DECL)
10726 continue;
10727 if (TREE_STATIC (field))
10728 continue;
10729 if (pred (field))
10730 return field;
10733 int i = 0;
10735 for (tree base_binfo, binfo = TYPE_BINFO (type);
10736 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
10738 tree base = TREE_TYPE (base_binfo);
10739 if (pred (base))
10740 return base;
10741 if (tree field = first_non_static_field (base, pred))
10742 return field;
10745 return NULL_TREE;
10748 struct NonPublicField
10750 bool operator() (const_tree t) const
10752 return DECL_P (t) && (TREE_PRIVATE (t) || TREE_PROTECTED (t));
10756 /* Return the DECL of the first non-public subobject of class TYPE
10757 or null if none can be found. */
10759 static inline tree
10760 first_non_public_field (tree type)
10762 return first_non_static_field (type, NonPublicField ());
10765 struct NonTrivialField
10767 bool operator() (const_tree t) const
10769 return !trivial_type_p (DECL_P (t) ? TREE_TYPE (t) : t);
10773 /* Return the DECL of the first non-trivial subobject of class TYPE
10774 or null if none can be found. */
10776 static inline tree
10777 first_non_trivial_field (tree type)
10779 return first_non_static_field (type, NonTrivialField ());
10782 } /* unnamed namespace */
10784 /* Return true if all copy and move assignment operator overloads for
10785 class TYPE are trivial and at least one of them is not deleted and,
10786 when ACCESS is set, accessible. Return false otherwise. Set
10787 HASASSIGN to true when the TYPE has a (not necessarily trivial)
10788 copy or move assignment. */
10790 static bool
10791 has_trivial_copy_assign_p (tree type, bool access, bool *hasassign)
10793 tree fns = get_class_binding (type, assign_op_identifier);
10794 bool all_trivial = true;
10796 /* Iterate over overloads of the assignment operator, checking
10797 accessible copy assignments for triviality. */
10799 for (tree f : ovl_range (fns))
10801 /* Skip operators that aren't copy assignments. */
10802 if (!copy_fn_p (f))
10803 continue;
10805 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10806 || accessible_p (TYPE_BINFO (type), f, true));
10808 /* Skip template assignment operators and deleted functions. */
10809 if (TREE_CODE (f) != FUNCTION_DECL || DECL_DELETED_FN (f))
10810 continue;
10812 if (accessible)
10813 *hasassign = true;
10815 if (!accessible || !trivial_fn_p (f))
10816 all_trivial = false;
10818 /* Break early when both properties have been determined. */
10819 if (*hasassign && !all_trivial)
10820 break;
10823 /* Return true if they're all trivial and one of the expressions
10824 TYPE() = TYPE() or TYPE() = (TYPE&)() is valid. */
10825 tree ref = cp_build_reference_type (type, false);
10826 return (all_trivial
10827 && (is_trivially_xible (MODIFY_EXPR, type, type)
10828 || is_trivially_xible (MODIFY_EXPR, type, ref)));
10831 /* Return true if all copy and move ctor overloads for class TYPE are
10832 trivial and at least one of them is not deleted and, when ACCESS is
10833 set, accessible. Return false otherwise. Set each element of HASCTOR[]
10834 to true when the TYPE has a (not necessarily trivial) default and copy
10835 (or move) ctor, respectively. */
10837 static bool
10838 has_trivial_copy_p (tree type, bool access, bool hasctor[2])
10840 tree fns = get_class_binding (type, complete_ctor_identifier);
10841 bool all_trivial = true;
10843 for (tree f : ovl_range (fns))
10845 /* Skip template constructors. */
10846 if (TREE_CODE (f) != FUNCTION_DECL)
10847 continue;
10849 bool cpy_or_move_ctor_p = copy_fn_p (f);
10851 /* Skip ctors other than default, copy, and move. */
10852 if (!cpy_or_move_ctor_p && !default_ctor_p (f))
10853 continue;
10855 if (DECL_DELETED_FN (f))
10856 continue;
10858 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
10859 || accessible_p (TYPE_BINFO (type), f, true));
10861 if (accessible)
10862 hasctor[cpy_or_move_ctor_p] = true;
10864 if (cpy_or_move_ctor_p && (!accessible || !trivial_fn_p (f)))
10865 all_trivial = false;
10867 /* Break early when both properties have been determined. */
10868 if (hasctor[0] && hasctor[1] && !all_trivial)
10869 break;
10872 return all_trivial;
10875 /* Issue a warning on a call to the built-in function FNDECL if it is
10876 a raw memory write whose destination is not an object of (something
10877 like) trivial or standard layout type with a non-deleted assignment
10878 and copy ctor. Detects const correctness violations, corrupting
10879 references, virtual table pointers, and bypassing non-trivial
10880 assignments. */
10882 static void
10883 maybe_warn_class_memaccess (location_t loc, tree fndecl,
10884 const vec<tree, va_gc> *args)
10886 /* Except for bcopy where it's second, the destination pointer is
10887 the first argument for all functions handled here. Compute
10888 the index of the destination and source arguments. */
10889 unsigned dstidx = DECL_FUNCTION_CODE (fndecl) == BUILT_IN_BCOPY;
10890 unsigned srcidx = !dstidx;
10892 tree dest = (*args)[dstidx];
10893 if (!TREE_TYPE (dest)
10894 || (TREE_CODE (TREE_TYPE (dest)) != ARRAY_TYPE
10895 && !INDIRECT_TYPE_P (TREE_TYPE (dest))))
10896 return;
10898 tree srctype = NULL_TREE;
10900 /* Determine the type of the pointed-to object and whether it's
10901 a complete class type. */
10902 tree desttype = TREE_TYPE (TREE_TYPE (dest));
10904 if (!desttype || !COMPLETE_TYPE_P (desttype) || !CLASS_TYPE_P (desttype))
10905 return;
10907 /* Check to see if the raw memory call is made by a non-static member
10908 function with THIS as the destination argument for the destination
10909 type. If so, and if the class has no non-trivial bases or members,
10910 be more permissive. */
10911 if (current_function_decl
10912 && DECL_OBJECT_MEMBER_FUNCTION_P (current_function_decl)
10913 && is_object_parameter (tree_strip_nop_conversions (dest)))
10915 tree ctx = DECL_CONTEXT (current_function_decl);
10916 bool special = same_type_ignoring_top_level_qualifiers_p (ctx, desttype);
10917 tree binfo = TYPE_BINFO (ctx);
10919 if (special
10920 && !BINFO_VTABLE (binfo)
10921 && !first_non_trivial_field (desttype))
10922 return;
10925 /* True if the class is trivial. */
10926 bool trivial = trivial_type_p (desttype);
10928 /* Set to true if DESTYPE has an accessible copy assignment. */
10929 bool hasassign = false;
10930 /* True if all of the class' overloaded copy assignment operators
10931 are all trivial (and not deleted) and at least one of them is
10932 accessible. */
10933 bool trivassign = has_trivial_copy_assign_p (desttype, true, &hasassign);
10935 /* Set to true if DESTTYPE has an accessible default and copy ctor,
10936 respectively. */
10937 bool hasctors[2] = { false, false };
10939 /* True if all of the class' overloaded copy constructors are all
10940 trivial (and not deleted) and at least one of them is accessible. */
10941 bool trivcopy = has_trivial_copy_p (desttype, true, hasctors);
10943 /* Set FLD to the first private/protected member of the class. */
10944 tree fld = trivial ? first_non_public_field (desttype) : NULL_TREE;
10946 /* The warning format string. */
10947 const char *warnfmt = NULL;
10948 /* A suggested alternative to offer instead of the raw memory call.
10949 Empty string when none can be come up with. */
10950 const char *suggest = "";
10951 bool warned = false;
10953 switch (DECL_FUNCTION_CODE (fndecl))
10955 case BUILT_IN_MEMSET:
10956 if (!integer_zerop (maybe_constant_value ((*args)[1])))
10958 /* Diagnose setting non-copy-assignable or non-trivial types,
10959 or types with a private member, to (potentially) non-zero
10960 bytes. Since the value of the bytes being written is unknown,
10961 suggest using assignment instead (if one exists). Also warn
10962 for writes into objects for which zero-initialization doesn't
10963 mean all bits clear (pointer-to-member data, where null is all
10964 bits set). Since the value being written is (most likely)
10965 non-zero, simply suggest assignment (but not copy assignment). */
10966 suggest = "; use assignment instead";
10967 if (!trivassign)
10968 warnfmt = G_("%qD writing to an object of type %#qT with "
10969 "no trivial copy-assignment");
10970 else if (!trivial)
10971 warnfmt = G_("%qD writing to an object of non-trivial type %#qT%s");
10972 else if (fld)
10974 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
10975 warned = warning_at (loc, OPT_Wclass_memaccess,
10976 "%qD writing to an object of type %#qT with "
10977 "%qs member %qD",
10978 fndecl, desttype, access, fld);
10980 else if (!zero_init_p (desttype))
10981 warnfmt = G_("%qD writing to an object of type %#qT containing "
10982 "a pointer to data member%s");
10984 break;
10986 /* Fall through. */
10988 case BUILT_IN_BZERO:
10989 /* Similarly to the above, diagnose clearing non-trivial or non-
10990 standard layout objects, or objects of types with no assignmenmt.
10991 Since the value being written is known to be zero, suggest either
10992 copy assignment, copy ctor, or default ctor as an alternative,
10993 depending on what's available. */
10995 if (hasassign && hasctors[0])
10996 suggest = G_("; use assignment or value-initialization instead");
10997 else if (hasassign)
10998 suggest = G_("; use assignment instead");
10999 else if (hasctors[0])
11000 suggest = G_("; use value-initialization instead");
11002 if (!trivassign)
11003 warnfmt = G_("%qD clearing an object of type %#qT with "
11004 "no trivial copy-assignment%s");
11005 else if (!trivial)
11006 warnfmt = G_("%qD clearing an object of non-trivial type %#qT%s");
11007 else if (!zero_init_p (desttype))
11008 warnfmt = G_("%qD clearing an object of type %#qT containing "
11009 "a pointer-to-member%s");
11010 break;
11012 case BUILT_IN_BCOPY:
11013 case BUILT_IN_MEMCPY:
11014 case BUILT_IN_MEMMOVE:
11015 case BUILT_IN_MEMPCPY:
11016 /* Determine the type of the source object. */
11017 srctype = TREE_TYPE ((*args)[srcidx]);
11018 if (!srctype || !INDIRECT_TYPE_P (srctype))
11019 srctype = void_type_node;
11020 else
11021 srctype = TREE_TYPE (srctype);
11023 /* Since it's impossible to determine wheter the byte copy is
11024 being used in place of assignment to an existing object or
11025 as a substitute for initialization, assume it's the former.
11026 Determine the best alternative to use instead depending on
11027 what's not deleted. */
11028 if (hasassign && hasctors[1])
11029 suggest = G_("; use copy-assignment or copy-initialization instead");
11030 else if (hasassign)
11031 suggest = G_("; use copy-assignment instead");
11032 else if (hasctors[1])
11033 suggest = G_("; use copy-initialization instead");
11035 if (!trivassign)
11036 warnfmt = G_("%qD writing to an object of type %#qT with no trivial "
11037 "copy-assignment%s");
11038 else if (!trivially_copyable_p (desttype))
11039 warnfmt = G_("%qD writing to an object of non-trivially copyable "
11040 "type %#qT%s");
11041 else if (!trivcopy)
11042 warnfmt = G_("%qD writing to an object with a deleted copy constructor");
11044 else if (!trivial
11045 && !VOID_TYPE_P (srctype)
11046 && !is_byte_access_type (srctype)
11047 && !same_type_ignoring_top_level_qualifiers_p (desttype,
11048 srctype))
11050 /* Warn when copying into a non-trivial object from an object
11051 of a different type other than void or char. */
11052 warned = warning_at (loc, OPT_Wclass_memaccess,
11053 "%qD copying an object of non-trivial type "
11054 "%#qT from an array of %#qT",
11055 fndecl, desttype, srctype);
11057 else if (fld
11058 && !VOID_TYPE_P (srctype)
11059 && !is_byte_access_type (srctype)
11060 && !same_type_ignoring_top_level_qualifiers_p (desttype,
11061 srctype))
11063 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
11064 warned = warning_at (loc, OPT_Wclass_memaccess,
11065 "%qD copying an object of type %#qT with "
11066 "%qs member %qD from an array of %#qT; use "
11067 "assignment or copy-initialization instead",
11068 fndecl, desttype, access, fld, srctype);
11070 else if (!trivial && vec_safe_length (args) > 2)
11072 tree sz = maybe_constant_value ((*args)[2]);
11073 if (!tree_fits_uhwi_p (sz))
11074 break;
11076 /* Finally, warn on partial copies. */
11077 unsigned HOST_WIDE_INT typesize
11078 = tree_to_uhwi (TYPE_SIZE_UNIT (desttype));
11079 if (typesize == 0)
11080 break;
11081 if (unsigned HOST_WIDE_INT partial = tree_to_uhwi (sz) % typesize)
11082 warned = warning_at (loc, OPT_Wclass_memaccess,
11083 (typesize - partial > 1
11084 ? G_("%qD writing to an object of "
11085 "a non-trivial type %#qT leaves %wu "
11086 "bytes unchanged")
11087 : G_("%qD writing to an object of "
11088 "a non-trivial type %#qT leaves %wu "
11089 "byte unchanged")),
11090 fndecl, desttype, typesize - partial);
11092 break;
11094 case BUILT_IN_REALLOC:
11096 if (!trivially_copyable_p (desttype))
11097 warnfmt = G_("%qD moving an object of non-trivially copyable type "
11098 "%#qT; use %<new%> and %<delete%> instead");
11099 else if (!trivcopy)
11100 warnfmt = G_("%qD moving an object of type %#qT with deleted copy "
11101 "constructor; use %<new%> and %<delete%> instead");
11102 else if (!get_dtor (desttype, tf_none))
11103 warnfmt = G_("%qD moving an object of type %#qT with deleted "
11104 "destructor");
11105 else if (!trivial)
11107 tree sz = maybe_constant_value ((*args)[1]);
11108 if (TREE_CODE (sz) == INTEGER_CST
11109 && tree_int_cst_lt (sz, TYPE_SIZE_UNIT (desttype)))
11110 /* Finally, warn on reallocation into insufficient space. */
11111 warned = warning_at (loc, OPT_Wclass_memaccess,
11112 "%qD moving an object of non-trivial type "
11113 "%#qT and size %E into a region of size %E",
11114 fndecl, desttype, TYPE_SIZE_UNIT (desttype),
11115 sz);
11117 break;
11119 default:
11120 return;
11123 if (warnfmt)
11125 if (suggest)
11126 warned = warning_at (loc, OPT_Wclass_memaccess,
11127 warnfmt, fndecl, desttype, suggest);
11128 else
11129 warned = warning_at (loc, OPT_Wclass_memaccess,
11130 warnfmt, fndecl, desttype);
11133 if (warned)
11134 inform (location_of (desttype), "%#qT declared here", desttype);
11137 /* Build and return a call to FN, using NARGS arguments in ARGARRAY.
11138 If FN is the result of resolving an overloaded target built-in,
11139 ORIG_FNDECL is the original function decl, otherwise it is null.
11140 This function performs no overload resolution, conversion, or other
11141 high-level operations. */
11143 tree
11144 build_cxx_call (tree fn, int nargs, tree *argarray,
11145 tsubst_flags_t complain, tree orig_fndecl)
11147 tree fndecl;
11149 /* Remember roughly where this call is. */
11150 location_t loc = cp_expr_loc_or_input_loc (fn);
11151 fn = build_call_a (fn, nargs, argarray);
11152 SET_EXPR_LOCATION (fn, loc);
11154 fndecl = get_callee_fndecl (fn);
11155 if (!orig_fndecl)
11156 orig_fndecl = fndecl;
11158 /* Check that arguments to builtin functions match the expectations. */
11159 if (fndecl
11160 && !processing_template_decl
11161 && fndecl_built_in_p (fndecl))
11163 int i;
11165 /* We need to take care that values to BUILT_IN_NORMAL
11166 are reduced. */
11167 for (i = 0; i < nargs; i++)
11168 argarray[i] = maybe_constant_value (argarray[i]);
11170 if (!check_builtin_function_arguments (EXPR_LOCATION (fn), vNULL, fndecl,
11171 orig_fndecl, nargs, argarray))
11172 return error_mark_node;
11173 else if (fndecl_built_in_p (fndecl, BUILT_IN_CLEAR_PADDING))
11175 tree arg0 = argarray[0];
11176 STRIP_NOPS (arg0);
11177 if (TREE_CODE (arg0) == ADDR_EXPR
11178 && DECL_P (TREE_OPERAND (arg0, 0))
11179 && same_type_ignoring_top_level_qualifiers_p
11180 (TREE_TYPE (TREE_TYPE (argarray[0])),
11181 TREE_TYPE (TREE_TYPE (arg0))))
11182 /* For __builtin_clear_padding (&var) we know the type
11183 is for a complete object, so there is no risk in clearing
11184 padding that is reused in some derived class member. */;
11185 else if (!trivially_copyable_p (TREE_TYPE (TREE_TYPE (argarray[0]))))
11187 error_at (EXPR_LOC_OR_LOC (argarray[0], input_location),
11188 "argument %u in call to function %qE "
11189 "has pointer to a non-trivially-copyable type (%qT)",
11190 1, fndecl, TREE_TYPE (argarray[0]));
11191 return error_mark_node;
11196 if (VOID_TYPE_P (TREE_TYPE (fn)))
11197 return fn;
11199 /* 5.2.2/11: If a function call is a prvalue of object type: if the
11200 function call is either the operand of a decltype-specifier or the
11201 right operand of a comma operator that is the operand of a
11202 decltype-specifier, a temporary object is not introduced for the
11203 prvalue. The type of the prvalue may be incomplete. */
11204 if (!(complain & tf_decltype))
11206 fn = require_complete_type (fn, complain);
11207 if (fn == error_mark_node)
11208 return error_mark_node;
11210 if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
11212 fn = build_cplus_new (TREE_TYPE (fn), fn, complain);
11213 maybe_warn_parm_abi (TREE_TYPE (fn), loc);
11216 return convert_from_reference (fn);
11219 /* Returns the value to use for the in-charge parameter when making a
11220 call to a function with the indicated NAME.
11222 FIXME:Can't we find a neater way to do this mapping? */
11224 tree
11225 in_charge_arg_for_name (tree name)
11227 if (IDENTIFIER_CTOR_P (name))
11229 if (name == complete_ctor_identifier)
11230 return integer_one_node;
11231 gcc_checking_assert (name == base_ctor_identifier);
11233 else
11235 if (name == complete_dtor_identifier)
11236 return integer_two_node;
11237 else if (name == deleting_dtor_identifier)
11238 /* The deleting dtor should now be handled by
11239 build_delete_destructor_body. */
11240 gcc_unreachable ();
11241 gcc_checking_assert (name == base_dtor_identifier);
11244 return integer_zero_node;
11247 /* We've built up a constructor call RET. Complain if it delegates to the
11248 constructor we're currently compiling. */
11250 static void
11251 check_self_delegation (tree ret)
11253 if (TREE_CODE (ret) == TARGET_EXPR)
11254 ret = TARGET_EXPR_INITIAL (ret);
11255 tree fn = cp_get_callee_fndecl_nofold (ret);
11256 if (fn && DECL_ABSTRACT_ORIGIN (fn) == current_function_decl)
11257 error ("constructor delegates to itself");
11260 /* Build a call to a constructor, destructor, or an assignment
11261 operator for INSTANCE, an expression with class type. NAME
11262 indicates the special member function to call; *ARGS are the
11263 arguments. ARGS may be NULL. This may change ARGS. BINFO
11264 indicates the base of INSTANCE that is to be passed as the `this'
11265 parameter to the member function called.
11267 FLAGS are the LOOKUP_* flags to use when processing the call.
11269 If NAME indicates a complete object constructor, INSTANCE may be
11270 NULL_TREE. In this case, the caller will call build_cplus_new to
11271 store the newly constructed object into a VAR_DECL. */
11273 tree
11274 build_special_member_call (tree instance, tree name, vec<tree, va_gc> **args,
11275 tree binfo, int flags, tsubst_flags_t complain)
11277 tree fns;
11278 /* The type of the subobject to be constructed or destroyed. */
11279 tree class_type;
11280 vec<tree, va_gc> *allocated = NULL;
11281 tree ret;
11283 gcc_assert (IDENTIFIER_CDTOR_P (name) || name == assign_op_identifier);
11285 if (error_operand_p (instance))
11286 return error_mark_node;
11288 if (IDENTIFIER_DTOR_P (name))
11290 gcc_assert (args == NULL || vec_safe_is_empty (*args));
11291 if (!type_build_dtor_call (TREE_TYPE (instance)))
11292 /* Shortcut to avoid lazy destructor declaration. */
11293 return build_trivial_dtor_call (instance);
11296 if (TYPE_P (binfo))
11298 /* Resolve the name. */
11299 if (!complete_type_or_maybe_complain (binfo, NULL_TREE, complain))
11300 return error_mark_node;
11302 binfo = TYPE_BINFO (binfo);
11305 gcc_assert (binfo != NULL_TREE);
11307 class_type = BINFO_TYPE (binfo);
11309 /* Handle the special case where INSTANCE is NULL_TREE. */
11310 if (name == complete_ctor_identifier && !instance)
11311 instance = build_dummy_object (class_type);
11312 else
11314 /* Convert to the base class, if necessary. */
11315 if (!same_type_ignoring_top_level_qualifiers_p
11316 (TREE_TYPE (instance), BINFO_TYPE (binfo)))
11318 if (IDENTIFIER_CDTOR_P (name))
11319 /* For constructors and destructors, either the base is
11320 non-virtual, or it is virtual but we are doing the
11321 conversion from a constructor or destructor for the
11322 complete object. In either case, we can convert
11323 statically. */
11324 instance = convert_to_base_statically (instance, binfo);
11325 else
11327 /* However, for assignment operators, we must convert
11328 dynamically if the base is virtual. */
11329 gcc_checking_assert (name == assign_op_identifier);
11330 instance = build_base_path (PLUS_EXPR, instance,
11331 binfo, /*nonnull=*/1, complain);
11336 gcc_assert (instance != NULL_TREE);
11338 /* In C++17, "If the initializer expression is a prvalue and the
11339 cv-unqualified version of the source type is the same class as the class
11340 of the destination, the initializer expression is used to initialize the
11341 destination object." Handle that here to avoid doing overload
11342 resolution. */
11343 if (cxx_dialect >= cxx17
11344 && args && vec_safe_length (*args) == 1
11345 && !unsafe_return_slot_p (instance))
11347 tree arg = (**args)[0];
11349 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
11350 && !TYPE_HAS_LIST_CTOR (class_type)
11351 && !CONSTRUCTOR_IS_DESIGNATED_INIT (arg)
11352 && CONSTRUCTOR_NELTS (arg) == 1)
11353 arg = CONSTRUCTOR_ELT (arg, 0)->value;
11355 if ((TREE_CODE (arg) == TARGET_EXPR
11356 || TREE_CODE (arg) == CONSTRUCTOR)
11357 && (same_type_ignoring_top_level_qualifiers_p
11358 (class_type, TREE_TYPE (arg))))
11360 if (is_dummy_object (instance))
11361 return arg;
11362 else if (TREE_CODE (arg) == TARGET_EXPR)
11363 TARGET_EXPR_DIRECT_INIT_P (arg) = true;
11365 if ((complain & tf_error)
11366 && (flags & LOOKUP_DELEGATING_CONS))
11367 check_self_delegation (arg);
11368 /* Avoid change of behavior on Wunused-var-2.C. */
11369 instance = mark_lvalue_use (instance);
11370 return cp_build_init_expr (instance, arg);
11374 fns = lookup_fnfields (binfo, name, 1, complain);
11376 /* When making a call to a constructor or destructor for a subobject
11377 that uses virtual base classes, pass down a pointer to a VTT for
11378 the subobject. */
11379 if ((name == base_ctor_identifier
11380 || name == base_dtor_identifier)
11381 && CLASSTYPE_VBASECLASSES (class_type))
11383 tree vtt;
11384 tree sub_vtt;
11386 /* If the current function is a complete object constructor
11387 or destructor, then we fetch the VTT directly.
11388 Otherwise, we look it up using the VTT we were given. */
11389 vtt = DECL_CHAIN (CLASSTYPE_VTABLES (current_class_type));
11390 vtt = decay_conversion (vtt, complain);
11391 if (vtt == error_mark_node)
11392 return error_mark_node;
11393 vtt = build_if_in_charge (vtt, current_vtt_parm);
11394 if (BINFO_SUBVTT_INDEX (binfo))
11395 sub_vtt = fold_build_pointer_plus (vtt, BINFO_SUBVTT_INDEX (binfo));
11396 else
11397 sub_vtt = vtt;
11399 if (args == NULL)
11401 allocated = make_tree_vector ();
11402 args = &allocated;
11405 vec_safe_insert (*args, 0, sub_vtt);
11408 ret = build_new_method_call (instance, fns, args,
11409 TYPE_BINFO (BINFO_TYPE (binfo)),
11410 flags, /*fn=*/NULL,
11411 complain);
11413 if (allocated != NULL)
11414 release_tree_vector (allocated);
11416 if ((complain & tf_error)
11417 && (flags & LOOKUP_DELEGATING_CONS)
11418 && name == complete_ctor_identifier)
11419 check_self_delegation (ret);
11421 return ret;
11424 /* Return the NAME, as a C string. The NAME indicates a function that
11425 is a member of TYPE. *FREE_P is set to true if the caller must
11426 free the memory returned.
11428 Rather than go through all of this, we should simply set the names
11429 of constructors and destructors appropriately, and dispense with
11430 ctor_identifier, dtor_identifier, etc. */
11432 static char *
11433 name_as_c_string (tree name, tree type, bool *free_p)
11435 const char *pretty_name;
11437 /* Assume that we will not allocate memory. */
11438 *free_p = false;
11439 /* Constructors and destructors are special. */
11440 if (IDENTIFIER_CDTOR_P (name))
11442 pretty_name
11443 = identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type)));
11444 /* For a destructor, add the '~'. */
11445 if (IDENTIFIER_DTOR_P (name))
11447 pretty_name = concat ("~", pretty_name, NULL);
11448 /* Remember that we need to free the memory allocated. */
11449 *free_p = true;
11452 else if (IDENTIFIER_CONV_OP_P (name))
11454 pretty_name = concat ("operator ",
11455 type_as_string_translate (TREE_TYPE (name),
11456 TFF_PLAIN_IDENTIFIER),
11457 NULL);
11458 /* Remember that we need to free the memory allocated. */
11459 *free_p = true;
11461 else
11462 pretty_name = identifier_to_locale (IDENTIFIER_POINTER (name));
11464 return CONST_CAST (char *, pretty_name);
11467 /* If CANDIDATES contains exactly one candidate, return it, otherwise
11468 return NULL. */
11470 static z_candidate *
11471 single_z_candidate (z_candidate *candidates)
11473 if (candidates == NULL)
11474 return NULL;
11476 if (candidates->next)
11477 return NULL;
11479 return candidates;
11482 /* If CANDIDATE is invalid due to a bad argument type, return the
11483 pertinent conversion_info.
11485 Otherwise, return NULL. */
11487 static const conversion_info *
11488 maybe_get_bad_conversion_for_unmatched_call (const z_candidate *candidate)
11490 /* Must be an rr_arg_conversion or rr_bad_arg_conversion. */
11491 rejection_reason *r = candidate->reason;
11493 if (r == NULL)
11494 return NULL;
11496 switch (r->code)
11498 default:
11499 return NULL;
11501 case rr_arg_conversion:
11502 return &r->u.conversion;
11504 case rr_bad_arg_conversion:
11505 return &r->u.bad_conversion;
11509 /* Issue an error and note complaining about a bad argument type at a
11510 callsite with a single candidate FNDECL.
11512 ARG_LOC is the location of the argument (or UNKNOWN_LOCATION, in which
11513 case input_location is used).
11514 FROM_TYPE is the type of the actual argument; TO_TYPE is the type of
11515 the formal parameter. */
11517 void
11518 complain_about_bad_argument (location_t arg_loc,
11519 tree from_type, tree to_type,
11520 tree fndecl, int parmnum)
11522 auto_diagnostic_group d;
11523 range_label_for_type_mismatch rhs_label (from_type, to_type);
11524 range_label *label = &rhs_label;
11525 if (arg_loc == UNKNOWN_LOCATION)
11527 arg_loc = input_location;
11528 label = NULL;
11530 gcc_rich_location richloc (arg_loc, label, highlight_colors::percent_h);
11531 error_at (&richloc,
11532 "cannot convert %qH to %qI",
11533 from_type, to_type);
11534 maybe_inform_about_fndecl_for_bogus_argument_init
11535 (fndecl,
11536 parmnum,
11537 highlight_colors::percent_i);
11540 /* Subroutine of build_new_method_call_1, for where there are no viable
11541 candidates for the call. */
11543 static void
11544 complain_about_no_candidates_for_method_call (tree instance,
11545 z_candidate *candidates,
11546 tree explicit_targs,
11547 tree basetype,
11548 tree optype, tree name,
11549 bool skip_first_for_error,
11550 vec<tree, va_gc> *user_args)
11552 auto_diagnostic_group d;
11553 if (!COMPLETE_OR_OPEN_TYPE_P (basetype))
11554 cxx_incomplete_type_error (instance, basetype);
11555 else if (optype)
11556 error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
11557 basetype, optype, build_tree_list_vec (user_args),
11558 TREE_TYPE (instance));
11559 else
11561 /* Special-case for when there's a single candidate that's failing
11562 due to a bad argument type. */
11563 if (z_candidate *candidate = single_z_candidate (candidates))
11564 if (const conversion_info *conv
11565 = maybe_get_bad_conversion_for_unmatched_call (candidate))
11567 tree from_type = conv->from;
11568 if (!TYPE_P (conv->from))
11569 from_type = lvalue_type (conv->from);
11570 complain_about_bad_argument (conv->loc,
11571 from_type, conv->to_type,
11572 candidate->fn, conv->n_arg);
11573 return;
11576 tree arglist = build_tree_list_vec (user_args);
11577 tree errname = name;
11578 bool twiddle = false;
11579 if (IDENTIFIER_CDTOR_P (errname))
11581 twiddle = IDENTIFIER_DTOR_P (errname);
11582 errname = constructor_name (basetype);
11584 if (explicit_targs)
11585 errname = lookup_template_function (errname, explicit_targs);
11586 if (skip_first_for_error)
11587 arglist = TREE_CHAIN (arglist);
11588 error ("no matching function for call to %<%T::%s%E(%A)%#V%>",
11589 basetype, &"~"[!twiddle], errname, arglist,
11590 TREE_TYPE (instance));
11592 print_z_candidates (location_of (name), candidates);
11595 /* Build a call to "INSTANCE.FN (ARGS)". If FN_P is non-NULL, it will
11596 be set, upon return, to the function called. ARGS may be NULL.
11597 This may change ARGS. */
11599 tree
11600 build_new_method_call (tree instance, tree fns, vec<tree, va_gc> **args,
11601 tree conversion_path, int flags,
11602 tree *fn_p, tsubst_flags_t complain)
11604 struct z_candidate *candidates = 0, *cand;
11605 tree explicit_targs = NULL_TREE;
11606 tree basetype = NULL_TREE;
11607 tree access_binfo;
11608 tree optype;
11609 tree first_mem_arg = NULL_TREE;
11610 tree name;
11611 bool skip_first_for_error;
11612 vec<tree, va_gc> *user_args;
11613 tree call;
11614 tree fn;
11615 int template_only = 0;
11616 bool any_viable_p;
11617 tree orig_instance;
11618 tree orig_fns;
11619 vec<tree, va_gc> *orig_args = NULL;
11621 auto_cond_timevar tv (TV_OVERLOAD);
11623 gcc_assert (instance != NULL_TREE);
11625 /* We don't know what function we're going to call, yet. */
11626 if (fn_p)
11627 *fn_p = NULL_TREE;
11629 if (error_operand_p (instance)
11630 || !fns || error_operand_p (fns))
11631 return error_mark_node;
11633 if (!BASELINK_P (fns))
11635 if (complain & tf_error)
11636 error ("call to non-function %qD", fns);
11637 return error_mark_node;
11640 orig_instance = instance;
11641 orig_fns = fns;
11643 /* Dismantle the baselink to collect all the information we need. */
11644 if (!conversion_path)
11645 conversion_path = BASELINK_BINFO (fns);
11646 access_binfo = BASELINK_ACCESS_BINFO (fns);
11647 optype = BASELINK_OPTYPE (fns);
11648 fns = BASELINK_FUNCTIONS (fns);
11649 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11651 explicit_targs = TREE_OPERAND (fns, 1);
11652 fns = TREE_OPERAND (fns, 0);
11653 template_only = 1;
11655 gcc_assert (OVL_P (fns));
11656 fn = OVL_FIRST (fns);
11657 name = DECL_NAME (fn);
11659 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
11660 gcc_assert (CLASS_TYPE_P (basetype));
11662 user_args = args == NULL ? NULL : *args;
11663 /* Under DR 147 A::A() is an invalid constructor call,
11664 not a functional cast. */
11665 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
11667 if (! (complain & tf_error))
11668 return error_mark_node;
11670 basetype = DECL_CONTEXT (fn);
11671 name = constructor_name (basetype);
11672 auto_diagnostic_group d;
11673 if (permerror (input_location,
11674 "cannot call constructor %<%T::%D%> directly",
11675 basetype, name))
11676 inform (input_location, "for a function-style cast, remove the "
11677 "redundant %<::%D%>", name);
11678 call = build_functional_cast (input_location, basetype,
11679 build_tree_list_vec (user_args),
11680 complain);
11681 return call;
11684 if (processing_template_decl)
11685 orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
11687 /* Process the argument list. */
11688 if (args != NULL && *args != NULL)
11690 *args = resolve_args (*args, complain);
11691 if (*args == NULL)
11692 return error_mark_node;
11693 user_args = *args;
11696 /* Consider the object argument to be used even if we end up selecting a
11697 static member function. */
11698 instance = mark_type_use (instance);
11700 /* Figure out whether to skip the first argument for the error
11701 message we will display to users if an error occurs. We don't
11702 want to display any compiler-generated arguments. The "this"
11703 pointer hasn't been added yet. However, we must remove the VTT
11704 pointer if this is a call to a base-class constructor or
11705 destructor. */
11706 skip_first_for_error = false;
11707 if (IDENTIFIER_CDTOR_P (name))
11709 /* Callers should explicitly indicate whether they want to ctor
11710 the complete object or just the part without virtual bases. */
11711 gcc_assert (name != ctor_identifier);
11713 /* Remove the VTT pointer, if present. */
11714 if ((name == base_ctor_identifier || name == base_dtor_identifier)
11715 && CLASSTYPE_VBASECLASSES (basetype))
11716 skip_first_for_error = true;
11718 /* It's OK to call destructors and constructors on cv-qualified
11719 objects. Therefore, convert the INSTANCE to the unqualified
11720 type, if necessary. */
11721 if (!same_type_p (basetype, TREE_TYPE (instance)))
11723 instance = build_this (instance);
11724 instance = build_nop (build_pointer_type (basetype), instance);
11725 instance = build_fold_indirect_ref (instance);
11728 else
11729 gcc_assert (!DECL_DESTRUCTOR_P (fn) && !DECL_CONSTRUCTOR_P (fn));
11731 /* For the overload resolution we need to find the actual `this`
11732 that would be captured if the call turns out to be to a
11733 non-static member function. Do not actually capture it at this
11734 point. */
11735 if (DECL_CONSTRUCTOR_P (fn))
11736 /* Constructors don't use the enclosing 'this'. */
11737 first_mem_arg = instance;
11738 else
11739 first_mem_arg = maybe_resolve_dummy (instance, false);
11741 conversion_obstack_sentinel cos;
11743 /* The number of arguments artificial parms in ARGS; we subtract one because
11744 there's no 'this' in ARGS. */
11745 unsigned skip = num_artificial_parms_for (fn) - 1;
11747 /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
11748 initializer, not T({ }). */
11749 if (DECL_CONSTRUCTOR_P (fn)
11750 && vec_safe_length (user_args) > skip
11751 && DIRECT_LIST_INIT_P ((*user_args)[skip]))
11753 tree init_list = (*user_args)[skip];
11754 tree init = NULL_TREE;
11756 gcc_assert (user_args->length () == skip + 1
11757 && !(flags & LOOKUP_ONLYCONVERTING));
11759 /* If the initializer list has no elements and T is a class type with
11760 a default constructor, the object is value-initialized. Handle
11761 this here so we don't need to handle it wherever we use
11762 build_special_member_call. */
11763 if (CONSTRUCTOR_NELTS (init_list) == 0
11764 && TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
11765 /* For a user-provided default constructor, use the normal
11766 mechanisms so that protected access works. */
11767 && type_has_non_user_provided_default_constructor (basetype)
11768 && !processing_template_decl)
11769 init = build_value_init (basetype, complain);
11771 /* If BASETYPE is an aggregate, we need to do aggregate
11772 initialization. */
11773 else if (CP_AGGREGATE_TYPE_P (basetype))
11775 init = reshape_init (basetype, init_list, complain);
11776 init = digest_init (basetype, init, complain);
11779 if (init)
11781 if (is_dummy_object (instance))
11782 return get_target_expr (init, complain);
11783 return cp_build_init_expr (instance, init);
11786 /* Otherwise go ahead with overload resolution. */
11787 add_list_candidates (fns, first_mem_arg, user_args,
11788 basetype, explicit_targs, template_only,
11789 conversion_path, access_binfo, flags,
11790 &candidates, complain);
11792 else
11793 add_candidates (fns, first_mem_arg, user_args, optype,
11794 explicit_targs, template_only, conversion_path,
11795 access_binfo, flags, &candidates, complain);
11797 any_viable_p = false;
11798 candidates = splice_viable (candidates, false, &any_viable_p);
11800 if (!any_viable_p)
11802 /* [dcl.init], 17.6.2.2:
11804 Otherwise, if no constructor is viable, the destination type is
11805 a (possibly cv-qualified) aggregate class A, and the initializer
11806 is a parenthesized expression-list, the object is initialized as
11807 follows...
11809 We achieve this by building up a CONSTRUCTOR, as for list-init,
11810 and setting CONSTRUCTOR_IS_PAREN_INIT to distinguish between
11811 the two. */
11812 if (DECL_CONSTRUCTOR_P (fn)
11813 && !(flags & LOOKUP_ONLYCONVERTING)
11814 && cxx_dialect >= cxx20
11815 && CP_AGGREGATE_TYPE_P (basetype)
11816 && !vec_safe_is_empty (user_args))
11818 /* Create a CONSTRUCTOR from ARGS, e.g. {1, 2} from <1, 2>. */
11819 tree ctor = build_constructor_from_vec (init_list_type_node,
11820 user_args);
11821 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
11822 CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
11823 if (is_dummy_object (instance))
11824 return ctor;
11825 else
11827 ctor = digest_init (basetype, ctor, complain);
11828 if (ctor == error_mark_node)
11829 return error_mark_node;
11830 return cp_build_init_expr (instance, ctor);
11833 if (complain & tf_error)
11834 complain_about_no_candidates_for_method_call (instance, candidates,
11835 explicit_targs, basetype,
11836 optype, name,
11837 skip_first_for_error,
11838 user_args);
11839 call = error_mark_node;
11841 else
11843 cand = tourney (candidates, complain);
11844 if (cand == 0)
11846 char *pretty_name;
11847 bool free_p;
11848 tree arglist;
11850 if (complain & tf_error)
11852 pretty_name = name_as_c_string (name, basetype, &free_p);
11853 arglist = build_tree_list_vec (user_args);
11854 if (skip_first_for_error)
11855 arglist = TREE_CHAIN (arglist);
11856 auto_diagnostic_group d;
11857 if (!any_strictly_viable (candidates))
11858 error ("no matching function for call to %<%s(%A)%>",
11859 pretty_name, arglist);
11860 else
11861 error ("call of overloaded %<%s(%A)%> is ambiguous",
11862 pretty_name, arglist);
11863 print_z_candidates (location_of (name), candidates);
11864 if (free_p)
11865 free (pretty_name);
11867 call = error_mark_node;
11868 if (fn_p)
11869 *fn_p = error_mark_node;
11871 else
11873 fn = cand->fn;
11874 call = NULL_TREE;
11876 if (!(flags & LOOKUP_NONVIRTUAL)
11877 && DECL_PURE_VIRTUAL_P (fn)
11878 && instance == current_class_ref
11879 && (complain & tf_warning))
11881 /* This is not an error, it is runtime undefined
11882 behavior. */
11883 if (!current_function_decl)
11884 warning (0, "pure virtual %q#D called from "
11885 "non-static data member initializer", fn);
11886 else if (DECL_CONSTRUCTOR_P (current_function_decl)
11887 || DECL_DESTRUCTOR_P (current_function_decl))
11888 warning (0, (DECL_CONSTRUCTOR_P (current_function_decl)
11889 ? G_("pure virtual %q#D called from constructor")
11890 : G_("pure virtual %q#D called from destructor")),
11891 fn);
11894 if (DECL_OBJECT_MEMBER_FUNCTION_P (fn)
11895 && !DECL_CONSTRUCTOR_P (fn)
11896 && is_dummy_object (instance))
11898 instance = maybe_resolve_dummy (instance, true);
11899 if (instance == error_mark_node)
11900 call = error_mark_node;
11901 else if (!is_dummy_object (instance))
11903 /* We captured 'this' in the current lambda now that
11904 we know we really need it. */
11905 cand->first_arg = instance;
11907 else if (current_class_ptr && any_dependent_bases_p ())
11908 /* We can't tell until instantiation time whether we can use
11909 *this as the implicit object argument. */;
11910 else
11912 if (complain & tf_error)
11913 error ("cannot call member function %qD without object",
11914 fn);
11915 call = error_mark_node;
11919 if (call != error_mark_node)
11921 /* Now we know what function is being called. */
11922 if (fn_p)
11923 *fn_p = fn;
11924 /* Build the actual CALL_EXPR. */
11925 call = build_over_call (cand, flags, complain);
11927 /* Suppress warnings for if (my_struct.operator= (x)) where
11928 my_struct is implicitly converted to bool. */
11929 if (TREE_CODE (call) == MODIFY_EXPR)
11930 suppress_warning (call, OPT_Wparentheses);
11932 /* In an expression of the form `a->f()' where `f' turns
11933 out to be a static member function, `a' is
11934 none-the-less evaluated. */
11935 if (!is_dummy_object (instance))
11936 call = keep_unused_object_arg (call, instance, fn);
11937 if (call != error_mark_node
11938 && DECL_DESTRUCTOR_P (cand->fn)
11939 && !VOID_TYPE_P (TREE_TYPE (call)))
11940 /* An explicit call of the form "x->~X()" has type
11941 "void". However, on platforms where destructors
11942 return "this" (i.e., those where
11943 targetm.cxx.cdtor_returns_this is true), such calls
11944 will appear to have a return value of pointer type
11945 to the low-level call machinery. We do not want to
11946 change the low-level machinery, since we want to be
11947 able to optimize "delete f()" on such platforms as
11948 "operator delete(~X(f()))" (rather than generating
11949 "t = f(), ~X(t), operator delete (t)"). */
11950 call = build_nop (void_type_node, call);
11955 if (processing_template_decl && call != error_mark_node)
11957 bool cast_to_void = false;
11959 if (TREE_CODE (call) == COMPOUND_EXPR)
11960 call = TREE_OPERAND (call, 1);
11961 else if (TREE_CODE (call) == NOP_EXPR)
11963 cast_to_void = true;
11964 call = TREE_OPERAND (call, 0);
11966 if (INDIRECT_REF_P (call))
11967 call = TREE_OPERAND (call, 0);
11969 /* Prune all but the selected function from the original overload
11970 set so that we can avoid some duplicate work at instantiation time. */
11971 if (really_overloaded_fn (fns))
11973 if (DECL_TEMPLATE_INFO (fn)
11974 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
11976 /* Use the selected template, not the specialization, so that
11977 this looks like an actual lookup result for sake of
11978 filter_memfn_lookup. */
11980 if (OVL_SINGLE_P (fns))
11981 /* If the original overload set consists of a single function
11982 template, this isn't beneficial. */
11983 goto skip_prune;
11985 fn = ovl_make (DECL_TI_TEMPLATE (fn));
11986 if (template_only)
11987 fn = lookup_template_function (fn, explicit_targs);
11989 orig_fns = copy_node (orig_fns);
11990 BASELINK_FUNCTIONS (orig_fns) = fn;
11991 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (orig_fns) = true;
11994 skip_prune:
11995 call = (build_min_non_dep_call_vec
11996 (call,
11997 build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
11998 orig_instance, orig_fns, NULL_TREE),
11999 orig_args));
12000 SET_EXPR_LOCATION (call, input_location);
12001 call = convert_from_reference (call);
12002 if (cast_to_void)
12003 call = build_nop (void_type_node, call);
12006 if (orig_args != NULL)
12007 release_tree_vector (orig_args);
12009 return call;
12012 /* Returns true iff standard conversion sequence ICS1 is a proper
12013 subsequence of ICS2. */
12015 static bool
12016 is_subseq (conversion *ics1, conversion *ics2)
12018 /* We can assume that a conversion of the same code
12019 between the same types indicates a subsequence since we only get
12020 here if the types we are converting from are the same. */
12022 while (ics1->kind == ck_rvalue
12023 || ics1->kind == ck_lvalue)
12024 ics1 = next_conversion (ics1);
12026 while (1)
12028 while (ics2->kind == ck_rvalue
12029 || ics2->kind == ck_lvalue)
12030 ics2 = next_conversion (ics2);
12032 if (ics2->kind == ck_user
12033 || !has_next (ics2->kind))
12034 /* At this point, ICS1 cannot be a proper subsequence of
12035 ICS2. We can get a USER_CONV when we are comparing the
12036 second standard conversion sequence of two user conversion
12037 sequences. */
12038 return false;
12040 ics2 = next_conversion (ics2);
12042 while (ics2->kind == ck_rvalue
12043 || ics2->kind == ck_lvalue)
12044 ics2 = next_conversion (ics2);
12046 if (ics2->kind == ics1->kind
12047 && same_type_p (ics2->type, ics1->type)
12048 && (ics1->kind == ck_identity
12049 || same_type_p (next_conversion (ics2)->type,
12050 next_conversion (ics1)->type)))
12051 return true;
12055 /* Returns nonzero iff DERIVED is derived from BASE. The inputs may
12056 be any _TYPE nodes. */
12058 bool
12059 is_properly_derived_from (tree derived, tree base)
12061 if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
12062 return false;
12064 /* We only allow proper derivation here. The DERIVED_FROM_P macro
12065 considers every class derived from itself. */
12066 return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
12067 && DERIVED_FROM_P (base, derived));
12070 /* We build the ICS for an implicit object parameter as a pointer
12071 conversion sequence. However, such a sequence should be compared
12072 as if it were a reference conversion sequence. If ICS is the
12073 implicit conversion sequence for an implicit object parameter,
12074 modify it accordingly. */
12076 static void
12077 maybe_handle_implicit_object (conversion **ics)
12079 if ((*ics)->this_p)
12081 /* [over.match.funcs]
12083 For non-static member functions, the type of the
12084 implicit object parameter is "reference to cv X"
12085 where X is the class of which the function is a
12086 member and cv is the cv-qualification on the member
12087 function declaration. */
12088 conversion *t = *ics;
12089 tree reference_type;
12091 /* The `this' parameter is a pointer to a class type. Make the
12092 implicit conversion talk about a reference to that same class
12093 type. */
12094 reference_type = TREE_TYPE (t->type);
12095 reference_type = build_reference_type (reference_type);
12097 if (t->kind == ck_qual)
12098 t = next_conversion (t);
12099 if (t->kind == ck_ptr)
12100 t = next_conversion (t);
12101 t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
12102 t = direct_reference_binding (reference_type, t);
12103 t->this_p = 1;
12104 t->rvaluedness_matches_p = 0;
12105 *ics = t;
12109 /* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
12110 and return the initial reference binding conversion. Otherwise,
12111 leave *ICS unchanged and return NULL. */
12113 static conversion *
12114 maybe_handle_ref_bind (conversion **ics)
12116 if ((*ics)->kind == ck_ref_bind)
12118 conversion *old_ics = *ics;
12119 *ics = next_conversion (old_ics);
12120 (*ics)->user_conv_p = old_ics->user_conv_p;
12121 return old_ics;
12124 return NULL;
12127 /* Get the expression at the beginning of the conversion chain C. */
12129 static tree
12130 conv_get_original_expr (conversion *c)
12132 for (; c; c = next_conversion (c))
12133 if (c->kind == ck_identity || c->kind == ck_ambig || c->kind == ck_aggr)
12134 return c->u.expr;
12135 return NULL_TREE;
12138 /* Return a tree representing the number of elements initialized by the
12139 list-initialization C. The caller must check that C converts to an
12140 array type. */
12142 static tree
12143 nelts_initialized_by_list_init (conversion *c)
12145 /* If the array we're converting to has a dimension, we'll use that. */
12146 if (TYPE_DOMAIN (c->type))
12147 return array_type_nelts_top (c->type);
12148 else
12150 /* Otherwise, we look at how many elements the constructor we're
12151 initializing from has. */
12152 tree ctor = conv_get_original_expr (c);
12153 return size_int (CONSTRUCTOR_NELTS (ctor));
12157 /* True iff C is a conversion that binds a reference or a pointer to
12158 an array of unknown bound. */
12160 static inline bool
12161 conv_binds_to_array_of_unknown_bound (conversion *c)
12163 /* ck_ref_bind won't have the reference stripped. */
12164 tree type = non_reference (c->type);
12165 /* ck_qual won't have the pointer stripped. */
12166 type = strip_pointer_operator (type);
12167 return (TREE_CODE (type) == ARRAY_TYPE
12168 && TYPE_DOMAIN (type) == NULL_TREE);
12171 /* Compare two implicit conversion sequences according to the rules set out in
12172 [over.ics.rank]. Return values:
12174 1: ics1 is better than ics2
12175 -1: ics2 is better than ics1
12176 0: ics1 and ics2 are indistinguishable */
12178 static int
12179 compare_ics (conversion *ics1, conversion *ics2)
12181 tree from_type1;
12182 tree from_type2;
12183 tree to_type1;
12184 tree to_type2;
12185 tree deref_from_type1 = NULL_TREE;
12186 tree deref_from_type2 = NULL_TREE;
12187 tree deref_to_type1 = NULL_TREE;
12188 tree deref_to_type2 = NULL_TREE;
12189 conversion_rank rank1, rank2;
12191 /* REF_BINDING is nonzero if the result of the conversion sequence
12192 is a reference type. In that case REF_CONV is the reference
12193 binding conversion. */
12194 conversion *ref_conv1;
12195 conversion *ref_conv2;
12197 /* Compare badness before stripping the reference conversion. */
12198 if (ics1->bad_p > ics2->bad_p)
12199 return -1;
12200 else if (ics1->bad_p < ics2->bad_p)
12201 return 1;
12203 /* Handle implicit object parameters. */
12204 maybe_handle_implicit_object (&ics1);
12205 maybe_handle_implicit_object (&ics2);
12207 /* Handle reference parameters. */
12208 ref_conv1 = maybe_handle_ref_bind (&ics1);
12209 ref_conv2 = maybe_handle_ref_bind (&ics2);
12211 /* List-initialization sequence L1 is a better conversion sequence than
12212 list-initialization sequence L2 if L1 converts to
12213 std::initializer_list<X> for some X and L2 does not. */
12214 if (ics1->kind == ck_list && ics2->kind != ck_list)
12215 return 1;
12216 if (ics2->kind == ck_list && ics1->kind != ck_list)
12217 return -1;
12219 /* [over.ics.rank]
12221 When comparing the basic forms of implicit conversion sequences (as
12222 defined in _over.best.ics_)
12224 --a standard conversion sequence (_over.ics.scs_) is a better
12225 conversion sequence than a user-defined conversion sequence
12226 or an ellipsis conversion sequence, and
12228 --a user-defined conversion sequence (_over.ics.user_) is a
12229 better conversion sequence than an ellipsis conversion sequence
12230 (_over.ics.ellipsis_). */
12231 /* Use BAD_CONVERSION_RANK because we already checked for a badness
12232 mismatch. If both ICS are bad, we try to make a decision based on
12233 what would have happened if they'd been good. This is not an
12234 extension, we'll still give an error when we build up the call; this
12235 just helps us give a more helpful error message. */
12236 rank1 = BAD_CONVERSION_RANK (ics1);
12237 rank2 = BAD_CONVERSION_RANK (ics2);
12239 if (rank1 > rank2)
12240 return -1;
12241 else if (rank1 < rank2)
12242 return 1;
12244 if (ics1->ellipsis_p)
12245 /* Both conversions are ellipsis conversions. */
12246 return 0;
12248 /* User-defined conversion sequence U1 is a better conversion sequence
12249 than another user-defined conversion sequence U2 if they contain the
12250 same user-defined conversion operator or constructor and if the sec-
12251 ond standard conversion sequence of U1 is better than the second
12252 standard conversion sequence of U2. */
12254 /* Handle list-conversion with the same code even though it isn't always
12255 ranked as a user-defined conversion and it doesn't have a second
12256 standard conversion sequence; it will still have the desired effect.
12257 Specifically, we need to do the reference binding comparison at the
12258 end of this function. */
12260 if (ics1->user_conv_p || ics1->kind == ck_list
12261 || ics1->kind == ck_aggr || ics2->kind == ck_aggr)
12263 conversion *t1 = strip_standard_conversion (ics1);
12264 conversion *t2 = strip_standard_conversion (ics2);
12266 if (!t1 || !t2 || t1->kind != t2->kind)
12267 return 0;
12268 else if (t1->kind == ck_user)
12270 tree f1 = t1->cand ? t1->cand->fn : t1->type;
12271 tree f2 = t2->cand ? t2->cand->fn : t2->type;
12272 if (f1 != f2)
12273 return 0;
12275 /* List-initialization sequence L1 is a better conversion sequence than
12276 list-initialization sequence L2 if
12278 -- L1 and L2 convert to arrays of the same element type, and either
12279 the number of elements n1 initialized by L1 is less than the number
12280 of elements n2 initialized by L2, or n1=n2 and L2 converts to an array
12281 of unknown bound and L1 does not. (Added in CWG 1307 and extended by
12282 P0388R4.) */
12283 else if (t1->kind == ck_aggr
12284 && TREE_CODE (t1->type) == ARRAY_TYPE
12285 && TREE_CODE (t2->type) == ARRAY_TYPE
12286 && same_type_p (TREE_TYPE (t1->type), TREE_TYPE (t2->type)))
12288 tree n1 = nelts_initialized_by_list_init (t1);
12289 tree n2 = nelts_initialized_by_list_init (t2);
12290 if (tree_int_cst_lt (n1, n2))
12291 return 1;
12292 else if (tree_int_cst_lt (n2, n1))
12293 return -1;
12294 /* The n1 == n2 case. */
12295 bool c1 = conv_binds_to_array_of_unknown_bound (t1);
12296 bool c2 = conv_binds_to_array_of_unknown_bound (t2);
12297 if (c1 && !c2)
12298 return -1;
12299 else if (!c1 && c2)
12300 return 1;
12301 else
12302 return 0;
12304 else
12306 /* For ambiguous or aggregate conversions, use the target type as
12307 a proxy for the conversion function. */
12308 if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
12309 return 0;
12312 /* We can just fall through here, after setting up
12313 FROM_TYPE1 and FROM_TYPE2. */
12314 from_type1 = t1->type;
12315 from_type2 = t2->type;
12317 else
12319 conversion *t1;
12320 conversion *t2;
12322 /* We're dealing with two standard conversion sequences.
12324 [over.ics.rank]
12326 Standard conversion sequence S1 is a better conversion
12327 sequence than standard conversion sequence S2 if
12329 --S1 is a proper subsequence of S2 (comparing the conversion
12330 sequences in the canonical form defined by _over.ics.scs_,
12331 excluding any Lvalue Transformation; the identity
12332 conversion sequence is considered to be a subsequence of
12333 any non-identity conversion sequence */
12335 t1 = ics1;
12336 while (t1->kind != ck_identity)
12337 t1 = next_conversion (t1);
12338 from_type1 = t1->type;
12340 t2 = ics2;
12341 while (t2->kind != ck_identity)
12342 t2 = next_conversion (t2);
12343 from_type2 = t2->type;
12346 /* One sequence can only be a subsequence of the other if they start with
12347 the same type. They can start with different types when comparing the
12348 second standard conversion sequence in two user-defined conversion
12349 sequences. */
12350 if (same_type_p (from_type1, from_type2))
12352 if (is_subseq (ics1, ics2))
12353 return 1;
12354 if (is_subseq (ics2, ics1))
12355 return -1;
12358 /* [over.ics.rank]
12360 Or, if not that,
12362 --the rank of S1 is better than the rank of S2 (by the rules
12363 defined below):
12365 Standard conversion sequences are ordered by their ranks: an Exact
12366 Match is a better conversion than a Promotion, which is a better
12367 conversion than a Conversion.
12369 Two conversion sequences with the same rank are indistinguishable
12370 unless one of the following rules applies:
12372 --A conversion that does not a convert a pointer, pointer to member,
12373 or std::nullptr_t to bool is better than one that does.
12375 The ICS_STD_RANK automatically handles the pointer-to-bool rule,
12376 so that we do not have to check it explicitly. */
12377 if (ics1->rank < ics2->rank)
12378 return 1;
12379 else if (ics2->rank < ics1->rank)
12380 return -1;
12382 to_type1 = ics1->type;
12383 to_type2 = ics2->type;
12385 /* A conversion from scalar arithmetic type to complex is worse than a
12386 conversion between scalar arithmetic types. */
12387 if (same_type_p (from_type1, from_type2)
12388 && ARITHMETIC_TYPE_P (from_type1)
12389 && ARITHMETIC_TYPE_P (to_type1)
12390 && ARITHMETIC_TYPE_P (to_type2)
12391 && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
12392 != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
12394 if (TREE_CODE (to_type1) == COMPLEX_TYPE)
12395 return -1;
12396 else
12397 return 1;
12401 /* A conversion in either direction between floating-point type FP1 and
12402 floating-point type FP2 is better than a conversion in the same
12403 direction between FP1 and arithmetic type T3 if
12404 - the floating-point conversion rank of FP1 is equal to the rank of
12405 FP2, and
12406 - T3 is not a floating-point type, or T3 is a floating-point type
12407 whose rank is not equal to the rank of FP1, or the floating-point
12408 conversion subrank of FP2 is greater than the subrank of T3. */
12409 tree fp1 = from_type1;
12410 tree fp2 = to_type1;
12411 tree fp3 = from_type2;
12412 tree t3 = to_type2;
12413 int ret = 1;
12414 if (TYPE_MAIN_VARIANT (fp2) == TYPE_MAIN_VARIANT (t3))
12416 std::swap (fp1, fp2);
12417 std::swap (fp3, t3);
12419 if (TYPE_MAIN_VARIANT (fp1) == TYPE_MAIN_VARIANT (fp3)
12420 && SCALAR_FLOAT_TYPE_P (fp1)
12421 /* Only apply this rule if at least one of the 3 types is
12422 extended floating-point type, otherwise keep them as
12423 before for compatibility reasons with types like __float128.
12424 float, double and long double alone have different conversion
12425 ranks and so when just those 3 types are involved, this
12426 rule doesn't trigger. */
12427 && (extended_float_type_p (fp1)
12428 || (SCALAR_FLOAT_TYPE_P (fp2) && extended_float_type_p (fp2))
12429 || (SCALAR_FLOAT_TYPE_P (t3) && extended_float_type_p (t3))))
12431 if (TREE_CODE (fp2) != REAL_TYPE)
12433 ret = -ret;
12434 std::swap (fp2, t3);
12436 if (SCALAR_FLOAT_TYPE_P (fp2))
12438 /* cp_compare_floating_point_conversion_ranks returns -1, 0 or 1
12439 if the conversion rank is equal (-1 or 1 if the subrank is
12440 different). */
12441 if (IN_RANGE (cp_compare_floating_point_conversion_ranks (fp1,
12442 fp2),
12443 -1, 1))
12445 /* Conversion ranks of FP1 and FP2 are equal. */
12446 if (TREE_CODE (t3) != REAL_TYPE
12447 || !IN_RANGE (cp_compare_floating_point_conversion_ranks
12448 (fp1, t3),
12449 -1, 1))
12450 /* FP1 <-> FP2 conversion is better. */
12451 return ret;
12452 int c = cp_compare_floating_point_conversion_ranks (fp2, t3);
12453 gcc_assert (IN_RANGE (c, -1, 1));
12454 if (c == 1)
12455 /* Conversion subrank of FP2 is greater than subrank of T3.
12456 FP1 <-> FP2 conversion is better. */
12457 return ret;
12458 else if (c == -1)
12459 /* Conversion subrank of FP2 is less than subrank of T3.
12460 FP1 <-> T3 conversion is better. */
12461 return -ret;
12463 else if (SCALAR_FLOAT_TYPE_P (t3)
12464 && IN_RANGE (cp_compare_floating_point_conversion_ranks
12465 (fp1, t3),
12466 -1, 1))
12467 /* Conversion ranks of FP1 and FP2 are not equal, conversion
12468 ranks of FP1 and T3 are equal.
12469 FP1 <-> T3 conversion is better. */
12470 return -ret;
12475 if (TYPE_PTR_P (from_type1)
12476 && TYPE_PTR_P (from_type2)
12477 && TYPE_PTR_P (to_type1)
12478 && TYPE_PTR_P (to_type2))
12480 deref_from_type1 = TREE_TYPE (from_type1);
12481 deref_from_type2 = TREE_TYPE (from_type2);
12482 deref_to_type1 = TREE_TYPE (to_type1);
12483 deref_to_type2 = TREE_TYPE (to_type2);
12485 /* The rules for pointers to members A::* are just like the rules
12486 for pointers A*, except opposite: if B is derived from A then
12487 A::* converts to B::*, not vice versa. For that reason, we
12488 switch the from_ and to_ variables here. */
12489 else if ((TYPE_PTRDATAMEM_P (from_type1) && TYPE_PTRDATAMEM_P (from_type2)
12490 && TYPE_PTRDATAMEM_P (to_type1) && TYPE_PTRDATAMEM_P (to_type2))
12491 || (TYPE_PTRMEMFUNC_P (from_type1)
12492 && TYPE_PTRMEMFUNC_P (from_type2)
12493 && TYPE_PTRMEMFUNC_P (to_type1)
12494 && TYPE_PTRMEMFUNC_P (to_type2)))
12496 deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
12497 deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
12498 deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
12499 deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
12502 if (deref_from_type1 != NULL_TREE
12503 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
12504 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
12506 /* This was one of the pointer or pointer-like conversions.
12508 [over.ics.rank]
12510 --If class B is derived directly or indirectly from class A,
12511 conversion of B* to A* is better than conversion of B* to
12512 void*, and conversion of A* to void* is better than
12513 conversion of B* to void*. */
12514 if (VOID_TYPE_P (deref_to_type1)
12515 && VOID_TYPE_P (deref_to_type2))
12517 if (is_properly_derived_from (deref_from_type1,
12518 deref_from_type2))
12519 return -1;
12520 else if (is_properly_derived_from (deref_from_type2,
12521 deref_from_type1))
12522 return 1;
12524 else if (VOID_TYPE_P (deref_to_type1)
12525 || VOID_TYPE_P (deref_to_type2))
12527 if (same_type_p (deref_from_type1, deref_from_type2))
12529 if (VOID_TYPE_P (deref_to_type2))
12531 if (is_properly_derived_from (deref_from_type1,
12532 deref_to_type1))
12533 return 1;
12535 /* We know that DEREF_TO_TYPE1 is `void' here. */
12536 else if (is_properly_derived_from (deref_from_type1,
12537 deref_to_type2))
12538 return -1;
12541 else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
12542 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
12544 /* [over.ics.rank]
12546 --If class B is derived directly or indirectly from class A
12547 and class C is derived directly or indirectly from B,
12549 --conversion of C* to B* is better than conversion of C* to
12552 --conversion of B* to A* is better than conversion of C* to
12553 A* */
12554 if (same_type_p (deref_from_type1, deref_from_type2))
12556 if (is_properly_derived_from (deref_to_type1,
12557 deref_to_type2))
12558 return 1;
12559 else if (is_properly_derived_from (deref_to_type2,
12560 deref_to_type1))
12561 return -1;
12563 else if (same_type_p (deref_to_type1, deref_to_type2))
12565 if (is_properly_derived_from (deref_from_type2,
12566 deref_from_type1))
12567 return 1;
12568 else if (is_properly_derived_from (deref_from_type1,
12569 deref_from_type2))
12570 return -1;
12574 else if (CLASS_TYPE_P (non_reference (from_type1))
12575 && same_type_p (from_type1, from_type2))
12577 tree from = non_reference (from_type1);
12579 /* [over.ics.rank]
12581 --binding of an expression of type C to a reference of type
12582 B& is better than binding an expression of type C to a
12583 reference of type A&
12585 --conversion of C to B is better than conversion of C to A, */
12586 if (is_properly_derived_from (from, to_type1)
12587 && is_properly_derived_from (from, to_type2))
12589 if (is_properly_derived_from (to_type1, to_type2))
12590 return 1;
12591 else if (is_properly_derived_from (to_type2, to_type1))
12592 return -1;
12595 else if (CLASS_TYPE_P (non_reference (to_type1))
12596 && same_type_p (to_type1, to_type2))
12598 tree to = non_reference (to_type1);
12600 /* [over.ics.rank]
12602 --binding of an expression of type B to a reference of type
12603 A& is better than binding an expression of type C to a
12604 reference of type A&,
12606 --conversion of B to A is better than conversion of C to A */
12607 if (is_properly_derived_from (from_type1, to)
12608 && is_properly_derived_from (from_type2, to))
12610 if (is_properly_derived_from (from_type2, from_type1))
12611 return 1;
12612 else if (is_properly_derived_from (from_type1, from_type2))
12613 return -1;
12617 /* [over.ics.rank]
12619 --S1 and S2 differ only in their qualification conversion and yield
12620 similar types T1 and T2 (_conv.qual_), respectively, and the cv-
12621 qualification signature of type T1 is a proper subset of the cv-
12622 qualification signature of type T2 */
12623 if (ics1->kind == ck_qual
12624 && ics2->kind == ck_qual
12625 && same_type_p (from_type1, from_type2))
12627 int result = comp_cv_qual_signature (to_type1, to_type2);
12628 if (result != 0)
12629 return result;
12632 /* [over.ics.rank]
12634 --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
12635 to an implicit object parameter of a non-static member function
12636 declared without a ref-qualifier, and either S1 binds an lvalue
12637 reference to an lvalue and S2 binds an rvalue reference or S1 binds an
12638 rvalue reference to an rvalue and S2 binds an lvalue reference (C++0x
12639 draft standard, 13.3.3.2)
12641 --S1 and S2 are reference bindings (_dcl.init.ref_), and the
12642 types to which the references refer are the same type except for
12643 top-level cv-qualifiers, and the type to which the reference
12644 initialized by S2 refers is more cv-qualified than the type to
12645 which the reference initialized by S1 refers.
12647 DR 1328 [over.match.best]: the context is an initialization by
12648 conversion function for direct reference binding (13.3.1.6) of a
12649 reference to function type, the return type of F1 is the same kind of
12650 reference (i.e. lvalue or rvalue) as the reference being initialized,
12651 and the return type of F2 is not. */
12653 if (ref_conv1 && ref_conv2)
12655 if (!ref_conv1->this_p && !ref_conv2->this_p
12656 && (ref_conv1->rvaluedness_matches_p
12657 != ref_conv2->rvaluedness_matches_p)
12658 && (same_type_p (ref_conv1->type, ref_conv2->type)
12659 || (TYPE_REF_IS_RVALUE (ref_conv1->type)
12660 != TYPE_REF_IS_RVALUE (ref_conv2->type))))
12662 if (ref_conv1->bad_p
12663 && !same_type_p (TREE_TYPE (ref_conv1->type),
12664 TREE_TYPE (ref_conv2->type)))
12665 /* Don't prefer a bad conversion that drops cv-quals to a bad
12666 conversion with the wrong rvalueness. */
12667 return 0;
12668 return (ref_conv1->rvaluedness_matches_p
12669 - ref_conv2->rvaluedness_matches_p);
12672 if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
12674 /* Per P0388R4:
12676 void f (int(&)[]), // (1)
12677 f (int(&)[1]), // (2)
12678 f (int*); // (3)
12680 (2) is better than (1), but (3) should be equal to (1) and to
12681 (2). For that reason we don't use ck_qual for (1) which would
12682 give it the cr_exact rank while (3) remains ck_identity.
12683 Therefore we compare (1) and (2) here. For (1) we'll have
12685 ck_ref_bind <- ck_identity
12686 int[] & int[1]
12688 so to handle this we must look at ref_conv. */
12689 bool c1 = conv_binds_to_array_of_unknown_bound (ref_conv1);
12690 bool c2 = conv_binds_to_array_of_unknown_bound (ref_conv2);
12691 if (c1 && !c2)
12692 return -1;
12693 else if (!c1 && c2)
12694 return 1;
12696 int q1 = cp_type_quals (TREE_TYPE (ref_conv1->type));
12697 int q2 = cp_type_quals (TREE_TYPE (ref_conv2->type));
12698 if (ref_conv1->bad_p)
12700 /* Prefer the one that drops fewer cv-quals. */
12701 tree ftype = next_conversion (ref_conv1)->type;
12702 int fquals = cp_type_quals (ftype);
12703 q1 ^= fquals;
12704 q2 ^= fquals;
12706 return comp_cv_qualification (q2, q1);
12710 /* [over.ics.rank]
12712 Per CWG 1601:
12713 -- A conversion that promotes an enumeration whose underlying type
12714 is fixed to its underlying type is better than one that promotes to
12715 the promoted underlying type, if the two are different. */
12716 if (ics1->rank == cr_promotion
12717 && ics2->rank == cr_promotion
12718 && UNSCOPED_ENUM_P (from_type1)
12719 && ENUM_FIXED_UNDERLYING_TYPE_P (from_type1)
12720 && same_type_p (from_type1, from_type2))
12722 tree utype = ENUM_UNDERLYING_TYPE (from_type1);
12723 tree prom = type_promotes_to (from_type1);
12724 if (!same_type_p (utype, prom))
12726 if (same_type_p (to_type1, utype)
12727 && same_type_p (to_type2, prom))
12728 return 1;
12729 else if (same_type_p (to_type2, utype)
12730 && same_type_p (to_type1, prom))
12731 return -1;
12735 /* Neither conversion sequence is better than the other. */
12736 return 0;
12739 /* The source type for this standard conversion sequence. */
12741 static tree
12742 source_type (conversion *t)
12744 return strip_standard_conversion (t)->type;
12747 /* Note a warning about preferring WINNER to LOSER. We do this by storing
12748 a pointer to LOSER and re-running joust to produce the warning if WINNER
12749 is actually used. */
12751 static void
12752 add_warning (struct z_candidate *winner, struct z_candidate *loser)
12754 candidate_warning *cw = (candidate_warning *)
12755 conversion_obstack_alloc (sizeof (candidate_warning));
12756 cw->loser = loser;
12757 cw->next = winner->warnings;
12758 winner->warnings = cw;
12761 /* CAND is a constructor candidate in joust in C++17 and up. If it copies a
12762 prvalue returned from a conversion function, return true. Otherwise, return
12763 false. */
12765 static bool
12766 joust_maybe_elide_copy (z_candidate *cand)
12768 tree fn = cand->fn;
12769 if (!DECL_COPY_CONSTRUCTOR_P (fn) && !DECL_MOVE_CONSTRUCTOR_P (fn))
12770 return false;
12771 conversion *conv = cand->convs[0];
12772 if (conv->kind == ck_ambig)
12773 return false;
12774 gcc_checking_assert (conv->kind == ck_ref_bind);
12775 conv = next_conversion (conv);
12776 if (conv->kind == ck_user && !TYPE_REF_P (conv->type))
12778 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
12779 (conv->type, DECL_CONTEXT (fn)));
12780 z_candidate *uc = conv->cand;
12781 if (DECL_CONV_FN_P (uc->fn))
12782 return true;
12784 return false;
12787 /* Return the class that CAND's implicit object parameter refers to. */
12789 static tree
12790 class_of_implicit_object (z_candidate *cand)
12792 if (!DECL_IOBJ_MEMBER_FUNCTION_P (cand->fn))
12793 return NULL_TREE;
12795 /* "For conversion functions that are implicit object member functions,
12796 the function is considered to be a member of the class of the implied
12797 object argument for the purpose of defining the type of the implicit
12798 object parameter." */
12799 if (DECL_CONV_FN_P (cand->fn))
12800 return TYPE_MAIN_VARIANT (TREE_TYPE (cand->first_arg));
12802 /* "For non-conversion functions that are implicit object member
12803 functions nominated by a using-declaration in a derived class, the
12804 function is considered to be a member of the derived class for the
12805 purpose of defining the type of the implicit object parameter."
12807 That derived class is reflected in the conversion_path binfo. */
12808 return BINFO_TYPE (cand->conversion_path);
12811 /* Return whether the first parameter of C1 matches the second parameter
12812 of C2. */
12814 static bool
12815 reversed_match (z_candidate *c1, z_candidate *c2)
12817 tree fn1 = c1->fn;
12818 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (c2->fn));
12819 tree parm2 = TREE_VALUE (TREE_CHAIN (parms2));
12820 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn1))
12822 tree ctx = class_of_implicit_object (c1);
12823 return iobj_parm_corresponds_to (fn1, parm2, ctx);
12825 else
12827 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
12828 tree parm1 = TREE_VALUE (parms1);
12829 return same_type_p (parm1, parm2);
12833 /* True if the defining declarations of the two candidates have equivalent
12834 parameters. MATCH_KIND controls whether we're trying to compare the
12835 original declarations (for a warning) or the actual candidates. */
12837 enum class pmatch { original, current };
12839 static bool
12840 cand_parms_match (z_candidate *c1, z_candidate *c2, pmatch match_kind)
12842 tree fn1 = c1->fn;
12843 tree fn2 = c2->fn;
12844 bool reversed = (match_kind == pmatch::current
12845 && c1->reversed () != c2->reversed ());
12846 if (fn1 == fn2 && !reversed)
12847 return true;
12848 if (identifier_p (fn1) || identifier_p (fn2))
12849 return false;
12850 if (match_kind == pmatch::original)
12852 /* We don't look at c1->template_decl because that's only set for
12853 primary templates, not e.g. non-template member functions of
12854 class templates. */
12855 tree t1 = most_general_template (fn1);
12856 tree t2 = most_general_template (fn2);
12857 if (t1 || t2)
12859 if (!t1 || !t2)
12860 return false;
12861 if (t1 == t2)
12862 return true;
12863 fn1 = DECL_TEMPLATE_RESULT (t1);
12864 fn2 = DECL_TEMPLATE_RESULT (t2);
12868 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
12869 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (fn2));
12871 if (DECL_FUNCTION_MEMBER_P (fn1)
12872 && DECL_FUNCTION_MEMBER_P (fn2))
12874 tree base1 = DECL_CONTEXT (strip_inheriting_ctors (fn1));
12875 tree base2 = DECL_CONTEXT (strip_inheriting_ctors (fn2));
12876 if (base1 != base2)
12877 return false;
12879 if (reversed)
12880 return (reversed_match (c1, c2)
12881 && reversed_match (c2, c1));
12883 /* Use object_parms_correspond to simplify comparing iobj/xobj/static
12884 member functions. */
12885 if (!object_parms_correspond (fn1, fn2, base1))
12886 return false;
12888 /* We just compared the object parameters, if they don't correspond
12889 we already returned false. */
12890 auto skip_parms = [] (tree fn, tree parms)
12892 if (DECL_XOBJ_MEMBER_FUNCTION_P (fn))
12893 return TREE_CHAIN (parms);
12894 else
12895 return skip_artificial_parms_for (fn, parms);
12897 parms1 = skip_parms (fn1, parms1);
12898 parms2 = skip_parms (fn2, parms2);
12900 else if (reversed)
12901 return (reversed_match (c1, c2)
12902 && reversed_match (c2, c1));
12903 return compparms (parms1, parms2);
12906 /* True iff FN is a copy or move constructor or assignment operator. */
12908 static bool
12909 sfk_copy_or_move (tree fn)
12911 if (TREE_CODE (fn) != FUNCTION_DECL)
12912 return false;
12913 special_function_kind sfk = special_function_p (fn);
12914 return sfk >= sfk_copy_constructor && sfk <= sfk_move_assignment;
12917 /* Compare two candidates for overloading as described in
12918 [over.match.best]. Return values:
12920 1: cand1 is better than cand2
12921 -1: cand2 is better than cand1
12922 0: cand1 and cand2 are indistinguishable */
12924 static int
12925 joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn,
12926 tsubst_flags_t complain)
12928 int winner = 0;
12929 int off1 = 0, off2 = 0;
12930 size_t i;
12931 size_t len;
12933 /* Candidates that involve bad conversions are always worse than those
12934 that don't. */
12935 if (cand1->viable > cand2->viable)
12936 return 1;
12937 if (cand1->viable < cand2->viable)
12938 return -1;
12940 /* If we have two pseudo-candidates for conversions to the same type,
12941 or two candidates for the same function, arbitrarily pick one. */
12942 if (cand1->fn == cand2->fn
12943 && cand1->reversed () == cand2->reversed ()
12944 && (IS_TYPE_OR_DECL_P (cand1->fn)))
12945 return 1;
12947 /* Prefer a non-deleted function over an implicitly deleted move
12948 constructor or assignment operator. This differs slightly from the
12949 wording for issue 1402 (which says the move op is ignored by overload
12950 resolution), but this way produces better error messages. */
12951 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12952 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12953 && DECL_DELETED_FN (cand1->fn) != DECL_DELETED_FN (cand2->fn))
12955 if (DECL_DELETED_FN (cand1->fn) && DECL_DEFAULTED_FN (cand1->fn)
12956 && move_fn_p (cand1->fn))
12957 return -1;
12958 if (DECL_DELETED_FN (cand2->fn) && DECL_DEFAULTED_FN (cand2->fn)
12959 && move_fn_p (cand2->fn))
12960 return 1;
12963 /* a viable function F1
12964 is defined to be a better function than another viable function F2 if
12965 for all arguments i, ICSi(F1) is not a worse conversion sequence than
12966 ICSi(F2), and then */
12968 /* for some argument j, ICSj(F1) is a better conversion sequence than
12969 ICSj(F2) */
12971 /* For comparing static and non-static member functions, we ignore
12972 the implicit object parameter of the non-static function. The
12973 standard says to pretend that the static function has an object
12974 parm, but that won't work with operator overloading. */
12975 len = cand1->num_convs;
12976 if (len != cand2->num_convs)
12978 int static_1 = (TREE_CODE (cand1->fn) == FUNCTION_DECL
12979 && DECL_STATIC_FUNCTION_P (cand1->fn));
12980 int static_2 = (TREE_CODE (cand2->fn) == FUNCTION_DECL
12981 && DECL_STATIC_FUNCTION_P (cand2->fn));
12983 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
12984 && TREE_CODE (cand2->fn) == FUNCTION_DECL
12985 && DECL_CONSTRUCTOR_P (cand1->fn)
12986 && is_list_ctor (cand1->fn) != is_list_ctor (cand2->fn))
12987 /* We're comparing a near-match list constructor and a near-match
12988 non-list constructor. Just treat them as unordered. */
12989 return 0;
12991 gcc_assert (static_1 != static_2);
12993 if (static_1)
12995 /* C++23 [over.best.ics.general] says:
12996 When the parameter is the implicit object parameter of a static
12997 member function, the implicit conversion sequence is a standard
12998 conversion sequence that is neither better nor worse than any
12999 other standard conversion sequence. */
13000 if (CONVERSION_RANK (cand2->convs[0]) >= cr_user)
13001 winner = 1;
13002 off2 = 1;
13004 else
13006 if (CONVERSION_RANK (cand1->convs[0]) >= cr_user)
13007 winner = -1;
13008 off1 = 1;
13009 --len;
13013 for (i = 0; i < len; ++i)
13015 conversion *t1 = cand1->convs[i + off1];
13016 conversion *t2 = cand2->convs[i + off2];
13017 int comp = compare_ics (t1, t2);
13019 if (comp != 0)
13021 if ((complain & tf_warning)
13022 && warn_sign_promo
13023 && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
13024 == cr_std + cr_promotion)
13025 && t1->kind == ck_std
13026 && t2->kind == ck_std
13027 && TREE_CODE (t1->type) == INTEGER_TYPE
13028 && TREE_CODE (t2->type) == INTEGER_TYPE
13029 && (TYPE_PRECISION (t1->type)
13030 == TYPE_PRECISION (t2->type))
13031 && (TYPE_UNSIGNED (next_conversion (t1)->type)
13032 || (TREE_CODE (next_conversion (t1)->type)
13033 == ENUMERAL_TYPE)))
13035 tree type = next_conversion (t1)->type;
13036 tree type1, type2;
13037 struct z_candidate *w, *l;
13038 if (comp > 0)
13039 type1 = t1->type, type2 = t2->type,
13040 w = cand1, l = cand2;
13041 else
13042 type1 = t2->type, type2 = t1->type,
13043 w = cand2, l = cand1;
13045 if (warn)
13047 warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
13048 type, type1, type2);
13049 warning (OPT_Wsign_promo, " in call to %qD", w->fn);
13051 else
13052 add_warning (w, l);
13055 if (winner && comp != winner)
13057 /* Ambiguity between normal and reversed comparison operators
13058 with the same parameter types. P2468 decided not to go with
13059 this approach to resolving the ambiguity, so pedwarn. */
13060 if ((complain & tf_warning_or_error)
13061 && (cand1->reversed () != cand2->reversed ())
13062 && cand_parms_match (cand1, cand2, pmatch::original))
13064 struct z_candidate *w, *l;
13065 if (cand2->reversed ())
13066 winner = 1, w = cand1, l = cand2;
13067 else
13068 winner = -1, w = cand2, l = cand1;
13069 if (warn)
13071 auto_diagnostic_group d;
13072 if (pedwarn (input_location, 0,
13073 "C++20 says that these are ambiguous, "
13074 "even though the second is reversed:"))
13076 print_z_candidate (input_location,
13077 N_("candidate 1:"), w);
13078 print_z_candidate (input_location,
13079 N_("candidate 2:"), l);
13080 if (w->fn == l->fn
13081 && DECL_IOBJ_MEMBER_FUNCTION_P (w->fn)
13082 && (type_memfn_quals (TREE_TYPE (w->fn))
13083 & TYPE_QUAL_CONST) == 0)
13085 /* Suggest adding const to
13086 struct A { bool operator==(const A&); }; */
13087 tree parmtype
13088 = FUNCTION_FIRST_USER_PARMTYPE (w->fn);
13089 parmtype = TREE_VALUE (parmtype);
13090 if (TYPE_REF_P (parmtype)
13091 && TYPE_READONLY (TREE_TYPE (parmtype))
13092 && (same_type_ignoring_top_level_qualifiers_p
13093 (TREE_TYPE (parmtype),
13094 DECL_CONTEXT (w->fn))))
13095 inform (DECL_SOURCE_LOCATION (w->fn),
13096 "try making the operator a %<const%> "
13097 "member function");
13101 else
13102 add_warning (w, l);
13103 return winner;
13106 winner = 0;
13107 goto tweak;
13109 winner = comp;
13113 /* warn about confusing overload resolution for user-defined conversions,
13114 either between a constructor and a conversion op, or between two
13115 conversion ops. */
13116 if ((complain & tf_warning)
13117 /* In C++17, the constructor might have been elided, which means that
13118 an originally null ->second_conv could become non-null. */
13119 && winner && warn_conversion && cand1->second_conv && cand2->second_conv
13120 && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
13121 && winner != compare_ics (cand1->second_conv, cand2->second_conv))
13123 struct z_candidate *w, *l;
13124 bool give_warning = false;
13126 if (winner == 1)
13127 w = cand1, l = cand2;
13128 else
13129 w = cand2, l = cand1;
13131 /* We don't want to complain about `X::operator T1 ()'
13132 beating `X::operator T2 () const', when T2 is a no less
13133 cv-qualified version of T1. */
13134 if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
13135 && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
13137 tree t = TREE_TYPE (TREE_TYPE (l->fn));
13138 tree f = TREE_TYPE (TREE_TYPE (w->fn));
13140 if (TREE_CODE (t) == TREE_CODE (f) && INDIRECT_TYPE_P (t))
13142 t = TREE_TYPE (t);
13143 f = TREE_TYPE (f);
13145 if (!comp_ptr_ttypes (t, f))
13146 give_warning = true;
13148 else
13149 give_warning = true;
13151 if (!give_warning)
13152 /*NOP*/;
13153 else if (warn)
13155 tree source = source_type (w->convs[0]);
13156 if (INDIRECT_TYPE_P (source))
13157 source = TREE_TYPE (source);
13158 auto_diagnostic_group d;
13159 if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
13160 && warning (OPT_Wconversion, " for conversion from %qH to %qI",
13161 source, w->second_conv->type))
13163 inform (input_location, " because conversion sequence "
13164 "for the argument is better");
13167 else
13168 add_warning (w, l);
13171 if (winner)
13172 return winner;
13174 /* DR 495 moved this tiebreaker above the template ones. */
13175 /* or, if not that,
13176 the context is an initialization by user-defined conversion (see
13177 _dcl.init_ and _over.match.user_) and the standard conversion
13178 sequence from the return type of F1 to the destination type (i.e.,
13179 the type of the entity being initialized) is a better conversion
13180 sequence than the standard conversion sequence from the return type
13181 of F2 to the destination type. */
13183 if (cand1->second_conv)
13185 winner = compare_ics (cand1->second_conv, cand2->second_conv);
13186 if (winner)
13187 return winner;
13190 /* CWG2735 (PR109247): A copy/move ctor/op= for which its operand uses an
13191 explicit conversion (due to list-initialization) is worse. */
13193 z_candidate *sp = nullptr;
13194 if (sfk_copy_or_move (cand1->fn))
13195 sp = cand1;
13196 if (sfk_copy_or_move (cand2->fn))
13197 sp = sp ? nullptr : cand2;
13198 if (sp)
13200 conversion *conv = sp->convs[!DECL_CONSTRUCTOR_P (sp->fn)];
13201 if (conv->user_conv_p)
13202 for (; conv; conv = next_conversion (conv))
13203 if (conv->kind == ck_user
13204 && DECL_P (conv->cand->fn)
13205 && DECL_NONCONVERTING_P (conv->cand->fn))
13206 return (sp == cand1) ? -1 : 1;
13210 /* DR2327: C++17 copy elision in [over.match.ctor] (direct-init) context.
13211 The standard currently says that only constructors are candidates, but if
13212 one copies a prvalue returned by a conversion function we prefer that.
13214 Clang does something similar, as discussed at
13215 http://lists.isocpp.org/core/2017/10/3166.php
13216 http://lists.isocpp.org/core/2019/03/5721.php */
13217 if (len == 1 && cxx_dialect >= cxx17
13218 && DECL_P (cand1->fn)
13219 && DECL_COMPLETE_CONSTRUCTOR_P (cand1->fn)
13220 && !(cand1->flags & LOOKUP_ONLYCONVERTING))
13222 bool elided1 = joust_maybe_elide_copy (cand1);
13223 bool elided2 = joust_maybe_elide_copy (cand2);
13224 winner = elided1 - elided2;
13225 if (winner)
13226 return winner;
13229 /* or, if not that,
13230 F1 is a non-template function and F2 is a template function
13231 specialization. */
13233 if (!cand1->template_decl && cand2->template_decl)
13234 return 1;
13235 else if (cand1->template_decl && !cand2->template_decl)
13236 return -1;
13238 /* or, if not that,
13239 F1 and F2 are template functions and the function template for F1 is
13240 more specialized than the template for F2 according to the partial
13241 ordering rules. */
13243 if (cand1->template_decl && cand2->template_decl)
13245 winner = more_specialized_fn
13246 (TI_TEMPLATE (cand1->template_decl),
13247 TI_TEMPLATE (cand2->template_decl),
13248 /* [temp.func.order]: The presence of unused ellipsis and default
13249 arguments has no effect on the partial ordering of function
13250 templates. add_function_candidate() will not have
13251 counted the "this" argument for constructors. */
13252 cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
13253 if (winner)
13254 return winner;
13257 /* F1 and F2 are non-template functions and
13258 - they have the same non-object-parameter-type-lists ([dcl.fct]), and
13259 - if they are member functions, both are direct members of the same
13260 class, and
13261 - if both are non-static member functions, they have the same types for
13262 their object parameters, and
13263 - F1 is more constrained than F2 according to the partial ordering of
13264 constraints described in [temp.constr.order]. */
13265 if (flag_concepts && DECL_P (cand1->fn) && DECL_P (cand2->fn)
13266 && !cand1->template_decl && !cand2->template_decl
13267 && cand_parms_match (cand1, cand2, pmatch::current))
13269 winner = more_constrained (cand1->fn, cand2->fn);
13270 if (winner)
13271 return winner;
13274 /* F2 is a rewritten candidate (12.4.1.2) and F1 is not, or F1 and F2 are
13275 rewritten candidates, and F2 is a synthesized candidate with reversed
13276 order of parameters and F1 is not. */
13277 if (cand1->rewritten ())
13279 if (!cand2->rewritten ())
13280 return -1;
13281 if (!cand1->reversed () && cand2->reversed ())
13282 return 1;
13283 if (cand1->reversed () && !cand2->reversed ())
13284 return -1;
13286 else if (cand2->rewritten ())
13287 return 1;
13289 if (deduction_guide_p (cand1->fn))
13291 gcc_assert (deduction_guide_p (cand2->fn));
13293 /* F1 and F2 are generated from class template argument deduction for a
13294 class D, and F2 is generated from inheriting constructors from a base
13295 class of D while F1 is not, and for each explicit function argument,
13296 the corresponding parameters of F1 and F2 are either both ellipses or
13297 have the same type. */
13298 bool inherited1 = inherited_guide_p (cand1->fn);
13299 bool inherited2 = inherited_guide_p (cand2->fn);
13300 if (int diff = inherited2 - inherited1)
13302 for (i = 0; i < len; ++i)
13304 conversion *t1 = cand1->convs[i + off1];
13305 conversion *t2 = cand2->convs[i + off2];
13306 /* ??? It seems the ellipses part of this tiebreaker isn't
13307 needed since a mismatch should have broken the tie earlier
13308 during ICS comparison. */
13309 gcc_checking_assert (t1->ellipsis_p == t2->ellipsis_p);
13310 if (!same_type_p (t1->type, t2->type))
13311 break;
13313 if (i == len)
13314 return diff;
13317 /* F1 is generated from a deduction-guide (13.3.1.8) and F2 is not */
13318 /* We distinguish between candidates from an explicit deduction guide and
13319 candidates built from a constructor based on DECL_ARTIFICIAL. */
13320 int art1 = DECL_ARTIFICIAL (cand1->fn);
13321 int art2 = DECL_ARTIFICIAL (cand2->fn);
13322 if (art1 != art2)
13323 return art2 - art1;
13325 if (art1)
13327 /* Prefer the special copy guide over a declared copy/move
13328 constructor. */
13329 if (copy_guide_p (cand1->fn))
13330 return 1;
13331 if (copy_guide_p (cand2->fn))
13332 return -1;
13334 /* Prefer a candidate generated from a non-template constructor. */
13335 int tg1 = template_guide_p (cand1->fn);
13336 int tg2 = template_guide_p (cand2->fn);
13337 if (tg1 != tg2)
13338 return tg2 - tg1;
13342 /* F1 is a constructor for a class D, F2 is a constructor for a base class B
13343 of D, and for all arguments the corresponding parameters of F1 and F2 have
13344 the same type (CWG 2273/2277). */
13345 if (DECL_INHERITED_CTOR (cand1->fn) || DECL_INHERITED_CTOR (cand2->fn))
13347 tree base1 = DECL_CONTEXT (strip_inheriting_ctors (cand1->fn));
13348 tree base2 = DECL_CONTEXT (strip_inheriting_ctors (cand2->fn));
13350 bool used1 = false;
13351 bool used2 = false;
13352 if (base1 == base2)
13353 /* No difference. */;
13354 else if (DERIVED_FROM_P (base1, base2))
13355 used1 = true;
13356 else if (DERIVED_FROM_P (base2, base1))
13357 used2 = true;
13359 if (int diff = used2 - used1)
13361 for (i = 0; i < len; ++i)
13363 conversion *t1 = cand1->convs[i + off1];
13364 conversion *t2 = cand2->convs[i + off2];
13365 if (!same_type_p (t1->type, t2->type))
13366 break;
13368 if (i == len)
13369 return diff;
13373 /* Check whether we can discard a builtin candidate, either because we
13374 have two identical ones or matching builtin and non-builtin candidates.
13376 (Pedantically in the latter case the builtin which matched the user
13377 function should not be added to the overload set, but we spot it here.
13379 [over.match.oper]
13380 ... the builtin candidates include ...
13381 - do not have the same parameter type list as any non-template
13382 non-member candidate. */
13384 if (identifier_p (cand1->fn) || identifier_p (cand2->fn))
13386 for (i = 0; i < len; ++i)
13387 if (!same_type_p (cand1->convs[i]->type,
13388 cand2->convs[i]->type))
13389 break;
13390 if (i == cand1->num_convs)
13392 if (cand1->fn == cand2->fn)
13393 /* Two built-in candidates; arbitrarily pick one. */
13394 return 1;
13395 else if (identifier_p (cand1->fn))
13396 /* cand1 is built-in; prefer cand2. */
13397 return -1;
13398 else
13399 /* cand2 is built-in; prefer cand1. */
13400 return 1;
13404 /* For candidates of a multi-versioned function, make the version with
13405 the highest priority win. This version will be checked for dispatching
13406 first. If this version can be inlined into the caller, the front-end
13407 will simply make a direct call to this function. */
13409 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
13410 && DECL_FUNCTION_VERSIONED (cand1->fn)
13411 && TREE_CODE (cand2->fn) == FUNCTION_DECL
13412 && DECL_FUNCTION_VERSIONED (cand2->fn))
13414 tree f1 = TREE_TYPE (cand1->fn);
13415 tree f2 = TREE_TYPE (cand2->fn);
13416 tree p1 = TYPE_ARG_TYPES (f1);
13417 tree p2 = TYPE_ARG_TYPES (f2);
13419 /* Check if cand1->fn and cand2->fn are versions of the same function. It
13420 is possible that cand1->fn and cand2->fn are function versions but of
13421 different functions. Check types to see if they are versions of the same
13422 function. */
13423 if (compparms (p1, p2)
13424 && same_type_p (TREE_TYPE (f1), TREE_TYPE (f2)))
13426 /* Always make the version with the higher priority, more
13427 specialized, win. */
13428 gcc_assert (targetm.compare_version_priority);
13429 if (targetm.compare_version_priority (cand1->fn, cand2->fn) >= 0)
13430 return 1;
13431 else
13432 return -1;
13436 /* If the two function declarations represent the same function (this can
13437 happen with declarations in multiple scopes and arg-dependent lookup),
13438 arbitrarily choose one. But first make sure the default args we're
13439 using match. */
13440 if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
13441 && equal_functions (cand1->fn, cand2->fn))
13443 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
13444 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
13446 gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
13448 for (i = 0; i < len; ++i)
13450 /* Don't crash if the fn is variadic. */
13451 if (!parms1)
13452 break;
13453 parms1 = TREE_CHAIN (parms1);
13454 parms2 = TREE_CHAIN (parms2);
13457 if (off1)
13458 parms1 = TREE_CHAIN (parms1);
13459 else if (off2)
13460 parms2 = TREE_CHAIN (parms2);
13462 for (; parms1; ++i)
13464 if (!cp_tree_equal (TREE_PURPOSE (parms1),
13465 TREE_PURPOSE (parms2)))
13467 if (warn)
13469 if (complain & tf_error)
13471 auto_diagnostic_group d;
13472 if (permerror (input_location,
13473 "default argument mismatch in "
13474 "overload resolution"))
13476 inform (DECL_SOURCE_LOCATION (cand1->fn),
13477 " candidate 1: %q#F", cand1->fn);
13478 inform (DECL_SOURCE_LOCATION (cand2->fn),
13479 " candidate 2: %q#F", cand2->fn);
13482 else
13483 return 0;
13485 else
13486 add_warning (cand1, cand2);
13487 break;
13489 parms1 = TREE_CHAIN (parms1);
13490 parms2 = TREE_CHAIN (parms2);
13493 return 1;
13496 tweak:
13498 /* Extension: If the worst conversion for one candidate is better than the
13499 worst conversion for the other, take the first. */
13500 if (!pedantic && (complain & tf_warning_or_error))
13502 conversion_rank rank1 = cr_identity, rank2 = cr_identity;
13503 struct z_candidate *w = 0, *l = 0;
13505 for (i = 0; i < len; ++i)
13507 if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
13508 rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
13509 if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
13510 rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
13512 if (rank1 < rank2)
13513 winner = 1, w = cand1, l = cand2;
13514 if (rank1 > rank2)
13515 winner = -1, w = cand2, l = cand1;
13516 if (winner)
13518 /* Don't choose a deleted function over ambiguity. */
13519 if (DECL_P (w->fn) && DECL_DELETED_FN (w->fn))
13520 return 0;
13521 if (warn)
13523 auto_diagnostic_group d;
13524 if (pedwarn (input_location, 0,
13525 "ISO C++ says that these are ambiguous, even "
13526 "though the worst conversion for the first is "
13527 "better than the worst conversion for the second:"))
13529 print_z_candidate (input_location, N_("candidate 1:"), w);
13530 print_z_candidate (input_location, N_("candidate 2:"), l);
13533 else
13534 add_warning (w, l);
13535 return winner;
13539 gcc_assert (!winner);
13540 return 0;
13543 /* Given a list of candidates for overloading, find the best one, if any.
13544 This algorithm has a worst case of O(2n) (winner is last), and a best
13545 case of O(n/2) (totally ambiguous); much better than a sorting
13546 algorithm. The candidates list is assumed to be sorted according
13547 to viability (via splice_viable). */
13549 static struct z_candidate *
13550 tourney (struct z_candidate *candidates, tsubst_flags_t complain)
13552 struct z_candidate **champ = &candidates, **challenger;
13553 int fate;
13554 struct z_candidate *previous_worse_champ = nullptr;
13556 /* Walk through the list once, comparing each current champ to the next
13557 candidate, knocking out a candidate or two with each comparison. */
13559 for (challenger = &candidates->next; *challenger && (*challenger)->viable; )
13561 fate = joust (*champ, *challenger, 0, complain);
13562 if (fate == 1)
13563 challenger = &(*challenger)->next;
13564 else if (fate == -1)
13566 previous_worse_champ = *champ;
13567 champ = challenger;
13568 challenger = &(*challenger)->next;
13570 else
13572 previous_worse_champ = nullptr;
13573 champ = &(*challenger)->next;
13574 if (!*champ || !(*champ)->viable
13575 || (*champ)->viable < (*challenger)->viable)
13577 champ = nullptr;
13578 break;
13580 challenger = &(*champ)->next;
13584 /* Make sure the champ is better than all the candidates it hasn't yet
13585 been compared to. */
13587 if (champ)
13588 for (challenger = &candidates;
13589 challenger != champ;
13590 challenger = &(*challenger)->next)
13592 if (*challenger == previous_worse_champ)
13593 /* We already know this candidate is worse than the champ. */
13594 continue;
13595 fate = joust (*champ, *challenger, 0, complain);
13596 if (fate != 1)
13598 champ = nullptr;
13599 break;
13603 if (!champ)
13604 return nullptr;
13606 /* Move the champ to the front of the candidate list. */
13608 if (champ != &candidates)
13610 z_candidate *saved_champ = *champ;
13611 *champ = saved_champ->next;
13612 saved_champ->next = candidates;
13613 candidates = saved_champ;
13616 return candidates;
13619 /* Returns nonzero if things of type FROM can be converted to TO. */
13621 bool
13622 can_convert (tree to, tree from, tsubst_flags_t complain)
13624 tree arg = NULL_TREE;
13625 /* implicit_conversion only considers user-defined conversions
13626 if it has an expression for the call argument list. */
13627 if (CLASS_TYPE_P (from) || CLASS_TYPE_P (to))
13628 arg = build_stub_object (from);
13629 return can_convert_arg (to, from, arg, LOOKUP_IMPLICIT, complain);
13632 /* Returns nonzero if things of type FROM can be converted to TO with a
13633 standard conversion. */
13635 bool
13636 can_convert_standard (tree to, tree from, tsubst_flags_t complain)
13638 return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT, complain);
13641 /* Returns nonzero if ARG (of type FROM) can be converted to TO. */
13643 bool
13644 can_convert_arg (tree to, tree from, tree arg, int flags,
13645 tsubst_flags_t complain)
13647 conversion *t;
13648 bool ok_p;
13650 conversion_obstack_sentinel cos;
13651 /* We want to discard any access checks done for this test,
13652 as we might not be in the appropriate access context and
13653 we'll do the check again when we actually perform the
13654 conversion. */
13655 push_deferring_access_checks (dk_deferred);
13657 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
13658 flags, complain);
13659 ok_p = (t && !t->bad_p);
13661 /* Discard the access checks now. */
13662 pop_deferring_access_checks ();
13664 return ok_p;
13667 /* Like can_convert_arg, but allows dubious conversions as well. */
13669 bool
13670 can_convert_arg_bad (tree to, tree from, tree arg, int flags,
13671 tsubst_flags_t complain)
13673 conversion *t;
13675 conversion_obstack_sentinel cos;
13676 /* Try to perform the conversion. */
13677 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
13678 flags, complain);
13680 return t != NULL;
13683 /* Return an IMPLICIT_CONV_EXPR from EXPR to TYPE with bits set from overload
13684 resolution FLAGS. */
13686 tree
13687 build_implicit_conv_flags (tree type, tree expr, int flags)
13689 /* In a template, we are only concerned about determining the
13690 type of non-dependent expressions, so we do not have to
13691 perform the actual conversion. But for initializers, we
13692 need to be able to perform it at instantiation
13693 (or instantiate_non_dependent_expr) time. */
13694 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
13695 if (!(flags & LOOKUP_ONLYCONVERTING))
13696 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13697 if (flags & LOOKUP_NO_NARROWING)
13698 IMPLICIT_CONV_EXPR_BRACED_INIT (expr) = true;
13699 return expr;
13702 /* Convert EXPR to TYPE. Return the converted expression.
13704 Note that we allow bad conversions here because by the time we get to
13705 this point we are committed to doing the conversion. If we end up
13706 doing a bad conversion, convert_like will complain. */
13708 tree
13709 perform_implicit_conversion_flags (tree type, tree expr,
13710 tsubst_flags_t complain, int flags)
13712 conversion *conv;
13713 location_t loc = cp_expr_loc_or_input_loc (expr);
13715 if (TYPE_REF_P (type))
13716 expr = mark_lvalue_use (expr);
13717 else
13718 expr = mark_rvalue_use (expr);
13720 if (error_operand_p (expr))
13721 return error_mark_node;
13723 conversion_obstack_sentinel cos;
13725 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
13726 /*c_cast_p=*/false,
13727 flags, complain);
13729 if (!conv)
13731 if (complain & tf_error)
13732 implicit_conversion_error (loc, type, expr);
13733 expr = error_mark_node;
13735 else if (processing_template_decl && conv->kind != ck_identity)
13736 expr = build_implicit_conv_flags (type, expr, flags);
13737 else
13739 /* Give a conversion call the same location as expr. */
13740 iloc_sentinel il (loc);
13741 expr = convert_like (conv, expr, complain);
13744 return expr;
13747 tree
13748 perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
13750 return perform_implicit_conversion_flags (type, expr, complain,
13751 LOOKUP_IMPLICIT);
13754 /* Convert EXPR to TYPE (as a direct-initialization) if that is
13755 permitted. If the conversion is valid, the converted expression is
13756 returned. Otherwise, NULL_TREE is returned, except in the case
13757 that TYPE is a class type; in that case, an error is issued. If
13758 C_CAST_P is true, then this direct-initialization is taking
13759 place as part of a static_cast being attempted as part of a C-style
13760 cast. */
13762 tree
13763 perform_direct_initialization_if_possible (tree type,
13764 tree expr,
13765 bool c_cast_p,
13766 tsubst_flags_t complain)
13768 conversion *conv;
13770 if (type == error_mark_node || error_operand_p (expr))
13771 return error_mark_node;
13772 /* [dcl.init]
13774 If the destination type is a (possibly cv-qualified) class type:
13776 -- If the initialization is direct-initialization ...,
13777 constructors are considered.
13779 -- If overload resolution is successful, the selected constructor
13780 is called to initialize the object, with the initializer expression
13781 or expression-list as its argument(s).
13783 -- Otherwise, if no constructor is viable, the destination type is
13784 a (possibly cv-qualified) aggregate class A, and the initializer is
13785 a parenthesized expression-list, the object is initialized as
13786 follows... */
13787 if (CLASS_TYPE_P (type))
13789 releasing_vec args (make_tree_vector_single (expr));
13790 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
13791 &args, type, LOOKUP_NORMAL, complain);
13792 return build_cplus_new (type, expr, complain);
13795 conversion_obstack_sentinel cos;
13797 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
13798 c_cast_p,
13799 LOOKUP_NORMAL, complain);
13800 if (!conv || conv->bad_p)
13801 expr = NULL_TREE;
13802 else if (processing_template_decl && conv->kind != ck_identity)
13804 /* In a template, we are only concerned about determining the
13805 type of non-dependent expressions, so we do not have to
13806 perform the actual conversion. But for initializers, we
13807 need to be able to perform it at instantiation
13808 (or instantiate_non_dependent_expr) time. */
13809 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
13810 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13812 else
13813 expr = convert_like (conv, expr, NULL_TREE, 0,
13814 /*issue_conversion_warnings=*/false,
13815 c_cast_p, /*nested_p=*/false, complain);
13817 return expr;
13820 /* When initializing a reference that lasts longer than a full-expression,
13821 this special rule applies:
13823 [class.temporary]
13825 The temporary to which the reference is bound or the temporary
13826 that is the complete object to which the reference is bound
13827 persists for the lifetime of the reference.
13829 The temporaries created during the evaluation of the expression
13830 initializing the reference, except the temporary to which the
13831 reference is bound, are destroyed at the end of the
13832 full-expression in which they are created.
13834 In that case, we store the converted expression into a new
13835 VAR_DECL in a new scope.
13837 However, we want to be careful not to create temporaries when
13838 they are not required. For example, given:
13840 struct B {};
13841 struct D : public B {};
13842 D f();
13843 const B& b = f();
13845 there is no need to copy the return value from "f"; we can just
13846 extend its lifetime. Similarly, given:
13848 struct S {};
13849 struct T { operator S(); };
13850 T t;
13851 const S& s = t;
13853 we can extend the lifetime of the return value of the conversion
13854 operator.
13856 The next several functions are involved in this lifetime extension. */
13858 /* DECL is a VAR_DECL or FIELD_DECL whose type is a REFERENCE_TYPE. The
13859 reference is being bound to a temporary. Create and return a new
13860 VAR_DECL with the indicated TYPE; this variable will store the value to
13861 which the reference is bound. */
13863 tree
13864 make_temporary_var_for_ref_to_temp (tree decl, tree type)
13866 tree var = create_temporary_var (type);
13868 /* Register the variable. */
13869 if (VAR_P (decl)
13870 && (TREE_STATIC (decl) || CP_DECL_THREAD_LOCAL_P (decl)))
13872 /* Namespace-scope or local static; give it a mangled name. */
13874 /* If an initializer is visible to multiple translation units, those
13875 translation units must agree on the addresses of the
13876 temporaries. Therefore the temporaries must be given a consistent name
13877 and vague linkage. The mangled name of a temporary is the name of the
13878 non-temporary object in whose initializer they appear, prefixed with
13879 GR and suffixed with a sequence number mangled using the usual rules
13880 for a seq-id. Temporaries are numbered with a pre-order, depth-first,
13881 left-to-right walk of the complete initializer. */
13882 copy_linkage (var, decl);
13884 tree name = mangle_ref_init_variable (decl);
13885 DECL_NAME (var) = name;
13886 SET_DECL_ASSEMBLER_NAME (var, name);
13888 /* Set the context to make the variable mergeable in modules. */
13889 DECL_CONTEXT (var) = current_scope ();
13891 else
13892 /* Create a new cleanup level if necessary. */
13893 maybe_push_cleanup_level (type);
13895 return pushdecl (var);
13898 /* EXPR is the initializer for a variable DECL of reference or
13899 std::initializer_list type. Create, push and return a new VAR_DECL
13900 for the initializer so that it will live as long as DECL. Any
13901 cleanup for the new variable is returned through CLEANUP, and the
13902 code to initialize the new variable is returned through INITP. */
13904 static tree
13905 set_up_extended_ref_temp (tree decl, tree expr, vec<tree, va_gc> **cleanups,
13906 tree *initp, tree *cond_guard)
13908 tree init;
13909 tree type;
13910 tree var;
13912 /* Create the temporary variable. */
13913 type = TREE_TYPE (expr);
13914 var = make_temporary_var_for_ref_to_temp (decl, type);
13915 layout_decl (var, 0);
13916 /* If the rvalue is the result of a function call it will be
13917 a TARGET_EXPR. If it is some other construct (such as a
13918 member access expression where the underlying object is
13919 itself the result of a function call), turn it into a
13920 TARGET_EXPR here. It is important that EXPR be a
13921 TARGET_EXPR below since otherwise the INIT_EXPR will
13922 attempt to make a bitwise copy of EXPR to initialize
13923 VAR. */
13924 if (TREE_CODE (expr) != TARGET_EXPR)
13925 expr = get_target_expr (expr);
13926 else
13928 if (TREE_ADDRESSABLE (expr))
13929 TREE_ADDRESSABLE (var) = 1;
13930 if (DECL_MERGEABLE (TARGET_EXPR_SLOT (expr)))
13931 DECL_MERGEABLE (var) = true;
13934 if (TREE_CODE (decl) == FIELD_DECL
13935 && extra_warnings && !warning_suppressed_p (decl))
13937 warning (OPT_Wextra, "a temporary bound to %qD only persists "
13938 "until the constructor exits", decl);
13939 suppress_warning (decl);
13942 /* Recursively extend temps in this initializer. */
13943 TARGET_EXPR_INITIAL (expr)
13944 = extend_ref_init_temps (decl, TARGET_EXPR_INITIAL (expr), cleanups,
13945 cond_guard);
13947 /* Any reference temp has a non-trivial initializer. */
13948 DECL_NONTRIVIALLY_INITIALIZED_P (var) = true;
13950 /* If the initializer is constant, put it in DECL_INITIAL so we get
13951 static initialization and use in constant expressions. */
13952 init = maybe_constant_init (expr, var, /*manifestly_const_eval=*/true);
13953 /* As in store_init_value. */
13954 init = cp_fully_fold (init);
13955 if (TREE_CONSTANT (init))
13957 if (literal_type_p (type)
13958 && CP_TYPE_CONST_NON_VOLATILE_P (type)
13959 && !TYPE_HAS_MUTABLE_P (type))
13961 /* 5.19 says that a constant expression can include an
13962 lvalue-rvalue conversion applied to "a glvalue of literal type
13963 that refers to a non-volatile temporary object initialized
13964 with a constant expression". Rather than try to communicate
13965 that this VAR_DECL is a temporary, just mark it constexpr. */
13966 DECL_DECLARED_CONSTEXPR_P (var) = true;
13967 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var) = true;
13968 TREE_CONSTANT (var) = true;
13969 TREE_READONLY (var) = true;
13971 DECL_INITIAL (var) = init;
13972 init = NULL_TREE;
13974 else
13975 /* Create the INIT_EXPR that will initialize the temporary
13976 variable. */
13977 init = split_nonconstant_init (var, expr);
13978 if (at_function_scope_p ())
13980 add_decl_expr (var);
13982 if (TREE_STATIC (var))
13983 init = add_stmt_to_compound (init, register_dtor_fn (var));
13984 else
13986 tree cleanup = cxx_maybe_build_cleanup (var, tf_warning_or_error);
13987 if (cleanup)
13989 if (cond_guard && cleanup != error_mark_node)
13991 if (*cond_guard == NULL_TREE)
13993 *cond_guard = build_local_temp (boolean_type_node);
13994 add_decl_expr (*cond_guard);
13995 tree set = cp_build_modify_expr (UNKNOWN_LOCATION,
13996 *cond_guard, NOP_EXPR,
13997 boolean_false_node,
13998 tf_warning_or_error);
13999 finish_expr_stmt (set);
14001 cleanup = build3 (COND_EXPR, void_type_node,
14002 *cond_guard, cleanup, NULL_TREE);
14004 vec_safe_push (*cleanups, cleanup);
14008 /* We must be careful to destroy the temporary only
14009 after its initialization has taken place. If the
14010 initialization throws an exception, then the
14011 destructor should not be run. We cannot simply
14012 transform INIT into something like:
14014 (INIT, ({ CLEANUP_STMT; }))
14016 because emit_local_var always treats the
14017 initializer as a full-expression. Thus, the
14018 destructor would run too early; it would run at the
14019 end of initializing the reference variable, rather
14020 than at the end of the block enclosing the
14021 reference variable.
14023 The solution is to pass back a cleanup expression
14024 which the caller is responsible for attaching to
14025 the statement tree. */
14027 else
14029 rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
14030 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
14032 if (CP_DECL_THREAD_LOCAL_P (var))
14033 tls_aggregates = tree_cons (NULL_TREE, var,
14034 tls_aggregates);
14035 else
14036 static_aggregates = tree_cons (NULL_TREE, var,
14037 static_aggregates);
14039 else
14040 /* Check whether the dtor is callable. */
14041 cxx_maybe_build_cleanup (var, tf_warning_or_error);
14043 /* Avoid -Wunused-variable warning (c++/38958). */
14044 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
14045 && VAR_P (decl))
14046 TREE_USED (decl) = DECL_READ_P (decl) = true;
14048 *initp = init;
14049 return var;
14052 /* Convert EXPR to the indicated reference TYPE, in a way suitable for
14053 initializing a variable of that TYPE. */
14055 tree
14056 initialize_reference (tree type, tree expr,
14057 int flags, tsubst_flags_t complain)
14059 conversion *conv;
14060 location_t loc = cp_expr_loc_or_input_loc (expr);
14062 if (type == error_mark_node || error_operand_p (expr))
14063 return error_mark_node;
14065 conversion_obstack_sentinel cos;
14067 conv = reference_binding (type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
14068 flags, complain);
14069 /* If this conversion failed, we're in C++20, and we have something like
14070 A& a(b) where A is an aggregate, try again, this time as A& a{b}. */
14071 if ((!conv || conv->bad_p)
14072 && (flags & LOOKUP_AGGREGATE_PAREN_INIT))
14074 tree e = build_constructor_single (init_list_type_node, NULL_TREE, expr);
14075 CONSTRUCTOR_IS_DIRECT_INIT (e) = true;
14076 CONSTRUCTOR_IS_PAREN_INIT (e) = true;
14077 conversion *c = reference_binding (type, TREE_TYPE (e), e,
14078 /*c_cast_p=*/false, flags, complain);
14079 /* If this worked, use it. */
14080 if (c && !c->bad_p)
14081 expr = e, conv = c;
14083 if (!conv || conv->bad_p)
14085 if (complain & tf_error)
14087 if (conv)
14088 convert_like (conv, expr, complain);
14089 else if (!CP_TYPE_CONST_P (TREE_TYPE (type))
14090 && !TYPE_REF_IS_RVALUE (type)
14091 && !lvalue_p (expr))
14092 error_at (loc, "invalid initialization of non-const reference of "
14093 "type %qH from an rvalue of type %qI",
14094 type, TREE_TYPE (expr));
14095 else
14096 error_at (loc, "invalid initialization of reference of type "
14097 "%qH from expression of type %qI", type,
14098 TREE_TYPE (expr));
14100 return error_mark_node;
14103 if (conv->kind == ck_ref_bind)
14104 /* Perform the conversion. */
14105 expr = convert_like (conv, expr, complain);
14106 else if (conv->kind == ck_ambig)
14107 /* We gave an error in build_user_type_conversion_1. */
14108 expr = error_mark_node;
14109 else
14110 gcc_unreachable ();
14112 return expr;
14115 /* Return true if T is std::pair<const T&, const T&>. */
14117 static bool
14118 std_pair_ref_ref_p (tree t)
14120 /* First, check if we have std::pair. */
14121 if (!NON_UNION_CLASS_TYPE_P (t)
14122 || !CLASSTYPE_TEMPLATE_INSTANTIATION (t))
14123 return false;
14124 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (t));
14125 if (!decl_in_std_namespace_p (tdecl))
14126 return false;
14127 tree name = DECL_NAME (tdecl);
14128 if (!name || !id_equal (name, "pair"))
14129 return false;
14131 /* Now see if the template arguments are both const T&. */
14132 tree args = CLASSTYPE_TI_ARGS (t);
14133 if (TREE_VEC_LENGTH (args) != 2)
14134 return false;
14135 for (int i = 0; i < 2; i++)
14136 if (!TYPE_REF_OBJ_P (TREE_VEC_ELT (args, i))
14137 || !CP_TYPE_CONST_P (TREE_TYPE (TREE_VEC_ELT (args, i))))
14138 return false;
14140 return true;
14143 /* Return true if a class T has a reference member. */
14145 static bool
14146 class_has_reference_member_p (tree t)
14148 for (tree fields = TYPE_FIELDS (t);
14149 fields;
14150 fields = DECL_CHAIN (fields))
14151 if (TREE_CODE (fields) == FIELD_DECL
14152 && !DECL_ARTIFICIAL (fields)
14153 && TYPE_REF_P (TREE_TYPE (fields)))
14154 return true;
14155 return false;
14158 /* A wrapper for the above suitable as a callback for dfs_walk_once. */
14160 static tree
14161 class_has_reference_member_p_r (tree binfo, void *)
14163 return (class_has_reference_member_p (BINFO_TYPE (binfo))
14164 ? integer_one_node : NULL_TREE);
14168 /* Return true if T (either a class or a function) has been marked as
14169 not-dangling. */
14171 static bool
14172 no_dangling_p (tree t)
14174 t = lookup_attribute ("no_dangling", TYPE_ATTRIBUTES (t));
14175 if (!t)
14176 return false;
14178 t = TREE_VALUE (t);
14179 if (!t)
14180 return true;
14182 t = build_converted_constant_bool_expr (TREE_VALUE (t), tf_warning_or_error);
14183 t = cxx_constant_value (t);
14184 return t == boolean_true_node;
14187 /* Return true if a class CTYPE is either std::reference_wrapper or
14188 std::ref_view, or a reference wrapper class. We consider a class
14189 a reference wrapper class if it has a reference member. We no
14190 longer check that it has a constructor taking the same reference type
14191 since that approach still generated too many false positives. */
14193 static bool
14194 reference_like_class_p (tree ctype)
14196 if (!CLASS_TYPE_P (ctype))
14197 return false;
14199 if (no_dangling_p (ctype))
14200 return true;
14202 /* Also accept a std::pair<const T&, const T&>. */
14203 if (std_pair_ref_ref_p (ctype))
14204 return true;
14206 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
14207 if (decl_in_std_namespace_p (tdecl))
14209 tree name = DECL_NAME (tdecl);
14210 if (name
14211 && (id_equal (name, "reference_wrapper")
14212 || id_equal (name, "span")
14213 || id_equal (name, "ref_view")))
14214 return true;
14217 /* Avoid warning if CTYPE looks like std::span: it has a T* member and
14218 a trivial destructor. For example,
14220 template<typename T>
14221 struct Span {
14222 T* data_;
14223 std::size len_;
14226 is considered std::span-like. */
14227 if (NON_UNION_CLASS_TYPE_P (ctype) && TYPE_HAS_TRIVIAL_DESTRUCTOR (ctype))
14228 for (tree field = next_aggregate_field (TYPE_FIELDS (ctype));
14229 field; field = next_aggregate_field (DECL_CHAIN (field)))
14230 if (TYPE_PTR_P (TREE_TYPE (field)))
14231 return true;
14233 /* Some classes, such as std::tuple, have the reference member in its
14234 (non-direct) base class. */
14235 if (dfs_walk_once (TYPE_BINFO (ctype), class_has_reference_member_p_r,
14236 nullptr, nullptr))
14237 return true;
14239 return false;
14242 /* Helper for maybe_warn_dangling_reference to find a problematic temporary
14243 in EXPR (as outlined in maybe_warn_dangling_reference), or NULL_TREE
14244 if none found. For instance:
14246 const S& s = S().self(); // S()
14247 const int& r = (42, f(1)); // temporary for passing 1 to f
14248 const int& t = b ? f(1) : f(2); // temporary for 1
14249 const int& u = b ? f(1) : f(g); // temporary for 1
14250 const int& v = b ? f(g) : f(2); // temporary for 2
14251 const int& w = b ? f(g) : f(g); // NULL_TREE
14252 const int& y = (f(1), 42); // NULL_TREE
14253 const int& z = f(f(1)); // temporary for 1
14255 EXPR is the initializer. If ARG_P is true, we're processing an argument
14256 to a function; the point is to distinguish between, for example,
14258 Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
14260 where we shouldn't warn, and
14262 Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
14264 where we should warn (Ref is a reference_like_class_p so we see through
14265 it. */
14267 static tree
14268 do_warn_dangling_reference (tree expr, bool arg_p)
14270 STRIP_NOPS (expr);
14272 if (arg_p && expr_represents_temporary_p (expr))
14274 /* An attempt to reduce the number of -Wdangling-reference
14275 false positives concerning reference wrappers (c++/107532).
14276 When we encounter a reference_like_class_p, we don't warn
14277 just yet; instead, we keep recursing to see if there were
14278 any temporaries behind the reference-wrapper class. */
14279 tree e = expr;
14280 while (handled_component_p (e))
14281 e = TREE_OPERAND (e, 0);
14282 tree type = TREE_TYPE (e);
14283 /* If the temporary represents a lambda, we don't really know
14284 what's going on here. */
14285 if (!reference_like_class_p (type) && !LAMBDA_TYPE_P (type))
14286 return expr;
14289 switch (TREE_CODE (expr))
14291 case CALL_EXPR:
14293 tree fndecl = cp_get_callee_fndecl_nofold (expr);
14294 if (!fndecl
14295 || warning_suppressed_p (fndecl, OPT_Wdangling_reference)
14296 || !warning_enabled_at (DECL_SOURCE_LOCATION (fndecl),
14297 OPT_Wdangling_reference)
14298 /* Don't emit a false positive for:
14299 std::vector<int> v = ...;
14300 std::vector<int>::const_iterator it = v.begin();
14301 const int &r = *it++;
14302 because R refers to one of the int elements of V, not to
14303 a temporary object. Member operator* may return a reference
14304 but probably not to one of its arguments. */
14305 || (DECL_OBJECT_MEMBER_FUNCTION_P (fndecl)
14306 && DECL_OVERLOADED_OPERATOR_P (fndecl)
14307 && DECL_OVERLOADED_OPERATOR_IS (fndecl, INDIRECT_REF))
14308 || no_dangling_p (TREE_TYPE (fndecl)))
14309 return NULL_TREE;
14311 tree rettype = TREE_TYPE (TREE_TYPE (fndecl));
14312 /* If the function doesn't return a reference, don't warn. This
14313 can be e.g.
14314 const int& z = std::min({1, 2, 3, 4, 5, 6, 7});
14315 which doesn't dangle: std::min here returns an int.
14317 If the function returns a std::pair<const T&, const T&>, we
14318 warn, to detect e.g.
14319 std::pair<const int&, const int&> v = std::minmax(1, 2);
14320 which also creates a dangling reference, because std::minmax
14321 returns std::pair<const T&, const T&>(b, a). */
14322 if (!(TYPE_REF_OBJ_P (rettype) || reference_like_class_p (rettype)))
14323 return NULL_TREE;
14325 /* Here we're looking to see if any of the arguments is a temporary
14326 initializing a reference parameter. */
14327 for (int i = 0; i < call_expr_nargs (expr); ++i)
14329 tree arg = CALL_EXPR_ARG (expr, i);
14330 /* Check that this argument initializes a reference, except for
14331 the argument initializing the object of a member function. */
14332 if (!DECL_IOBJ_MEMBER_FUNCTION_P (fndecl)
14333 && !TYPE_REF_P (TREE_TYPE (arg)))
14334 continue;
14335 STRIP_NOPS (arg);
14336 if (TREE_CODE (arg) == ADDR_EXPR)
14337 arg = TREE_OPERAND (arg, 0);
14338 /* Recurse to see if the argument is a temporary. It could also
14339 be another call taking a temporary and returning it and
14340 initializing this reference parameter. */
14341 if ((arg = do_warn_dangling_reference (arg, /*arg_p=*/true)))
14343 /* If we know the temporary could not bind to the return type,
14344 don't warn. This is for scalars and empty classes only
14345 because for other classes we can't be sure we are not
14346 returning its sub-object. */
14347 if ((SCALAR_TYPE_P (TREE_TYPE (arg))
14348 || is_empty_class (TREE_TYPE (arg)))
14349 && TYPE_REF_P (rettype)
14350 && !reference_related_p (TREE_TYPE (rettype),
14351 TREE_TYPE (arg)))
14352 continue;
14353 return arg;
14355 /* Don't warn about member functions like:
14356 std::any a(...);
14357 S& s = a.emplace<S>({0}, 0);
14358 which construct a new object and return a reference to it, but
14359 we still want to detect:
14360 struct S { const S& self () { return *this; } };
14361 const S& s = S().self();
14362 where 's' dangles. If we've gotten here, the object this function
14363 is invoked on is not a temporary. */
14364 if (DECL_OBJECT_MEMBER_FUNCTION_P (fndecl))
14365 break;
14367 return NULL_TREE;
14369 case COMPOUND_EXPR:
14370 return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
14371 case COND_EXPR:
14372 if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
14373 return t;
14374 return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
14375 case PAREN_EXPR:
14376 return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
14377 case TARGET_EXPR:
14378 return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
14379 default:
14380 return NULL_TREE;
14384 /* Implement -Wdangling-reference, to detect cases like
14386 int n = 1;
14387 const int& r = std::max(n - 1, n + 1); // r is dangling
14389 This creates temporaries from the arguments, returns a reference to
14390 one of the temporaries, but both temporaries are destroyed at the end
14391 of the full expression.
14393 This works by checking if a reference is initialized with a function
14394 that returns a reference, and at least one parameter of the function
14395 is a reference that is bound to a temporary. It assumes that such a
14396 function actually returns one of its arguments.
14398 DECL is the reference being initialized, INIT is the initializer. */
14400 static void
14401 maybe_warn_dangling_reference (const_tree decl, tree init)
14403 if (!warn_dangling_reference)
14404 return;
14405 tree type = TREE_TYPE (decl);
14406 /* Only warn if what we're initializing has type T&& or const T&, or
14407 std::pair<const T&, const T&>. (A non-const lvalue reference can't
14408 bind to a temporary.) */
14409 if (!((TYPE_REF_OBJ_P (type)
14410 && (TYPE_REF_IS_RVALUE (type)
14411 || CP_TYPE_CONST_P (TREE_TYPE (type))))
14412 || std_pair_ref_ref_p (type)))
14413 return;
14414 /* Don't suppress the diagnostic just because the call comes from
14415 a system header. If the DECL is not in a system header, or if
14416 -Wsystem-headers was provided, warn. */
14417 auto wsh
14418 = make_temp_override (global_dc->m_warn_system_headers,
14419 (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
14420 || global_dc->m_warn_system_headers));
14421 if (tree call = do_warn_dangling_reference (init, /*arg_p=*/false))
14423 auto_diagnostic_group d;
14424 if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
14425 "possibly dangling reference to a temporary"))
14426 inform (EXPR_LOCATION (call), "%qT temporary created here",
14427 TREE_TYPE (call));
14431 /* If *P is an xvalue expression, prevent temporary lifetime extension if it
14432 gets used to initialize a reference. */
14434 static tree
14435 prevent_lifetime_extension (tree t)
14437 tree *p = &t;
14438 while (TREE_CODE (*p) == COMPOUND_EXPR)
14439 p = &TREE_OPERAND (*p, 1);
14440 while (handled_component_p (*p))
14441 p = &TREE_OPERAND (*p, 0);
14442 /* Change a TARGET_EXPR from prvalue to xvalue. */
14443 if (TREE_CODE (*p) == TARGET_EXPR)
14444 *p = build2 (COMPOUND_EXPR, TREE_TYPE (*p), *p,
14445 move (TARGET_EXPR_SLOT (*p)));
14446 return t;
14449 /* Subroutine of extend_ref_init_temps. Possibly extend one initializer,
14450 which is bound either to a reference or a std::initializer_list. */
14452 static tree
14453 extend_ref_init_temps_1 (tree decl, tree init, vec<tree, va_gc> **cleanups,
14454 tree *cond_guard)
14456 /* CWG1299 (C++20): The temporary object to which the reference is bound or
14457 the temporary object that is the complete object of a subobject to which
14458 the reference is bound persists for the lifetime of the reference if the
14459 glvalue to which the reference is bound was obtained through one of the
14460 following:
14461 - a temporary materialization conversion ([conv.rval]),
14462 - ( expression ), where expression is one of these expressions,
14463 - subscripting ([expr.sub]) of an array operand, where that operand is one
14464 of these expressions,
14465 - a class member access ([expr.ref]) using the . operator where the left
14466 operand is one of these expressions and the right operand designates a
14467 non-static data member of non-reference type,
14468 - a pointer-to-member operation ([expr.mptr.oper]) using the .* operator
14469 where the left operand is one of these expressions and the right operand
14470 is a pointer to data member of non-reference type,
14471 - a const_cast ([expr.const.cast]), static_cast ([expr.static.cast]),
14472 dynamic_cast ([expr.dynamic.cast]), or reinterpret_cast
14473 ([expr.reinterpret.cast]) converting, without a user-defined conversion,
14474 a glvalue operand that is one of these expressions to a glvalue that
14475 refers to the object designated by the operand, or to its complete
14476 object or a subobject thereof,
14477 - a conditional expression ([expr.cond]) that is a glvalue where the
14478 second or third operand is one of these expressions, or
14479 - a comma expression ([expr.comma]) that is a glvalue where the right
14480 operand is one of these expressions. */
14482 /* FIXME several cases are still handled wrong (101572, 81420). */
14484 tree sub = init;
14485 tree *p;
14486 STRIP_NOPS (sub);
14487 if (TREE_CODE (sub) == COMPOUND_EXPR)
14489 TREE_OPERAND (sub, 1)
14490 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14491 cond_guard);
14492 return init;
14494 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
14495 && TYPE_PTRDATAMEM_P (TREE_TYPE (tree_strip_nop_conversions
14496 (TREE_OPERAND (sub, 1)))))
14498 /* A pointer-to-member operation. */
14499 TREE_OPERAND (sub, 0)
14500 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 0), cleanups,
14501 cond_guard);
14502 return init;
14504 if (TREE_CODE (sub) == COND_EXPR)
14506 tree cur_cond_guard = NULL_TREE;
14507 if (TREE_OPERAND (sub, 1))
14508 TREE_OPERAND (sub, 1)
14509 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14510 &cur_cond_guard);
14511 if (cur_cond_guard)
14513 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14514 NOP_EXPR, boolean_true_node,
14515 tf_warning_or_error);
14516 TREE_OPERAND (sub, 1)
14517 = cp_build_compound_expr (set, TREE_OPERAND (sub, 1),
14518 tf_warning_or_error);
14520 cur_cond_guard = NULL_TREE;
14521 if (TREE_OPERAND (sub, 2))
14522 TREE_OPERAND (sub, 2)
14523 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 2), cleanups,
14524 &cur_cond_guard);
14525 if (cur_cond_guard)
14527 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14528 NOP_EXPR, boolean_true_node,
14529 tf_warning_or_error);
14530 TREE_OPERAND (sub, 2)
14531 = cp_build_compound_expr (set, TREE_OPERAND (sub, 2),
14532 tf_warning_or_error);
14534 return init;
14536 if (TREE_CODE (sub) != ADDR_EXPR)
14537 return init;
14538 /* Deal with binding to a subobject. */
14539 for (p = &TREE_OPERAND (sub, 0);
14540 TREE_CODE (*p) == COMPONENT_REF || TREE_CODE (*p) == ARRAY_REF; )
14541 p = &TREE_OPERAND (*p, 0);
14542 if (TREE_CODE (*p) == TARGET_EXPR)
14544 tree subinit = NULL_TREE;
14545 *p = set_up_extended_ref_temp (decl, *p, cleanups, &subinit, cond_guard);
14546 recompute_tree_invariant_for_addr_expr (sub);
14547 if (init != sub)
14548 init = fold_convert (TREE_TYPE (init), sub);
14549 if (subinit)
14550 init = build2 (COMPOUND_EXPR, TREE_TYPE (init), subinit, init);
14552 return init;
14555 /* INIT is part of the initializer for DECL. If there are any
14556 reference or initializer lists being initialized, extend their
14557 lifetime to match that of DECL. */
14559 tree
14560 extend_ref_init_temps (tree decl, tree init, vec<tree, va_gc> **cleanups,
14561 tree *cond_guard)
14563 tree type = TREE_TYPE (init);
14564 if (processing_template_decl)
14565 return init;
14567 /* P2718R0 - ignore temporaries in C++23 for-range-initializer, those
14568 have all extended lifetime. */
14569 if (DECL_NAME (decl) == for_range__identifier
14570 && flag_range_for_ext_temps)
14571 return init;
14573 maybe_warn_dangling_reference (decl, init);
14575 if (TYPE_REF_P (type))
14576 init = extend_ref_init_temps_1 (decl, init, cleanups, cond_guard);
14577 else
14579 tree ctor = init;
14580 if (TREE_CODE (ctor) == TARGET_EXPR)
14581 ctor = TARGET_EXPR_INITIAL (ctor);
14582 if (TREE_CODE (ctor) == CONSTRUCTOR)
14584 /* [dcl.init] When initializing an aggregate from a parenthesized list
14585 of values... a temporary object bound to a reference does not have
14586 its lifetime extended. */
14587 if (CONSTRUCTOR_IS_PAREN_INIT (ctor))
14588 return init;
14590 if (is_std_init_list (type))
14592 /* The temporary array underlying a std::initializer_list
14593 is handled like a reference temporary. */
14594 tree array = CONSTRUCTOR_ELT (ctor, 0)->value;
14595 array = extend_ref_init_temps_1 (decl, array, cleanups,
14596 cond_guard);
14597 CONSTRUCTOR_ELT (ctor, 0)->value = array;
14599 else
14601 unsigned i;
14602 constructor_elt *p;
14603 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
14604 FOR_EACH_VEC_SAFE_ELT (elts, i, p)
14605 p->value = extend_ref_init_temps (decl, p->value, cleanups,
14606 cond_guard);
14608 recompute_constructor_flags (ctor);
14609 if (decl_maybe_constant_var_p (decl) && TREE_CONSTANT (ctor))
14610 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
14614 return init;
14617 /* Returns true iff an initializer for TYPE could contain temporaries that
14618 need to be extended because they are bound to references or
14619 std::initializer_list. */
14621 bool
14622 type_has_extended_temps (tree type)
14624 type = strip_array_types (type);
14625 if (TYPE_REF_P (type))
14626 return true;
14627 if (CLASS_TYPE_P (type))
14629 if (is_std_init_list (type))
14630 return true;
14631 for (tree f = next_aggregate_field (TYPE_FIELDS (type));
14632 f; f = next_aggregate_field (DECL_CHAIN (f)))
14633 if (type_has_extended_temps (TREE_TYPE (f)))
14634 return true;
14636 return false;
14639 /* Returns true iff TYPE is some variant of std::initializer_list. */
14641 bool
14642 is_std_init_list (tree type)
14644 if (!TYPE_P (type))
14645 return false;
14646 if (cxx_dialect == cxx98)
14647 return false;
14648 /* Look through typedefs. */
14649 type = TYPE_MAIN_VARIANT (type);
14650 return (CLASS_TYPE_P (type)
14651 && CP_TYPE_CONTEXT (type) == std_node
14652 && init_list_identifier == DECL_NAME (TYPE_NAME (type)));
14655 /* Returns true iff DECL is a list constructor: i.e. a constructor which
14656 will accept an argument list of a single std::initializer_list<T>. */
14658 bool
14659 is_list_ctor (tree decl)
14661 tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
14662 tree arg;
14664 if (!args || args == void_list_node)
14665 return false;
14667 arg = non_reference (TREE_VALUE (args));
14668 if (!is_std_init_list (arg))
14669 return false;
14671 args = TREE_CHAIN (args);
14673 if (args && args != void_list_node && !TREE_PURPOSE (args))
14674 /* There are more non-defaulted parms. */
14675 return false;
14677 return true;
14680 /* We know that can_convert_arg_bad already said "no" when trying to convert
14681 FROM to TO with ARG and FLAGS. Try to figure out if it was because
14682 an explicit conversion function was skipped when looking for a way to
14683 perform the conversion. At this point we've already printed an error. */
14685 void
14686 maybe_show_nonconverting_candidate (tree to, tree from, tree arg, int flags)
14688 if (!(flags & LOOKUP_ONLYCONVERTING))
14689 return;
14691 conversion_obstack_sentinel cos;
14692 conversion *c = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
14693 flags & ~LOOKUP_ONLYCONVERTING, tf_none);
14694 if (c && !c->bad_p && c->user_conv_p)
14695 /* Ay, the conversion would have worked in direct-init context. */
14696 for (; c; c = next_conversion (c))
14697 if (c->kind == ck_user
14698 && DECL_P (c->cand->fn)
14699 && DECL_NONCONVERTING_P (c->cand->fn))
14700 inform (DECL_SOURCE_LOCATION (c->cand->fn), "explicit conversion "
14701 "function was not considered");
14704 /* We're converting EXPR to TYPE. If that conversion involves a conversion
14705 function and we're binding EXPR to a reference parameter of that function,
14706 return true. */
14708 bool
14709 conv_binds_to_reference_parm_p (tree type, tree expr)
14711 conversion_obstack_sentinel cos;
14712 conversion *c = implicit_conversion (type, TREE_TYPE (expr), expr,
14713 /*c_cast_p=*/false, LOOKUP_NORMAL,
14714 tf_none);
14715 if (c && !c->bad_p && c->user_conv_p)
14716 for (; c; c = next_conversion (c))
14717 if (c->kind == ck_user)
14718 for (z_candidate *cand = c->cand; cand; cand = cand->next)
14719 if (cand->viable == 1)
14720 for (size_t i = 0; i < cand->num_convs; ++i)
14721 if (cand->convs[i]->kind == ck_ref_bind
14722 && conv_get_original_expr (cand->convs[i]) == expr)
14723 return true;
14725 return false;
14728 #include "gt-cp-call.h"