Debian Codegraph @

gcc/cp/call.cc

raw
1 /* Functions related to invoking -*- C++ -*- methods and overloaded functions.
2 Copyright (C) 1987-2025 Free Software Foundation, Inc.
3 Contributed by Michael Tiemann ([email protected]) and
4 modified by Brendan Kehoe ([email protected]).
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
21
22
23 /* High-level class interface. */
24
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "target.h"
29 #include "cp-tree.h"
30 #include "timevar.h"
31 #include "stringpool.h"
32 #include "cgraph.h"
33 #include "stor-layout.h"
34 #include "trans-mem.h"
35 #include "flags.h"
36 #include "toplev.h"
37 #include "intl.h"
38 #include "convert.h"
39 #include "langhooks.h"
40 #include "c-family/c-objc.h"
41 #include "internal-fn.h"
42 #include "stringpool.h"
43 #include "attribs.h"
44 #include "decl.h"
45 #include "c-family/c-type-mismatch.h"
46 #include "tristate.h"
47 #include "tree-pretty-print-markup.h"
48
49 /* The various kinds of conversion. */
50
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,
72 };
73
74 /* The rank of the conversion. Order of the enumerals matters; better
75 conversions should come earlier in the list. */
76
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
86 };
87
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. */
91
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;
148 };
149
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)
155
156 #define BAD_CONVERSION_RANK(NODE) \
157 ((NODE)->ellipsis_p ? cr_ellipsis \
158 : (NODE)->user_conv_p ? cr_user \
159 : (NODE)->rank)
160
161 static struct obstack conversion_obstack;
162 static bool conversion_obstack_initialized;
163 struct rejection_reason;
164
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);
228
229 /* Returns nonzero iff the destructor name specified in NAME matches BASETYPE.
230 NAME can take many forms... */
231
232 bool
233 check_dtor_name (tree basetype, tree name)
234 {
235 /* Just accept something we've already complained about. */
236 if (name == error_mark_node)
237 return true;
238
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))
244 {
245 if ((MAYBE_CLASS_TYPE_P (basetype)
246 || TREE_CODE (basetype) == ENUMERAL_TYPE)
247 && name == constructor_name (basetype))
248 return true;
249
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;
258 }
259 else
260 {
261 /* In the case of:
262
263 template <class T> struct S { ~S(); };
264 int i;
265 i.~S();
266
267 NAME will be a class template. */
268 gcc_assert (DECL_CLASS_TEMPLATE_P (name));
269 return false;
270 }
271
272 return same_type_p (TYPE_MAIN_VARIANT (basetype), TYPE_MAIN_VARIANT (name));
273 }
274
275 /* We want the address of a function or method. We avoid creating a
276 pointer-to-member function. */
277
278 tree
279 build_addr_func (tree function, tsubst_flags_t complain)
280 {
281 tree type = TREE_TYPE (function);
282
283 /* We have to do these by hand to avoid real pointer to member
284 functions. */
285 if (TREE_CODE (type) == METHOD_TYPE)
286 {
287 if (TREE_CODE (function) == OFFSET_REF)
288 {
289 tree object = build_address (TREE_OPERAND (function, 0));
290 return get_member_function_from_ptrfunc (&object,
291 TREE_OPERAND (function, 1),
292 complain);
293 }
294 function = build_address (function);
295 }
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);
301
302 return function;
303 }
304
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. */
310
311 tree
312 build_call_n (tree function, int n, ...)
313 {
314 if (n == 0)
315 return build_call_a (function, 0, NULL);
316 else
317 {
318 tree *argarray = XALLOCAVEC (tree, n);
319 va_list ap;
320 int i;
321
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);
327 }
328 }
329
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. */
332
333 void
334 set_flags_from_callee (tree call)
335 {
336 /* Handle both CALL_EXPRs and AGGR_INIT_EXPRs. */
337 tree decl = cp_get_callee_fndecl_nofold (call);
338
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;
348
349 if (cfun && cp_function_chain && !cp_unevaluated_operand)
350 {
351 if (!nothrow && at_function_scope_p ())
352 cp_function_chain->can_throw = 1;
353
354 if (decl && TREE_THIS_VOLATILE (decl))
355 current_function_returns_abnormally = 1;
356 }
357
358 TREE_NOTHROW (call) = nothrow;
359 }
360
361 tree
362 build_call_a (tree function, int n, tree *argarray)
363 {
364 tree decl;
365 tree result_type;
366 tree fntype;
367 int i;
368
369 function = build_addr_func (function, tf_warning_or_error);
370
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);
378
379 function = build_call_array_loc (input_location,
380 result_type, function, n, argarray);
381 set_flags_from_callee (function);
382
383 decl = get_callee_fndecl (function);
384
385 if (decl && !TREE_USED (decl))
386 {
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);
395 }
396
397 require_complete_eh_spec_types (fntype, decl);
398
399 TREE_HAS_CONSTRUCTOR (function) = (decl && DECL_CONSTRUCTOR_P (decl));
400
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++)
406 {
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))
410 {
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;
418 }
419 }
420
421 return function;
422 }
423
424 /* New overloading code. */
425
426 struct z_candidate;
427
428 struct candidate_warning {
429 z_candidate *loser;
430 candidate_warning *next;
431 };
432
433 /* Information for providing diagnostics about why overloading failed. */
434
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,
447 };
448
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;
458 };
459
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;
495 };
496
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;
535
536 /* The flags active in add_candidate. */
537 int flags;
538
539 bool rewritten () const { return (flags & LOOKUP_REWRITTEN); }
540 bool reversed () const { return (flags & LOOKUP_REVERSED); }
541 };
542
543 /* Returns true iff T is a null pointer constant in the sense of
544 [conv.ptr]. */
545
546 bool
547 null_ptr_cst_p (tree t)
548 {
549 tree type = TREE_TYPE (t);
550
551 /* [conv.ptr]
552
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;
557
558 if (cxx_dialect >= cxx11)
559 {
560 STRIP_ANY_LOCATION_WRAPPER (t);
561
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;
569 }
570 else if (CP_INTEGRAL_TYPE_P (type))
571 {
572 t = fold_non_dependent_expr (t, tf_none);
573 STRIP_NOPS (t);
574 if (integer_zerop (t) && !TREE_OVERFLOW (t))
575 return true;
576 }
577
578 return false;
579 }
580
581 /* Returns true iff T is a null member pointer value (4.11). */
582
583 bool
584 null_member_pointer_value_p (tree t)
585 {
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;
597 }
598
599 /* Returns nonzero if PARMLIST consists of only default parms,
600 ellipsis, and/or undeduced parameter packs. */
601
602 bool
603 sufficient_parms_p (const_tree parmlist)
604 {
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;
611 }
612
613 /* Allocate N bytes of memory from the conversion obstack. The memory
614 is zeroed before being returned. */
615
616 static void *
617 conversion_obstack_alloc (size_t n)
618 {
619 void *p;
620 if (!conversion_obstack_initialized)
621 {
622 gcc_obstack_init (&conversion_obstack);
623 conversion_obstack_initialized = true;
624 }
625 p = obstack_alloc (&conversion_obstack, n);
626 memset (p, 0, n);
627 return p;
628 }
629
630 /* RAII class to discard anything added to conversion_obstack. */
631
632 struct conversion_obstack_sentinel
633 {
634 void *p;
635 conversion_obstack_sentinel (): p (conversion_obstack_alloc (0)) {}
636 ~conversion_obstack_sentinel () { obstack_free (&conversion_obstack, p); }
637 };
638
639 /* Allocate rejection reasons. */
640
641 static struct rejection_reason *
642 alloc_rejection (enum rejection_reason_code code)
643 {
644 struct rejection_reason *p;
645 p = (struct rejection_reason *) conversion_obstack_alloc (sizeof *p);
646 p->code = code;
647 return p;
648 }
649
650 static struct rejection_reason *
651 arity_rejection (tree first_arg, int expected, int actual, bool least_p = false)
652 {
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;
659 }
660
661 static struct rejection_reason *
662 arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
663 location_t loc)
664 {
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;
672 }
673
674 static struct rejection_reason *
675 bad_arg_conversion_rejection (tree first_arg, int n_arg, tree from, tree to,
676 location_t loc)
677 {
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;
685 }
686
687 static struct rejection_reason *
688 explicit_conversion_rejection (tree from, tree to)
689 {
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;
696 }
697
698 static struct rejection_reason *
699 template_conversion_rejection (tree from, tree to)
700 {
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;
707 }
708
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)
714 {
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;
729 }
730
731 static struct rejection_reason *
732 template_unification_error_rejection (void)
733 {
734 return alloc_rejection (rr_template_unification);
735 }
736
737 static struct rejection_reason *
738 invalid_copy_with_fn_template_rejection (void)
739 {
740 struct rejection_reason *r = alloc_rejection (rr_invalid_copy);
741 return r;
742 }
743
744 static struct rejection_reason *
745 inherited_ctor_rejection (void)
746 {
747 struct rejection_reason *r = alloc_rejection (rr_inherited_ctor);
748 return r;
749 }
750
751 /* Build a constraint failure record. */
752
753 static struct rejection_reason *
754 constraint_failure (void)
755 {
756 struct rejection_reason *r = alloc_rejection (rr_constraint_failure);
757 return r;
758 }
759
760 /* Dynamically allocate a conversion. */
761
762 static conversion *
763 alloc_conversion (conversion_kind kind)
764 {
765 conversion *c;
766 c = (conversion *) conversion_obstack_alloc (sizeof (conversion));
767 c->kind = kind;
768 return c;
769 }
770
771 /* Make sure that all memory on the conversion obstack has been
772 freed. */
773
774 void
775 validate_conversion_obstack (void)
776 {
777 if (conversion_obstack_initialized)
778 gcc_assert ((obstack_next_free (&conversion_obstack)
779 == obstack_base (&conversion_obstack)));
780 }
781
782 /* Dynamically allocate an array of N conversions. */
783
784 static conversion **
785 alloc_conversions (size_t n)
786 {
787 return (conversion **) conversion_obstack_alloc (n * sizeof (conversion *));
788 }
789
790 /* True iff the active member of conversion::u for code CODE is NEXT. */
791
792 static inline bool
793 has_next (conversion_kind code)
794 {
795 return !(code == ck_identity
796 || code == ck_ambig
797 || code == ck_list
798 || code == ck_aggr
799 || code == ck_deferred_bad);
800 }
801
802 static conversion *
803 build_conv (conversion_kind code, tree type, conversion *from)
804 {
805 conversion *t;
806 conversion_rank rank = CONVERSION_RANK (from);
807
808 /* Only call this function for conversions that use u.next. */
809 gcc_assert (from == NULL || has_next (code));
810
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;
816
817 switch (code)
818 {
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;
826
827 case ck_qual:
828 case ck_fnptr:
829 if (rank < cr_exact)
830 rank = cr_exact;
831 break;
832
833 default:
834 break;
835 }
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;
841 }
842
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. */
846
847 static conversion *
848 build_list_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
849 {
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;
856
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;
862
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;
868
869 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
870 {
871 if (TREE_CODE (val) == RAW_DATA_CST)
872 {
873 tree elt
874 = build_int_cst (TREE_TYPE (val), RAW_DATA_UCHAR_ELT (val, 0));
875 conversion *sub
876 = implicit_conversion (elttype, TREE_TYPE (val), elt,
877 false, flags, complain);
878 conversion *next;
879 if (sub == NULL)
880 return NULL;
881 /* For conversion to initializer_list<unsigned char> or
882 initializer_list<char> or initializer_list<signed char>
883 we can optimize and keep RAW_DATA_CST with adjusted
884 type if we report narrowing errors if needed.
885 Use just one subconversion for that case. */
886 if (sub->kind == ck_std
887 && sub->type
888 && (TREE_CODE (sub->type) == INTEGER_TYPE
889 || is_byte_access_type (sub->type))
890 && TYPE_PRECISION (sub->type) == CHAR_BIT
891 && (next = next_conversion (sub))
892 && next->kind == ck_identity)
893 {
894 subconvs[i] = sub;
895 continue;
896 }
897 /* Otherwise. build separate subconv for each RAW_DATA_CST
898 byte. Wrap those into an artificial ck_list which convert_like
899 will then handle. */
900 conversion **subsubconvs = alloc_conversions (RAW_DATA_LENGTH (val));
901 unsigned int j;
902 subsubconvs[0] = sub;
903 for (j = 1; j < (unsigned) RAW_DATA_LENGTH (val); ++j)
904 {
905 elt = build_int_cst (TREE_TYPE (val),
906 RAW_DATA_UCHAR_ELT (val, j));
907 sub = implicit_conversion (elttype, TREE_TYPE (val), elt,
908 false, flags, complain);
909 if (sub == NULL)
910 return NULL;
911 subsubconvs[j] = sub;
912 }
913
914 t = alloc_conversion (ck_list);
915 t->type = type;
916 t->u.list = subsubconvs;
917 t->rank = cr_exact;
918 for (j = 0; j < (unsigned) RAW_DATA_LENGTH (val); ++j)
919 {
920 sub = subsubconvs[j];
921 if (sub->rank > t->rank)
922 t->rank = sub->rank;
923 if (sub->user_conv_p)
924 t->user_conv_p = true;
925 if (sub->bad_p)
926 t->bad_p = true;
927 }
928 subconvs[i] = t;
929 continue;
930 }
931
932 conversion *sub
933 = implicit_conversion (elttype, TREE_TYPE (val), val,
934 false, flags, complain);
935 if (sub == NULL)
936 return NULL;
937
938 subconvs[i] = sub;
939 }
940
941 t = alloc_conversion (ck_list);
942 t->type = type;
943 t->u.list = subconvs;
944 t->rank = cr_exact;
945
946 for (i = 0; i < len; ++i)
947 {
948 conversion *sub = subconvs[i];
949 if (sub->rank > t->rank)
950 t->rank = sub->rank;
951 if (sub->user_conv_p)
952 t->user_conv_p = true;
953 if (sub->bad_p)
954 t->bad_p = true;
955 }
956
957 return t;
958 }
959
960 /* Return the next conversion of the conversion chain (if applicable),
961 or NULL otherwise. Please use this function instead of directly
962 accessing fields of struct conversion. */
963
964 static conversion *
965 next_conversion (conversion *conv)
966 {
967 if (conv == NULL
968 || !has_next (conv->kind))
969 return NULL;
970 return conv->u.next;
971 }
972
973 /* Strip to the first ck_user, ck_ambig, ck_list, ck_aggr or ck_identity
974 encountered. */
975
976 static conversion *
977 strip_standard_conversion (conversion *conv)
978 {
979 while (conv
980 && conv->kind != ck_user
981 && has_next (conv->kind))
982 conv = next_conversion (conv);
983 return conv;
984 }
985
986 /* Subroutine of build_aggr_conv: check whether FROM is a valid aggregate
987 initializer for array type ATYPE. */
988
989 static bool
990 can_convert_array (tree atype, tree from, int flags, tsubst_flags_t complain)
991 {
992 tree elttype = TREE_TYPE (atype);
993 unsigned i;
994
995 if (TREE_CODE (from) == CONSTRUCTOR)
996 {
997 for (i = 0; i < CONSTRUCTOR_NELTS (from); ++i)
998 {
999 tree val = CONSTRUCTOR_ELT (from, i)->value;
1000 bool ok;
1001 if (TREE_CODE (elttype) == ARRAY_TYPE)
1002 ok = can_convert_array (elttype, val, flags, complain);
1003 else
1004 ok = can_convert_arg (elttype, TREE_TYPE (val), val, flags,
1005 complain);
1006 if (!ok)
1007 return false;
1008 }
1009 return true;
1010 }
1011
1012 if (char_type_p (TYPE_MAIN_VARIANT (elttype))
1013 && TREE_CODE (tree_strip_any_location_wrapper (from)) == STRING_CST)
1014 return array_string_literal_compatible_p (atype, from);
1015
1016 /* No other valid way to aggregate initialize an array. */
1017 return false;
1018 }
1019
1020 /* Helper for build_aggr_conv. Return true if FIELD is in PSET, or if
1021 FIELD has ANON_AGGR_TYPE_P and any initializable field in there recursively
1022 is in PSET. */
1023
1024 static bool
1025 field_in_pset (hash_set<tree, true> &pset, tree field)
1026 {
1027 if (pset.contains (field))
1028 return true;
1029 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1030 for (field = TYPE_FIELDS (TREE_TYPE (field));
1031 field; field = DECL_CHAIN (field))
1032 {
1033 field = next_aggregate_field (field);
1034 if (field == NULL_TREE)
1035 break;
1036 if (field_in_pset (pset, field))
1037 return true;
1038 }
1039 return false;
1040 }
1041
1042 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
1043 aggregate class, if such a conversion is possible. */
1044
1045 static conversion *
1046 build_aggr_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
1047 {
1048 unsigned HOST_WIDE_INT i = 0;
1049 conversion *c;
1050 tree field = next_aggregate_field (TYPE_FIELDS (type));
1051 tree empty_ctor = NULL_TREE;
1052 hash_set<tree, true> pset;
1053
1054 /* We already called reshape_init in implicit_conversion, but it might not
1055 have done anything in the case of parenthesized aggr init. */
1056
1057 /* The conversions within the init-list aren't affected by the enclosing
1058 context; they're always simple copy-initialization. */
1059 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1060
1061 /* For designated initializers, verify that each initializer is convertible
1062 to corresponding TREE_TYPE (ce->index) and mark those FIELD_DECLs as
1063 visited. In the following loop then ignore already visited
1064 FIELD_DECLs. */
1065 tree idx, val;
1066 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, idx, val)
1067 {
1068 if (!idx)
1069 break;
1070
1071 gcc_checking_assert (TREE_CODE (idx) == FIELD_DECL);
1072
1073 tree ftype = TREE_TYPE (idx);
1074 bool ok;
1075
1076 if (TREE_CODE (ftype) == ARRAY_TYPE)
1077 ok = can_convert_array (ftype, val, flags, complain);
1078 else
1079 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1080 complain);
1081
1082 if (!ok)
1083 return NULL;
1084
1085 /* For unions, there should be just one initializer. */
1086 if (TREE_CODE (type) == UNION_TYPE)
1087 {
1088 field = NULL_TREE;
1089 i = 1;
1090 break;
1091 }
1092 pset.add (idx);
1093 }
1094
1095 for (; field; field = next_aggregate_field (DECL_CHAIN (field)))
1096 {
1097 tree ftype = TREE_TYPE (field);
1098 bool ok;
1099
1100 if (!pset.is_empty () && field_in_pset (pset, field))
1101 continue;
1102 if (i < CONSTRUCTOR_NELTS (ctor))
1103 {
1104 constructor_elt *ce = CONSTRUCTOR_ELT (ctor, i);
1105 gcc_checking_assert (!ce->index);
1106 val = ce->value;
1107 ++i;
1108 }
1109 else if (DECL_INITIAL (field))
1110 val = get_nsdmi (field, /*ctor*/false, complain);
1111 else if (TYPE_REF_P (ftype))
1112 /* Value-initialization of reference is ill-formed. */
1113 return NULL;
1114 else
1115 {
1116 if (empty_ctor == NULL_TREE)
1117 empty_ctor = build_constructor (init_list_type_node, NULL);
1118 val = empty_ctor;
1119 }
1120
1121 if (TREE_CODE (ftype) == ARRAY_TYPE)
1122 ok = can_convert_array (ftype, val, flags, complain);
1123 else
1124 ok = can_convert_arg (ftype, TREE_TYPE (val), val, flags,
1125 complain);
1126
1127 if (!ok)
1128 return NULL;
1129
1130 if (TREE_CODE (type) == UNION_TYPE)
1131 break;
1132 }
1133
1134 if (i < CONSTRUCTOR_NELTS (ctor))
1135 return NULL;
1136
1137 c = alloc_conversion (ck_aggr);
1138 c->type = type;
1139 c->rank = cr_exact;
1140 c->user_conv_p = true;
1141 c->check_narrowing = true;
1142 c->u.expr = ctor;
1143 return c;
1144 }
1145
1146 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
1147 array type, if such a conversion is possible. */
1148
1149 static conversion *
1150 build_array_conv (tree type, tree ctor, int flags, tsubst_flags_t complain)
1151 {
1152 conversion *c;
1153 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1154 tree elttype = TREE_TYPE (type);
1155 bool bad = false;
1156 bool user = false;
1157 enum conversion_rank rank = cr_exact;
1158
1159 /* We might need to propagate the size from the element to the array. */
1160 complete_type (type);
1161
1162 if (TYPE_DOMAIN (type)
1163 && !variably_modified_type_p (TYPE_DOMAIN (type), NULL_TREE))
1164 {
1165 unsigned HOST_WIDE_INT alen = tree_to_uhwi (array_type_nelts_top (type));
1166 if (alen < len)
1167 return NULL;
1168 }
1169
1170 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1171
1172 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1173 {
1174 conversion *sub
1175 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1176 false, flags, complain);
1177 if (sub == NULL)
1178 return NULL;
1179
1180 if (sub->rank > rank)
1181 rank = sub->rank;
1182 if (sub->user_conv_p)
1183 user = true;
1184 if (sub->bad_p)
1185 bad = true;
1186 }
1187
1188 c = alloc_conversion (ck_aggr);
1189 c->type = type;
1190 c->rank = rank;
1191 c->user_conv_p = user;
1192 c->bad_p = bad;
1193 c->u.expr = ctor;
1194 return c;
1195 }
1196
1197 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
1198 complex type, if such a conversion is possible. */
1199
1200 static conversion *
1201 build_complex_conv (tree type, tree ctor, int flags,
1202 tsubst_flags_t complain)
1203 {
1204 conversion *c;
1205 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (ctor);
1206 tree elttype = TREE_TYPE (type);
1207 bool bad = false;
1208 bool user = false;
1209 enum conversion_rank rank = cr_exact;
1210
1211 if (len != 2)
1212 return NULL;
1213
1214 flags = LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING;
1215
1216 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1217 {
1218 conversion *sub
1219 = implicit_conversion (elttype, TREE_TYPE (e.value), e.value,
1220 false, flags, complain);
1221 if (sub == NULL)
1222 return NULL;
1223
1224 if (sub->rank > rank)
1225 rank = sub->rank;
1226 if (sub->user_conv_p)
1227 user = true;
1228 if (sub->bad_p)
1229 bad = true;
1230 }
1231
1232 c = alloc_conversion (ck_aggr);
1233 c->type = type;
1234 c->rank = rank;
1235 c->user_conv_p = user;
1236 c->bad_p = bad;
1237 c->u.expr = ctor;
1238 return c;
1239 }
1240
1241 /* Build a representation of the identity conversion from EXPR to
1242 itself. The TYPE should match the type of EXPR, if EXPR is non-NULL. */
1243
1244 static conversion *
1245 build_identity_conv (tree type, tree expr)
1246 {
1247 conversion *c;
1248
1249 c = alloc_conversion (ck_identity);
1250 c->type = type;
1251 c->u.expr = expr;
1252
1253 return c;
1254 }
1255
1256 /* Converting from EXPR to TYPE was ambiguous in the sense that there
1257 were multiple user-defined conversions to accomplish the job.
1258 Build a conversion that indicates that ambiguity. */
1259
1260 static conversion *
1261 build_ambiguous_conv (tree type, tree expr)
1262 {
1263 conversion *c;
1264
1265 c = alloc_conversion (ck_ambig);
1266 c->type = type;
1267 c->u.expr = expr;
1268
1269 return c;
1270 }
1271
1272 tree
1273 strip_top_quals (tree t)
1274 {
1275 if (TREE_CODE (t) == ARRAY_TYPE)
1276 return t;
1277 return cp_build_qualified_type (t, 0);
1278 }
1279
1280 /* Returns the standard conversion path (see [conv]) from type FROM to type
1281 TO, if any. For proper handling of null pointer constants, you must
1282 also pass the expression EXPR to convert from. If C_CAST_P is true,
1283 this conversion is coming from a C-style cast. */
1284
1285 static conversion *
1286 standard_conversion (tree to, tree from, tree expr, bool c_cast_p,
1287 int flags, tsubst_flags_t complain)
1288 {
1289 enum tree_code fcode, tcode;
1290 conversion *conv;
1291 bool fromref = false;
1292 tree qualified_to;
1293
1294 to = non_reference (to);
1295 if (TYPE_REF_P (from))
1296 {
1297 fromref = true;
1298 from = TREE_TYPE (from);
1299 }
1300 qualified_to = to;
1301 to = strip_top_quals (to);
1302 from = strip_top_quals (from);
1303
1304 if (expr && type_unknown_p (expr))
1305 {
1306 if (TYPE_PTRFN_P (to) || TYPE_PTRMEMFUNC_P (to))
1307 {
1308 tsubst_flags_t tflags = tf_conv;
1309 expr = instantiate_type (to, expr, tflags);
1310 if (expr == error_mark_node)
1311 return NULL;
1312 from = TREE_TYPE (expr);
1313 }
1314 else if (TREE_CODE (to) == BOOLEAN_TYPE)
1315 {
1316 /* Necessary for eg, TEMPLATE_ID_EXPRs (c++/50961). */
1317 expr = resolve_nondeduced_context (expr, complain);
1318 from = TREE_TYPE (expr);
1319 }
1320 }
1321
1322 fcode = TREE_CODE (from);
1323 tcode = TREE_CODE (to);
1324
1325 conv = build_identity_conv (from, expr);
1326 if (fcode == FUNCTION_TYPE || fcode == ARRAY_TYPE)
1327 {
1328 from = type_decays_to (from);
1329 fcode = TREE_CODE (from);
1330 /* Tell convert_like that we're using the address. */
1331 conv->rvaluedness_matches_p = true;
1332 conv = build_conv (ck_lvalue, from, conv);
1333 }
1334 /* Wrapping a ck_rvalue around a class prvalue (as a result of using
1335 obvalue_p) seems odd, since it's already a prvalue, but that's how we
1336 express the copy constructor call required by copy-initialization. */
1337 else if (fromref || (expr && obvalue_p (expr)))
1338 {
1339 if (expr)
1340 {
1341 tree bitfield_type;
1342 bitfield_type = is_bitfield_expr_with_lowered_type (expr);
1343 if (bitfield_type)
1344 {
1345 from = strip_top_quals (bitfield_type);
1346 fcode = TREE_CODE (from);
1347 }
1348 }
1349 conv = build_conv (ck_rvalue, from, conv);
1350 /* If we're performing copy-initialization, remember to skip
1351 explicit constructors. */
1352 if (flags & LOOKUP_ONLYCONVERTING)
1353 conv->copy_init_p = true;
1354 }
1355
1356 /* Allow conversion between `__complex__' data types. */
1357 if (tcode == COMPLEX_TYPE && fcode == COMPLEX_TYPE)
1358 {
1359 /* The standard conversion sequence to convert FROM to TO is
1360 the standard conversion sequence to perform componentwise
1361 conversion. */
1362 conversion *part_conv = standard_conversion
1363 (TREE_TYPE (to), TREE_TYPE (from), NULL_TREE, c_cast_p, flags,
1364 complain);
1365
1366 if (!part_conv)
1367 conv = NULL;
1368 else if (part_conv->kind == ck_identity)
1369 /* Leave conv alone. */;
1370 else
1371 {
1372 conv = build_conv (part_conv->kind, to, conv);
1373 conv->rank = part_conv->rank;
1374 }
1375
1376 return conv;
1377 }
1378
1379 if (same_type_p (from, to))
1380 {
1381 if (CLASS_TYPE_P (to) && conv->kind == ck_rvalue)
1382 conv->type = qualified_to;
1383 else if (from != to)
1384 /* Use TO in order to not lose TO in diagnostics. */
1385 conv->type = to;
1386 return conv;
1387 }
1388
1389 /* [conv.ptr]
1390 A null pointer constant can be converted to a pointer type; ... A
1391 null pointer constant of integral type can be converted to an
1392 rvalue of type std::nullptr_t. */
1393 if ((tcode == POINTER_TYPE || TYPE_PTRMEM_P (to)
1394 || NULLPTR_TYPE_P (to))
1395 && ((expr && null_ptr_cst_p (expr))
1396 || NULLPTR_TYPE_P (from)))
1397 conv = build_conv (ck_std, to, conv);
1398 else if ((tcode == INTEGER_TYPE && fcode == POINTER_TYPE)
1399 || (tcode == POINTER_TYPE && fcode == INTEGER_TYPE))
1400 {
1401 /* For backwards brain damage compatibility, allow interconversion of
1402 pointers and integers with a pedwarn. */
1403 conv = build_conv (ck_std, to, conv);
1404 conv->bad_p = true;
1405 }
1406 else if (UNSCOPED_ENUM_P (to) && fcode == INTEGER_TYPE)
1407 {
1408 /* For backwards brain damage compatibility, allow interconversion of
1409 enums and integers with a pedwarn. */
1410 conv = build_conv (ck_std, to, conv);
1411 conv->bad_p = true;
1412 }
1413 else if ((tcode == POINTER_TYPE && fcode == POINTER_TYPE)
1414 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from)))
1415 {
1416 tree to_pointee;
1417 tree from_pointee;
1418
1419 if (tcode == POINTER_TYPE)
1420 {
1421 to_pointee = TREE_TYPE (to);
1422 from_pointee = TREE_TYPE (from);
1423
1424 /* Since this is the target of a pointer, it can't have function
1425 qualifiers, so any TYPE_QUALS must be for attributes const or
1426 noreturn. Strip them. */
1427 if (TREE_CODE (to_pointee) == FUNCTION_TYPE
1428 && TYPE_QUALS (to_pointee))
1429 to_pointee = build_qualified_type (to_pointee, TYPE_UNQUALIFIED);
1430 if (TREE_CODE (from_pointee) == FUNCTION_TYPE
1431 && TYPE_QUALS (from_pointee))
1432 from_pointee = build_qualified_type (from_pointee, TYPE_UNQUALIFIED);
1433 }
1434 else
1435 {
1436 to_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (to);
1437 from_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (from);
1438 }
1439
1440 if (tcode == POINTER_TYPE
1441 && same_type_ignoring_top_level_qualifiers_p (from_pointee,
1442 to_pointee))
1443 ;
1444 else if (VOID_TYPE_P (to_pointee)
1445 && !TYPE_PTRDATAMEM_P (from)
1446 && TREE_CODE (from_pointee) != FUNCTION_TYPE)
1447 {
1448 tree nfrom = TREE_TYPE (from);
1449 /* Don't try to apply restrict to void. */
1450 int quals = cp_type_quals (nfrom) & ~TYPE_QUAL_RESTRICT;
1451 from_pointee = cp_build_qualified_type (void_type_node, quals);
1452 from = build_pointer_type (from_pointee);
1453 conv = build_conv (ck_ptr, from, conv);
1454 }
1455 else if (TYPE_PTRDATAMEM_P (from))
1456 {
1457 tree fbase = TYPE_PTRMEM_CLASS_TYPE (from);
1458 tree tbase = TYPE_PTRMEM_CLASS_TYPE (to);
1459
1460 if (same_type_p (fbase, tbase))
1461 /* No base conversion needed. */;
1462 else if (DERIVED_FROM_P (fbase, tbase)
1463 && (same_type_ignoring_top_level_qualifiers_p
1464 (from_pointee, to_pointee)))
1465 {
1466 from = build_ptrmem_type (tbase, from_pointee);
1467 conv = build_conv (ck_pmem, from, conv);
1468 }
1469 else
1470 return NULL;
1471 }
1472 else if (CLASS_TYPE_P (from_pointee)
1473 && CLASS_TYPE_P (to_pointee)
1474 /* [conv.ptr]
1475
1476 An rvalue of type "pointer to cv D," where D is a
1477 class type, can be converted to an rvalue of type
1478 "pointer to cv B," where B is a base class (clause
1479 _class.derived_) of D. If B is an inaccessible
1480 (clause _class.access_) or ambiguous
1481 (_class.member.lookup_) base class of D, a program
1482 that necessitates this conversion is ill-formed.
1483 Therefore, we use DERIVED_FROM_P, and do not check
1484 access or uniqueness. */
1485 && DERIVED_FROM_P (to_pointee, from_pointee))
1486 {
1487 from_pointee
1488 = cp_build_qualified_type (to_pointee,
1489 cp_type_quals (from_pointee));
1490 from = build_pointer_type (from_pointee);
1491 conv = build_conv (ck_ptr, from, conv);
1492 conv->base_p = true;
1493 }
1494
1495 if (same_type_p (from, to))
1496 /* OK */;
1497 else if (c_cast_p && comp_ptr_ttypes_const (to, from, bounds_either))
1498 /* In a C-style cast, we ignore CV-qualification because we
1499 are allowed to perform a static_cast followed by a
1500 const_cast. */
1501 conv = build_conv (ck_qual, to, conv);
1502 else if (!c_cast_p && comp_ptr_ttypes (to_pointee, from_pointee))
1503 conv = build_conv (ck_qual, to, conv);
1504 else if (expr && string_conv_p (to, expr, 0))
1505 /* converting from string constant to char *. */
1506 conv = build_conv (ck_qual, to, conv);
1507 else if (fnptr_conv_p (to, from))
1508 conv = build_conv (ck_fnptr, to, conv);
1509 /* Allow conversions among compatible ObjC pointer types (base
1510 conversions have been already handled above). */
1511 else if (c_dialect_objc ()
1512 && objc_compare_types (to, from, -4, NULL_TREE))
1513 conv = build_conv (ck_ptr, to, conv);
1514 else if (ptr_reasonably_similar (to_pointee, from_pointee))
1515 {
1516 conv = build_conv (ck_ptr, to, conv);
1517 conv->bad_p = true;
1518 }
1519 else
1520 return NULL;
1521
1522 from = to;
1523 }
1524 else if (TYPE_PTRMEMFUNC_P (to) && TYPE_PTRMEMFUNC_P (from))
1525 {
1526 tree fromfn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (from));
1527 tree tofn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (to));
1528 tree fbase = class_of_this_parm (fromfn);
1529 tree tbase = class_of_this_parm (tofn);
1530
1531 /* If FBASE and TBASE are equivalent but incomplete, DERIVED_FROM_P
1532 yields false. But a pointer to member of incomplete class is OK. */
1533 if (!same_type_p (fbase, tbase) && !DERIVED_FROM_P (fbase, tbase))
1534 return NULL;
1535
1536 tree fstat = static_fn_type (fromfn);
1537 tree tstat = static_fn_type (tofn);
1538 if (same_type_p (tstat, fstat)
1539 || fnptr_conv_p (tstat, fstat))
1540 /* OK */;
1541 else
1542 return NULL;
1543
1544 if (!same_type_p (fbase, tbase))
1545 {
1546 from = build_memfn_type (fstat,
1547 tbase,
1548 cp_type_quals (tbase),
1549 type_memfn_rqual (tofn));
1550 from = build_ptrmemfunc_type (build_pointer_type (from));
1551 conv = build_conv (ck_pmem, from, conv);
1552 conv->base_p = true;
1553 }
1554 if (fnptr_conv_p (tstat, fstat))
1555 conv = build_conv (ck_fnptr, to, conv);
1556 }
1557 else if (tcode == BOOLEAN_TYPE)
1558 {
1559 /* [conv.bool]
1560
1561 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer
1562 to member type can be converted to a prvalue of type bool. ...
1563 For direct-initialization (8.5 [dcl.init]), a prvalue of type
1564 std::nullptr_t can be converted to a prvalue of type bool; */
1565 if (ARITHMETIC_TYPE_P (from)
1566 || UNSCOPED_ENUM_P (from)
1567 || fcode == POINTER_TYPE
1568 || TYPE_PTRMEM_P (from)
1569 || NULLPTR_TYPE_P (from))
1570 {
1571 conv = build_conv (ck_std, to, conv);
1572 if (fcode == POINTER_TYPE
1573 || TYPE_PTRDATAMEM_P (from)
1574 || (TYPE_PTRMEMFUNC_P (from)
1575 && conv->rank < cr_pbool)
1576 || NULLPTR_TYPE_P (from))
1577 conv->rank = cr_pbool;
1578 if (NULLPTR_TYPE_P (from) && (flags & LOOKUP_ONLYCONVERTING))
1579 conv->bad_p = true;
1580 if (flags & LOOKUP_NO_NARROWING)
1581 conv->check_narrowing = true;
1582 return conv;
1583 }
1584
1585 return NULL;
1586 }
1587 /* We don't check for ENUMERAL_TYPE here because there are no standard
1588 conversions to enum type. */
1589 /* As an extension, allow conversion to complex type. */
1590 else if (ARITHMETIC_TYPE_P (to))
1591 {
1592 if (! (INTEGRAL_CODE_P (fcode)
1593 || (fcode == REAL_TYPE && !(flags & LOOKUP_NO_NON_INTEGRAL)))
1594 || SCOPED_ENUM_P (from))
1595 return NULL;
1596
1597 /* If we're parsing an enum with no fixed underlying type, we're
1598 dealing with an incomplete type, which renders the conversion
1599 ill-formed. */
1600 if (!COMPLETE_TYPE_P (from))
1601 return NULL;
1602
1603 conv = build_conv (ck_std, to, conv);
1604
1605 tree underlying_type = NULL_TREE;
1606 if (TREE_CODE (from) == ENUMERAL_TYPE
1607 && ENUM_FIXED_UNDERLYING_TYPE_P (from))
1608 underlying_type = ENUM_UNDERLYING_TYPE (from);
1609
1610 /* Give this a better rank if it's a promotion.
1611
1612 To handle CWG 1601, also bump the rank if we are converting
1613 an enumeration with a fixed underlying type to the underlying
1614 type. */
1615 if ((same_type_p (to, type_promotes_to (from))
1616 || (underlying_type && same_type_p (to, underlying_type)))
1617 && next_conversion (conv)->rank <= cr_promotion)
1618 conv->rank = cr_promotion;
1619
1620 /* A prvalue of floating-point type can be converted to a prvalue of
1621 another floating-point type with a greater or equal conversion
1622 rank ([conv.rank]). A prvalue of standard floating-point type can
1623 be converted to a prvalue of another standard floating-point type.
1624 For backwards compatibility with handling __float128 and other
1625 non-standard floating point types, allow all implicit floating
1626 point conversions if neither type is extended floating-point
1627 type and if at least one of them is, fail if they have unordered
1628 conversion rank or from has higher conversion rank. */
1629 if (fcode == REAL_TYPE
1630 && tcode == REAL_TYPE
1631 && (extended_float_type_p (from)
1632 || extended_float_type_p (to))
1633 && cp_compare_floating_point_conversion_ranks (from, to) >= 2)
1634 conv->bad_p = true;
1635 }
1636 else if (fcode == VECTOR_TYPE && tcode == VECTOR_TYPE
1637 && vector_types_convertible_p (from, to, false))
1638 return build_conv (ck_std, to, conv);
1639 else if (MAYBE_CLASS_TYPE_P (to) && MAYBE_CLASS_TYPE_P (from)
1640 && is_properly_derived_from (from, to))
1641 {
1642 if (conv->kind == ck_rvalue)
1643 conv = next_conversion (conv);
1644 conv = build_conv (ck_base, to, conv);
1645 /* The derived-to-base conversion indicates the initialization
1646 of a parameter with base type from an object of a derived
1647 type. A temporary object is created to hold the result of
1648 the conversion unless we're binding directly to a reference. */
1649 conv->need_temporary_p = !(flags & LOOKUP_NO_TEMP_BIND);
1650 /* If we're performing copy-initialization, remember to skip
1651 explicit constructors. */
1652 if (flags & LOOKUP_ONLYCONVERTING)
1653 conv->copy_init_p = true;
1654 }
1655 else
1656 return NULL;
1657
1658 if (flags & LOOKUP_NO_NARROWING)
1659 conv->check_narrowing = true;
1660
1661 return conv;
1662 }
1663
1664 /* Returns nonzero if T1 is reference-related to T2.
1665
1666 This is considered when a reference to T1 is initialized by a T2. */
1667
1668 bool
1669 reference_related_p (tree t1, tree t2)
1670 {
1671 if (t1 == error_mark_node || t2 == error_mark_node)
1672 return false;
1673
1674 t1 = TYPE_MAIN_VARIANT (t1);
1675 t2 = TYPE_MAIN_VARIANT (t2);
1676
1677 /* [dcl.init.ref]
1678
1679 Given types "cv1 T1" and "cv2 T2," "cv1 T1" is reference-related
1680 to "cv2 T2" if T1 is similar to T2, or T1 is a base class of T2. */
1681 return (similar_type_p (t1, t2)
1682 || (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
1683 && DERIVED_FROM_P (t1, t2)));
1684 }
1685
1686 /* Returns nonzero if T1 is reference-compatible with T2. */
1687
1688 bool
1689 reference_compatible_p (tree t1, tree t2)
1690 {
1691 /* [dcl.init.ref]
1692
1693 "cv1 T1" is reference compatible with "cv2 T2" if
1694 a prvalue of type "pointer to cv2 T2" can be converted to the type
1695 "pointer to cv1 T1" via a standard conversion sequence. */
1696 tree ptype1 = build_pointer_type (t1);
1697 tree ptype2 = build_pointer_type (t2);
1698 conversion *conv = standard_conversion (ptype1, ptype2, NULL_TREE,
1699 /*c_cast_p=*/false, 0, tf_none);
1700 if (!conv || conv->bad_p)
1701 return false;
1702 return true;
1703 }
1704
1705 /* Return true if converting FROM to TO would involve a qualification
1706 conversion. */
1707
1708 static bool
1709 involves_qualification_conversion_p (tree to, tree from)
1710 {
1711 /* If we're not convering a pointer to another one, we won't get
1712 a qualification conversion. */
1713 if (!((TYPE_PTR_P (to) && TYPE_PTR_P (from))
1714 || (TYPE_PTRDATAMEM_P (to) && TYPE_PTRDATAMEM_P (from))))
1715 return false;
1716
1717 conversion *conv = standard_conversion (to, from, NULL_TREE,
1718 /*c_cast_p=*/false, 0, tf_none);
1719 for (conversion *t = conv; t; t = next_conversion (t))
1720 if (t->kind == ck_qual)
1721 return true;
1722
1723 return false;
1724 }
1725
1726 /* A reference of the indicated TYPE is being bound directly to the
1727 expression represented by the implicit conversion sequence CONV.
1728 Return a conversion sequence for this binding. */
1729
1730 static conversion *
1731 direct_reference_binding (tree type, conversion *conv)
1732 {
1733 tree t;
1734
1735 gcc_assert (TYPE_REF_P (type));
1736 gcc_assert (!TYPE_REF_P (conv->type));
1737
1738 t = TREE_TYPE (type);
1739
1740 if (conv->kind == ck_identity)
1741 /* Mark the identity conv as to not decay to rvalue. */
1742 conv->rvaluedness_matches_p = true;
1743
1744 /* [over.ics.rank]
1745
1746 When a parameter of reference type binds directly
1747 (_dcl.init.ref_) to an argument expression, the implicit
1748 conversion sequence is the identity conversion, unless the
1749 argument expression has a type that is a derived class of the
1750 parameter type, in which case the implicit conversion sequence is
1751 a derived-to-base Conversion.
1752
1753 If the parameter binds directly to the result of applying a
1754 conversion function to the argument expression, the implicit
1755 conversion sequence is a user-defined conversion sequence
1756 (_over.ics.user_), with the second standard conversion sequence
1757 either an identity conversion or, if the conversion function
1758 returns an entity of a type that is a derived class of the
1759 parameter type, a derived-to-base conversion. */
1760 if (is_properly_derived_from (conv->type, t))
1761 {
1762 /* Represent the derived-to-base conversion. */
1763 conv = build_conv (ck_base, t, conv);
1764 /* We will actually be binding to the base-class subobject in
1765 the derived class, so we mark this conversion appropriately.
1766 That way, convert_like knows not to generate a temporary. */
1767 conv->need_temporary_p = false;
1768 }
1769 else if (involves_qualification_conversion_p (t, conv->type))
1770 /* Represent the qualification conversion. After DR 2352
1771 #1 and #2 were indistinguishable conversion sequences:
1772
1773 void f(int*); // #1
1774 void f(const int* const &); // #2
1775 void g(int* p) { f(p); }
1776
1777 because the types "int *" and "const int *const" are
1778 reference-related and we were binding both directly and they
1779 had the same rank. To break it up, we add a ck_qual under the
1780 ck_ref_bind so that conversion sequence ranking chooses #1.
1781
1782 We strip_top_quals here which is also what standard_conversion
1783 does. Failure to do so would confuse comp_cv_qual_signature
1784 into thinking that in
1785
1786 void f(const int * const &); // #1
1787 void f(const int *); // #2
1788 int *x;
1789 f(x);
1790
1791 #2 is a better match than #1 even though they're ambiguous (97296). */
1792 conv = build_conv (ck_qual, strip_top_quals (t), conv);
1793
1794 return build_conv (ck_ref_bind, type, conv);
1795 }
1796
1797 /* Returns the conversion path from type FROM to reference type TO for
1798 purposes of reference binding. For lvalue binding, either pass a
1799 reference type to FROM or an lvalue expression to EXPR. If the
1800 reference will be bound to a temporary, NEED_TEMPORARY_P is set for
1801 the conversion returned. If C_CAST_P is true, this
1802 conversion is coming from a C-style cast. */
1803
1804 static conversion *
1805 reference_binding (tree rto, tree rfrom, tree expr, bool c_cast_p, int flags,
1806 tsubst_flags_t complain)
1807 {
1808 conversion *conv = NULL;
1809 conversion *bad_direct_conv = nullptr;
1810 tree to = TREE_TYPE (rto);
1811 tree from = rfrom;
1812 tree tfrom;
1813 bool related_p;
1814 bool compatible_p;
1815 cp_lvalue_kind gl_kind;
1816 bool is_lvalue;
1817
1818 if (TREE_CODE (to) == FUNCTION_TYPE && expr && type_unknown_p (expr))
1819 {
1820 expr = instantiate_type (to, expr, tf_none);
1821 if (expr == error_mark_node)
1822 return NULL;
1823 from = TREE_TYPE (expr);
1824 }
1825
1826 bool copy_list_init = false;
1827 bool single_list_conv = false;
1828 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1829 {
1830 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
1831 /* DR 1288: Otherwise, if the initializer list has a single element
1832 of type E and ... [T's] referenced type is reference-related to E,
1833 the object or reference is initialized from that element...
1834
1835 ??? With P0388R4, we should bind 't' directly to U{}:
1836 using U = A[2];
1837 A (&&t)[] = {U{}};
1838 because A[] and A[2] are reference-related. But we don't do it
1839 because grok_reference_init has deduced the array size (to 1), and
1840 A[1] and A[2] aren't reference-related. */
1841 if (CONSTRUCTOR_NELTS (expr) == 1
1842 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
1843 {
1844 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
1845 if (error_operand_p (elt))
1846 return NULL;
1847 tree etype = TREE_TYPE (elt);
1848 if (reference_related_p (to, etype))
1849 {
1850 expr = elt;
1851 from = etype;
1852 goto skip;
1853 }
1854 else if (CLASS_TYPE_P (etype) && TYPE_HAS_CONVERSION (etype))
1855 /* CWG1996: jason's proposed drafting adds "or initializing T from E
1856 would bind directly". We check that in the direct binding with
1857 conversion code below. */
1858 single_list_conv = true;
1859 }
1860 /* Otherwise, if T is a reference type, a prvalue temporary of the type
1861 referenced by T is copy-list-initialized, and the reference is bound
1862 to that temporary. */
1863 copy_list_init = true;
1864 skip:;
1865 }
1866
1867 if (TYPE_REF_P (from))
1868 {
1869 from = TREE_TYPE (from);
1870 if (!TYPE_REF_IS_RVALUE (rfrom)
1871 || TREE_CODE (from) == FUNCTION_TYPE)
1872 gl_kind = clk_ordinary;
1873 else
1874 gl_kind = clk_rvalueref;
1875 }
1876 else if (expr)
1877 gl_kind = lvalue_kind (expr);
1878 else if (CLASS_TYPE_P (from)
1879 || TREE_CODE (from) == ARRAY_TYPE)
1880 gl_kind = clk_class;
1881 else
1882 gl_kind = clk_none;
1883
1884 /* Don't allow a class prvalue when LOOKUP_NO_TEMP_BIND. */
1885 if ((flags & LOOKUP_NO_TEMP_BIND)
1886 && (gl_kind & clk_class))
1887 gl_kind = clk_none;
1888
1889 /* Same mask as real_lvalue_p. */
1890 is_lvalue = gl_kind && !(gl_kind & (clk_rvalueref|clk_class));
1891
1892 tfrom = from;
1893 if ((gl_kind & clk_bitfield) != 0)
1894 tfrom = unlowered_expr_type (expr);
1895
1896 /* Figure out whether or not the types are reference-related and
1897 reference compatible. We have to do this after stripping
1898 references from FROM. */
1899 related_p = reference_related_p (to, tfrom);
1900 /* If this is a C cast, first convert to an appropriately qualified
1901 type, so that we can later do a const_cast to the desired type. */
1902 if (related_p && c_cast_p
1903 && !at_least_as_qualified_p (to, tfrom))
1904 to = cp_build_qualified_type (to, cp_type_quals (tfrom));
1905 compatible_p = reference_compatible_p (to, tfrom);
1906
1907 /* Directly bind reference when target expression's type is compatible with
1908 the reference and expression is an lvalue. In DR391, the wording in
1909 [8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
1910 const and rvalue references to rvalues of compatible class type.
1911 We should also do direct bindings for non-class xvalues. */
1912 if ((related_p || compatible_p) && gl_kind)
1913 {
1914 /* [dcl.init.ref]
1915
1916 If the initializer expression
1917
1918 -- is an lvalue (but not an lvalue for a bit-field), and "cv1 T1"
1919 is reference-compatible with "cv2 T2,"
1920
1921 the reference is bound directly to the initializer expression
1922 lvalue.
1923
1924 [...]
1925 If the initializer expression is an rvalue, with T2 a class type,
1926 and "cv1 T1" is reference-compatible with "cv2 T2", the reference
1927 is bound to the object represented by the rvalue or to a sub-object
1928 within that object. */
1929
1930 conv = build_identity_conv (tfrom, expr);
1931 conv = direct_reference_binding (rto, conv);
1932
1933 if (TYPE_REF_P (rfrom))
1934 /* Handle rvalue reference to function properly. */
1935 conv->rvaluedness_matches_p
1936 = (TYPE_REF_IS_RVALUE (rto) == TYPE_REF_IS_RVALUE (rfrom));
1937 else
1938 conv->rvaluedness_matches_p
1939 = (TYPE_REF_IS_RVALUE (rto) == !is_lvalue);
1940
1941 if ((gl_kind & clk_bitfield) != 0
1942 || ((gl_kind & clk_packed) != 0 && !TYPE_PACKED (to)))
1943 /* For the purposes of overload resolution, we ignore the fact
1944 this expression is a bitfield or packed field. (In particular,
1945 [over.ics.ref] says specifically that a function with a
1946 non-const reference parameter is viable even if the
1947 argument is a bitfield.)
1948
1949 However, when we actually call the function we must create
1950 a temporary to which to bind the reference. If the
1951 reference is volatile, or isn't const, then we cannot make
1952 a temporary, so we just issue an error when the conversion
1953 actually occurs. */
1954 conv->need_temporary_p = true;
1955
1956 /* Don't allow binding of lvalues (other than function lvalues) to
1957 rvalue references. */
1958 if (is_lvalue && TYPE_REF_IS_RVALUE (rto)
1959 && TREE_CODE (to) != FUNCTION_TYPE)
1960 conv->bad_p = true;
1961
1962 /* Nor the reverse. */
1963 if (!is_lvalue && !TYPE_REF_IS_RVALUE (rto)
1964 /* Unless it's really a C++20 lvalue being treated as an xvalue.
1965 But in C++23, such an expression is just an xvalue, not a special
1966 lvalue, so the binding is once again ill-formed. */
1967 && !(cxx_dialect <= cxx20
1968 && (gl_kind & clk_implicit_rval))
1969 && (!CP_TYPE_CONST_NON_VOLATILE_P (to)
1970 || (flags & LOOKUP_NO_RVAL_BIND))
1971 && TREE_CODE (to) != FUNCTION_TYPE)
1972 conv->bad_p = true;
1973
1974 if (!compatible_p)
1975 conv->bad_p = true;
1976
1977 return conv;
1978 }
1979 /* [class.conv.fct] A conversion function is never used to convert a
1980 (possibly cv-qualified) object to the (possibly cv-qualified) same
1981 object type (or a reference to it), to a (possibly cv-qualified) base
1982 class of that type (or a reference to it).... */
1983 else if (!related_p
1984 && !(flags & LOOKUP_NO_CONVERSION)
1985 && (CLASS_TYPE_P (from) || single_list_conv))
1986 {
1987 tree rexpr = expr;
1988 if (single_list_conv)
1989 rexpr = CONSTRUCTOR_ELT (expr, 0)->value;
1990
1991 /* [dcl.init.ref]
1992
1993 If the initializer expression
1994
1995 -- has a class type (i.e., T2 is a class type) can be
1996 implicitly converted to an lvalue of type "cv3 T3," where
1997 "cv1 T1" is reference-compatible with "cv3 T3". (this
1998 conversion is selected by enumerating the applicable
1999 conversion functions (_over.match.ref_) and choosing the
2000 best one through overload resolution. (_over.match_).
2001
2002 the reference is bound to the lvalue result of the conversion
2003 in the second case. */
2004 z_candidate *cand = build_user_type_conversion_1 (rto, rexpr, flags,
2005 complain);
2006 if (cand)
2007 {
2008 if (!cand->second_conv->bad_p)
2009 return cand->second_conv;
2010
2011 /* Direct reference binding wasn't successful and yielded a bad
2012 conversion. Proceed with trying to go through a temporary
2013 instead, and if that also fails then we'll return this bad
2014 conversion rather than no conversion for sake of better
2015 diagnostics. */
2016 bad_direct_conv = cand->second_conv;
2017 }
2018 }
2019
2020 /* From this point on, we conceptually need temporaries, even if we
2021 elide them. Only the cases above are "direct bindings". */
2022 if (flags & LOOKUP_NO_TEMP_BIND)
2023 return bad_direct_conv ? bad_direct_conv : nullptr;
2024
2025 /* [over.ics.rank]
2026
2027 When a parameter of reference type is not bound directly to an
2028 argument expression, the conversion sequence is the one required
2029 to convert the argument expression to the underlying type of the
2030 reference according to _over.best.ics_. Conceptually, this
2031 conversion sequence corresponds to copy-initializing a temporary
2032 of the underlying type with the argument expression. Any
2033 difference in top-level cv-qualification is subsumed by the
2034 initialization itself and does not constitute a conversion. */
2035
2036 bool maybe_valid_p = true;
2037
2038 /* [dcl.init.ref]
2039
2040 Otherwise, the reference shall be an lvalue reference to a
2041 non-volatile const type, or the reference shall be an rvalue
2042 reference. */
2043 if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto))
2044 maybe_valid_p = false;
2045
2046 /* [dcl.init.ref]
2047
2048 Otherwise, a temporary of type "cv1 T1" is created and
2049 initialized from the initializer expression using the rules for a
2050 non-reference copy initialization. If T1 is reference-related to
2051 T2, cv1 must be the same cv-qualification as, or greater
2052 cv-qualification than, cv2; otherwise, the program is ill-formed. */
2053 if (related_p && !at_least_as_qualified_p (to, from))
2054 maybe_valid_p = false;
2055
2056 /* We try below to treat an invalid reference binding as a bad conversion
2057 to improve diagnostics, but doing so may cause otherwise unnecessary
2058 instantiations that can lead to a hard error. So during the first pass
2059 of overload resolution wherein we shortcut bad conversions, instead just
2060 produce a special conversion indicating a second pass is necessary if
2061 there's no strictly viable candidate. */
2062 if (!maybe_valid_p && (flags & LOOKUP_SHORTCUT_BAD_CONVS))
2063 {
2064 if (bad_direct_conv)
2065 return bad_direct_conv;
2066
2067 conv = alloc_conversion (ck_deferred_bad);
2068 conv->bad_p = true;
2069 return conv;
2070 }
2071
2072 /* We're generating a temporary now, but don't bind any more in the
2073 conversion (specifically, don't slice the temporary returned by a
2074 conversion operator). */
2075 flags |= LOOKUP_NO_TEMP_BIND;
2076
2077 /* Core issue 899: When [copy-]initializing a temporary to be bound
2078 to the first parameter of a copy constructor (12.8) called with
2079 a single argument in the context of direct-initialization,
2080 explicit conversion functions are also considered.
2081
2082 So don't set LOOKUP_ONLYCONVERTING in that case. */
2083 if (!(flags & LOOKUP_COPY_PARM))
2084 flags |= LOOKUP_ONLYCONVERTING;
2085
2086 if (!conv)
2087 conv = implicit_conversion (to, from, expr, c_cast_p,
2088 flags, complain);
2089 if (!conv)
2090 return bad_direct_conv ? bad_direct_conv : nullptr;
2091
2092 if (conv->user_conv_p)
2093 {
2094 if (copy_list_init)
2095 /* Remember this was copy-list-initialization. */
2096 conv->need_temporary_p = true;
2097
2098 /* If initializing the temporary used a conversion function,
2099 recalculate the second conversion sequence. */
2100 for (conversion *t = conv; t; t = next_conversion (t))
2101 if (t->kind == ck_user
2102 && c_cast_p && !maybe_valid_p)
2103 {
2104 if (complain & tf_warning)
2105 warning (OPT_Wcast_user_defined,
2106 "casting %qT to %qT does not use %qD",
2107 from, rto, t->cand->fn);
2108 /* Don't let recalculation try to make this valid. */
2109 break;
2110 }
2111 else if (t->kind == ck_user
2112 && DECL_CONV_FN_P (t->cand->fn))
2113 {
2114 tree ftype = TREE_TYPE (TREE_TYPE (t->cand->fn));
2115 /* A prvalue of non-class type is cv-unqualified. */
2116 if (!TYPE_REF_P (ftype) && !CLASS_TYPE_P (ftype))
2117 ftype = cv_unqualified (ftype);
2118 int sflags = (flags|LOOKUP_NO_CONVERSION)&~LOOKUP_NO_TEMP_BIND;
2119 conversion *new_second
2120 = reference_binding (rto, ftype, NULL_TREE, c_cast_p,
2121 sflags, complain);
2122 if (!new_second)
2123 return bad_direct_conv ? bad_direct_conv : nullptr;
2124 conv = merge_conversion_sequences (t, new_second);
2125 gcc_assert (maybe_valid_p || conv->bad_p);
2126 return conv;
2127 }
2128 }
2129
2130 conv = build_conv (ck_ref_bind, rto, conv);
2131 /* This reference binding, unlike those above, requires the
2132 creation of a temporary. */
2133 conv->need_temporary_p = true;
2134 conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
2135 conv->bad_p |= !maybe_valid_p;
2136
2137 return conv;
2138 }
2139
2140 /* Returns the implicit conversion sequence (see [over.ics]) from type
2141 FROM to type TO. The optional expression EXPR may affect the
2142 conversion. FLAGS are the usual overloading flags. If C_CAST_P is
2143 true, this conversion is coming from a C-style cast. */
2144
2145 static conversion *
2146 implicit_conversion (tree to, tree from, tree expr, bool c_cast_p,
2147 int flags, tsubst_flags_t complain)
2148 {
2149 conversion *conv;
2150
2151 if (from == error_mark_node || to == error_mark_node
2152 || expr == error_mark_node)
2153 return NULL;
2154
2155 /* Other flags only apply to the primary function in overload
2156 resolution, or after we've chosen one. */
2157 flags &= (LOOKUP_ONLYCONVERTING|LOOKUP_NO_CONVERSION|LOOKUP_COPY_PARM
2158 |LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND|LOOKUP_NO_NARROWING
2159 |LOOKUP_PROTECT|LOOKUP_NO_NON_INTEGRAL|LOOKUP_SHORTCUT_BAD_CONVS);
2160
2161 /* FIXME: actually we don't want warnings either, but we can't just
2162 have 'complain &= ~(tf_warning|tf_error)' because it would cause
2163 the regression of, eg, g++.old-deja/g++.benjamin/16077.C.
2164 We really ought not to issue that warning until we've committed
2165 to that conversion. */
2166 complain &= ~tf_error;
2167
2168 /* Call reshape_init early to remove redundant braces. */
2169 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr) && CLASS_TYPE_P (to))
2170 {
2171 to = complete_type (to);
2172 if (!COMPLETE_TYPE_P (to))
2173 return nullptr;
2174 if (!CLASSTYPE_NON_AGGREGATE (to))
2175 {
2176 expr = reshape_init (to, expr, complain);
2177 if (expr == error_mark_node)
2178 return nullptr;
2179 from = TREE_TYPE (expr);
2180 }
2181 }
2182
2183 /* An argument should have gone through convert_from_reference. */
2184 gcc_checking_assert (!expr || !TYPE_REF_P (from));
2185
2186 if (TYPE_REF_P (to))
2187 conv = reference_binding (to, from, expr, c_cast_p, flags, complain);
2188 else
2189 conv = standard_conversion (to, from, expr, c_cast_p, flags, complain);
2190
2191 if (conv)
2192 return conv;
2193
2194 if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
2195 {
2196 if (is_std_init_list (to) && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2197 return build_list_conv (to, expr, flags, complain);
2198
2199 /* As an extension, allow list-initialization of _Complex. */
2200 if (TREE_CODE (to) == COMPLEX_TYPE
2201 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2202 {
2203 conv = build_complex_conv (to, expr, flags, complain);
2204 if (conv)
2205 return conv;
2206 }
2207
2208 /* Allow conversion from an initializer-list with one element to a
2209 scalar type. */
2210 if (SCALAR_TYPE_P (to))
2211 {
2212 int nelts = CONSTRUCTOR_NELTS (expr);
2213 tree elt;
2214
2215 if (nelts == 0)
2216 elt = build_value_init (to, tf_none);
2217 else if (nelts == 1 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr))
2218 elt = CONSTRUCTOR_ELT (expr, 0)->value;
2219 else
2220 elt = error_mark_node;
2221
2222 conv = implicit_conversion (to, TREE_TYPE (elt), elt,
2223 c_cast_p, flags, complain);
2224 if (conv)
2225 {
2226 conv->check_narrowing = true;
2227 if (BRACE_ENCLOSED_INITIALIZER_P (elt))
2228 /* Too many levels of braces, i.e. '{{1}}'. */
2229 conv->bad_p = true;
2230 return conv;
2231 }
2232 }
2233 else if (TREE_CODE (to) == ARRAY_TYPE)
2234 return build_array_conv (to, expr, flags, complain);
2235 }
2236
2237 if (expr != NULL_TREE
2238 && (MAYBE_CLASS_TYPE_P (from)
2239 || MAYBE_CLASS_TYPE_P (to))
2240 && (flags & LOOKUP_NO_CONVERSION) == 0)
2241 {
2242 struct z_candidate *cand;
2243
2244 if (CLASS_TYPE_P (to)
2245 && BRACE_ENCLOSED_INITIALIZER_P (expr)
2246 && !CLASSTYPE_NON_AGGREGATE (complete_type (to)))
2247 return build_aggr_conv (to, expr, flags, complain);
2248
2249 cand = build_user_type_conversion_1 (to, expr, flags, complain);
2250 if (cand)
2251 {
2252 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
2253 && CONSTRUCTOR_NELTS (expr) == 1
2254 && !CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
2255 && !is_list_ctor (cand->fn))
2256 {
2257 /* "If C is not an initializer-list constructor and the
2258 initializer list has a single element of type cv U, where U is
2259 X or a class derived from X, the implicit conversion sequence
2260 has Exact Match rank if U is X, or Conversion rank if U is
2261 derived from X." */
2262 tree elt = CONSTRUCTOR_ELT (expr, 0)->value;
2263 tree elttype = TREE_TYPE (elt);
2264 if (reference_related_p (to, elttype))
2265 return implicit_conversion (to, elttype, elt,
2266 c_cast_p, flags, complain);
2267 }
2268 conv = cand->second_conv;
2269 }
2270
2271 /* We used to try to bind a reference to a temporary here, but that
2272 is now handled after the recursive call to this function at the end
2273 of reference_binding. */
2274 return conv;
2275 }
2276
2277 return NULL;
2278 }
2279
2280 /* Like implicit_conversion, but return NULL if the conversion is bad.
2281
2282 This is not static so that check_non_deducible_conversion can call it within
2283 add_template_candidate_real as part of overload resolution; it should not be
2284 called outside of overload resolution. */
2285
2286 conversion *
2287 good_conversion (tree to, tree from, tree expr,
2288 int flags, tsubst_flags_t complain)
2289 {
2290 conversion *c = implicit_conversion (to, from, expr, /*cast*/false,
2291 flags, complain);
2292 if (c && c->bad_p)
2293 c = NULL;
2294 return c;
2295 }
2296
2297 /* Add a new entry to the list of candidates. Used by the add_*_candidate
2298 functions. ARGS will not be changed until a single candidate is
2299 selected. */
2300
2301 static struct z_candidate *
2302 add_candidate (struct z_candidate **candidates,
2303 tree fn, tree first_arg, const vec<tree, va_gc> *args,
2304 size_t num_convs, conversion **convs,
2305 tree access_path, tree conversion_path,
2306 int viable, struct rejection_reason *reason,
2307 int flags)
2308 {
2309 struct z_candidate *cand = (struct z_candidate *)
2310 conversion_obstack_alloc (sizeof (struct z_candidate));
2311
2312 cand->fn = fn;
2313 cand->first_arg = first_arg;
2314 cand->args = args;
2315 cand->convs = convs;
2316 cand->num_convs = num_convs;
2317 cand->access_path = access_path;
2318 cand->conversion_path = conversion_path;
2319 cand->viable = viable;
2320 cand->reason = reason;
2321 cand->next = *candidates;
2322 cand->flags = flags;
2323 *candidates = cand;
2324
2325 if (convs && cand->reversed ())
2326 /* Swap the conversions for comparison in joust; we'll swap them back
2327 before build_over_call. */
2328 std::swap (convs[0], convs[1]);
2329
2330 return cand;
2331 }
2332
2333 /* FN is a function from the overload set that we outright didn't even
2334 consider (for some reason); add it to the list as an non-viable "ignored"
2335 candidate. */
2336
2337 static z_candidate *
2338 add_ignored_candidate (z_candidate **candidates, tree fn)
2339 {
2340 /* No need to dynamically allocate these. */
2341 static const rejection_reason reason_ignored = { rr_ignored, {} };
2342
2343 struct z_candidate *cand = (struct z_candidate *)
2344 conversion_obstack_alloc (sizeof (struct z_candidate));
2345
2346 cand->fn = fn;
2347 cand->reason = const_cast<rejection_reason *> (&reason_ignored);
2348 cand->next = *candidates;
2349 *candidates = cand;
2350
2351 return cand;
2352 }
2353
2354 /* True iff CAND is a candidate added by add_ignored_candidate. */
2355
2356 static bool
2357 ignored_candidate_p (const z_candidate *cand)
2358 {
2359 return cand->reason && cand->reason->code == rr_ignored;
2360 }
2361
2362 /* Return the number of remaining arguments in the parameter list
2363 beginning with ARG. */
2364
2365 int
2366 remaining_arguments (tree arg)
2367 {
2368 int n;
2369
2370 for (n = 0; arg != NULL_TREE && arg != void_list_node;
2371 arg = TREE_CHAIN (arg))
2372 n++;
2373
2374 return n;
2375 }
2376
2377 /* [over.match.copy]: When initializing a temporary object (12.2) to be bound
2378 to the first parameter of a constructor where the parameter is of type
2379 "reference to possibly cv-qualified T" and the constructor is called with a
2380 single argument in the context of direct-initialization of an object of type
2381 "cv2 T", explicit conversion functions are also considered.
2382
2383 So set LOOKUP_COPY_PARM to let reference_binding know that
2384 it's being called in that context. */
2385
2386 int
2387 conv_flags (int i, int nargs, tree fn, tree arg, int flags)
2388 {
2389 int lflags = flags;
2390 tree t;
2391 if (i == 0 && nargs == 1 && DECL_CONSTRUCTOR_P (fn)
2392 && (t = FUNCTION_FIRST_USER_PARMTYPE (fn))
2393 && (same_type_ignoring_top_level_qualifiers_p
2394 (non_reference (TREE_VALUE (t)), DECL_CONTEXT (fn))))
2395 {
2396 if (!(flags & LOOKUP_ONLYCONVERTING))
2397 lflags |= LOOKUP_COPY_PARM;
2398 if ((flags & LOOKUP_LIST_INIT_CTOR)
2399 && BRACE_ENCLOSED_INITIALIZER_P (arg))
2400 lflags |= LOOKUP_NO_CONVERSION;
2401 }
2402 else
2403 lflags |= LOOKUP_ONLYCONVERTING;
2404
2405 return lflags;
2406 }
2407
2408 /* Build an appropriate 'this' conversion for the method FN and class
2409 type CTYPE from the value ARG (having type ARGTYPE) to the type PARMTYPE.
2410 This function modifies PARMTYPE, ARGTYPE and ARG. */
2411
2412 static conversion *
2413 build_this_conversion (tree fn, tree ctype,
2414 tree& parmtype, tree& argtype, tree& arg,
2415 int flags, tsubst_flags_t complain)
2416 {
2417 gcc_assert (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
2418 && !DECL_CONSTRUCTOR_P (fn));
2419
2420 /* The type of the implicit object parameter ('this') for
2421 overload resolution is not always the same as for the
2422 function itself; conversion functions are considered to
2423 be members of the class being converted, and functions
2424 introduced by a using-declaration are considered to be
2425 members of the class that uses them.
2426
2427 Since build_over_call ignores the ICS for the `this'
2428 parameter, we can just change the parm type. */
2429 parmtype = cp_build_qualified_type (ctype,
2430 cp_type_quals (TREE_TYPE (parmtype)));
2431 bool this_p = true;
2432 if (FUNCTION_REF_QUALIFIED (TREE_TYPE (fn)))
2433 {
2434 /* If the function has a ref-qualifier, the implicit
2435 object parameter has reference type. */
2436 bool rv = FUNCTION_RVALUE_QUALIFIED (TREE_TYPE (fn));
2437 parmtype = cp_build_reference_type (parmtype, rv);
2438 /* The special handling of 'this' conversions in compare_ics
2439 does not apply if there is a ref-qualifier. */
2440 this_p = false;
2441 }
2442 else
2443 {
2444 parmtype = build_pointer_type (parmtype);
2445 /* We don't use build_this here because we don't want to
2446 capture the object argument until we've chosen a
2447 non-static member function. */
2448 arg = build_address (arg);
2449 argtype = lvalue_type (arg);
2450 }
2451 flags |= LOOKUP_ONLYCONVERTING;
2452 conversion *t = implicit_conversion (parmtype, argtype, arg,
2453 /*c_cast_p=*/false, flags, complain);
2454 t->this_p = this_p;
2455 return t;
2456 }
2457
2458 /* Create an overload candidate for the function or method FN called
2459 with the argument list FIRST_ARG/ARGS and add it to CANDIDATES.
2460 FLAGS is passed on to implicit_conversion.
2461
2462 This does not change ARGS.
2463
2464 CTYPE, if non-NULL, is the type we want to pretend this function
2465 comes from for purposes of overload resolution.
2466
2467 SHORTCUT_BAD_CONVS controls how we handle "bad" argument conversions.
2468 If true, we stop computing conversions upon seeing the first bad
2469 conversion. This is used by add_candidates to avoid computing
2470 more conversions than necessary in the presence of a strictly viable
2471 candidate, while preserving the defacto behavior of overload resolution
2472 when it turns out there are only non-strictly viable candidates. */
2473
2474 static struct z_candidate *
2475 add_function_candidate (struct z_candidate **candidates,
2476 tree fn, tree ctype, tree first_arg,
2477 const vec<tree, va_gc> *args, tree access_path,
2478 tree conversion_path, int flags,
2479 conversion **convs,
2480 bool shortcut_bad_convs,
2481 tsubst_flags_t complain)
2482 {
2483 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
2484 int i, len;
2485 tree parmnode;
2486 tree orig_first_arg = first_arg;
2487 int skip;
2488 int viable = 1;
2489 struct rejection_reason *reason = NULL;
2490
2491 /* The `this', `in_chrg' and VTT arguments to constructors are not
2492 considered in overload resolution. */
2493 if (DECL_CONSTRUCTOR_P (fn))
2494 {
2495 if (ctor_omit_inherited_parms (fn))
2496 /* Bring back parameters omitted from an inherited ctor. */
2497 parmlist = FUNCTION_FIRST_USER_PARMTYPE (DECL_ORIGIN (fn));
2498 else
2499 parmlist = skip_artificial_parms_for (fn, parmlist);
2500 skip = num_artificial_parms_for (fn);
2501 if (skip > 0 && first_arg != NULL_TREE)
2502 {
2503 --skip;
2504 first_arg = NULL_TREE;
2505 }
2506 }
2507 else
2508 skip = 0;
2509
2510 len = vec_safe_length (args) - skip + (first_arg != NULL_TREE ? 1 : 0);
2511 if (!convs)
2512 convs = alloc_conversions (len);
2513
2514 /* 13.3.2 - Viable functions [over.match.viable]
2515 First, to be a viable function, a candidate function shall have enough
2516 parameters to agree in number with the arguments in the list.
2517
2518 We need to check this first; otherwise, checking the ICSes might cause
2519 us to produce an ill-formed template instantiation. */
2520
2521 parmnode = parmlist;
2522 for (i = 0; i < len; ++i)
2523 {
2524 if (parmnode == NULL_TREE || parmnode == void_list_node)
2525 break;
2526 parmnode = TREE_CHAIN (parmnode);
2527 }
2528
2529 if ((i < len && parmnode)
2530 || !sufficient_parms_p (parmnode))
2531 {
2532 int remaining = remaining_arguments (parmnode);
2533 viable = 0;
2534 reason = arity_rejection (first_arg, i + remaining, len);
2535 }
2536
2537 /* An inherited constructor (12.6.3 [class.inhctor.init]) that has a first
2538 parameter of type "reference to cv C" (including such a constructor
2539 instantiated from a template) is excluded from the set of candidate
2540 functions when used to construct an object of type D with an argument list
2541 containing a single argument if C is reference-related to D. */
2542 if (viable && len == 1 && parmlist && DECL_CONSTRUCTOR_P (fn)
2543 && flag_new_inheriting_ctors
2544 && DECL_INHERITED_CTOR (fn))
2545 {
2546 tree ptype = non_reference (TREE_VALUE (parmlist));
2547 tree dtype = DECL_CONTEXT (fn);
2548 tree btype = DECL_INHERITED_CTOR_BASE (fn);
2549 if (reference_related_p (ptype, dtype)
2550 && reference_related_p (btype, ptype))
2551 {
2552 viable = false;
2553 reason = inherited_ctor_rejection ();
2554 }
2555 }
2556
2557 /* Second, for a function to be viable, its constraints must be
2558 satisfied. */
2559 if (flag_concepts && viable && !constraints_satisfied_p (fn))
2560 {
2561 reason = constraint_failure ();
2562 viable = false;
2563 }
2564
2565 /* When looking for a function from a subobject from an implicit
2566 copy/move constructor/operator=, don't consider anything that takes (a
2567 reference to) an unrelated type. See c++/44909 and core 1092. */
2568 if (viable && parmlist && (flags & LOOKUP_DEFAULTED))
2569 {
2570 if (DECL_CONSTRUCTOR_P (fn))
2571 i = 1;
2572 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
2573 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR))
2574 i = 2;
2575 else
2576 i = 0;
2577 if (i && len == i)
2578 {
2579 parmnode = chain_index (i-1, parmlist);
2580 if (!reference_related_p (non_reference (TREE_VALUE (parmnode)),
2581 ctype))
2582 viable = 0;
2583 }
2584
2585 /* This only applies at the top level. */
2586 flags &= ~LOOKUP_DEFAULTED;
2587 }
2588
2589 if (! viable)
2590 goto out;
2591
2592 if (shortcut_bad_convs)
2593 flags |= LOOKUP_SHORTCUT_BAD_CONVS;
2594 else
2595 flags &= ~LOOKUP_SHORTCUT_BAD_CONVS;
2596
2597 /* Third, for F to be a viable function, there shall exist for each
2598 argument an implicit conversion sequence that converts that argument
2599 to the corresponding parameter of F. */
2600
2601 parmnode = parmlist;
2602
2603 for (i = 0; i < len; ++i)
2604 {
2605 tree argtype, to_type;
2606 tree arg;
2607
2608 if (parmnode == void_list_node)
2609 break;
2610
2611 if (convs[i])
2612 {
2613 /* Already set during deduction. */
2614 parmnode = TREE_CHAIN (parmnode);
2615 continue;
2616 }
2617
2618 if (i == 0 && first_arg != NULL_TREE)
2619 arg = first_arg;
2620 else
2621 arg = CONST_CAST_TREE (
2622 (*args)[i + skip - (first_arg != NULL_TREE ? 1 : 0)]);
2623 argtype = lvalue_type (arg);
2624
2625 conversion *t;
2626 if (parmnode)
2627 {
2628 tree parmtype = TREE_VALUE (parmnode);
2629 if (i == 0
2630 && DECL_IOBJ_MEMBER_FUNCTION_P (fn)
2631 && !DECL_CONSTRUCTOR_P (fn))
2632 t = build_this_conversion (fn, ctype, parmtype, argtype, arg,
2633 flags, complain);
2634 else
2635 {
2636 int lflags = conv_flags (i, len-skip, fn, arg, flags);
2637 t = implicit_conversion (parmtype, argtype, arg,
2638 /*c_cast_p=*/false, lflags, complain);
2639 }
2640 to_type = parmtype;
2641 parmnode = TREE_CHAIN (parmnode);
2642 }
2643 else
2644 {
2645 t = build_identity_conv (argtype, arg);
2646 t->ellipsis_p = true;
2647 to_type = argtype;
2648 }
2649
2650 convs[i] = t;
2651 if (! t)
2652 {
2653 viable = 0;
2654 reason = arg_conversion_rejection (first_arg, i, argtype, to_type,
2655 EXPR_LOCATION (arg));
2656 break;
2657 }
2658
2659 if (t->bad_p)
2660 {
2661 viable = -1;
2662 reason = bad_arg_conversion_rejection (first_arg, i, arg, to_type,
2663 EXPR_LOCATION (arg));
2664 if (shortcut_bad_convs)
2665 break;
2666 }
2667 }
2668
2669 out:
2670 return add_candidate (candidates, fn, orig_first_arg, args, len, convs,
2671 access_path, conversion_path, viable, reason, flags);
2672 }
2673
2674 /* Create an overload candidate for the conversion function FN which will
2675 be invoked for expression OBJ, producing a pointer-to-function which
2676 will in turn be called with the argument list FIRST_ARG/ARGLIST,
2677 and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
2678 passed on to implicit_conversion.
2679
2680 Actually, we don't really care about FN; we care about the type it
2681 converts to. There may be multiple conversion functions that will
2682 convert to that type, and we rely on build_user_type_conversion_1 to
2683 choose the best one; so when we create our candidate, we record the type
2684 instead of the function. */
2685
2686 static struct z_candidate *
2687 add_conv_candidate (struct z_candidate **candidates, tree fn, tree obj,
2688 const vec<tree, va_gc> *arglist,
2689 tree access_path, tree conversion_path,
2690 tsubst_flags_t complain)
2691 {
2692 tree totype = TREE_TYPE (TREE_TYPE (fn));
2693 int i, len, viable, flags;
2694 tree parmlist, parmnode;
2695 conversion **convs;
2696 struct rejection_reason *reason;
2697
2698 for (parmlist = totype; TREE_CODE (parmlist) != FUNCTION_TYPE; )
2699 parmlist = TREE_TYPE (parmlist);
2700 parmlist = TYPE_ARG_TYPES (parmlist);
2701
2702 len = vec_safe_length (arglist) + 1;
2703 convs = alloc_conversions (len);
2704 parmnode = parmlist;
2705 viable = 1;
2706 flags = LOOKUP_IMPLICIT;
2707 reason = NULL;
2708
2709 /* Don't bother looking up the same type twice. */
2710 if (*candidates && (*candidates)->fn == totype)
2711 return NULL;
2712
2713 if (!constraints_satisfied_p (fn))
2714 {
2715 reason = constraint_failure ();
2716 viable = 0;
2717 return add_candidate (candidates, fn, obj, arglist, len, convs,
2718 access_path, conversion_path, viable, reason, flags);
2719 }
2720
2721 for (i = 0; i < len; ++i)
2722 {
2723 tree arg, argtype, convert_type = NULL_TREE;
2724 conversion *t;
2725
2726 if (i == 0)
2727 arg = obj;
2728 else
2729 arg = (*arglist)[i - 1];
2730 argtype = lvalue_type (arg);
2731
2732 if (i == 0)
2733 {
2734 t = build_identity_conv (argtype, NULL_TREE);
2735 t = build_conv (ck_user, totype, t);
2736 /* Leave the 'cand' field null; we'll figure out the conversion in
2737 convert_like if this candidate is chosen. */
2738 convert_type = totype;
2739 }
2740 else if (parmnode == void_list_node)
2741 break;
2742 else if (parmnode)
2743 {
2744 t = implicit_conversion (TREE_VALUE (parmnode), argtype, arg,
2745 /*c_cast_p=*/false, flags, complain);
2746 convert_type = TREE_VALUE (parmnode);
2747 }
2748 else
2749 {
2750 t = build_identity_conv (argtype, arg);
2751 t->ellipsis_p = true;
2752 convert_type = argtype;
2753 }
2754
2755 convs[i] = t;
2756 if (! t)
2757 break;
2758
2759 if (t->bad_p)
2760 {
2761 viable = -1;
2762 reason = bad_arg_conversion_rejection (NULL_TREE, i, arg, convert_type,
2763 EXPR_LOCATION (arg));
2764 }
2765
2766 if (i == 0)
2767 continue;
2768
2769 if (parmnode)
2770 parmnode = TREE_CHAIN (parmnode);
2771 }
2772
2773 if (i < len
2774 || ! sufficient_parms_p (parmnode))
2775 {
2776 int remaining = remaining_arguments (parmnode);
2777 viable = 0;
2778 reason = arity_rejection (NULL_TREE, i + remaining, len);
2779 }
2780
2781 return add_candidate (candidates, totype, obj, arglist, len, convs,
2782 access_path, conversion_path, viable, reason, flags);
2783 }
2784
2785 static void
2786 build_builtin_candidate (struct z_candidate **candidates, tree fnname,
2787 tree type1, tree type2, const vec<tree,va_gc> &args,
2788 tree *argtypes, int flags, tsubst_flags_t complain)
2789 {
2790 conversion *t;
2791 conversion **convs;
2792 size_t num_convs;
2793 int viable = 1;
2794 tree types[2];
2795 struct rejection_reason *reason = NULL;
2796
2797 types[0] = type1;
2798 types[1] = type2;
2799
2800 num_convs = args.length ();
2801 convs = alloc_conversions (num_convs);
2802
2803 /* TRUTH_*_EXPR do "contextual conversion to bool", which means explicit
2804 conversion ops are allowed. We handle that here by just checking for
2805 boolean_type_node because other operators don't ask for it. COND_EXPR
2806 also does contextual conversion to bool for the first operand, but we
2807 handle that in build_conditional_expr, and type1 here is operand 2. */
2808 if (type1 != boolean_type_node)
2809 flags |= LOOKUP_ONLYCONVERTING;
2810
2811 for (unsigned i = 0; i < 2 && i < num_convs; ++i)
2812 {
2813 t = implicit_conversion (types[i], argtypes[i], args[i],
2814 /*c_cast_p=*/false, flags, complain);
2815 if (! t)
2816 {
2817 viable = 0;
2818 /* We need something for printing the candidate. */
2819 t = build_identity_conv (types[i], NULL_TREE);
2820 reason = arg_conversion_rejection (NULL_TREE, i, argtypes[i],
2821 types[i], EXPR_LOCATION (args[i]));
2822 }
2823 else if (t->bad_p)
2824 {
2825 viable = 0;
2826 reason = bad_arg_conversion_rejection (NULL_TREE, i, args[i],
2827 types[i],
2828 EXPR_LOCATION (args[i]));
2829 }
2830 convs[i] = t;
2831 }
2832
2833 /* For COND_EXPR we rearranged the arguments; undo that now. */
2834 if (num_convs == 3)
2835 {
2836 convs[2] = convs[1];
2837 convs[1] = convs[0];
2838 t = implicit_conversion (boolean_type_node, argtypes[2], args[2],
2839 /*c_cast_p=*/false, flags,
2840 complain);
2841 if (t)
2842 convs[0] = t;
2843 else
2844 {
2845 viable = 0;
2846 reason = arg_conversion_rejection (NULL_TREE, 0, argtypes[2],
2847 boolean_type_node,
2848 EXPR_LOCATION (args[2]));
2849 }
2850 }
2851
2852 add_candidate (candidates, fnname, /*first_arg=*/NULL_TREE, /*args=*/NULL,
2853 num_convs, convs,
2854 /*access_path=*/NULL_TREE,
2855 /*conversion_path=*/NULL_TREE,
2856 viable, reason, flags);
2857 }
2858
2859 static bool
2860 is_complete (tree t)
2861 {
2862 return COMPLETE_TYPE_P (complete_type (t));
2863 }
2864
2865 /* Returns nonzero if TYPE is a promoted arithmetic type. */
2866
2867 static bool
2868 promoted_arithmetic_type_p (tree type)
2869 {
2870 /* [over.built]
2871
2872 In this section, the term promoted integral type is used to refer
2873 to those integral types which are preserved by integral promotion
2874 (including e.g. int and long but excluding e.g. char).
2875 Similarly, the term promoted arithmetic type refers to promoted
2876 integral types plus floating types. */
2877 return ((CP_INTEGRAL_TYPE_P (type)
2878 && same_type_p (type_promotes_to (type), type))
2879 || SCALAR_FLOAT_TYPE_P (type));
2880 }
2881
2882 /* Create any builtin operator overload candidates for the operator in
2883 question given the converted operand types TYPE1 and TYPE2. The other
2884 args are passed through from add_builtin_candidates to
2885 build_builtin_candidate.
2886
2887 TYPE1 and TYPE2 may not be permissible, and we must filter them.
2888 If CODE is requires candidates operands of the same type of the kind
2889 of which TYPE1 and TYPE2 are, we add both candidates
2890 CODE (TYPE1, TYPE1) and CODE (TYPE2, TYPE2). */
2891
2892 static void
2893 add_builtin_candidate (struct z_candidate **candidates, enum tree_code code,
2894 enum tree_code code2, tree fnname, tree type1,
2895 tree type2, vec<tree,va_gc> &args, tree *argtypes,
2896 int flags, tsubst_flags_t complain)
2897 {
2898 switch (code)
2899 {
2900 case POSTINCREMENT_EXPR:
2901 case POSTDECREMENT_EXPR:
2902 args[1] = integer_zero_node;
2903 type2 = integer_type_node;
2904 break;
2905 default:
2906 break;
2907 }
2908
2909 switch (code)
2910 {
2911
2912 /* 4 For every pair (T, VQ), where T is an arithmetic type other than bool,
2913 and VQ is either volatile or empty, there exist candidate operator
2914 functions of the form
2915 VQ T& operator++(VQ T&);
2916 T operator++(VQ T&, int);
2917 5 For every pair (T, VQ), where T is an arithmetic type other than bool,
2918 and VQ is either volatile or empty, there exist candidate operator
2919 functions of the form
2920 VQ T& operator--(VQ T&);
2921 T operator--(VQ T&, int);
2922 6 For every pair (T, VQ), where T is a cv-qualified or cv-unqualified object
2923 type, and VQ is either volatile or empty, there exist candidate operator
2924 functions of the form
2925 T*VQ& operator++(T*VQ&);
2926 T*VQ& operator--(T*VQ&);
2927 T* operator++(T*VQ&, int);
2928 T* operator--(T*VQ&, int); */
2929
2930 case POSTDECREMENT_EXPR:
2931 case PREDECREMENT_EXPR:
2932 if (TREE_CODE (type1) == BOOLEAN_TYPE)
2933 return;
2934 /* FALLTHRU */
2935 case POSTINCREMENT_EXPR:
2936 case PREINCREMENT_EXPR:
2937 /* P0002R1, Remove deprecated operator++(bool) added "other than bool"
2938 to p4. */
2939 if (TREE_CODE (type1) == BOOLEAN_TYPE && cxx_dialect >= cxx17)
2940 return;
2941 if (ARITHMETIC_TYPE_P (type1) || TYPE_PTROB_P (type1))
2942 {
2943 type1 = build_reference_type (type1);
2944 break;
2945 }
2946 return;
2947
2948 /* 7 For every cv-qualified or cv-unqualified object type T, there
2949 exist candidate operator functions of the form
2950
2951 T& operator*(T*);
2952
2953
2954 8 For every function type T that does not have cv-qualifiers or
2955 a ref-qualifier, there exist candidate operator functions of the form
2956 T& operator*(T*); */
2957
2958 case INDIRECT_REF:
2959 if (TYPE_PTR_P (type1)
2960 && (TYPE_PTROB_P (type1)
2961 || TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE))
2962 break;
2963 return;
2964
2965 /* 9 For every type T, there exist candidate operator functions of the form
2966 T* operator+(T*);
2967
2968 10 For every floating-point or promoted integral type T, there exist
2969 candidate operator functions of the form
2970 T operator+(T);
2971 T operator-(T); */
2972
2973 case UNARY_PLUS_EXPR: /* unary + */
2974 if (TYPE_PTR_P (type1))
2975 break;
2976 /* FALLTHRU */
2977 case NEGATE_EXPR:
2978 if (ARITHMETIC_TYPE_P (type1))
2979 break;
2980 return;
2981
2982 /* 11 For every promoted integral type T, there exist candidate operator
2983 functions of the form
2984 T operator~(T); */
2985
2986 case BIT_NOT_EXPR:
2987 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1))
2988 break;
2989 return;
2990
2991 /* 12 For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, C1
2992 is the same type as C2 or is a derived class of C2, and T is an object
2993 type or a function type there exist candidate operator functions of the
2994 form
2995 CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
2996 where CV12 is the union of CV1 and CV2. */
2997
2998 case MEMBER_REF:
2999 if (TYPE_PTR_P (type1) && TYPE_PTRMEM_P (type2))
3000 {
3001 tree c1 = TREE_TYPE (type1);
3002 tree c2 = TYPE_PTRMEM_CLASS_TYPE (type2);
3003
3004 if (CLASS_TYPE_P (c1) && DERIVED_FROM_P (c2, c1)
3005 && (TYPE_PTRMEMFUNC_P (type2)
3006 || is_complete (TYPE_PTRMEM_POINTED_TO_TYPE (type2))))
3007 break;
3008 }
3009 return;
3010
3011 /* 13 For every pair of types L and R, where each of L and R is a floating-point
3012 or promoted integral type, there exist candidate operator functions of the
3013 form
3014 LR operator*(L, R);
3015 LR operator/(L, R);
3016 LR operator+(L, R);
3017 LR operator-(L, R);
3018 bool operator<(L, R);
3019 bool operator>(L, R);
3020 bool operator<=(L, R);
3021 bool operator>=(L, R);
3022 bool operator==(L, R);
3023 bool operator!=(L, R);
3024 where LR is the result of the usual arithmetic conversions between
3025 types L and R.
3026
3027 14 For every integral type T there exists a candidate operator function of
3028 the form
3029
3030 std::strong_ordering operator<=>(T, T);
3031
3032 15 For every pair of floating-point types L and R, there exists a candidate
3033 operator function of the form
3034
3035 std::partial_ordering operator<=>(L, R);
3036
3037 16 For every cv-qualified or cv-unqualified object type T there exist
3038 candidate operator functions of the form
3039 T* operator+(T*, std::ptrdiff_t);
3040 T& operator[](T*, std::ptrdiff_t);
3041 T* operator-(T*, std::ptrdiff_t);
3042 T* operator+(std::ptrdiff_t, T*);
3043 T& operator[](std::ptrdiff_t, T*);
3044
3045 17 For every T, where T is a pointer to object type, there exist candidate
3046 operator functions of the form
3047 std::ptrdiff_t operator-(T, T);
3048
3049 18 For every T, where T is an enumeration type or a pointer type, there
3050 exist candidate operator functions of the form
3051 bool operator<(T, T);
3052 bool operator>(T, T);
3053 bool operator<=(T, T);
3054 bool operator>=(T, T);
3055 bool operator==(T, T);
3056 bool operator!=(T, T);
3057 R operator<=>(T, T);
3058
3059 where R is the result type specified in [expr.spaceship].
3060
3061 19 For every T, where T is a pointer-to-member type or std::nullptr_t,
3062 there exist candidate operator functions of the form
3063 bool operator==(T, T);
3064 bool operator!=(T, T); */
3065
3066 case MINUS_EXPR:
3067 if (TYPE_PTROB_P (type1) && TYPE_PTROB_P (type2))
3068 break;
3069 if (TYPE_PTROB_P (type1)
3070 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3071 {
3072 type2 = ptrdiff_type_node;
3073 break;
3074 }
3075 /* FALLTHRU */
3076 case MULT_EXPR:
3077 case TRUNC_DIV_EXPR:
3078 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3079 break;
3080 return;
3081
3082 /* This isn't exactly what's specified above for operator<=>, but it's
3083 close enough. In particular, we don't care about the return type
3084 specified above; it doesn't participate in overload resolution and it
3085 doesn't affect the semantics of the built-in operator. */
3086 case SPACESHIP_EXPR:
3087 case EQ_EXPR:
3088 case NE_EXPR:
3089 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3090 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2)))
3091 break;
3092 if (NULLPTR_TYPE_P (type1) && NULLPTR_TYPE_P (type2))
3093 break;
3094 if (TYPE_PTRMEM_P (type1) && null_ptr_cst_p (args[1]))
3095 {
3096 type2 = type1;
3097 break;
3098 }
3099 if (TYPE_PTRMEM_P (type2) && null_ptr_cst_p (args[0]))
3100 {
3101 type1 = type2;
3102 break;
3103 }
3104 /* Fall through. */
3105 case LT_EXPR:
3106 case GT_EXPR:
3107 case LE_EXPR:
3108 case GE_EXPR:
3109 case MAX_EXPR:
3110 case MIN_EXPR:
3111 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3112 break;
3113 if (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3114 break;
3115 if (TREE_CODE (type1) == ENUMERAL_TYPE
3116 && TREE_CODE (type2) == ENUMERAL_TYPE)
3117 break;
3118 if (TYPE_PTR_P (type1)
3119 && null_ptr_cst_p (args[1]))
3120 {
3121 type2 = type1;
3122 break;
3123 }
3124 if (null_ptr_cst_p (args[0])
3125 && TYPE_PTR_P (type2))
3126 {
3127 type1 = type2;
3128 break;
3129 }
3130 return;
3131
3132 case PLUS_EXPR:
3133 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3134 break;
3135 /* FALLTHRU */
3136 case ARRAY_REF:
3137 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && TYPE_PTROB_P (type2))
3138 {
3139 type1 = ptrdiff_type_node;
3140 break;
3141 }
3142 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3143 {
3144 type2 = ptrdiff_type_node;
3145 break;
3146 }
3147 return;
3148
3149 /* 18For every pair of promoted integral types L and R, there exist candi-
3150 date operator functions of the form
3151 LR operator%(L, R);
3152 LR operator&(L, R);
3153 LR operator^(L, R);
3154 LR operator|(L, R);
3155 L operator<<(L, R);
3156 L operator>>(L, R);
3157 where LR is the result of the usual arithmetic conversions between
3158 types L and R. */
3159
3160 case TRUNC_MOD_EXPR:
3161 case BIT_AND_EXPR:
3162 case BIT_IOR_EXPR:
3163 case BIT_XOR_EXPR:
3164 case LSHIFT_EXPR:
3165 case RSHIFT_EXPR:
3166 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3167 break;
3168 return;
3169
3170 /* 19For every triple L, VQ, R), where L is an arithmetic or enumeration
3171 type, VQ is either volatile or empty, and R is a promoted arithmetic
3172 type, there exist candidate operator functions of the form
3173 VQ L& operator=(VQ L&, R);
3174 VQ L& operator*=(VQ L&, R);
3175 VQ L& operator/=(VQ L&, R);
3176 VQ L& operator+=(VQ L&, R);
3177 VQ L& operator-=(VQ L&, R);
3178
3179 20For every pair T, VQ), where T is any type and VQ is either volatile
3180 or empty, there exist candidate operator functions of the form
3181 T*VQ& operator=(T*VQ&, T*);
3182
3183 21For every pair T, VQ), where T is a pointer to member type and VQ is
3184 either volatile or empty, there exist candidate operator functions of
3185 the form
3186 VQ T& operator=(VQ T&, T);
3187
3188 22For every triple T, VQ, I), where T is a cv-qualified or cv-
3189 unqualified complete object type, VQ is either volatile or empty, and
3190 I is a promoted integral type, there exist candidate operator func-
3191 tions of the form
3192 T*VQ& operator+=(T*VQ&, I);
3193 T*VQ& operator-=(T*VQ&, I);
3194
3195 23For every triple L, VQ, R), where L is an integral or enumeration
3196 type, VQ is either volatile or empty, and R is a promoted integral
3197 type, there exist candidate operator functions of the form
3198
3199 VQ L& operator%=(VQ L&, R);
3200 VQ L& operator<<=(VQ L&, R);
3201 VQ L& operator>>=(VQ L&, R);
3202 VQ L& operator&=(VQ L&, R);
3203 VQ L& operator^=(VQ L&, R);
3204 VQ L& operator|=(VQ L&, R); */
3205
3206 case MODIFY_EXPR:
3207 switch (code2)
3208 {
3209 case PLUS_EXPR:
3210 case MINUS_EXPR:
3211 if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3212 {
3213 type2 = ptrdiff_type_node;
3214 break;
3215 }
3216 /* FALLTHRU */
3217 case MULT_EXPR:
3218 case TRUNC_DIV_EXPR:
3219 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3220 break;
3221 return;
3222
3223 case TRUNC_MOD_EXPR:
3224 case BIT_AND_EXPR:
3225 case BIT_IOR_EXPR:
3226 case BIT_XOR_EXPR:
3227 case LSHIFT_EXPR:
3228 case RSHIFT_EXPR:
3229 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
3230 break;
3231 return;
3232
3233 case NOP_EXPR:
3234 if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
3235 break;
3236 if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
3237 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3238 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3239 || ((TYPE_PTRMEMFUNC_P (type1)
3240 || TYPE_PTR_P (type1))
3241 && null_ptr_cst_p (args[1])))
3242 {
3243 type2 = type1;
3244 break;
3245 }
3246 return;
3247
3248 default:
3249 gcc_unreachable ();
3250 }
3251 type1 = build_reference_type (type1);
3252 break;
3253
3254 case COND_EXPR:
3255 /* [over.built]
3256
3257 For every pair of promoted arithmetic types L and R, there
3258 exist candidate operator functions of the form
3259
3260 LR operator?(bool, L, R);
3261
3262 where LR is the result of the usual arithmetic conversions
3263 between types L and R.
3264
3265 For every type T, where T is a pointer or pointer-to-member
3266 type, there exist candidate operator functions of the form T
3267 operator?(bool, T, T); */
3268
3269 if (promoted_arithmetic_type_p (type1)
3270 && promoted_arithmetic_type_p (type2))
3271 /* That's OK. */
3272 break;
3273
3274 /* Otherwise, the types should be pointers. */
3275 if (!((TYPE_PTR_OR_PTRMEM_P (type1) || null_ptr_cst_p (args[0]))
3276 && (TYPE_PTR_OR_PTRMEM_P (type2) || null_ptr_cst_p (args[1]))))
3277 return;
3278
3279 /* We don't check that the two types are the same; the logic
3280 below will actually create two candidates; one in which both
3281 parameter types are TYPE1, and one in which both parameter
3282 types are TYPE2. */
3283 break;
3284
3285 case REALPART_EXPR:
3286 case IMAGPART_EXPR:
3287 if (ARITHMETIC_TYPE_P (type1))
3288 break;
3289 return;
3290
3291 default:
3292 gcc_unreachable ();
3293 }
3294
3295 /* Make sure we don't create builtin candidates with dependent types. */
3296 bool u1 = uses_template_parms (type1);
3297 bool u2 = type2 ? uses_template_parms (type2) : false;
3298 if (u1 || u2)
3299 {
3300 /* Try to recover if one of the types is non-dependent. But if
3301 there's only one type, there's nothing we can do. */
3302 if (!type2)
3303 return;
3304 /* And we lose if both are dependent. */
3305 if (u1 && u2)
3306 return;
3307 /* Or if they have different forms. */
3308 if (TREE_CODE (type1) != TREE_CODE (type2))
3309 return;
3310
3311 if (u1 && !u2)
3312 type1 = type2;
3313 else if (u2 && !u1)
3314 type2 = type1;
3315 }
3316
3317 /* If we're dealing with two pointer types or two enumeral types,
3318 we need candidates for both of them. */
3319 if (type2 && !same_type_p (type1, type2)
3320 && TREE_CODE (type1) == TREE_CODE (type2)
3321 && (TYPE_REF_P (type1)
3322 || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
3323 || (TYPE_PTRDATAMEM_P (type1) && TYPE_PTRDATAMEM_P (type2))
3324 || TYPE_PTRMEMFUNC_P (type1)
3325 || MAYBE_CLASS_TYPE_P (type1)
3326 || TREE_CODE (type1) == ENUMERAL_TYPE))
3327 {
3328 if (TYPE_PTR_OR_PTRMEM_P (type1))
3329 {
3330 tree cptype = composite_pointer_type (input_location,
3331 type1, type2,
3332 error_mark_node,
3333 error_mark_node,
3334 CPO_CONVERSION,
3335 tf_none);
3336 if (cptype != error_mark_node)
3337 {
3338 build_builtin_candidate
3339 (candidates, fnname, cptype, cptype, args, argtypes,
3340 flags, complain);
3341 return;
3342 }
3343 }
3344
3345 build_builtin_candidate
3346 (candidates, fnname, type1, type1, args, argtypes, flags, complain);
3347 build_builtin_candidate
3348 (candidates, fnname, type2, type2, args, argtypes, flags, complain);
3349 return;
3350 }
3351
3352 build_builtin_candidate
3353 (candidates, fnname, type1, type2, args, argtypes, flags, complain);
3354 }
3355
3356 tree
3357 type_decays_to (tree type)
3358 {
3359 if (TREE_CODE (type) == ARRAY_TYPE)
3360 return build_pointer_type (TREE_TYPE (type));
3361 if (TREE_CODE (type) == FUNCTION_TYPE)
3362 return build_pointer_type (type);
3363 return type;
3364 }
3365
3366 /* There are three conditions of builtin candidates:
3367
3368 1) bool-taking candidates. These are the same regardless of the input.
3369 2) pointer-pair taking candidates. These are generated for each type
3370 one of the input types converts to.
3371 3) arithmetic candidates. According to the standard, we should generate
3372 all of these, but I'm trying not to...
3373
3374 Here we generate a superset of the possible candidates for this particular
3375 case. That is a subset of the full set the standard defines, plus some
3376 other cases which the standard disallows. add_builtin_candidate will
3377 filter out the invalid set. */
3378
3379 static void
3380 add_builtin_candidates (struct z_candidate **candidates, enum tree_code code,
3381 enum tree_code code2, tree fnname,
3382 vec<tree, va_gc> *argv,
3383 int flags, tsubst_flags_t complain)
3384 {
3385 int ref1;
3386 int enum_p = 0;
3387 tree type, argtypes[3], t;
3388 /* TYPES[i] is the set of possible builtin-operator parameter types
3389 we will consider for the Ith argument. */
3390 vec<tree, va_gc> *types[2];
3391 unsigned ix;
3392 vec<tree, va_gc> &args = *argv;
3393 unsigned len = args.length ();
3394
3395 for (unsigned i = 0; i < len; ++i)
3396 {
3397 if (args[i])
3398 argtypes[i] = unlowered_expr_type (args[i]);
3399 else
3400 argtypes[i] = NULL_TREE;
3401 }
3402
3403 switch (code)
3404 {
3405 /* 4 For every pair T, VQ), where T is an arithmetic or enumeration type,
3406 and VQ is either volatile or empty, there exist candidate operator
3407 functions of the form
3408 VQ T& operator++(VQ T&); */
3409
3410 case POSTINCREMENT_EXPR:
3411 case PREINCREMENT_EXPR:
3412 case POSTDECREMENT_EXPR:
3413 case PREDECREMENT_EXPR:
3414 case MODIFY_EXPR:
3415 ref1 = 1;
3416 break;
3417
3418 /* 24There also exist candidate operator functions of the form
3419 bool operator!(bool);
3420 bool operator&&(bool, bool);
3421 bool operator||(bool, bool); */
3422
3423 case TRUTH_NOT_EXPR:
3424 build_builtin_candidate
3425 (candidates, fnname, boolean_type_node,
3426 NULL_TREE, args, argtypes, flags, complain);
3427 return;
3428
3429 case TRUTH_ORIF_EXPR:
3430 case TRUTH_ANDIF_EXPR:
3431 build_builtin_candidate
3432 (candidates, fnname, boolean_type_node,
3433 boolean_type_node, args, argtypes, flags, complain);
3434 return;
3435
3436 case ADDR_EXPR:
3437 case COMPOUND_EXPR:
3438 case COMPONENT_REF:
3439 case CO_AWAIT_EXPR:
3440 return;
3441
3442 case COND_EXPR:
3443 case EQ_EXPR:
3444 case NE_EXPR:
3445 case LT_EXPR:
3446 case LE_EXPR:
3447 case GT_EXPR:
3448 case GE_EXPR:
3449 case SPACESHIP_EXPR:
3450 enum_p = 1;
3451 /* Fall through. */
3452
3453 default:
3454 ref1 = 0;
3455 }
3456
3457 types[0] = make_tree_vector ();
3458 types[1] = make_tree_vector ();
3459
3460 if (len == 3)
3461 len = 2;
3462 for (unsigned i = 0; i < len; ++i)
3463 {
3464 if (MAYBE_CLASS_TYPE_P (argtypes[i]))
3465 {
3466 tree convs;
3467
3468 if (i == 0 && code == MODIFY_EXPR && code2 == NOP_EXPR)
3469 return;
3470
3471 convs = lookup_conversions (argtypes[i]);
3472
3473 if (code == COND_EXPR)
3474 {
3475 if (lvalue_p (args[i]))
3476 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3477
3478 vec_safe_push (types[i], TYPE_MAIN_VARIANT (argtypes[i]));
3479 }
3480
3481 else if (! convs)
3482 return;
3483
3484 for (; convs; convs = TREE_CHAIN (convs))
3485 {
3486 type = TREE_TYPE (convs);
3487
3488 if (i == 0 && ref1
3489 && (!TYPE_REF_P (type)
3490 || CP_TYPE_CONST_P (TREE_TYPE (type))))
3491 continue;
3492
3493 if (code == COND_EXPR && TYPE_REF_P (type))
3494 vec_safe_push (types[i], type);
3495
3496 type = non_reference (type);
3497 if (i != 0 || ! ref1)
3498 {
3499 type = cv_unqualified (type_decays_to (type));
3500 if (enum_p && TREE_CODE (type) == ENUMERAL_TYPE)
3501 vec_safe_push (types[i], type);
3502 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3503 type = type_promotes_to (type);
3504 }
3505
3506 if (! vec_member (type, types[i]))
3507 vec_safe_push (types[i], type);
3508 }
3509 }
3510 else
3511 {
3512 if (code == COND_EXPR && lvalue_p (args[i]))
3513 vec_safe_push (types[i], build_reference_type (argtypes[i]));
3514 type = non_reference (argtypes[i]);
3515 if (i != 0 || ! ref1)
3516 {
3517 type = cv_unqualified (type_decays_to (type));
3518 if (enum_p && UNSCOPED_ENUM_P (type))
3519 vec_safe_push (types[i], type);
3520 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3521 type = type_promotes_to (type);
3522 }
3523 vec_safe_push (types[i], type);
3524 }
3525 }
3526
3527 /* Run through the possible parameter types of both arguments,
3528 creating candidates with those parameter types. */
3529 FOR_EACH_VEC_ELT_REVERSE (*(types[0]), ix, t)
3530 {
3531 unsigned jx;
3532 tree u;
3533
3534 if (!types[1]->is_empty ())
3535 FOR_EACH_VEC_ELT_REVERSE (*(types[1]), jx, u)
3536 add_builtin_candidate
3537 (candidates, code, code2, fnname, t,
3538 u, args, argtypes, flags, complain);
3539 else
3540 add_builtin_candidate
3541 (candidates, code, code2, fnname, t,
3542 NULL_TREE, args, argtypes, flags, complain);
3543 }
3544
3545 release_tree_vector (types[0]);
3546 release_tree_vector (types[1]);
3547 }
3548
3549
3550 /* If TMPL can be successfully instantiated as indicated by
3551 EXPLICIT_TARGS and ARGLIST, adds the instantiation to CANDIDATES.
3552
3553 TMPL is the template. EXPLICIT_TARGS are any explicit template
3554 arguments. ARGLIST is the arguments provided at the call-site.
3555 This does not change ARGLIST. The RETURN_TYPE is the desired type
3556 for conversion operators. If OBJ is NULL_TREE, FLAGS and CTYPE are
3557 as for add_function_candidate. If an OBJ is supplied, FLAGS and
3558 CTYPE are ignored, and OBJ is as for add_conv_candidate.
3559
3560 SHORTCUT_BAD_CONVS is as in add_function_candidate. */
3561
3562 static struct z_candidate*
3563 add_template_candidate_real (struct z_candidate **candidates, tree tmpl,
3564 tree ctype, tree explicit_targs, tree first_arg,
3565 const vec<tree, va_gc> *arglist, tree return_type,
3566 tree access_path, tree conversion_path,
3567 int flags, tree obj, unification_kind_t strict,
3568 bool shortcut_bad_convs, tsubst_flags_t complain)
3569 {
3570 int ntparms = DECL_NTPARMS (tmpl);
3571 tree targs = make_tree_vec (ntparms);
3572 unsigned int len = vec_safe_length (arglist);
3573 unsigned int nargs = (first_arg == NULL_TREE ? 0 : 1) + len;
3574 unsigned int skip_without_in_chrg = 0;
3575 tree first_arg_without_in_chrg = first_arg;
3576 tree *args_without_in_chrg;
3577 unsigned int nargs_without_in_chrg;
3578 unsigned int ia, ix;
3579 tree arg;
3580 struct z_candidate *cand;
3581 tree fn;
3582 struct rejection_reason *reason = NULL;
3583 int errs;
3584 conversion **convs = NULL;
3585
3586 /* We don't do deduction on the in-charge parameter, the VTT
3587 parameter or 'this'. */
3588 if (DECL_IOBJ_MEMBER_FUNCTION_P (tmpl))
3589 {
3590 if (first_arg_without_in_chrg != NULL_TREE)
3591 first_arg_without_in_chrg = NULL_TREE;
3592 else if (return_type && strict == DEDUCE_CALL)
3593 /* We're deducing for a call to the result of a template conversion
3594 function, so the args don't contain 'this'; leave them alone. */;
3595 else
3596 ++skip_without_in_chrg;
3597 }
3598
3599 if ((DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (tmpl)
3600 || DECL_BASE_CONSTRUCTOR_P (tmpl))
3601 && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (tmpl)))
3602 {
3603 if (first_arg_without_in_chrg != NULL_TREE)
3604 first_arg_without_in_chrg = NULL_TREE;
3605 else
3606 ++skip_without_in_chrg;
3607 }
3608
3609 if (len < skip_without_in_chrg)
3610 return add_ignored_candidate (candidates, tmpl);
3611
3612 if (DECL_CONSTRUCTOR_P (tmpl) && nargs == 2
3613 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (first_arg),
3614 TREE_TYPE ((*arglist)[0])))
3615 {
3616 /* 12.8/6 says, "A declaration of a constructor for a class X is
3617 ill-formed if its first parameter is of type (optionally cv-qualified)
3618 X and either there are no other parameters or else all other
3619 parameters have default arguments. A member function template is never
3620 instantiated to produce such a constructor signature."
3621
3622 So if we're trying to copy an object of the containing class, don't
3623 consider a template constructor that has a first parameter type that
3624 is just a template parameter, as we would deduce a signature that we
3625 would then reject in the code below. */
3626 if (tree firstparm = FUNCTION_FIRST_USER_PARMTYPE (tmpl))
3627 {
3628 firstparm = TREE_VALUE (firstparm);
3629 if (PACK_EXPANSION_P (firstparm))
3630 firstparm = PACK_EXPANSION_PATTERN (firstparm);
3631 if (TREE_CODE (firstparm) == TEMPLATE_TYPE_PARM)
3632 {
3633 gcc_assert (!explicit_targs);
3634 reason = invalid_copy_with_fn_template_rejection ();
3635 goto fail;
3636 }
3637 }
3638 }
3639
3640 nargs_without_in_chrg = ((first_arg_without_in_chrg != NULL_TREE ? 1 : 0)
3641 + (len - skip_without_in_chrg));
3642 args_without_in_chrg = XALLOCAVEC (tree, nargs_without_in_chrg);
3643 ia = 0;
3644 if (first_arg_without_in_chrg != NULL_TREE)
3645 {
3646 args_without_in_chrg[ia] = first_arg_without_in_chrg;
3647 ++ia;
3648 }
3649 for (ix = skip_without_in_chrg;
3650 vec_safe_iterate (arglist, ix, &arg);
3651 ++ix)
3652 {
3653 args_without_in_chrg[ia] = arg;
3654 ++ia;
3655 }
3656 gcc_assert (ia == nargs_without_in_chrg);
3657
3658 if (!obj)
3659 {
3660 /* Check that there's no obvious arity mismatch before proceeding with
3661 deduction. This avoids substituting explicit template arguments
3662 into the template or e.g. derived-to-base parm/arg unification
3663 (which could result in an error outside the immediate context) when
3664 the resulting candidate would be unviable anyway. */
3665 int min_arity = 0, max_arity = 0;
3666 tree parms = TYPE_ARG_TYPES (TREE_TYPE (tmpl));
3667 parms = skip_artificial_parms_for (tmpl, parms);
3668 for (; parms != void_list_node; parms = TREE_CHAIN (parms))
3669 {
3670 if (!parms || PACK_EXPANSION_P (TREE_VALUE (parms)))
3671 {
3672 max_arity = -1;
3673 break;
3674 }
3675 if (TREE_PURPOSE (parms))
3676 /* A parameter with a default argument. */
3677 ++max_arity;
3678 else
3679 ++min_arity, ++max_arity;
3680 }
3681 if (ia < (unsigned)min_arity)
3682 {
3683 /* Too few arguments. */
3684 reason = arity_rejection (NULL_TREE, min_arity, ia,
3685 /*least_p=*/(max_arity == -1));
3686 goto fail;
3687 }
3688 else if (max_arity != -1 && ia > (unsigned)max_arity)
3689 {
3690 /* Too many arguments. */
3691 reason = arity_rejection (NULL_TREE, max_arity, ia);
3692 goto fail;
3693 }
3694
3695 convs = alloc_conversions (nargs);
3696
3697 if (shortcut_bad_convs
3698 && DECL_IOBJ_MEMBER_FUNCTION_P (tmpl)
3699 && !DECL_CONSTRUCTOR_P (tmpl))
3700 {
3701 /* Check the 'this' conversion before proceeding with deduction.
3702 This is effectively an extension of the DR 1391 resolution
3703 that we perform in check_non_deducible_conversions, though it's
3704 convenient to do this extra check here instead of there. */
3705 tree parmtype = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (tmpl)));
3706 tree argtype = lvalue_type (first_arg);
3707 tree arg = first_arg;
3708 conversion *t = build_this_conversion (tmpl, ctype,
3709 parmtype, argtype, arg,
3710 flags, complain);
3711 convs[0] = t;
3712 if (t->bad_p)
3713 {
3714 reason = bad_arg_conversion_rejection (first_arg, 0,
3715 arg, parmtype,
3716 EXPR_LOCATION (arg));
3717 goto fail;
3718 }
3719 }
3720 }
3721
3722 errs = errorcount+sorrycount;
3723 fn = fn_type_unification (tmpl, explicit_targs, targs,
3724 args_without_in_chrg,
3725 nargs_without_in_chrg,
3726 return_type, strict, flags, convs,
3727 false, complain & tf_decltype);
3728
3729 if (fn == error_mark_node)
3730 {
3731 /* Don't repeat unification later if it already resulted in errors. */
3732 if (errorcount+sorrycount == errs)
3733 reason = template_unification_rejection (tmpl, explicit_targs,
3734 targs, args_without_in_chrg,
3735 nargs_without_in_chrg,
3736 return_type, strict, flags);
3737 else
3738 reason = template_unification_error_rejection ();
3739 goto fail;
3740 }
3741
3742 /* Now the explicit specifier might have been deduced; check if this
3743 declaration is explicit. If it is and we're ignoring non-converting
3744 constructors, don't add this function to the set of candidates. */
3745 if (((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
3746 == LOOKUP_ONLYCONVERTING)
3747 && DECL_NONCONVERTING_P (fn))
3748 return add_ignored_candidate (candidates, fn);
3749
3750 if (DECL_CONSTRUCTOR_P (fn) && nargs == 2)
3751 {
3752 tree arg_types = FUNCTION_FIRST_USER_PARMTYPE (fn);
3753 if (arg_types && same_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (arg_types)),
3754 ctype))
3755 {
3756 /* We're trying to produce a constructor with a prohibited signature,
3757 as discussed above; handle here any cases we didn't catch then,
3758 such as X(X<T>). */
3759 reason = invalid_copy_with_fn_template_rejection ();
3760 goto fail;
3761 }
3762 }
3763
3764 if (obj != NULL_TREE)
3765 /* Aha, this is a conversion function. */
3766 cand = add_conv_candidate (candidates, fn, obj, arglist,
3767 access_path, conversion_path, complain);
3768 else
3769 cand = add_function_candidate (candidates, fn, ctype,
3770 first_arg, arglist, access_path,
3771 conversion_path, flags, convs,
3772 shortcut_bad_convs, complain);
3773 if (DECL_TI_TEMPLATE (fn) != tmpl)
3774 /* This situation can occur if a member template of a template
3775 class is specialized. Then, instantiate_template might return
3776 an instantiation of the specialization, in which case the
3777 DECL_TI_TEMPLATE field will point at the original
3778 specialization. For example:
3779
3780 template <class T> struct S { template <class U> void f(U);
3781 template <> void f(int) {}; };
3782 S<double> sd;
3783 sd.f(3);
3784
3785 Here, TMPL will be template <class U> S<double>::f(U).
3786 And, instantiate template will give us the specialization
3787 template <> S<double>::f(int). But, the DECL_TI_TEMPLATE field
3788 for this will point at template <class T> template <> S<T>::f(int),
3789 so that we can find the definition. For the purposes of
3790 overload resolution, however, we want the original TMPL. */
3791 cand->template_decl = build_template_info (tmpl, targs);
3792 else
3793 cand->template_decl = DECL_TEMPLATE_INFO (fn);
3794 cand->explicit_targs = explicit_targs;
3795
3796 return cand;
3797 fail:
3798 int viable = (reason->code == rr_bad_arg_conversion ? -1 : 0);
3799 return add_candidate (candidates, tmpl, first_arg, arglist, nargs, convs,
3800 access_path, conversion_path, viable, reason, flags);
3801 }
3802
3803
3804 static struct z_candidate *
3805 add_template_candidate (struct z_candidate **candidates, tree tmpl, tree ctype,
3806 tree explicit_targs, tree first_arg,
3807 const vec<tree, va_gc> *arglist, tree return_type,
3808 tree access_path, tree conversion_path, int flags,
3809 unification_kind_t strict, bool shortcut_bad_convs,
3810 tsubst_flags_t complain)
3811 {
3812 return
3813 add_template_candidate_real (candidates, tmpl, ctype,
3814 explicit_targs, first_arg, arglist,
3815 return_type, access_path, conversion_path,
3816 flags, NULL_TREE, strict, shortcut_bad_convs,
3817 complain);
3818 }
3819
3820 /* Create an overload candidate for the conversion function template TMPL,
3821 returning RETURN_TYPE, which will be invoked for expression OBJ to produce a
3822 pointer-to-function which will in turn be called with the argument list
3823 ARGLIST, and add it to CANDIDATES. This does not change ARGLIST. FLAGS is
3824 passed on to implicit_conversion. */
3825
3826 static struct z_candidate *
3827 add_template_conv_candidate (struct z_candidate **candidates, tree tmpl,
3828 tree obj,
3829 const vec<tree, va_gc> *arglist,
3830 tree return_type, tree access_path,
3831 tree conversion_path, tsubst_flags_t complain)
3832 {
3833 return
3834 add_template_candidate_real (candidates, tmpl, NULL_TREE, NULL_TREE,
3835 NULL_TREE, arglist, return_type, access_path,
3836 conversion_path, 0, obj, DEDUCE_CALL,
3837 /*shortcut_bad_convs=*/false, complain);
3838 }
3839
3840 /* The CANDS are the set of candidates that were considered for
3841 overload resolution. Sort CANDS so that the strictly viable
3842 candidates appear first, followed by non-strictly viable candidates,
3843 followed by non-viable candidates. Returns the first candidate
3844 in this sorted list. If any of the candidates were viable, set
3845 *ANY_VIABLE_P to true. STRICT_P is true if a candidate should be
3846 considered viable only if it is strictly viable when setting
3847 *ANY_VIABLE_P. */
3848
3849 static struct z_candidate*
3850 splice_viable (struct z_candidate *cands,
3851 bool strict_p,
3852 bool *any_viable_p)
3853 {
3854 z_candidate *strictly_viable = nullptr;
3855 z_candidate **strictly_viable_tail = &strictly_viable;
3856
3857 z_candidate *non_strictly_viable = nullptr;
3858 z_candidate **non_strictly_viable_tail = &non_strictly_viable;
3859
3860 z_candidate *non_viable = nullptr;
3861 z_candidate **non_viable_tail = &non_viable;
3862
3863 z_candidate *non_viable_ignored = nullptr;
3864 z_candidate **non_viable_ignored_tail = &non_viable_ignored;
3865
3866 /* Be strict inside templates, since build_over_call won't actually
3867 do the conversions to get pedwarns. */
3868 if (processing_template_decl)
3869 strict_p = true;
3870
3871 for (z_candidate *cand = cands; cand; cand = cand->next)
3872 {
3873 if (!strict_p
3874 && (cand->viable == 1 || TREE_CODE (cand->fn) == TEMPLATE_DECL))
3875 /* Be strict in the presence of a viable candidate. Also if
3876 there are template candidates, so that we get deduction errors
3877 for them instead of silently preferring a bad conversion. */
3878 strict_p = true;
3879
3880 /* Move this candidate to the appropriate list according to
3881 its viability. */
3882 auto& tail = (cand->viable == 1 ? strictly_viable_tail
3883 : cand->viable == -1 ? non_strictly_viable_tail
3884 : ignored_candidate_p (cand) ? non_viable_ignored_tail
3885 : non_viable_tail);
3886 *tail = cand;
3887 tail = &cand->next;
3888 }
3889
3890 *any_viable_p = (strictly_viable != nullptr
3891 || (!strict_p && non_strictly_viable != nullptr));
3892
3893 /* Combine the lists. */
3894 *non_viable_ignored_tail = nullptr;
3895 *non_viable_tail = non_viable_ignored;
3896 *non_strictly_viable_tail = non_viable;
3897 *strictly_viable_tail = non_strictly_viable;
3898
3899 return strictly_viable;
3900 }
3901
3902 static bool
3903 any_strictly_viable (struct z_candidate *cands)
3904 {
3905 for (; cands; cands = cands->next)
3906 if (cands->viable == 1)
3907 return true;
3908 return false;
3909 }
3910
3911 /* OBJ is being used in an expression like "OBJ.f (...)". In other
3912 words, it is about to become the "this" pointer for a member
3913 function call. Take the address of the object. */
3914
3915 static tree
3916 build_this (tree obj)
3917 {
3918 /* In a template, we are only concerned about the type of the
3919 expression, so we can take a shortcut. */
3920 if (processing_template_decl)
3921 return build_address (obj);
3922
3923 return cp_build_addr_expr (obj, tf_warning_or_error);
3924 }
3925
3926 /* Returns true iff functions are equivalent. Equivalent functions are
3927 not '==' only if one is a function-local extern function or if
3928 both are extern "C". */
3929
3930 static inline int
3931 equal_functions (tree fn1, tree fn2)
3932 {
3933 if (TREE_CODE (fn1) != TREE_CODE (fn2))
3934 return 0;
3935 if (TREE_CODE (fn1) == TEMPLATE_DECL)
3936 return fn1 == fn2;
3937 if (DECL_LOCAL_DECL_P (fn1) || DECL_LOCAL_DECL_P (fn2)
3938 || DECL_EXTERN_C_FUNCTION_P (fn1))
3939 return decls_match (fn1, fn2);
3940 return fn1 == fn2;
3941 }
3942
3943 /* Print information about a candidate FN being rejected due to INFO. */
3944
3945 static void
3946 print_conversion_rejection (location_t loc, struct conversion_info *info,
3947 tree fn)
3948 {
3949 tree from = info->from;
3950 if (!TYPE_P (from))
3951 from = lvalue_type (from);
3952 if (info->n_arg == -1)
3953 {
3954 /* Conversion of implicit `this' argument failed. */
3955 if (!TYPE_P (info->from))
3956 /* A bad conversion for 'this' must be discarding cv-quals. */
3957 inform (loc, "passing %qT as %<this%> "
3958 "argument discards qualifiers",
3959 from);
3960 else
3961 inform (loc, "no known conversion for implicit "
3962 "%<this%> parameter from %qH to %qI",
3963 from, info->to_type);
3964 }
3965 else if (!TYPE_P (info->from))
3966 {
3967 if (info->n_arg >= 0)
3968 inform (loc, "conversion of argument %d would be ill-formed:",
3969 info->n_arg + 1);
3970 iloc_sentinel ils = loc;
3971 perform_implicit_conversion (info->to_type, info->from,
3972 tf_warning_or_error);
3973 }
3974 else if (info->n_arg == -2)
3975 /* Conversion of conversion function return value failed. */
3976 inform (loc, "no known conversion from %qH to %qI",
3977 from, info->to_type);
3978 else
3979 {
3980 if (TREE_CODE (fn) == FUNCTION_DECL)
3981 loc = get_fndecl_argument_location (fn, info->n_arg);
3982 inform (loc, "no known conversion for argument %d from %qH to %qI",
3983 info->n_arg + 1, from, info->to_type);
3984 }
3985 }
3986
3987 /* Print information about a candidate with WANT parameters and we found
3988 HAVE. */
3989
3990 static void
3991 print_arity_information (location_t loc, unsigned int have, unsigned int want,
3992 bool least_p)
3993 {
3994 if (least_p)
3995 inform_n (loc, want,
3996 "candidate expects at least %d argument, %d provided",
3997 "candidate expects at least %d arguments, %d provided",
3998 want, have);
3999 else
4000 inform_n (loc, want,
4001 "candidate expects %d argument, %d provided",
4002 "candidate expects %d arguments, %d provided",
4003 want, have);
4004 }
4005
4006 /* Print information about one overload candidate CANDIDATE. MSGSTR
4007 is the text to print before the candidate itself.
4008
4009 NOTE: Unlike most diagnostic functions in GCC, MSGSTR is expected
4010 to have been run through gettext by the caller. This wart makes
4011 life simpler in print_z_candidates and for the translators. */
4012
4013 static void
4014 print_z_candidate (location_t loc, const char *msgstr,
4015 struct z_candidate *candidate)
4016 {
4017 const char *msg = (msgstr == NULL
4018 ? ""
4019 : ACONCAT ((_(msgstr), " ", NULL)));
4020 tree fn = candidate->fn;
4021 if (flag_new_inheriting_ctors)
4022 fn = strip_inheriting_ctors (fn);
4023 location_t cloc = location_of (fn);
4024
4025 if (identifier_p (fn))
4026 {
4027 cloc = loc;
4028 if (candidate->num_convs == 3)
4029 inform (cloc, "%s%<%D(%T, %T, %T)%> (built-in)", msg, fn,
4030 candidate->convs[0]->type,
4031 candidate->convs[1]->type,
4032 candidate->convs[2]->type);
4033 else if (candidate->num_convs == 2)
4034 inform (cloc, "%s%<%D(%T, %T)%> (built-in)", msg, fn,
4035 candidate->convs[0]->type,
4036 candidate->convs[1]->type);
4037 else
4038 inform (cloc, "%s%<%D(%T)%> (built-in)", msg, fn,
4039 candidate->convs[0]->type);
4040 }
4041 else if (TYPE_P (fn))
4042 inform (cloc, "%s%qT (conversion)", msg, fn);
4043 else if (candidate->viable == -1)
4044 inform (cloc, "%s%#qD (near match)", msg, fn);
4045 else if (ignored_candidate_p (candidate))
4046 inform (cloc, "%s%#qD (ignored)", msg, fn);
4047 else if (DECL_DELETED_FN (fn))
4048 inform (cloc, "%s%#qD (deleted)", msg, fn);
4049 else if (candidate->reversed ())
4050 inform (cloc, "%s%#qD (reversed)", msg, fn);
4051 else if (candidate->rewritten ())
4052 inform (cloc, "%s%#qD (rewritten)", msg, fn);
4053 else
4054 inform (cloc, "%s%#qD", msg, fn);
4055 if (fn != candidate->fn)
4056 {
4057 cloc = location_of (candidate->fn);
4058 inform (cloc, "inherited here");
4059 }
4060 /* Give the user some information about why this candidate failed. */
4061 if (candidate->reason != NULL)
4062 {
4063 auto_diagnostic_nesting_level sentinel;
4064 struct rejection_reason *r = candidate->reason;
4065
4066 switch (r->code)
4067 {
4068 case rr_arity:
4069 print_arity_information (cloc, r->u.arity.actual,
4070 r->u.arity.expected,
4071 r->u.arity.least_p);
4072 break;
4073 case rr_arg_conversion:
4074 print_conversion_rejection (cloc, &r->u.conversion, fn);
4075 break;
4076 case rr_bad_arg_conversion:
4077 print_conversion_rejection (cloc, &r->u.bad_conversion, fn);
4078 break;
4079 case rr_explicit_conversion:
4080 inform (cloc, "return type %qT of explicit conversion function "
4081 "cannot be converted to %qT with a qualification "
4082 "conversion", r->u.conversion.from,
4083 r->u.conversion.to_type);
4084 break;
4085 case rr_template_conversion:
4086 inform (cloc, "conversion from return type %qT of template "
4087 "conversion function specialization to %qT is not an "
4088 "exact match", r->u.conversion.from,
4089 r->u.conversion.to_type);
4090 break;
4091 case rr_template_unification:
4092 /* We use template_unification_error_rejection if unification caused
4093 actual non-SFINAE errors, in which case we don't need to repeat
4094 them here. */
4095 if (r->u.template_unification.tmpl == NULL_TREE)
4096 {
4097 inform (cloc, "substitution of deduced template arguments "
4098 "resulted in errors seen above");
4099 break;
4100 }
4101 /* Re-run template unification with diagnostics. */
4102 inform (cloc, "template argument deduction/substitution failed:");
4103 {
4104 auto_diagnostic_nesting_level sentinel;
4105 fn_type_unification (r->u.template_unification.tmpl,
4106 r->u.template_unification.explicit_targs,
4107 (make_tree_vec
4108 (r->u.template_unification.num_targs)),
4109 r->u.template_unification.args,
4110 r->u.template_unification.nargs,
4111 r->u.template_unification.return_type,
4112 r->u.template_unification.strict,
4113 r->u.template_unification.flags,
4114 NULL, true, false);
4115 }
4116 break;
4117 case rr_invalid_copy:
4118 inform (cloc,
4119 "a constructor taking a single argument of its own "
4120 "class type is invalid");
4121 break;
4122 case rr_constraint_failure:
4123 {
4124 auto_diagnostic_nesting_level sentinel;
4125 diagnose_constraints (cloc, fn, NULL_TREE);
4126 }
4127 break;
4128 case rr_inherited_ctor:
4129 inform (cloc, "an inherited constructor is not a candidate for "
4130 "initialization from an expression of the same or derived "
4131 "type");
4132 break;
4133 case rr_ignored:
4134 break;
4135 case rr_none:
4136 default:
4137 /* This candidate didn't have any issues or we failed to
4138 handle a particular code. Either way... */
4139 gcc_unreachable ();
4140 }
4141 }
4142 }
4143
4144 /* Print information about each overload candidate in CANDIDATES,
4145 which is assumed to have gone through splice_viable and tourney
4146 (if splice_viable succeeded). */
4147
4148 static void
4149 print_z_candidates (location_t loc, struct z_candidate *candidates,
4150 tristate only_viable_p /* = tristate::unknown () */)
4151 {
4152 struct z_candidate *cand1;
4153 struct z_candidate **cand2;
4154
4155 if (!candidates)
4156 return;
4157
4158 /* Remove non-viable deleted candidates. */
4159 cand1 = candidates;
4160 for (cand2 = &cand1; *cand2; )
4161 {
4162 if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
4163 && !(*cand2)->viable
4164 && DECL_DELETED_FN ((*cand2)->fn))
4165 *cand2 = (*cand2)->next;
4166 else
4167 cand2 = &(*cand2)->next;
4168 }
4169 /* ...if there are any non-deleted ones. */
4170 if (cand1)
4171 candidates = cand1;
4172
4173 /* There may be duplicates in the set of candidates. We put off
4174 checking this condition as long as possible, since we have no way
4175 to eliminate duplicates from a set of functions in less than n^2
4176 time. Now we are about to emit an error message, so it is more
4177 permissible to go slowly. */
4178 for (cand1 = candidates; cand1; cand1 = cand1->next)
4179 {
4180 tree fn = cand1->fn;
4181 /* Skip builtin candidates and conversion functions. */
4182 if (!DECL_P (fn))
4183 continue;
4184 cand2 = &cand1->next;
4185 while (*cand2)
4186 {
4187 if (DECL_P ((*cand2)->fn)
4188 && equal_functions (fn, (*cand2)->fn))
4189 *cand2 = (*cand2)->next;
4190 else
4191 cand2 = &(*cand2)->next;
4192 }
4193 }
4194
4195 /* Unless otherwise specified, if there's a (strictly) viable candidate
4196 then we assume we're being called as part of diagnosing ambiguity, in
4197 which case we want to print only viable candidates since non-viable
4198 candidates couldn't have contributed to the ambiguity. */
4199 if (only_viable_p.is_unknown ())
4200 only_viable_p = candidates->viable == 1;
4201
4202 auto_diagnostic_nesting_level sentinel;
4203
4204 int num_candidates = 0;
4205 for (auto iter = candidates; iter; iter = iter->next)
4206 {
4207 if (only_viable_p.is_true () && iter->viable != 1)
4208 break;
4209 ++num_candidates;
4210 }
4211
4212 inform_n (loc,
4213 num_candidates, "there is %i candidate", "there are %i candidates",
4214 num_candidates);
4215 auto_diagnostic_nesting_level sentinel2;
4216
4217 int candidate_idx = 0;
4218 for (; candidates; candidates = candidates->next)
4219 {
4220 if (only_viable_p.is_true () && candidates->viable != 1)
4221 break;
4222 if (ignored_candidate_p (candidates) && !flag_diagnostics_all_candidates)
4223 {
4224 inform (loc, "some candidates omitted; "
4225 "use %<-fdiagnostics-all-candidates%> to display them");
4226 break;
4227 }
4228 pretty_printer pp;
4229 pp_printf (&pp, N_("candidate %i:"), candidate_idx + 1);
4230 const char *const msgstr = pp_formatted_text (&pp);
4231 print_z_candidate (loc, msgstr, candidates);
4232 ++candidate_idx;
4233 }
4234 }
4235
4236 /* USER_SEQ is a user-defined conversion sequence, beginning with a
4237 USER_CONV. STD_SEQ is the standard conversion sequence applied to
4238 the result of the conversion function to convert it to the final
4239 desired type. Merge the two sequences into a single sequence,
4240 and return the merged sequence. */
4241
4242 static conversion *
4243 merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
4244 {
4245 conversion **t;
4246 bool bad = user_seq->bad_p;
4247
4248 gcc_assert (user_seq->kind == ck_user);
4249
4250 /* Find the end of the second conversion sequence. */
4251 for (t = &std_seq; (*t)->kind != ck_identity; t = &((*t)->u.next))
4252 {
4253 /* The entire sequence is a user-conversion sequence. */
4254 (*t)->user_conv_p = true;
4255 if (bad)
4256 (*t)->bad_p = true;
4257 }
4258
4259 if ((*t)->rvaluedness_matches_p)
4260 /* We're binding a reference directly to the result of the conversion.
4261 build_user_type_conversion_1 stripped the REFERENCE_TYPE from the return
4262 type, but we want it back. */
4263 user_seq->type = TREE_TYPE (TREE_TYPE (user_seq->cand->fn));
4264
4265 /* Replace the identity conversion with the user conversion
4266 sequence. */
4267 *t = user_seq;
4268
4269 return std_seq;
4270 }
4271
4272 /* Handle overload resolution for initializing an object of class type from
4273 an initializer list. First we look for a suitable constructor that
4274 takes a std::initializer_list; if we don't find one, we then look for a
4275 non-list constructor.
4276
4277 Parameters are as for add_candidates, except that the arguments are in
4278 the form of a CONSTRUCTOR (the initializer list) rather than a vector, and
4279 the RETURN_TYPE parameter is replaced by TOTYPE, the desired type. */
4280
4281 static void
4282 add_list_candidates (tree fns, tree first_arg,
4283 const vec<tree, va_gc> *args, tree totype,
4284 tree explicit_targs, bool template_only,
4285 tree conversion_path, tree access_path,
4286 int flags,
4287 struct z_candidate **candidates,
4288 tsubst_flags_t complain)
4289 {
4290 gcc_assert (*candidates == NULL);
4291
4292 /* We're looking for a ctor for list-initialization. */
4293 flags |= LOOKUP_LIST_INIT_CTOR;
4294 /* And we don't allow narrowing conversions. We also use this flag to
4295 avoid the copy constructor call for copy-list-initialization. */
4296 flags |= LOOKUP_NO_NARROWING;
4297
4298 unsigned nart = num_artificial_parms_for (OVL_FIRST (fns)) - 1;
4299 tree init_list = (*args)[nart];
4300
4301 /* Always use the default constructor if the list is empty (DR 990). */
4302 if (CONSTRUCTOR_NELTS (init_list) == 0
4303 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
4304 ;
4305 else if (CONSTRUCTOR_IS_DESIGNATED_INIT (init_list)
4306 && !CP_AGGREGATE_TYPE_P (totype))
4307 {
4308 if (complain & tf_error)
4309 error ("designated initializers cannot be used with a "
4310 "non-aggregate type %qT", totype);
4311 return;
4312 }
4313 /* If the class has a list ctor, try passing the list as a single
4314 argument first, but only consider list ctors. */
4315 else if (TYPE_HAS_LIST_CTOR (totype))
4316 {
4317 flags |= LOOKUP_LIST_ONLY;
4318 add_candidates (fns, first_arg, args, NULL_TREE,
4319 explicit_targs, template_only, conversion_path,
4320 access_path, flags, candidates, complain);
4321 if (any_strictly_viable (*candidates))
4322 return;
4323 }
4324
4325 /* Expand the CONSTRUCTOR into a new argument vec. */
4326 vec<tree, va_gc> *new_args;
4327 vec_alloc (new_args, nart + CONSTRUCTOR_NELTS (init_list));
4328 for (unsigned i = 0; i < nart; ++i)
4329 new_args->quick_push ((*args)[i]);
4330 new_args = append_ctor_to_tree_vector (new_args, init_list);
4331
4332 /* We aren't looking for list-ctors anymore. */
4333 flags &= ~LOOKUP_LIST_ONLY;
4334 /* We allow more user-defined conversions within an init-list. */
4335 flags &= ~LOOKUP_NO_CONVERSION;
4336
4337 add_candidates (fns, first_arg, new_args, NULL_TREE,
4338 explicit_targs, template_only, conversion_path,
4339 access_path, flags, candidates, complain);
4340 }
4341
4342 /* Given C(std::initializer_list<A>), return A. */
4343
4344 static tree
4345 list_ctor_element_type (tree fn)
4346 {
4347 gcc_checking_assert (is_list_ctor (fn));
4348
4349 tree parm = FUNCTION_FIRST_USER_PARMTYPE (fn);
4350 parm = non_reference (TREE_VALUE (parm));
4351 return TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
4352 }
4353
4354 /* If EXPR is a braced-init-list where the elements all decay to the same type,
4355 return that type. */
4356
4357 static tree
4358 braced_init_element_type (tree expr)
4359 {
4360 if (TREE_CODE (expr) == CONSTRUCTOR
4361 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
4362 return TREE_TYPE (TREE_TYPE (expr));
4363 if (!BRACE_ENCLOSED_INITIALIZER_P (expr))
4364 return NULL_TREE;
4365
4366 tree elttype = NULL_TREE;
4367 for (constructor_elt &e: CONSTRUCTOR_ELTS (expr))
4368 {
4369 tree type = TREE_TYPE (e.value);
4370 type = type_decays_to (type);
4371 if (!elttype)
4372 elttype = type;
4373 else if (!same_type_p (type, elttype))
4374 return NULL_TREE;
4375 }
4376 return elttype;
4377 }
4378
4379 /* True iff EXPR contains any temporaries with non-trivial destruction.
4380
4381 ??? Also ignore classes with non-trivial but no-op destruction other than
4382 std::allocator? */
4383
4384 static bool
4385 has_non_trivial_temporaries (tree expr)
4386 {
4387 auto_vec<tree*> temps;
4388 cp_walk_tree_without_duplicates (&expr, find_temps_r, &temps);
4389 for (tree *p : temps)
4390 {
4391 tree t = TREE_TYPE (*p);
4392 if (!TYPE_HAS_TRIVIAL_DESTRUCTOR (t)
4393 && !is_std_allocator (t))
4394 return true;
4395 }
4396 return false;
4397 }
4398
4399 /* Return number of initialized elements in CTOR. */
4400
4401 unsigned HOST_WIDE_INT
4402 count_ctor_elements (tree ctor)
4403 {
4404 unsigned HOST_WIDE_INT len = 0;
4405 for (constructor_elt &e: CONSTRUCTOR_ELTS (ctor))
4406 if (TREE_CODE (e.value) == RAW_DATA_CST)
4407 len += RAW_DATA_LENGTH (e.value);
4408 else
4409 ++len;
4410 return len;
4411 }
4412
4413 /* We're initializing an array of ELTTYPE from INIT. If it seems useful,
4414 return INIT as an array (of its own type) so the caller can initialize the
4415 target array in a loop. */
4416
4417 static tree
4418 maybe_init_list_as_array (tree elttype, tree init)
4419 {
4420 /* Only do this if the array can go in rodata but not once converted. */
4421 if (!TYPE_NON_AGGREGATE_CLASS (elttype))
4422 return NULL_TREE;
4423 tree init_elttype = braced_init_element_type (init);
4424 if (!init_elttype || !SCALAR_TYPE_P (init_elttype) || !TREE_CONSTANT (init))
4425 return NULL_TREE;
4426
4427 /* Check with a stub expression to weed out special cases, and check whether
4428 we call the same function for direct-init as copy-list-init. */
4429 conversion_obstack_sentinel cos;
4430 init_elttype = cp_build_qualified_type (init_elttype, TYPE_QUAL_CONST);
4431 tree arg = build_stub_object (init_elttype);
4432 conversion *c = implicit_conversion (elttype, init_elttype, arg, false,
4433 LOOKUP_NORMAL, tf_none);
4434 if (c && c->kind == ck_rvalue)
4435 c = next_conversion (c);
4436 if (!c || c->kind != ck_user)
4437 return NULL_TREE;
4438 /* Check that we actually can perform the conversion. */
4439 if (convert_like (c, arg, tf_none) == error_mark_node)
4440 /* Let the normal code give the error. */
4441 return NULL_TREE;
4442
4443 /* A glvalue initializer might be significant to a reference constructor
4444 or conversion operator. */
4445 if (!DECL_CONSTRUCTOR_P (c->cand->fn)
4446 || (TYPE_REF_P (TREE_VALUE
4447 (FUNCTION_FIRST_USER_PARMTYPE (c->cand->fn)))))
4448 for (auto &ce : CONSTRUCTOR_ELTS (init))
4449 if (non_mergeable_glvalue_p (ce.value))
4450 return NULL_TREE;
4451
4452 tree first = CONSTRUCTOR_ELT (init, 0)->value;
4453 conversion *fc = implicit_conversion (elttype, init_elttype, first, false,
4454 LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING,
4455 tf_none);
4456 if (fc && fc->kind == ck_rvalue)
4457 fc = next_conversion (fc);
4458 if (!fc || fc->kind != ck_user || fc->cand->fn != c->cand->fn)
4459 return NULL_TREE;
4460 first = convert_like (fc, first, tf_none);
4461 if (first == error_mark_node)
4462 /* Let the normal code give the error. */
4463 return NULL_TREE;
4464
4465 /* Don't do this if the conversion would be constant. */
4466 first = maybe_constant_init (first);
4467 if (TREE_CONSTANT (first))
4468 return NULL_TREE;
4469
4470 /* We can't do this if the conversion creates temporaries that need
4471 to live until the whole array is initialized. */
4472 if (has_non_trivial_temporaries (first))
4473 return NULL_TREE;
4474
4475 /* We can't do this if copying from the initializer_list would be
4476 ill-formed. */
4477 tree copy_argtypes = make_tree_vec (1);
4478 TREE_VEC_ELT (copy_argtypes, 0)
4479 = cp_build_qualified_type (elttype, TYPE_QUAL_CONST);
4480 if (!is_xible (INIT_EXPR, elttype, copy_argtypes))
4481 return NULL_TREE;
4482
4483 unsigned HOST_WIDE_INT len = count_ctor_elements (init);
4484 tree arr = build_array_of_n_type (init_elttype, len);
4485 arr = finish_compound_literal (arr, init, tf_none);
4486 DECL_MERGEABLE (TARGET_EXPR_SLOT (arr)) = true;
4487 return arr;
4488 }
4489
4490 /* If we were going to call e.g. vector(initializer_list<string>) starting
4491 with a list of string-literals (which is inefficient, see PR105838),
4492 instead build an array of const char* and pass it to the range constructor.
4493 But only do this for standard library types, where we can assume the
4494 transformation makes sense.
4495
4496 Really the container classes should have initializer_list<U> constructors to
4497 get the same effect more simply; this is working around that lack. */
4498
4499 static tree
4500 maybe_init_list_as_range (tree fn, tree expr)
4501 {
4502 if (!processing_template_decl
4503 && BRACE_ENCLOSED_INITIALIZER_P (expr)
4504 && is_list_ctor (fn)
4505 && decl_in_std_namespace_p (fn))
4506 {
4507 tree to = list_ctor_element_type (fn);
4508 if (tree init = maybe_init_list_as_array (to, expr))
4509 {
4510 tree begin = decay_conversion (TARGET_EXPR_SLOT (init), tf_none);
4511 tree nelts = array_type_nelts_top (TREE_TYPE (init));
4512 tree end = cp_build_binary_op (input_location, PLUS_EXPR, begin,
4513 nelts, tf_none);
4514 begin = cp_build_compound_expr (init, begin, tf_none);
4515 return build_constructor_va (init_list_type_node, 2,
4516 NULL_TREE, begin, NULL_TREE, end);
4517 }
4518 }
4519
4520 return NULL_TREE;
4521 }
4522
4523 /* Returns the best overload candidate to perform the requested
4524 conversion. This function is used for three the overloading situations
4525 described in [over.match.copy], [over.match.conv], and [over.match.ref].
4526 If TOTYPE is a REFERENCE_TYPE, we're trying to find a direct binding as
4527 per [dcl.init.ref], so we ignore temporary bindings. */
4528
4529 static struct z_candidate *
4530 build_user_type_conversion_1 (tree totype, tree expr, int flags,
4531 tsubst_flags_t complain)
4532 {
4533 struct z_candidate *candidates, *cand;
4534 tree fromtype;
4535 tree ctors = NULL_TREE;
4536 tree conv_fns = NULL_TREE;
4537 conversion *conv = NULL;
4538 tree first_arg = NULL_TREE;
4539 vec<tree, va_gc> *args = NULL;
4540 bool any_viable_p;
4541 int convflags;
4542
4543 if (!expr)
4544 return NULL;
4545
4546 fromtype = TREE_TYPE (expr);
4547
4548 /* We represent conversion within a hierarchy using RVALUE_CONV and
4549 BASE_CONV, as specified by [over.best.ics]; these become plain
4550 constructor calls, as specified in [dcl.init]. */
4551 gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
4552 || !DERIVED_FROM_P (totype, fromtype));
4553
4554 if (CLASS_TYPE_P (totype))
4555 /* Use lookup_fnfields_slot instead of lookup_fnfields to avoid
4556 creating a garbage BASELINK; constructors can't be inherited. */
4557 ctors = get_class_binding (totype, complete_ctor_identifier);
4558
4559 tree to_nonref = non_reference (totype);
4560 if (MAYBE_CLASS_TYPE_P (fromtype))
4561 {
4562 if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
4563 (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
4564 && DERIVED_FROM_P (to_nonref, fromtype)))
4565 {
4566 /* [class.conv.fct] A conversion function is never used to
4567 convert a (possibly cv-qualified) object to the (possibly
4568 cv-qualified) same object type (or a reference to it), to a
4569 (possibly cv-qualified) base class of that type (or a
4570 reference to it)... */
4571 }
4572 else
4573 conv_fns = lookup_conversions (fromtype);
4574 }
4575
4576 candidates = 0;
4577 flags |= LOOKUP_NO_CONVERSION;
4578 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4579 flags |= LOOKUP_NO_NARROWING;
4580 /* Prevent add_candidates from treating a non-strictly viable candidate
4581 as unviable. */
4582 complain |= tf_conv;
4583
4584 /* It's OK to bind a temporary for converting constructor arguments, but
4585 not in converting the return value of a conversion operator. */
4586 convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION
4587 | (flags & LOOKUP_NO_NARROWING));
4588 flags &= ~LOOKUP_NO_TEMP_BIND;
4589
4590 if (ctors)
4591 {
4592 int ctorflags = flags;
4593
4594 first_arg = build_dummy_object (totype);
4595
4596 /* We should never try to call the abstract or base constructor
4597 from here. */
4598 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_FIRST (ctors))
4599 && !DECL_HAS_VTT_PARM_P (OVL_FIRST (ctors)));
4600
4601 args = make_tree_vector_single (expr);
4602 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4603 {
4604 /* List-initialization. */
4605 add_list_candidates (ctors, first_arg, args, totype, NULL_TREE,
4606 false, TYPE_BINFO (totype), TYPE_BINFO (totype),
4607 ctorflags, &candidates, complain);
4608 }
4609 else
4610 {
4611 add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
4612 TYPE_BINFO (totype), TYPE_BINFO (totype),
4613 ctorflags, &candidates, complain);
4614 }
4615
4616 for (cand = candidates; cand; cand = cand->next)
4617 {
4618 cand->second_conv = build_identity_conv (totype, NULL_TREE);
4619
4620 /* If totype isn't a reference, and LOOKUP_ONLYCONVERTING is
4621 set, then this is copy-initialization. In that case, "The
4622 result of the call is then used to direct-initialize the
4623 object that is the destination of the copy-initialization."
4624 [dcl.init]
4625
4626 We represent this in the conversion sequence with an
4627 rvalue conversion, which means a constructor call. */
4628 if (!TYPE_REF_P (totype)
4629 && cxx_dialect < cxx17
4630 && (flags & LOOKUP_ONLYCONVERTING)
4631 && !(convflags & LOOKUP_NO_TEMP_BIND))
4632 cand->second_conv
4633 = build_conv (ck_rvalue, totype, cand->second_conv);
4634 }
4635 }
4636
4637 if (conv_fns)
4638 {
4639 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4640 first_arg = CONSTRUCTOR_ELT (expr, 0)->value;
4641 else
4642 first_arg = expr;
4643 }
4644
4645 for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
4646 {
4647 tree conversion_path = TREE_PURPOSE (conv_fns);
4648 struct z_candidate *old_candidates;
4649
4650 /* If LOOKUP_NO_CONVERSION, don't consider a conversion function that
4651 would need an addional user-defined conversion, i.e. if the return
4652 type differs in class-ness from the desired type. So we avoid
4653 considering operator bool when calling a copy constructor.
4654
4655 This optimization avoids the failure in PR97600, and is allowed by
4656 [temp.inst]/9: "If the function selected by overload resolution can be
4657 determined without instantiating a class template definition, it is
4658 unspecified whether that instantiation actually takes place." */
4659 tree convtype = non_reference (TREE_TYPE (conv_fns));
4660 if ((flags & LOOKUP_NO_CONVERSION)
4661 && !WILDCARD_TYPE_P (convtype)
4662 && (CLASS_TYPE_P (to_nonref)
4663 != CLASS_TYPE_P (convtype)))
4664 continue;
4665
4666 /* If we are called to convert to a reference type, we are trying to
4667 find a direct binding, so don't even consider temporaries. If
4668 we don't find a direct binding, the caller will try again to
4669 look for a temporary binding. */
4670 if (TYPE_REF_P (totype))
4671 convflags |= LOOKUP_NO_TEMP_BIND;
4672
4673 old_candidates = candidates;
4674 add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
4675 NULL_TREE, false,
4676 conversion_path, TYPE_BINFO (fromtype),
4677 flags, &candidates, complain);
4678
4679 for (cand = candidates; cand != old_candidates; cand = cand->next)
4680 {
4681 if (cand->viable == 0)
4682 /* Already rejected, don't change to -1. */
4683 continue;
4684
4685 tree rettype = TREE_TYPE (TREE_TYPE (cand->fn));
4686 conversion *ics
4687 = implicit_conversion (totype,
4688 rettype,
4689 0,
4690 /*c_cast_p=*/false, convflags,
4691 complain);
4692
4693 /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
4694 copy-initialization. In that case, "The result of the
4695 call is then used to direct-initialize the object that is
4696 the destination of the copy-initialization." [dcl.init]
4697
4698 We represent this in the conversion sequence with an
4699 rvalue conversion, which means a constructor call. But
4700 don't add a second rvalue conversion if there's already
4701 one there. Which there really shouldn't be, but it's
4702 harmless since we'd add it here anyway. */
4703 if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
4704 && !(convflags & LOOKUP_NO_TEMP_BIND))
4705 ics = build_conv (ck_rvalue, totype, ics);
4706
4707 cand->second_conv = ics;
4708
4709 if (!ics)
4710 {
4711 cand->viable = 0;
4712 cand->reason = arg_conversion_rejection (NULL_TREE, -2,
4713 rettype, totype,
4714 EXPR_LOCATION (expr));
4715 }
4716 else if (TYPE_REF_P (totype) && !ics->rvaluedness_matches_p
4717 /* Limit this to non-templates for now (PR90546). */
4718 && !cand->template_decl
4719 && TREE_CODE (TREE_TYPE (totype)) != FUNCTION_TYPE)
4720 {
4721 /* If we are called to convert to a reference type, we are trying
4722 to find a direct binding per [over.match.ref], so rvaluedness
4723 must match for non-functions. */
4724 cand->viable = 0;
4725 }
4726 else if (DECL_NONCONVERTING_P (cand->fn)
4727 && ics->rank > cr_exact)
4728 {
4729 /* 13.3.1.5: For direct-initialization, those explicit
4730 conversion functions that are not hidden within S and
4731 yield type T or a type that can be converted to type T
4732 with a qualification conversion (4.4) are also candidate
4733 functions. */
4734 /* 13.3.1.6 doesn't have a parallel restriction, but it should;
4735 I've raised this issue with the committee. --jason 9/2011 */
4736 cand->viable = -1;
4737 cand->reason = explicit_conversion_rejection (rettype, totype);
4738 }
4739 else if (cand->viable == 1 && ics->bad_p)
4740 {
4741 cand->viable = -1;
4742 cand->reason
4743 = bad_arg_conversion_rejection (NULL_TREE, -2,
4744 rettype, totype,
4745 EXPR_LOCATION (expr));
4746 }
4747 else if (primary_template_specialization_p (cand->fn)
4748 && ics->rank > cr_exact)
4749 {
4750 /* 13.3.3.1.2: If the user-defined conversion is specified by
4751 a specialization of a conversion function template, the
4752 second standard conversion sequence shall have exact match
4753 rank. */
4754 cand->viable = -1;
4755 cand->reason = template_conversion_rejection (rettype, totype);
4756 }
4757 }
4758 }
4759
4760 candidates = splice_viable (candidates, false, &any_viable_p);
4761 if (!any_viable_p)
4762 {
4763 if (args)
4764 release_tree_vector (args);
4765 return NULL;
4766 }
4767
4768 cand = tourney (candidates, complain);
4769 if (cand == NULL)
4770 {
4771 if (complain & tf_error)
4772 {
4773 auto_diagnostic_group d;
4774 error_at (cp_expr_loc_or_input_loc (expr),
4775 "conversion from %qH to %qI is ambiguous",
4776 fromtype, totype);
4777 print_z_candidates (location_of (expr), candidates);
4778 }
4779
4780 cand = candidates; /* any one will do */
4781 cand->second_conv = build_ambiguous_conv (totype, expr);
4782 cand->second_conv->user_conv_p = true;
4783 if (!any_strictly_viable (candidates))
4784 cand->second_conv->bad_p = true;
4785 if (flags & LOOKUP_ONLYCONVERTING)
4786 cand->second_conv->need_temporary_p = true;
4787 /* If there are viable candidates, don't set ICS_BAD_FLAG; an
4788 ambiguous conversion is no worse than another user-defined
4789 conversion. */
4790
4791 return cand;
4792 }
4793
4794 /* Maybe pass { } as iterators instead of an initializer_list. */
4795 if (tree iters = maybe_init_list_as_range (cand->fn, expr))
4796 if (z_candidate *cand2
4797 = build_user_type_conversion_1 (totype, iters, flags, tf_none))
4798 if (cand2->viable == 1 && !is_list_ctor (cand2->fn))
4799 {
4800 cand = cand2;
4801 expr = iters;
4802 }
4803
4804 tree convtype;
4805 if (!DECL_CONSTRUCTOR_P (cand->fn))
4806 convtype = non_reference (TREE_TYPE (TREE_TYPE (cand->fn)));
4807 else if (cand->second_conv->kind == ck_rvalue)
4808 /* DR 5: [in the first step of copy-initialization]...if the function
4809 is a constructor, the call initializes a temporary of the
4810 cv-unqualified version of the destination type. */
4811 convtype = cv_unqualified (totype);
4812 else
4813 convtype = totype;
4814 /* Build the user conversion sequence. */
4815 conv = build_conv
4816 (ck_user,
4817 convtype,
4818 build_identity_conv (TREE_TYPE (expr), expr));
4819 conv->cand = cand;
4820 if (cand->viable == -1)
4821 conv->bad_p = true;
4822
4823 /* Remember that this was a list-initialization. */
4824 if (flags & LOOKUP_NO_NARROWING)
4825 conv->check_narrowing = true;
4826
4827 /* Combine it with the second conversion sequence. */
4828 cand->second_conv = merge_conversion_sequences (conv,
4829 cand->second_conv);
4830
4831 return cand;
4832 }
4833
4834 /* Wrapper for above. */
4835
4836 tree
4837 build_user_type_conversion (tree totype, tree expr, int flags,
4838 tsubst_flags_t complain)
4839 {
4840 struct z_candidate *cand;
4841 tree ret;
4842
4843 auto_cond_timevar tv (TV_OVERLOAD);
4844
4845 conversion_obstack_sentinel cos;
4846
4847 cand = build_user_type_conversion_1 (totype, expr, flags, complain);
4848
4849 if (cand)
4850 {
4851 if (cand->second_conv->kind == ck_ambig)
4852 ret = error_mark_node;
4853 else
4854 {
4855 expr = convert_like (cand->second_conv, expr, complain);
4856 ret = convert_from_reference (expr);
4857 }
4858 }
4859 else
4860 ret = NULL_TREE;
4861
4862 return ret;
4863 }
4864
4865 /* Give a helpful diagnostic when implicit_conversion fails. */
4866
4867 static void
4868 implicit_conversion_error (location_t loc, tree type, tree expr)
4869 {
4870 tsubst_flags_t complain = tf_warning_or_error;
4871
4872 /* If expr has unknown type, then it is an overloaded function.
4873 Call instantiate_type to get good error messages. */
4874 if (TREE_TYPE (expr) == unknown_type_node)
4875 instantiate_type (type, expr, complain);
4876 else if (invalid_nonstatic_memfn_p (loc, expr, complain))
4877 /* We gave an error. */;
4878 else if (BRACE_ENCLOSED_INITIALIZER_P (expr)
4879 && CONSTRUCTOR_IS_DESIGNATED_INIT (expr)
4880 && !CP_AGGREGATE_TYPE_P (type))
4881 error_at (loc, "designated initializers cannot be used with a "
4882 "non-aggregate type %qT", type);
4883 else
4884 {
4885 range_label_for_type_mismatch label (TREE_TYPE (expr), type);
4886 gcc_rich_location rich_loc (loc, &label,
4887 highlight_colors::percent_h);
4888 error_at (&rich_loc, "could not convert %qE from %qH to %qI",
4889 expr, TREE_TYPE (expr), type);
4890 }
4891 }
4892
4893 /* Worker for build_converted_constant_expr. */
4894
4895 static tree
4896 build_converted_constant_expr_internal (tree type, tree expr,
4897 int flags, tsubst_flags_t complain)
4898 {
4899 conversion *conv;
4900 tree t;
4901 location_t loc = cp_expr_loc_or_input_loc (expr);
4902
4903 if (error_operand_p (expr))
4904 return error_mark_node;
4905
4906 conversion_obstack_sentinel cos;
4907
4908 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
4909 /*c_cast_p=*/false, flags, complain);
4910
4911 /* A converted constant expression of type T is an expression, implicitly
4912 converted to type T, where the converted expression is a constant
4913 expression and the implicit conversion sequence contains only
4914
4915 * user-defined conversions,
4916 * lvalue-to-rvalue conversions (7.1),
4917 * array-to-pointer conversions (7.2),
4918 * function-to-pointer conversions (7.3),
4919 * qualification conversions (7.5),
4920 * integral promotions (7.6),
4921 * integral conversions (7.8) other than narrowing conversions (11.6.4),
4922 * null pointer conversions (7.11) from std::nullptr_t,
4923 * null member pointer conversions (7.12) from std::nullptr_t, and
4924 * function pointer conversions (7.13),
4925
4926 and where the reference binding (if any) binds directly. */
4927
4928 for (conversion *c = conv;
4929 c && c->kind != ck_identity;
4930 c = next_conversion (c))
4931 {
4932 switch (c->kind)
4933 {
4934 /* A conversion function is OK. If it isn't constexpr, we'll
4935 complain later that the argument isn't constant. */
4936 case ck_user:
4937 /* List-initialization is OK. */
4938 case ck_aggr:
4939 /* The lvalue-to-rvalue conversion is OK. */
4940 case ck_rvalue:
4941 /* Array-to-pointer and function-to-pointer. */
4942 case ck_lvalue:
4943 /* Function pointer conversions. */
4944 case ck_fnptr:
4945 /* Qualification conversions. */
4946 case ck_qual:
4947 break;
4948
4949 case ck_ref_bind:
4950 if (c->need_temporary_p)
4951 {
4952 if (complain & tf_error)
4953 error_at (loc, "initializing %qH with %qI in converted "
4954 "constant expression does not bind directly",
4955 type, next_conversion (c)->type);
4956 conv = NULL;
4957 }
4958 break;
4959
4960 case ck_base:
4961 case ck_pmem:
4962 case ck_ptr:
4963 case ck_std:
4964 t = next_conversion (c)->type;
4965 if (INTEGRAL_OR_ENUMERATION_TYPE_P (t)
4966 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4967 /* Integral promotion or conversion. */
4968 break;
4969 if (NULLPTR_TYPE_P (t))
4970 /* Conversion from nullptr to pointer or pointer-to-member. */
4971 break;
4972
4973 if (complain & tf_error)
4974 error_at (loc, "conversion from %qH to %qI in a "
4975 "converted constant expression", t, type);
4976 /* fall through. */
4977
4978 default:
4979 conv = NULL;
4980 break;
4981 }
4982 }
4983
4984 /* Avoid confusing convert_nontype_argument by introducing
4985 a redundant conversion to the same reference type. */
4986 if (conv && conv->kind == ck_ref_bind
4987 && REFERENCE_REF_P (expr))
4988 {
4989 tree ref = TREE_OPERAND (expr, 0);
4990 if (same_type_p (type, TREE_TYPE (ref)))
4991 return ref;
4992 }
4993
4994 if (conv)
4995 {
4996 /* Don't copy a class in a template. */
4997 if (CLASS_TYPE_P (type) && conv->kind == ck_rvalue
4998 && processing_template_decl)
4999 conv = next_conversion (conv);
5000
5001 /* Issuing conversion warnings for value-dependent expressions is
5002 likely too noisy. */
5003 warning_sentinel w (warn_conversion);
5004 conv->check_narrowing = true;
5005 conv->check_narrowing_const_only = true;
5006 expr = convert_like (conv, expr, complain);
5007 }
5008 else
5009 {
5010 if (complain & tf_error)
5011 implicit_conversion_error (loc, type, expr);
5012 expr = error_mark_node;
5013 }
5014
5015 return expr;
5016 }
5017
5018 /* Subroutine of convert_nontype_argument.
5019
5020 EXPR is an expression used in a context that requires a converted
5021 constant-expression, such as a template non-type parameter. Do any
5022 necessary conversions (that are permitted for converted
5023 constant-expressions) to convert it to the desired type.
5024
5025 This function doesn't consider explicit conversion functions. If
5026 you mean to use "a contextually converted constant expression of type
5027 bool", use build_converted_constant_bool_expr.
5028
5029 If conversion is successful, returns the converted expression;
5030 otherwise, returns error_mark_node. */
5031
5032 tree
5033 build_converted_constant_expr (tree type, tree expr, tsubst_flags_t complain)
5034 {
5035 return build_converted_constant_expr_internal (type, expr, LOOKUP_IMPLICIT,
5036 complain);
5037 }
5038
5039 /* Used to create "a contextually converted constant expression of type
5040 bool". This differs from build_converted_constant_expr in that it
5041 also considers explicit conversion functions. */
5042
5043 tree
5044 build_converted_constant_bool_expr (tree expr, tsubst_flags_t complain)
5045 {
5046 return build_converted_constant_expr_internal (boolean_type_node, expr,
5047 LOOKUP_NORMAL, complain);
5048 }
5049
5050 /* Do any initial processing on the arguments to a function call. */
5051
5052 vec<tree, va_gc> *
5053 resolve_args (vec<tree, va_gc> *args, tsubst_flags_t complain)
5054 {
5055 unsigned int ix;
5056 tree arg;
5057
5058 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
5059 {
5060 if (error_operand_p (arg))
5061 return NULL;
5062 else if (VOID_TYPE_P (TREE_TYPE (arg)))
5063 {
5064 if (complain & tf_error)
5065 error_at (cp_expr_loc_or_input_loc (arg),
5066 "invalid use of void expression");
5067 return NULL;
5068 }
5069 else if (invalid_nonstatic_memfn_p (EXPR_LOCATION (arg), arg, complain))
5070 return NULL;
5071
5072 /* Force auto deduction now. Omit tf_warning to avoid redundant
5073 deprecated warning on deprecated-14.C. */
5074 if (!mark_single_function (arg, complain & ~tf_warning))
5075 return NULL;
5076 }
5077 return args;
5078 }
5079
5080 /* Perform overload resolution on FN, which is called with the ARGS.
5081
5082 Return the candidate function selected by overload resolution, or
5083 NULL if the event that overload resolution failed. In the case
5084 that overload resolution fails, *CANDIDATES will be the set of
5085 candidates considered, and ANY_VIABLE_P will be set to true or
5086 false to indicate whether or not any of the candidates were
5087 viable.
5088
5089 The ARGS should already have gone through RESOLVE_ARGS before this
5090 function is called. */
5091
5092 static struct z_candidate *
5093 perform_overload_resolution (tree fn,
5094 const vec<tree, va_gc> *args,
5095 struct z_candidate **candidates,
5096 bool *any_viable_p, tsubst_flags_t complain)
5097 {
5098 struct z_candidate *cand;
5099 tree explicit_targs;
5100 int template_only;
5101
5102 auto_cond_timevar tv (TV_OVERLOAD);
5103
5104 explicit_targs = NULL_TREE;
5105 template_only = 0;
5106
5107 *candidates = NULL;
5108 *any_viable_p = true;
5109
5110 /* Check FN. */
5111 gcc_assert (OVL_P (fn) || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
5112
5113 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
5114 {
5115 explicit_targs = TREE_OPERAND (fn, 1);
5116 fn = TREE_OPERAND (fn, 0);
5117 template_only = 1;
5118 }
5119
5120 /* Add the various candidate functions. */
5121 add_candidates (fn, NULL_TREE, args, NULL_TREE,
5122 explicit_targs, template_only,
5123 /*conversion_path=*/NULL_TREE,
5124 /*access_path=*/NULL_TREE,
5125 LOOKUP_NORMAL,
5126 candidates, complain);
5127
5128 *candidates = splice_viable (*candidates, false, any_viable_p);
5129 if (*any_viable_p)
5130 cand = tourney (*candidates, complain);
5131 else
5132 cand = NULL;
5133
5134 return cand;
5135 }
5136
5137 /* Print an error message about being unable to build a call to FN with
5138 ARGS. ANY_VIABLE_P indicates whether any candidate functions could
5139 be located; CANDIDATES is a possibly empty list of such
5140 functions. */
5141
5142 static void
5143 print_error_for_call_failure (tree fn, const vec<tree, va_gc> *args,
5144 struct z_candidate *candidates)
5145 {
5146 tree targs = NULL_TREE;
5147 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
5148 {
5149 targs = TREE_OPERAND (fn, 1);
5150 fn = TREE_OPERAND (fn, 0);
5151 }
5152 tree name = OVL_NAME (fn);
5153 location_t loc = location_of (name);
5154 if (targs)
5155 name = lookup_template_function (name, targs);
5156
5157 auto_diagnostic_group d;
5158 if (!any_strictly_viable (candidates))
5159 error_at (loc, "no matching function for call to %<%D(%A)%>",
5160 name, build_tree_list_vec (args));
5161 else
5162 error_at (loc, "call of overloaded %<%D(%A)%> is ambiguous",
5163 name, build_tree_list_vec (args));
5164 if (candidates)
5165 print_z_candidates (loc, candidates);
5166 }
5167
5168 /* Perform overload resolution on the set of deduction guides DGUIDES
5169 using ARGS. Returns the selected deduction guide, or error_mark_node
5170 if overload resolution fails. */
5171
5172 tree
5173 perform_dguide_overload_resolution (tree dguides, const vec<tree, va_gc> *args,
5174 tsubst_flags_t complain)
5175 {
5176 z_candidate *candidates;
5177 bool any_viable_p;
5178 tree result;
5179
5180 gcc_assert (deduction_guide_p (OVL_FIRST (dguides)));
5181
5182 conversion_obstack_sentinel cos;
5183
5184 z_candidate *cand = perform_overload_resolution (dguides, args, &candidates,
5185 &any_viable_p, complain);
5186 if (!cand)
5187 {
5188 if (complain & tf_error)
5189 print_error_for_call_failure (dguides, args, candidates);
5190 result = error_mark_node;
5191 }
5192 else
5193 result = cand->fn;
5194
5195 return result;
5196 }
5197
5198 /* Return an expression for a call to FN (a namespace-scope function,
5199 or a static member function) with the ARGS. This may change
5200 ARGS. */
5201
5202 tree
5203 build_new_function_call (tree fn, vec<tree, va_gc> **args,
5204 tsubst_flags_t complain)
5205 {
5206 struct z_candidate *candidates, *cand;
5207 bool any_viable_p;
5208 tree result;
5209
5210 if (args != NULL && *args != NULL)
5211 {
5212 *args = resolve_args (*args, complain);
5213 if (*args == NULL)
5214 return error_mark_node;
5215 }
5216
5217 if (flag_tm)
5218 tm_malloc_replacement (fn);
5219
5220 conversion_obstack_sentinel cos;
5221
5222 cand = perform_overload_resolution (fn, *args, &candidates, &any_viable_p,
5223 complain);
5224
5225 if (!cand)
5226 {
5227 if (complain & tf_error)
5228 {
5229 // If there is a single (non-viable) function candidate,
5230 // let the error be diagnosed by cp_build_function_call_vec.
5231 if (!any_viable_p && candidates && ! candidates->next
5232 && TREE_CODE (candidates->fn) == FUNCTION_DECL
5233 /* A template-id callee consisting of a single (ignored)
5234 non-template candidate needs to be diagnosed the
5235 ordinary way. */
5236 && (TREE_CODE (fn) != TEMPLATE_ID_EXPR
5237 || candidates->template_decl))
5238 return cp_build_function_call_vec (candidates->fn, args, complain);
5239
5240 // Otherwise, emit notes for non-viable candidates.
5241 print_error_for_call_failure (fn, *args, candidates);
5242 }
5243 result = error_mark_node;
5244 }
5245 else
5246 {
5247 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5248 }
5249
5250 if (flag_coroutines
5251 && result
5252 && TREE_CODE (result) == CALL_EXPR
5253 && DECL_BUILT_IN_CLASS (TREE_OPERAND (CALL_EXPR_FN (result), 0))
5254 == BUILT_IN_NORMAL)
5255 result = coro_validate_builtin_call (result);
5256
5257 return result;
5258 }
5259
5260 /* Build a call to a global operator new. FNNAME is the name of the
5261 operator (either "operator new" or "operator new[]") and ARGS are
5262 the arguments provided. This may change ARGS. *SIZE points to the
5263 total number of bytes required by the allocation, and is updated if
5264 that is changed here. *COOKIE_SIZE is non-NULL if a cookie should
5265 be used. If this function determines that no cookie should be
5266 used, after all, *COOKIE_SIZE is set to NULL_TREE. If SIZE_CHECK
5267 is not NULL_TREE, it is evaluated before calculating the final
5268 array size, and if it fails, the array size is replaced with
5269 (size_t)-1 (usually triggering a std::bad_alloc exception). If FN
5270 is non-NULL, it will be set, upon return, to the allocation
5271 function called. */
5272
5273 tree
5274 build_operator_new_call (tree fnname, vec<tree, va_gc> **args,
5275 tree *size, tree *cookie_size,
5276 tree align_arg, tree size_check,
5277 tree *fn, tsubst_flags_t complain)
5278 {
5279 tree original_size = *size;
5280 tree fns;
5281 struct z_candidate *candidates;
5282 struct z_candidate *cand = NULL;
5283 bool any_viable_p;
5284
5285 if (fn)
5286 *fn = NULL_TREE;
5287 /* Set to (size_t)-1 if the size check fails. */
5288 if (size_check != NULL_TREE)
5289 {
5290 tree errval = TYPE_MAX_VALUE (sizetype);
5291 if (cxx_dialect >= cxx11 && flag_exceptions)
5292 errval = throw_bad_array_new_length ();
5293 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5294 original_size, errval);
5295 }
5296 vec_safe_insert (*args, 0, *size);
5297 *args = resolve_args (*args, complain);
5298 if (*args == NULL)
5299 return error_mark_node;
5300
5301 conversion_obstack_sentinel cos;
5302
5303 /* Based on:
5304
5305 [expr.new]
5306
5307 If this lookup fails to find the name, or if the allocated type
5308 is not a class type, the allocation function's name is looked
5309 up in the global scope.
5310
5311 we disregard block-scope declarations of "operator new". */
5312 fns = lookup_qualified_name (global_namespace, fnname);
5313
5314 if (align_arg)
5315 {
5316 vec<tree, va_gc>* align_args
5317 = vec_copy_and_insert (*args, align_arg, 1);
5318 cand = perform_overload_resolution (fns, align_args, &candidates,
5319 &any_viable_p, tf_none);
5320 if (cand)
5321 *args = align_args;
5322 /* If no aligned allocation function matches, try again without the
5323 alignment. */
5324 }
5325
5326 /* Figure out what function is being called. */
5327 if (!cand)
5328 cand = perform_overload_resolution (fns, *args, &candidates, &any_viable_p,
5329 complain);
5330
5331 /* If no suitable function could be found, issue an error message
5332 and give up. */
5333 if (!cand)
5334 {
5335 if (complain & tf_error)
5336 print_error_for_call_failure (fns, *args, candidates);
5337 return error_mark_node;
5338 }
5339
5340 /* If a cookie is required, add some extra space. Whether
5341 or not a cookie is required cannot be determined until
5342 after we know which function was called. */
5343 if (*cookie_size)
5344 {
5345 bool use_cookie = true;
5346 tree arg_types;
5347
5348 arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
5349 /* Skip the size_t parameter. */
5350 arg_types = TREE_CHAIN (arg_types);
5351 /* Check the remaining parameters (if any). */
5352 if (arg_types
5353 && TREE_CHAIN (arg_types) == void_list_node
5354 && same_type_p (TREE_VALUE (arg_types),
5355 ptr_type_node))
5356 use_cookie = false;
5357 /* If we need a cookie, adjust the number of bytes allocated. */
5358 if (use_cookie)
5359 {
5360 /* Update the total size. */
5361 *size = size_binop (PLUS_EXPR, original_size, *cookie_size);
5362 if (size_check)
5363 {
5364 /* Set to (size_t)-1 if the size check fails. */
5365 gcc_assert (size_check != NULL_TREE);
5366 *size = fold_build3 (COND_EXPR, sizetype, size_check,
5367 *size, TYPE_MAX_VALUE (sizetype));
5368 }
5369 /* Update the argument list to reflect the adjusted size. */
5370 (**args)[0] = *size;
5371 }
5372 else
5373 *cookie_size = NULL_TREE;
5374 }
5375
5376 /* Tell our caller which function we decided to call. */
5377 if (fn)
5378 *fn = cand->fn;
5379
5380 /* Build the CALL_EXPR. */
5381 tree ret = build_over_call (cand, LOOKUP_NORMAL, complain);
5382
5383 /* Set this flag for all callers of this function. In addition to
5384 new-expressions, this is called for allocating coroutine state; treat
5385 that as an implicit new-expression. */
5386 tree call = extract_call_expr (ret);
5387 if (TREE_CODE (call) == CALL_EXPR)
5388 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
5389
5390 return ret;
5391 }
5392
5393 /* Evaluate side-effects from OBJ before evaluating call
5394 to FN in RESULT expression.
5395 This is for expressions of the form `obj->fn(...)'
5396 where `fn' turns out to be a static member function and
5397 `obj' needs to be evaluated. `fn' could be also static operator[]
5398 or static operator(), in which cases the source expression
5399 would be `obj[...]' or `obj(...)'. */
5400
5401 tree
5402 keep_unused_object_arg (tree result, tree obj, tree fn)
5403 {
5404 if (result == NULL_TREE
5405 || result == error_mark_node
5406 || DECL_OBJECT_MEMBER_FUNCTION_P (fn)
5407 || !TREE_SIDE_EFFECTS (obj))
5408 return result;
5409
5410 /* But avoid the implicit lvalue-rvalue conversion when `obj' is
5411 volatile. */
5412 tree a = obj;
5413 if (TREE_THIS_VOLATILE (a))
5414 a = build_this (a);
5415 if (TREE_SIDE_EFFECTS (a))
5416 return cp_build_compound_expr (a, result, tf_error);
5417 return result;
5418 }
5419
5420 /* Build a new call to operator(). This may change ARGS. */
5421
5422 tree
5423 build_op_call (tree obj, vec<tree, va_gc> **args, tsubst_flags_t complain)
5424 {
5425 struct z_candidate *candidates = 0, *cand;
5426 tree fns, convs, first_mem_arg = NULL_TREE;
5427 bool any_viable_p;
5428 tree result = NULL_TREE;
5429
5430 auto_cond_timevar tv (TV_OVERLOAD);
5431
5432 obj = mark_lvalue_use (obj);
5433
5434 if (error_operand_p (obj))
5435 return error_mark_node;
5436
5437 tree type = TREE_TYPE (obj);
5438
5439 obj = prep_operand (obj);
5440
5441 if (TYPE_PTRMEMFUNC_P (type))
5442 {
5443 if (complain & tf_error)
5444 /* It's no good looking for an overloaded operator() on a
5445 pointer-to-member-function. */
5446 error ("pointer-to-member function %qE cannot be called without "
5447 "an object; consider using %<.*%> or %<->*%>", obj);
5448 return error_mark_node;
5449 }
5450
5451 if (TYPE_BINFO (type))
5452 {
5453 fns = lookup_fnfields (TYPE_BINFO (type), call_op_identifier, 1, complain);
5454 if (fns == error_mark_node)
5455 return error_mark_node;
5456 }
5457 else
5458 fns = NULL_TREE;
5459
5460 if (args != NULL && *args != NULL)
5461 {
5462 *args = resolve_args (*args, complain);
5463 if (*args == NULL)
5464 return error_mark_node;
5465 }
5466
5467 conversion_obstack_sentinel cos;
5468
5469 if (fns)
5470 {
5471 first_mem_arg = obj;
5472
5473 add_candidates (BASELINK_FUNCTIONS (fns),
5474 first_mem_arg, *args, NULL_TREE,
5475 NULL_TREE, false,
5476 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
5477 LOOKUP_NORMAL, &candidates, complain);
5478 }
5479
5480 bool any_call_ops = candidates != nullptr;
5481
5482 convs = lookup_conversions (type);
5483
5484 for (; convs; convs = TREE_CHAIN (convs))
5485 {
5486 tree totype = TREE_TYPE (convs);
5487
5488 if (TYPE_PTRFN_P (totype)
5489 || TYPE_REFFN_P (totype)
5490 || (TYPE_REF_P (totype)
5491 && TYPE_PTRFN_P (TREE_TYPE (totype))))
5492 for (tree fn : ovl_range (TREE_VALUE (convs)))
5493 {
5494 if (DECL_NONCONVERTING_P (fn))
5495 continue;
5496
5497 if (TREE_CODE (fn) == TEMPLATE_DECL)
5498 {
5499 /* Making this work broke PR 71117 and 85118, so until the
5500 committee resolves core issue 2189, let's disable this
5501 candidate if there are any call operators. */
5502 if (any_call_ops)
5503 continue;
5504
5505 add_template_conv_candidate
5506 (&candidates, fn, obj, *args, totype,
5507 /*access_path=*/NULL_TREE,
5508 /*conversion_path=*/NULL_TREE, complain);
5509 }
5510 else
5511 add_conv_candidate (&candidates, fn, obj,
5512 *args, /*conversion_path=*/NULL_TREE,
5513 /*access_path=*/NULL_TREE, complain);
5514 }
5515 }
5516
5517 /* Be strict here because if we choose a bad conversion candidate, the
5518 errors we get won't mention the call context. */
5519 candidates = splice_viable (candidates, true, &any_viable_p);
5520 if (!any_viable_p)
5521 {
5522 if (complain & tf_error)
5523 {
5524 auto_diagnostic_group d;
5525 error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
5526 build_tree_list_vec (*args));
5527 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5528 }
5529 result = error_mark_node;
5530 }
5531 else
5532 {
5533 cand = tourney (candidates, complain);
5534 if (cand == 0)
5535 {
5536 if (complain & tf_error)
5537 {
5538 auto_diagnostic_group d;
5539 error ("call of %<(%T) (%A)%> is ambiguous",
5540 TREE_TYPE (obj), build_tree_list_vec (*args));
5541 print_z_candidates (location_of (TREE_TYPE (obj)), candidates);
5542 }
5543 result = error_mark_node;
5544 }
5545 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
5546 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
5547 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, CALL_EXPR))
5548 {
5549 result = build_over_call (cand, LOOKUP_NORMAL, complain);
5550 /* In an expression of the form `a()' where cand->fn
5551 which is operator() turns out to be a static member function,
5552 `a' is none-the-less evaluated. */
5553 result = keep_unused_object_arg (result, obj, cand->fn);
5554 }
5555 else
5556 {
5557 if (TREE_CODE (cand->fn) == FUNCTION_DECL)
5558 obj = convert_like_with_context (cand->convs[0], obj, cand->fn,
5559 -1, complain);
5560 else
5561 {
5562 gcc_checking_assert (TYPE_P (cand->fn));
5563 obj = convert_like (cand->convs[0], obj, complain);
5564 }
5565 obj = convert_from_reference (obj);
5566 result = cp_build_function_call_vec (obj, args, complain);
5567 }
5568 }
5569
5570 return result;
5571 }
5572
5573 /* Subroutine for preparing format strings suitable for the error
5574 function. It concatenates a prefix (controlled by MATCH), ERRMSG,
5575 and SUFFIX. */
5576
5577 static const char *
5578 concat_op_error_string (bool match, const char *errmsg, const char *suffix)
5579 {
5580 return concat (match
5581 ? G_("ambiguous overload for ")
5582 : G_("no match for "),
5583 errmsg, suffix, nullptr);
5584 }
5585
5586 /* Called by op_error to prepare format strings suitable for the error
5587 function. It concatenates a prefix (controlled by MATCH), ERRMSG,
5588 and a suffix (controlled by NTYPES). */
5589
5590 static const char *
5591 op_error_string (const char *errmsg, int ntypes, bool match)
5592 {
5593 const char *suffix;
5594 if (ntypes == 3)
5595 suffix = G_(" (operand types are %qT, %qT, and %qT)");
5596 else if (ntypes == 2)
5597 suffix = G_(" (operand types are %qT and %qT)");
5598 else
5599 suffix = G_(" (operand type is %qT)");
5600 return concat_op_error_string (match, errmsg, suffix);
5601 }
5602
5603 /* Similar to op_error_string, but a special-case for binary ops that
5604 use %e for the args, rather than %qT. */
5605
5606 static const char *
5607 binop_error_string (const char *errmsg, bool match)
5608 {
5609 return concat_op_error_string (match, errmsg,
5610 G_(" (operand types are %e and %e)"));
5611 }
5612
5613 static void
5614 op_error (const op_location_t &loc,
5615 enum tree_code code, enum tree_code code2,
5616 tree arg1, tree arg2, tree arg3, bool match)
5617 {
5618 bool assop = code == MODIFY_EXPR;
5619 const char *opname = OVL_OP_INFO (assop, assop ? code2 : code)->name;
5620
5621 switch (code)
5622 {
5623 case COND_EXPR:
5624 if (flag_diagnostics_show_caret)
5625 error_at (loc, op_error_string (G_("ternary %<operator?:%>"),
5626 3, match),
5627 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5628 else
5629 error_at (loc, op_error_string (G_("ternary %<operator?:%> "
5630 "in %<%E ? %E : %E%>"), 3, match),
5631 arg1, arg2, arg3,
5632 TREE_TYPE (arg1), TREE_TYPE (arg2), TREE_TYPE (arg3));
5633 break;
5634
5635 case POSTINCREMENT_EXPR:
5636 case POSTDECREMENT_EXPR:
5637 if (flag_diagnostics_show_caret)
5638 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5639 opname, TREE_TYPE (arg1));
5640 else
5641 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E%s%>"),
5642 1, match),
5643 opname, arg1, opname, TREE_TYPE (arg1));
5644 break;
5645
5646 case ARRAY_REF:
5647 if (flag_diagnostics_show_caret)
5648 error_at (loc, op_error_string (G_("%<operator[]%>"), 2, match),
5649 TREE_TYPE (arg1), TREE_TYPE (arg2));
5650 else
5651 error_at (loc, op_error_string (G_("%<operator[]%> in %<%E[%E]%>"),
5652 2, match),
5653 arg1, arg2, TREE_TYPE (arg1), TREE_TYPE (arg2));
5654 break;
5655
5656 case REALPART_EXPR:
5657 case IMAGPART_EXPR:
5658 if (flag_diagnostics_show_caret)
5659 error_at (loc, op_error_string (G_("%qs"), 1, match),
5660 opname, TREE_TYPE (arg1));
5661 else
5662 error_at (loc, op_error_string (G_("%qs in %<%s %E%>"), 1, match),
5663 opname, opname, arg1, TREE_TYPE (arg1));
5664 break;
5665
5666 case CO_AWAIT_EXPR:
5667 if (flag_diagnostics_show_caret)
5668 error_at (loc, op_error_string (G_("%<operator %s%>"), 1, match),
5669 opname, TREE_TYPE (arg1));
5670 else
5671 error_at (loc, op_error_string (G_("%<operator %s%> in %<%s%E%>"),
5672 1, match),
5673 opname, opname, arg1, TREE_TYPE (arg1));
5674 break;
5675
5676 default:
5677 if (arg2)
5678 if (flag_diagnostics_show_caret)
5679 {
5680 binary_op_rich_location richloc (loc, arg1, arg2, true);
5681 pp_markup::element_quoted_type element_0
5682 (TREE_TYPE (arg1), highlight_colors::lhs);
5683 pp_markup::element_quoted_type element_1
5684 (TREE_TYPE (arg2), highlight_colors::rhs);
5685 error_at (&richloc,
5686 binop_error_string (G_("%<operator%s%>"), match),
5687 opname, &element_0, &element_1);
5688 }
5689 else
5690 error_at (loc, op_error_string (G_("%<operator%s%> in %<%E %s %E%>"),
5691 2, match),
5692 opname, arg1, opname, arg2,
5693 TREE_TYPE (arg1), TREE_TYPE (arg2));
5694 else
5695 if (flag_diagnostics_show_caret)
5696 error_at (loc, op_error_string (G_("%<operator%s%>"), 1, match),
5697 opname, TREE_TYPE (arg1));
5698 else
5699 error_at (loc, op_error_string (G_("%<operator%s%> in %<%s%E%>"),
5700 1, match),
5701 opname, opname, arg1, TREE_TYPE (arg1));
5702 break;
5703 }
5704 }
5705
5706 /* Return the implicit conversion sequence that could be used to
5707 convert E1 to E2 in [expr.cond]. */
5708
5709 static conversion *
5710 conditional_conversion (tree e1, tree e2, tsubst_flags_t complain)
5711 {
5712 tree t1 = non_reference (TREE_TYPE (e1));
5713 tree t2 = non_reference (TREE_TYPE (e2));
5714 conversion *conv;
5715 bool good_base;
5716
5717 /* [expr.cond]
5718
5719 If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5720 implicitly converted (clause _conv_) to the type "lvalue reference to
5721 T2", subject to the constraint that in the conversion the
5722 reference must bind directly (_dcl.init.ref_) to an lvalue.
5723
5724 If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5725 implicitly converted to the type "rvalue reference to T2", subject to
5726 the constraint that the reference must bind directly. */
5727 if (glvalue_p (e2))
5728 {
5729 tree rtype = cp_build_reference_type (t2, !lvalue_p (e2));
5730 conv = implicit_conversion (rtype,
5731 t1,
5732 e1,
5733 /*c_cast_p=*/false,
5734 LOOKUP_NO_TEMP_BIND|LOOKUP_NO_RVAL_BIND
5735 |LOOKUP_ONLYCONVERTING,
5736 complain);
5737 if (conv && !conv->bad_p)
5738 return conv;
5739 }
5740
5741 /* If E2 is a prvalue or if neither of the conversions above can be done
5742 and at least one of the operands has (possibly cv-qualified) class
5743 type: */
5744 if (!CLASS_TYPE_P (t1) && !CLASS_TYPE_P (t2))
5745 return NULL;
5746
5747 /* [expr.cond]
5748
5749 If E1 and E2 have class type, and the underlying class types are
5750 the same or one is a base class of the other: E1 can be converted
5751 to match E2 if the class of T2 is the same type as, or a base
5752 class of, the class of T1, and the cv-qualification of T2 is the
5753 same cv-qualification as, or a greater cv-qualification than, the
5754 cv-qualification of T1. If the conversion is applied, E1 is
5755 changed to an rvalue of type T2 that still refers to the original
5756 source class object (or the appropriate subobject thereof). */
5757 if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
5758 && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
5759 {
5760 if (good_base && at_least_as_qualified_p (t2, t1))
5761 {
5762 conv = build_identity_conv (t1, e1);
5763 if (!same_type_p (TYPE_MAIN_VARIANT (t1),
5764 TYPE_MAIN_VARIANT (t2)))
5765 conv = build_conv (ck_base, t2, conv);
5766 else
5767 conv = build_conv (ck_rvalue, t2, conv);
5768 return conv;
5769 }
5770 else
5771 return NULL;
5772 }
5773 else
5774 /* [expr.cond]
5775
5776 Otherwise: E1 can be converted to match E2 if E1 can be implicitly
5777 converted to the type that expression E2 would have if E2 were
5778 converted to an rvalue (or the type it has, if E2 is an rvalue). */
5779 return implicit_conversion (t2, t1, e1, /*c_cast_p=*/false,
5780 LOOKUP_IMPLICIT, complain);
5781 }
5782
5783 /* Implement [expr.cond]. ARG1, ARG2, and ARG3 are the three
5784 arguments to the conditional expression. */
5785
5786 tree
5787 build_conditional_expr (const op_location_t &loc,
5788 tree arg1, tree arg2, tree arg3,
5789 tsubst_flags_t complain)
5790 {
5791 tree arg2_type;
5792 tree arg3_type;
5793 tree result = NULL_TREE;
5794 tree result_type = NULL_TREE;
5795 tree semantic_result_type = NULL_TREE;
5796 bool is_glvalue = true;
5797 struct z_candidate *candidates = 0;
5798 struct z_candidate *cand;
5799 tree orig_arg2, orig_arg3;
5800
5801 auto_cond_timevar tv (TV_OVERLOAD);
5802
5803 /* As a G++ extension, the second argument to the conditional can be
5804 omitted. (So that `a ? : c' is roughly equivalent to `a ? a :
5805 c'.) If the second operand is omitted, make sure it is
5806 calculated only once. */
5807 if (!arg2)
5808 {
5809 if (complain & tf_error)
5810 pedwarn (loc, OPT_Wpedantic,
5811 "ISO C++ forbids omitting the middle term of "
5812 "a %<?:%> expression");
5813
5814 if ((complain & tf_warning) && !truth_value_p (TREE_CODE (arg1)))
5815 warn_for_omitted_condop (loc, arg1);
5816
5817 /* Make sure that lvalues remain lvalues. See g++.oliva/ext1.C. */
5818 if (glvalue_p (arg1))
5819 {
5820 arg1 = cp_stabilize_reference (arg1);
5821 arg2 = arg1 = prevent_lifetime_extension (arg1);
5822 }
5823 else if (TREE_CODE (arg1) == TARGET_EXPR)
5824 /* arg1 can't be a prvalue result of the conditional
5825 expression, since it needs to be materialized for the
5826 conversion to bool, so treat it as an xvalue in arg2. */
5827 arg2 = move (TARGET_EXPR_SLOT (arg1));
5828 else if (TREE_CODE (arg1) == EXCESS_PRECISION_EXPR)
5829 arg2 = arg1 = build1 (EXCESS_PRECISION_EXPR, TREE_TYPE (arg1),
5830 cp_save_expr (TREE_OPERAND (arg1, 0)));
5831 else
5832 arg2 = arg1 = cp_save_expr (arg1);
5833 }
5834
5835 /* If something has already gone wrong, just pass that fact up the
5836 tree. */
5837 if (error_operand_p (arg1)
5838 || error_operand_p (arg2)
5839 || error_operand_p (arg3))
5840 return error_mark_node;
5841
5842 conversion_obstack_sentinel cos;
5843
5844 orig_arg2 = arg2;
5845 orig_arg3 = arg3;
5846
5847 if (gnu_vector_type_p (TREE_TYPE (arg1))
5848 && VECTOR_INTEGER_TYPE_P (TREE_TYPE (arg1)))
5849 {
5850 tree arg1_type = TREE_TYPE (arg1);
5851
5852 /* If arg1 is another cond_expr choosing between -1 and 0,
5853 then we can use its comparison. It may help to avoid
5854 additional comparison, produce more accurate diagnostics
5855 and enables folding. */
5856 if (TREE_CODE (arg1) == VEC_COND_EXPR
5857 && integer_minus_onep (TREE_OPERAND (arg1, 1))
5858 && integer_zerop (TREE_OPERAND (arg1, 2)))
5859 arg1 = TREE_OPERAND (arg1, 0);
5860
5861 arg1 = force_rvalue (arg1, complain);
5862 arg2 = force_rvalue (arg2, complain);
5863 arg3 = force_rvalue (arg3, complain);
5864
5865 /* force_rvalue can return error_mark on valid arguments. */
5866 if (error_operand_p (arg1)
5867 || error_operand_p (arg2)
5868 || error_operand_p (arg3))
5869 return error_mark_node;
5870
5871 arg2_type = TREE_TYPE (arg2);
5872 arg3_type = TREE_TYPE (arg3);
5873
5874 if (!VECTOR_TYPE_P (arg2_type)
5875 && !VECTOR_TYPE_P (arg3_type))
5876 {
5877 /* Rely on the error messages of the scalar version. */
5878 tree scal = build_conditional_expr (loc, integer_one_node,
5879 orig_arg2, orig_arg3, complain);
5880 if (scal == error_mark_node)
5881 return error_mark_node;
5882 tree stype = TREE_TYPE (scal);
5883 tree ctype = TREE_TYPE (arg1_type);
5884 if (TYPE_SIZE (stype) != TYPE_SIZE (ctype)
5885 || (!INTEGRAL_TYPE_P (stype) && !SCALAR_FLOAT_TYPE_P (stype)))
5886 {
5887 if (complain & tf_error)
5888 error_at (loc, "inferred scalar type %qT is not an integer or "
5889 "floating-point type of the same size as %qT", stype,
5890 COMPARISON_CLASS_P (arg1)
5891 ? TREE_TYPE (TREE_TYPE (TREE_OPERAND (arg1, 0)))
5892 : ctype);
5893 return error_mark_node;
5894 }
5895
5896 tree vtype = build_opaque_vector_type (stype,
5897 TYPE_VECTOR_SUBPARTS (arg1_type));
5898 /* We could pass complain & tf_warning to unsafe_conversion_p,
5899 but the warnings (like Wsign-conversion) have already been
5900 given by the scalar build_conditional_expr_1. We still check
5901 unsafe_conversion_p to forbid truncating long long -> float. */
5902 if (unsafe_conversion_p (stype, arg2, NULL_TREE, false))
5903 {
5904 if (complain & tf_error)
5905 error_at (loc, "conversion of scalar %qH to vector %qI "
5906 "involves truncation", arg2_type, vtype);
5907 return error_mark_node;
5908 }
5909 if (unsafe_conversion_p (stype, arg3, NULL_TREE, false))
5910 {
5911 if (complain & tf_error)
5912 error_at (loc, "conversion of scalar %qH to vector %qI "
5913 "involves truncation", arg3_type, vtype);
5914 return error_mark_node;
5915 }
5916
5917 arg2 = cp_convert (stype, arg2, complain);
5918 arg2 = save_expr (arg2);
5919 arg2 = build_vector_from_val (vtype, arg2);
5920 arg2_type = vtype;
5921 arg3 = cp_convert (stype, arg3, complain);
5922 arg3 = save_expr (arg3);
5923 arg3 = build_vector_from_val (vtype, arg3);
5924 arg3_type = vtype;
5925 }
5926
5927 if ((gnu_vector_type_p (arg2_type) && !VECTOR_TYPE_P (arg3_type))
5928 || (gnu_vector_type_p (arg3_type) && !VECTOR_TYPE_P (arg2_type)))
5929 {
5930 enum stv_conv convert_flag =
5931 scalar_to_vector (loc, VEC_COND_EXPR, arg2, arg3,
5932 complain & tf_error);
5933
5934 switch (convert_flag)
5935 {
5936 case stv_error:
5937 return error_mark_node;
5938 case stv_firstarg:
5939 {
5940 arg2 = save_expr (arg2);
5941 arg2 = convert (TREE_TYPE (arg3_type), arg2);
5942 arg2 = build_vector_from_val (arg3_type, arg2);
5943 arg2_type = TREE_TYPE (arg2);
5944 break;
5945 }
5946 case stv_secondarg:
5947 {
5948 arg3 = save_expr (arg3);
5949 arg3 = convert (TREE_TYPE (arg2_type), arg3);
5950 arg3 = build_vector_from_val (arg2_type, arg3);
5951 arg3_type = TREE_TYPE (arg3);
5952 break;
5953 }
5954 default:
5955 break;
5956 }
5957 }
5958
5959 if (!gnu_vector_type_p (arg2_type)
5960 || !gnu_vector_type_p (arg3_type)
5961 || !same_type_p (arg2_type, arg3_type)
5962 || maybe_ne (TYPE_VECTOR_SUBPARTS (arg1_type),
5963 TYPE_VECTOR_SUBPARTS (arg2_type))
5964 || TYPE_SIZE (arg1_type) != TYPE_SIZE (arg2_type))
5965 {
5966 if (complain & tf_error)
5967 error_at (loc,
5968 "incompatible vector types in conditional expression: "
5969 "%qT, %qT and %qT", TREE_TYPE (arg1),
5970 TREE_TYPE (orig_arg2), TREE_TYPE (orig_arg3));
5971 return error_mark_node;
5972 }
5973
5974 if (!COMPARISON_CLASS_P (arg1))
5975 {
5976 tree cmp_type = truth_type_for (arg1_type);
5977 arg1 = build2 (NE_EXPR, cmp_type, arg1, build_zero_cst (arg1_type));
5978 }
5979 return build3_loc (loc, VEC_COND_EXPR, arg2_type, arg1, arg2, arg3);
5980 }
5981
5982 /* [expr.cond]
5983
5984 The first expression is implicitly converted to bool (clause
5985 _conv_). */
5986 arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
5987 LOOKUP_NORMAL);
5988 if (error_operand_p (arg1))
5989 return error_mark_node;
5990
5991 arg2_type = unlowered_expr_type (arg2);
5992 arg3_type = unlowered_expr_type (arg3);
5993
5994 if ((TREE_CODE (arg2) == EXCESS_PRECISION_EXPR
5995 || TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
5996 && (TREE_CODE (arg2_type) == INTEGER_TYPE
5997 || SCALAR_FLOAT_TYPE_P (arg2_type)
5998 || TREE_CODE (arg2_type) == COMPLEX_TYPE)
5999 && (TREE_CODE (arg3_type) == INTEGER_TYPE
6000 || SCALAR_FLOAT_TYPE_P (arg3_type)
6001 || TREE_CODE (arg3_type) == COMPLEX_TYPE))
6002 {
6003 semantic_result_type
6004 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6005 if (semantic_result_type == error_mark_node)
6006 {
6007 tree t1 = arg2_type;
6008 tree t2 = arg3_type;
6009 if (TREE_CODE (t1) == COMPLEX_TYPE)
6010 t1 = TREE_TYPE (t1);
6011 if (TREE_CODE (t2) == COMPLEX_TYPE)
6012 t2 = TREE_TYPE (t2);
6013 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6014 && SCALAR_FLOAT_TYPE_P (t2)
6015 && (extended_float_type_p (t1)
6016 || extended_float_type_p (t2))
6017 && cp_compare_floating_point_conversion_ranks
6018 (t1, t2) == 3);
6019 if (complain & tf_error)
6020 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6021 "have unordered conversion rank",
6022 arg2_type, arg3_type);
6023 return error_mark_node;
6024 }
6025 if (TREE_CODE (arg2) == EXCESS_PRECISION_EXPR)
6026 {
6027 arg2 = TREE_OPERAND (arg2, 0);
6028 arg2_type = TREE_TYPE (arg2);
6029 }
6030 if (TREE_CODE (arg3) == EXCESS_PRECISION_EXPR)
6031 {
6032 arg3 = TREE_OPERAND (arg3, 0);
6033 arg3_type = TREE_TYPE (arg3);
6034 }
6035 }
6036
6037 /* [expr.cond]
6038
6039 If either the second or the third operand has type (possibly
6040 cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
6041 array-to-pointer (_conv.array_), and function-to-pointer
6042 (_conv.func_) standard conversions are performed on the second
6043 and third operands. */
6044 if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
6045 {
6046 /* 'void' won't help in resolving an overloaded expression on the
6047 other side, so require it to resolve by itself. */
6048 if (arg2_type == unknown_type_node)
6049 {
6050 arg2 = resolve_nondeduced_context_or_error (arg2, complain);
6051 arg2_type = TREE_TYPE (arg2);
6052 }
6053 if (arg3_type == unknown_type_node)
6054 {
6055 arg3 = resolve_nondeduced_context_or_error (arg3, complain);
6056 arg3_type = TREE_TYPE (arg3);
6057 }
6058
6059 /* [expr.cond]
6060
6061 One of the following shall hold:
6062
6063 --The second or the third operand (but not both) is a
6064 throw-expression (_except.throw_); the result is of the type
6065 and value category of the other.
6066
6067 --Both the second and the third operands have type void; the
6068 result is of type void and is a prvalue. */
6069 if (TREE_CODE (arg2) == THROW_EXPR
6070 && TREE_CODE (arg3) != THROW_EXPR)
6071 {
6072 result_type = arg3_type;
6073 is_glvalue = glvalue_p (arg3);
6074 }
6075 else if (TREE_CODE (arg2) != THROW_EXPR
6076 && TREE_CODE (arg3) == THROW_EXPR)
6077 {
6078 result_type = arg2_type;
6079 is_glvalue = glvalue_p (arg2);
6080 }
6081 else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
6082 {
6083 result_type = void_type_node;
6084 is_glvalue = false;
6085 }
6086 else
6087 {
6088 if (complain & tf_error)
6089 {
6090 if (VOID_TYPE_P (arg2_type))
6091 error_at (cp_expr_loc_or_loc (arg3, loc),
6092 "second operand to the conditional operator "
6093 "is of type %<void%>, but the third operand is "
6094 "neither a throw-expression nor of type %<void%>");
6095 else
6096 error_at (cp_expr_loc_or_loc (arg2, loc),
6097 "third operand to the conditional operator "
6098 "is of type %<void%>, but the second operand is "
6099 "neither a throw-expression nor of type %<void%>");
6100 }
6101 return error_mark_node;
6102 }
6103
6104 goto valid_operands;
6105 }
6106 /* [expr.cond]
6107
6108 Otherwise, if the second and third operand have different types,
6109 and either has (possibly cv-qualified) class type, or if both are
6110 glvalues of the same value category and the same type except for
6111 cv-qualification, an attempt is made to convert each of those operands
6112 to the type of the other. */
6113 else if (!same_type_p (arg2_type, arg3_type)
6114 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)
6115 || (same_type_ignoring_top_level_qualifiers_p (arg2_type,
6116 arg3_type)
6117 && glvalue_p (arg2) && glvalue_p (arg3)
6118 && lvalue_p (arg2) == lvalue_p (arg3))))
6119 {
6120 conversion *conv2;
6121 conversion *conv3;
6122 bool converted = false;
6123
6124 conv2 = conditional_conversion (arg2, arg3, complain);
6125 conv3 = conditional_conversion (arg3, arg2, complain);
6126
6127 /* [expr.cond]
6128
6129 If both can be converted, or one can be converted but the
6130 conversion is ambiguous, the program is ill-formed. If
6131 neither can be converted, the operands are left unchanged and
6132 further checking is performed as described below. If exactly
6133 one conversion is possible, that conversion is applied to the
6134 chosen operand and the converted operand is used in place of
6135 the original operand for the remainder of this section. */
6136 if ((conv2 && !conv2->bad_p
6137 && conv3 && !conv3->bad_p)
6138 || (conv2 && conv2->kind == ck_ambig)
6139 || (conv3 && conv3->kind == ck_ambig))
6140 {
6141 if (complain & tf_error)
6142 {
6143 error_at (loc, "operands to %<?:%> have different types "
6144 "%qT and %qT",
6145 arg2_type, arg3_type);
6146 if (conv2 && !conv2->bad_p && conv3 && !conv3->bad_p)
6147 inform (loc, " and each type can be converted to the other");
6148 else if (conv2 && conv2->kind == ck_ambig)
6149 convert_like (conv2, arg2, complain);
6150 else
6151 convert_like (conv3, arg3, complain);
6152 }
6153 result = error_mark_node;
6154 }
6155 else if (conv2 && !conv2->bad_p)
6156 {
6157 arg2 = convert_like (conv2, arg2, complain);
6158 arg2 = convert_from_reference (arg2);
6159 arg2_type = TREE_TYPE (arg2);
6160 /* Even if CONV2 is a valid conversion, the result of the
6161 conversion may be invalid. For example, if ARG3 has type
6162 "volatile X", and X does not have a copy constructor
6163 accepting a "volatile X&", then even if ARG2 can be
6164 converted to X, the conversion will fail. */
6165 if (error_operand_p (arg2))
6166 result = error_mark_node;
6167 converted = true;
6168 }
6169 else if (conv3 && !conv3->bad_p)
6170 {
6171 arg3 = convert_like (conv3, arg3, complain);
6172 arg3 = convert_from_reference (arg3);
6173 arg3_type = TREE_TYPE (arg3);
6174 if (error_operand_p (arg3))
6175 result = error_mark_node;
6176 converted = true;
6177 }
6178
6179 if (result)
6180 return result;
6181
6182 /* If, after the conversion, both operands have class type,
6183 treat the cv-qualification of both operands as if it were the
6184 union of the cv-qualification of the operands.
6185
6186 The standard is not clear about what to do in this
6187 circumstance. For example, if the first operand has type
6188 "const X" and the second operand has a user-defined
6189 conversion to "volatile X", what is the type of the second
6190 operand after this step? Making it be "const X" (matching
6191 the first operand) seems wrong, as that discards the
6192 qualification without actually performing a copy. Leaving it
6193 as "volatile X" seems wrong as that will result in the
6194 conditional expression failing altogether, even though,
6195 according to this step, the one operand could be converted to
6196 the type of the other. */
6197 if (converted
6198 && CLASS_TYPE_P (arg2_type)
6199 && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
6200 arg2_type = arg3_type =
6201 cp_build_qualified_type (arg2_type,
6202 cp_type_quals (arg2_type)
6203 | cp_type_quals (arg3_type));
6204 }
6205
6206 /* [expr.cond]
6207
6208 If the second and third operands are glvalues of the same value
6209 category and have the same type, the result is of that type and
6210 value category. */
6211 if (((lvalue_p (arg2) && lvalue_p (arg3))
6212 || (xvalue_p (arg2) && xvalue_p (arg3)))
6213 && same_type_p (arg2_type, arg3_type))
6214 {
6215 result_type = arg2_type;
6216 goto valid_operands;
6217 }
6218
6219 /* [expr.cond]
6220
6221 Otherwise, the result is an rvalue. If the second and third
6222 operand do not have the same type, and either has (possibly
6223 cv-qualified) class type, overload resolution is used to
6224 determine the conversions (if any) to be applied to the operands
6225 (_over.match.oper_, _over.built_). */
6226 is_glvalue = false;
6227 if (!same_type_p (arg2_type, arg3_type)
6228 && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
6229 {
6230 releasing_vec args;
6231 conversion *conv;
6232 bool any_viable_p;
6233
6234 /* Rearrange the arguments so that add_builtin_candidate only has
6235 to know about two args. In build_builtin_candidate, the
6236 arguments are unscrambled. */
6237 args->quick_push (arg2);
6238 args->quick_push (arg3);
6239 args->quick_push (arg1);
6240 add_builtin_candidates (&candidates,
6241 COND_EXPR,
6242 NOP_EXPR,
6243 ovl_op_identifier (false, COND_EXPR),
6244 args,
6245 LOOKUP_NORMAL, complain);
6246
6247 /* [expr.cond]
6248
6249 If the overload resolution fails, the program is
6250 ill-formed. */
6251 candidates = splice_viable (candidates, false, &any_viable_p);
6252 if (!any_viable_p)
6253 {
6254 if (complain & tf_error)
6255 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6256 arg2_type, arg3_type);
6257 return error_mark_node;
6258 }
6259 cand = tourney (candidates, complain);
6260 if (!cand)
6261 {
6262 if (complain & tf_error)
6263 {
6264 auto_diagnostic_group d;
6265 op_error (loc, COND_EXPR, NOP_EXPR, arg1, arg2, arg3, false);
6266 print_z_candidates (loc, candidates);
6267 }
6268 return error_mark_node;
6269 }
6270
6271 /* [expr.cond]
6272
6273 Otherwise, the conversions thus determined are applied, and
6274 the converted operands are used in place of the original
6275 operands for the remainder of this section. */
6276 conv = cand->convs[0];
6277 arg1 = convert_like (conv, arg1, complain);
6278 conv = cand->convs[1];
6279 arg2 = convert_like (conv, arg2, complain);
6280 arg2_type = TREE_TYPE (arg2);
6281 conv = cand->convs[2];
6282 arg3 = convert_like (conv, arg3, complain);
6283 arg3_type = TREE_TYPE (arg3);
6284 }
6285
6286 /* [expr.cond]
6287
6288 Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
6289 and function-to-pointer (_conv.func_) standard conversions are
6290 performed on the second and third operands.
6291
6292 We need to force the lvalue-to-rvalue conversion here for class types,
6293 so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
6294 that isn't wrapped with a TARGET_EXPR plays havoc with exception
6295 regions. */
6296
6297 arg2 = force_rvalue (arg2, complain);
6298 if (!CLASS_TYPE_P (arg2_type))
6299 arg2_type = TREE_TYPE (arg2);
6300
6301 arg3 = force_rvalue (arg3, complain);
6302 if (!CLASS_TYPE_P (arg3_type))
6303 arg3_type = TREE_TYPE (arg3);
6304
6305 if (arg2 == error_mark_node || arg3 == error_mark_node)
6306 return error_mark_node;
6307
6308 /* [expr.cond]
6309
6310 After those conversions, one of the following shall hold:
6311
6312 --The second and third operands have the same type; the result is of
6313 that type. */
6314 if (same_type_p (arg2_type, arg3_type))
6315 result_type = arg2_type;
6316 /* [expr.cond]
6317
6318 --The second and third operands have arithmetic or enumeration
6319 type; the usual arithmetic conversions are performed to bring
6320 them to a common type, and the result is of that type. */
6321 else if ((ARITHMETIC_TYPE_P (arg2_type)
6322 || UNSCOPED_ENUM_P (arg2_type))
6323 && (ARITHMETIC_TYPE_P (arg3_type)
6324 || UNSCOPED_ENUM_P (arg3_type)))
6325 {
6326 /* A conditional expression between a floating-point
6327 type and an integer type should convert the integer type to
6328 the evaluation format of the floating-point type, with
6329 possible excess precision. */
6330 tree eptype2 = arg2_type;
6331 tree eptype3 = arg3_type;
6332 tree eptype;
6333 if (ANY_INTEGRAL_TYPE_P (arg2_type)
6334 && (eptype = excess_precision_type (arg3_type)) != NULL_TREE)
6335 {
6336 eptype3 = eptype;
6337 if (!semantic_result_type)
6338 semantic_result_type
6339 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6340 }
6341 else if (ANY_INTEGRAL_TYPE_P (arg3_type)
6342 && (eptype = excess_precision_type (arg2_type)) != NULL_TREE)
6343 {
6344 eptype2 = eptype;
6345 if (!semantic_result_type)
6346 semantic_result_type
6347 = type_after_usual_arithmetic_conversions (arg2_type, arg3_type);
6348 }
6349 result_type = type_after_usual_arithmetic_conversions (eptype2,
6350 eptype3);
6351 if (result_type == error_mark_node)
6352 {
6353 tree t1 = eptype2;
6354 tree t2 = eptype3;
6355 if (TREE_CODE (t1) == COMPLEX_TYPE)
6356 t1 = TREE_TYPE (t1);
6357 if (TREE_CODE (t2) == COMPLEX_TYPE)
6358 t2 = TREE_TYPE (t2);
6359 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6360 && SCALAR_FLOAT_TYPE_P (t2)
6361 && (extended_float_type_p (t1)
6362 || extended_float_type_p (t2))
6363 && cp_compare_floating_point_conversion_ranks
6364 (t1, t2) == 3);
6365 if (complain & tf_error)
6366 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6367 "have unordered conversion rank",
6368 eptype2, eptype3);
6369 return error_mark_node;
6370 }
6371 if (semantic_result_type == error_mark_node)
6372 {
6373 tree t1 = arg2_type;
6374 tree t2 = arg3_type;
6375 if (TREE_CODE (t1) == COMPLEX_TYPE)
6376 t1 = TREE_TYPE (t1);
6377 if (TREE_CODE (t2) == COMPLEX_TYPE)
6378 t2 = TREE_TYPE (t2);
6379 gcc_checking_assert (SCALAR_FLOAT_TYPE_P (t1)
6380 && SCALAR_FLOAT_TYPE_P (t2)
6381 && (extended_float_type_p (t1)
6382 || extended_float_type_p (t2))
6383 && cp_compare_floating_point_conversion_ranks
6384 (t1, t2) == 3);
6385 if (complain & tf_error)
6386 error_at (loc, "operands to %<?:%> of types %qT and %qT "
6387 "have unordered conversion rank",
6388 arg2_type, arg3_type);
6389 return error_mark_node;
6390 }
6391
6392 if (complain & tf_warning)
6393 do_warn_double_promotion (result_type, arg2_type, arg3_type,
6394 "implicit conversion from %qH to %qI to "
6395 "match other result of conditional",
6396 loc);
6397
6398 if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
6399 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
6400 {
6401 tree stripped_orig_arg2 = tree_strip_any_location_wrapper (orig_arg2);
6402 tree stripped_orig_arg3 = tree_strip_any_location_wrapper (orig_arg3);
6403 if (TREE_CODE (stripped_orig_arg2) == CONST_DECL
6404 && TREE_CODE (stripped_orig_arg3) == CONST_DECL
6405 && (DECL_CONTEXT (stripped_orig_arg2)
6406 == DECL_CONTEXT (stripped_orig_arg3)))
6407 /* Two enumerators from the same enumeration can have different
6408 types when the enumeration is still being defined. */;
6409 else if (complain & (cxx_dialect >= cxx26
6410 ? tf_warning_or_error : tf_warning))
6411 emit_diagnostic (cxx_dialect >= cxx26 ? DK_PEDWARN : DK_WARNING,
6412 loc, OPT_Wenum_compare, "enumerated mismatch "
6413 "in conditional expression: %qT vs %qT",
6414 arg2_type, arg3_type);
6415 else if (cxx_dialect >= cxx26)
6416 return error_mark_node;
6417 }
6418 else if ((((complain & (cxx_dialect >= cxx26
6419 ? tf_warning_or_error : tf_warning))
6420 && warn_deprecated_enum_float_conv)
6421 || (cxx_dialect >= cxx26
6422 && (complain & tf_warning_or_error) == 0))
6423 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6424 && SCALAR_FLOAT_TYPE_P (arg3_type))
6425 || (SCALAR_FLOAT_TYPE_P (arg2_type)
6426 && TREE_CODE (arg3_type) == ENUMERAL_TYPE)))
6427 {
6428 if (cxx_dialect >= cxx26 && (complain & tf_warning_or_error) == 0)
6429 return error_mark_node;
6430 if (cxx_dialect >= cxx26 && TREE_CODE (arg2_type) == ENUMERAL_TYPE)
6431 pedwarn (loc, OPT_Wdeprecated_enum_float_conversion,
6432 "conditional expression between enumeration type "
6433 "%qT and floating-point type %qT", arg2_type, arg3_type);
6434 else if (cxx_dialect >= cxx26)
6435 pedwarn (loc, OPT_Wdeprecated_enum_float_conversion,
6436 "conditional expression between floating-point type "
6437 "%qT and enumeration type %qT", arg2_type, arg3_type);
6438 else if (TREE_CODE (arg2_type) == ENUMERAL_TYPE)
6439 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6440 "conditional expression between enumeration type "
6441 "%qT and floating-point type %qT is deprecated",
6442 arg2_type, arg3_type);
6443 else
6444 warning_at (loc, OPT_Wdeprecated_enum_float_conversion,
6445 "conditional expression between floating-point "
6446 "type %qT and enumeration type %qT is deprecated",
6447 arg2_type, arg3_type);
6448 }
6449 else if ((extra_warnings || warn_enum_conversion)
6450 && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
6451 && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
6452 || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
6453 && !same_type_p (arg2_type,
6454 type_promotes_to (arg3_type)))))
6455 {
6456 if (complain & tf_warning)
6457 {
6458 enum opt_code opt = (warn_enum_conversion
6459 ? OPT_Wenum_conversion
6460 : OPT_Wextra);
6461 warning_at (loc, opt, "enumerated and "
6462 "non-enumerated type in conditional expression");
6463 }
6464 }
6465
6466 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6467 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6468 }
6469 /* [expr.cond]
6470
6471 --The second and third operands have pointer type, or one has
6472 pointer type and the other is a null pointer constant; pointer
6473 conversions (_conv.ptr_) and qualification conversions
6474 (_conv.qual_) are performed to bring them to their composite
6475 pointer type (_expr.rel_). The result is of the composite
6476 pointer type.
6477
6478 --The second and third operands have pointer to member type, or
6479 one has pointer to member type and the other is a null pointer
6480 constant; pointer to member conversions (_conv.mem_) and
6481 qualification conversions (_conv.qual_) are performed to bring
6482 them to a common type, whose cv-qualification shall match the
6483 cv-qualification of either the second or the third operand.
6484 The result is of the common type. */
6485 else if ((null_ptr_cst_p (arg2)
6486 && TYPE_PTR_OR_PTRMEM_P (arg3_type))
6487 || (null_ptr_cst_p (arg3)
6488 && TYPE_PTR_OR_PTRMEM_P (arg2_type))
6489 || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
6490 || (TYPE_PTRDATAMEM_P (arg2_type) && TYPE_PTRDATAMEM_P (arg3_type))
6491 || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
6492 {
6493 result_type = composite_pointer_type (loc,
6494 arg2_type, arg3_type, arg2,
6495 arg3, CPO_CONDITIONAL_EXPR,
6496 complain);
6497 if (result_type == error_mark_node)
6498 return error_mark_node;
6499 arg2 = perform_implicit_conversion (result_type, arg2, complain);
6500 arg3 = perform_implicit_conversion (result_type, arg3, complain);
6501 }
6502
6503 if (!result_type)
6504 {
6505 if (complain & tf_error)
6506 error_at (loc, "operands to %<?:%> have different types %qT and %qT",
6507 arg2_type, arg3_type);
6508 return error_mark_node;
6509 }
6510
6511 if (arg2 == error_mark_node || arg3 == error_mark_node)
6512 return error_mark_node;
6513
6514 valid_operands:
6515 if (processing_template_decl && is_glvalue)
6516 {
6517 /* Let lvalue_kind know this was a glvalue. */
6518 tree arg = (result_type == arg2_type ? arg2 : arg3);
6519 result_type = cp_build_reference_type (result_type, xvalue_p (arg));
6520 }
6521
6522 result = build3_loc (loc, COND_EXPR, result_type, arg1, arg2, arg3);
6523
6524 /* If the ARG2 and ARG3 are the same and don't have side-effects,
6525 warn here, because the COND_EXPR will be turned into ARG2. */
6526 if (warn_duplicated_branches
6527 && (complain & tf_warning)
6528 && (arg2 == arg3 || operand_equal_p (arg2, arg3,
6529 OEP_ADDRESS_OF_SAME_FIELD)))
6530 warning_at (EXPR_LOCATION (result), OPT_Wduplicated_branches,
6531 "this condition has identical branches");
6532
6533 /* We can't use result_type below, as fold might have returned a
6534 throw_expr. */
6535
6536 if (!is_glvalue)
6537 {
6538 /* Expand both sides into the same slot, hopefully the target of
6539 the ?: expression. We used to check for TARGET_EXPRs here,
6540 but now we sometimes wrap them in NOP_EXPRs so the test would
6541 fail. */
6542 if (CLASS_TYPE_P (TREE_TYPE (result)))
6543 {
6544 result = get_target_expr (result, complain);
6545 /* Tell gimplify_modify_expr_rhs not to strip this in
6546 assignment context: we want both arms to initialize
6547 the same temporary. */
6548 TARGET_EXPR_NO_ELIDE (result) = true;
6549 }
6550 /* If this expression is an rvalue, but might be mistaken for an
6551 lvalue, we must add a NON_LVALUE_EXPR. */
6552 result = rvalue (result);
6553 if (semantic_result_type)
6554 result = build1 (EXCESS_PRECISION_EXPR, semantic_result_type,
6555 result);
6556 }
6557 else
6558 {
6559 result = force_paren_expr (result);
6560 gcc_assert (semantic_result_type == NULL_TREE);
6561 }
6562
6563 return result;
6564 }
6565
6566 /* OPERAND is an operand to an expression. Perform necessary steps
6567 required before using it. If OPERAND is NULL_TREE, NULL_TREE is
6568 returned. */
6569
6570 static tree
6571 prep_operand (tree operand)
6572 {
6573 if (operand)
6574 {
6575 if (CLASS_TYPE_P (TREE_TYPE (operand))
6576 && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
6577 /* Make sure the template type is instantiated now. */
6578 instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
6579 }
6580
6581 return operand;
6582 }
6583
6584 /* True iff CONV represents a conversion sequence which no other can be better
6585 than under [over.ics.rank]: in other words, a "conversion" to the exact same
6586 type (including binding to a reference to the same type). This is stronger
6587 than the standard's "identity" category, which also includes reference
6588 bindings that add cv-qualifiers or change rvalueness. */
6589
6590 static bool
6591 perfect_conversion_p (conversion *conv)
6592 {
6593 if (CONVERSION_RANK (conv) != cr_identity)
6594 return false;
6595 if (conv->kind == ck_ref_bind)
6596 {
6597 if (!conv->rvaluedness_matches_p)
6598 return false;
6599 if (!same_type_p (TREE_TYPE (conv->type),
6600 next_conversion (conv)->type))
6601 return false;
6602 }
6603 if (conv->check_narrowing)
6604 /* Brace elision is imperfect. */
6605 return false;
6606 return true;
6607 }
6608
6609 /* True if CAND represents a perfect match, i.e. all perfect conversions, so no
6610 other candidate can be a better match. Since the template/non-template
6611 tiebreaker comes immediately after the conversion comparison in
6612 [over.match.best], a perfect non-template candidate is better than all
6613 templates. */
6614
6615 static bool
6616 perfect_candidate_p (z_candidate *cand)
6617 {
6618 if (cand->viable < 1)
6619 return false;
6620 /* CWG1402 makes an implicitly deleted move op worse than other
6621 candidates. */
6622 if (DECL_DELETED_FN (cand->fn) && DECL_DEFAULTED_FN (cand->fn)
6623 && move_fn_p (cand->fn))
6624 return false;
6625 int len = cand->num_convs;
6626 for (int i = 0; i < len; ++i)
6627 if (!perfect_conversion_p (cand->convs[i]))
6628 return false;
6629 if (conversion *conv = cand->second_conv)
6630 if (!perfect_conversion_p (conv))
6631 return false;
6632 return true;
6633 }
6634
6635 /* True iff one of CAND's argument conversions is missing. */
6636
6637 static bool
6638 missing_conversion_p (const z_candidate *cand)
6639 {
6640 for (unsigned i = 0; i < cand->num_convs; ++i)
6641 {
6642 conversion *conv = cand->convs[i];
6643 if (!conv)
6644 return true;
6645 if (conv->kind == ck_deferred_bad)
6646 {
6647 /* We don't know whether this conversion is outright invalid or
6648 just bad, so conservatively assume it's missing. */
6649 gcc_checking_assert (conv->bad_p);
6650 return true;
6651 }
6652 }
6653 return false;
6654 }
6655
6656 /* Add each of the viable functions in FNS (a FUNCTION_DECL or
6657 OVERLOAD) to the CANDIDATES, returning an updated list of
6658 CANDIDATES. The ARGS are the arguments provided to the call;
6659 if FIRST_ARG is non-null it is the implicit object argument,
6660 otherwise the first element of ARGS is used if needed. The
6661 EXPLICIT_TARGS are explicit template arguments provided.
6662 TEMPLATE_ONLY is true if only template functions should be
6663 considered. CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
6664 add_function_candidate. */
6665
6666 static void
6667 add_candidates (tree fns, tree first_arg, const vec<tree, va_gc> *args,
6668 tree return_type,
6669 tree explicit_targs, bool template_only,
6670 tree conversion_path, tree access_path,
6671 int flags,
6672 struct z_candidate **candidates,
6673 tsubst_flags_t complain)
6674 {
6675 tree ctype;
6676 const vec<tree, va_gc> *non_static_args;
6677 bool check_list_ctor = false;
6678 bool check_converting = false;
6679 unification_kind_t strict;
6680 tree ne_context = NULL_TREE;
6681 tree ne_fns = NULL_TREE;
6682
6683 if (!fns)
6684 return;
6685
6686 /* Precalculate special handling of constructors and conversion ops. */
6687 tree fn = OVL_FIRST (fns);
6688 if (DECL_CONV_FN_P (fn))
6689 {
6690 check_list_ctor = false;
6691 check_converting = (flags & LOOKUP_ONLYCONVERTING) != 0;
6692 if (flags & LOOKUP_NO_CONVERSION)
6693 /* We're doing return_type(x). */
6694 strict = DEDUCE_CONV;
6695 else
6696 /* We're doing x.operator return_type(). */
6697 strict = DEDUCE_EXACT;
6698 /* [over.match.funcs] For conversion functions, the function
6699 is considered to be a member of the class of the implicit
6700 object argument for the purpose of defining the type of
6701 the implicit object parameter. */
6702 ctype = TYPE_MAIN_VARIANT (TREE_TYPE (first_arg));
6703 }
6704 else
6705 {
6706 if (DECL_CONSTRUCTOR_P (fn))
6707 {
6708 check_list_ctor = (flags & LOOKUP_LIST_ONLY) != 0;
6709 /* For list-initialization we consider explicit constructors
6710 and complain if one is chosen. */
6711 check_converting
6712 = ((flags & (LOOKUP_ONLYCONVERTING|LOOKUP_LIST_INIT_CTOR))
6713 == LOOKUP_ONLYCONVERTING);
6714 }
6715 strict = DEDUCE_CALL;
6716 ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
6717 }
6718
6719 /* P2468: Check if operator== is a rewrite target with first operand
6720 (*args)[0]; for now just do the lookups. */
6721 if ((flags & (LOOKUP_REWRITTEN | LOOKUP_REVERSED))
6722 && DECL_OVERLOADED_OPERATOR_IS (fn, EQ_EXPR))
6723 {
6724 tree ne_name = ovl_op_identifier (false, NE_EXPR);
6725 if (DECL_CLASS_SCOPE_P (fn))
6726 {
6727 ne_context = DECL_CONTEXT (fn);
6728 ne_fns = lookup_fnfields (TREE_TYPE ((*args)[0]), ne_name,
6729 1, tf_none);
6730 if (ne_fns == error_mark_node || ne_fns == NULL_TREE)
6731 ne_fns = NULL_TREE;
6732 else
6733 ne_fns = BASELINK_FUNCTIONS (ne_fns);
6734 }
6735 else
6736 {
6737 ne_context = decl_namespace_context (fn);
6738 ne_fns = lookup_qualified_name (ne_context, ne_name,
6739 LOOK_want::NORMAL,
6740 /*complain*/false);
6741 if (ne_fns == error_mark_node
6742 || !is_overloaded_fn (ne_fns))
6743 ne_fns = NULL_TREE;
6744 }
6745 }
6746
6747 if (first_arg)
6748 non_static_args = args;
6749 else
6750 /* Delay creating the implicit this parameter until it is needed. */
6751 non_static_args = NULL;
6752
6753 bool seen_strictly_viable = any_strictly_viable (*candidates);
6754 /* If there's a non-template perfect match, we don't need to consider
6755 templates. So check non-templates first. This optimization is only
6756 really needed for the defaulted copy constructor of tuple and the like
6757 (96926), but it seems like we might as well enable it more generally. */
6758 bool seen_perfect = false;
6759 enum { templates, non_templates, either } which = either;
6760 if (template_only)
6761 which = templates;
6762 else /*if (flags & LOOKUP_DEFAULTED)*/
6763 which = non_templates;
6764
6765 /* Template candidates that we'll potentially ignore if the
6766 perfect candidate optimization succeeds. */
6767 z_candidate *ignored_template_cands = nullptr;
6768
6769 /* During overload resolution, we first consider each function under the
6770 assumption that we'll eventually find a strictly viable candidate.
6771 This allows us to circumvent our defacto behavior when checking
6772 argument conversions and shortcut consideration of the candidate
6773 upon encountering the first bad conversion. If this assumption
6774 turns out to be false, and all candidates end up being non-strictly
6775 viable, then we reconsider such candidates under the defacto behavior.
6776 This trick is important for pruning member function overloads according
6777 to their const/ref-qualifiers (since all 'this' conversions are at
6778 worst bad) without breaking -fpermissive. */
6779 z_candidate *bad_cands = nullptr;
6780 bool shortcut_bad_convs = true;
6781
6782 again:
6783 for (tree fn : lkp_range (fns))
6784 {
6785 if (which == templates && TREE_CODE (fn) != TEMPLATE_DECL)
6786 {
6787 if (template_only)
6788 add_ignored_candidate (candidates, fn);
6789 continue;
6790 }
6791 if (which == non_templates && TREE_CODE (fn) == TEMPLATE_DECL)
6792 {
6793 add_ignored_candidate (&ignored_template_cands, fn);
6794 continue;
6795 }
6796 if ((check_converting && DECL_NONCONVERTING_P (fn))
6797 || (check_list_ctor && !is_list_ctor (fn)))
6798 {
6799 add_ignored_candidate (candidates, fn);
6800 continue;
6801 }
6802
6803 tree fn_first_arg = NULL_TREE;
6804 const vec<tree, va_gc> *fn_args = args;
6805
6806 if (DECL_OBJECT_MEMBER_FUNCTION_P (fn))
6807 {
6808 /* Figure out where the object arg comes from. If this
6809 function is a non-static member and we didn't get an
6810 implicit object argument, move it out of args. */
6811 if (first_arg == NULL_TREE)
6812 {
6813 unsigned int ix;
6814 tree arg;
6815 vec<tree, va_gc> *tempvec;
6816 vec_alloc (tempvec, args->length () - 1);
6817 for (ix = 1; args->iterate (ix, &arg); ++ix)
6818 tempvec->quick_push (arg);
6819 non_static_args = tempvec;
6820 first_arg = (*args)[0];
6821 }
6822
6823 fn_first_arg = first_arg;
6824 fn_args = non_static_args;
6825 }
6826
6827 /* Don't bother reversing an operator with two identical parameters. */
6828 else if (vec_safe_length (args) == 2 && (flags & LOOKUP_REVERSED))
6829 {
6830 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
6831 if (same_type_p (TREE_VALUE (parmlist),
6832 TREE_VALUE (TREE_CHAIN (parmlist))))
6833 continue;
6834 }
6835
6836 /* When considering reversed operator==, if there's a corresponding
6837 operator!= in the same scope, it's not a rewrite target. */
6838 if (ne_context)
6839 {
6840 if (TREE_CODE (ne_context) == NAMESPACE_DECL)
6841 {
6842 /* With argument-dependent lookup, fns can span multiple
6843 namespaces; make sure we look in the fn's namespace for a
6844 corresponding operator!=. */
6845 tree fn_ns = decl_namespace_context (fn);
6846 if (fn_ns != ne_context)
6847 {
6848 ne_context = fn_ns;
6849 tree ne_name = ovl_op_identifier (false, NE_EXPR);
6850 ne_fns = lookup_qualified_name (ne_context, ne_name,
6851 LOOK_want::NORMAL,
6852 /*complain*/false);
6853 if (ne_fns == error_mark_node
6854 || !is_overloaded_fn (ne_fns))
6855 ne_fns = NULL_TREE;
6856 }
6857 }
6858 bool found = false;
6859 for (lkp_iterator ne (ne_fns); !found && ne; ++ne)
6860 if (0 && !ne.using_p ()
6861 && DECL_NAMESPACE_SCOPE_P (fn)
6862 && DECL_CONTEXT (*ne) != DECL_CONTEXT (fn))
6863 /* ??? This kludge excludes inline namespace members for the H
6864 test in spaceship-eq15.C, but I don't see why we would want
6865 that behavior. Asked Core 2022-11-04. Disabling for now. */;
6866 else if (fns_correspond (fn, *ne))
6867 {
6868 found = true;
6869 break;
6870 }
6871 if (found)
6872 continue;
6873 }
6874
6875 if (TREE_CODE (fn) == TEMPLATE_DECL)
6876 add_template_candidate (candidates,
6877 fn,
6878 ctype,
6879 explicit_targs,
6880 fn_first_arg,
6881 fn_args,
6882 return_type,
6883 access_path,
6884 conversion_path,
6885 flags,
6886 strict,
6887 shortcut_bad_convs,
6888 complain);
6889 else
6890 {
6891 add_function_candidate (candidates,
6892 fn,
6893 ctype,
6894 fn_first_arg,
6895 fn_args,
6896 access_path,
6897 conversion_path,
6898 flags,
6899 NULL,
6900 shortcut_bad_convs,
6901 complain);
6902 if (perfect_candidate_p (*candidates))
6903 seen_perfect = true;
6904 }
6905
6906 z_candidate *cand = *candidates;
6907 if (cand->viable == 1)
6908 seen_strictly_viable = true;
6909
6910 if (cand->viable == -1
6911 && shortcut_bad_convs
6912 && (missing_conversion_p (cand)
6913 || TREE_CODE (cand->fn) == TEMPLATE_DECL))
6914 {
6915 /* This candidate has been tentatively marked non-strictly viable,
6916 and we didn't compute all argument conversions for it (having
6917 stopped at the first bad conversion). Move it to BAD_CANDS to
6918 to fully reconsider later if we don't find any strictly viable
6919 candidates. */
6920 if (complain & (tf_error | tf_conv))
6921 {
6922 *candidates = cand->next;
6923 cand->next = bad_cands;
6924 bad_cands = cand;
6925 }
6926 else
6927 /* But if we're in a SFINAE context, just mark this candidate as
6928 unviable outright and avoid potentially reconsidering it.
6929 This is safe to do because in a SFINAE context, performing a bad
6930 conversion is always an error (even with -fpermissive), so a
6931 non-strictly viable candidate is effectively unviable anyway. */
6932 cand->viable = 0;
6933 }
6934 }
6935 if (which == non_templates && !seen_perfect)
6936 {
6937 which = templates;
6938 ignored_template_cands = nullptr;
6939 goto again;
6940 }
6941 else if (which == templates
6942 && !seen_strictly_viable
6943 && shortcut_bad_convs
6944 && bad_cands)
6945 {
6946 /* None of the candidates are strictly viable, so consider again those
6947 functions in BAD_CANDS, this time without shortcutting bad conversions
6948 so that all their argument conversions are computed. */
6949 which = either;
6950 fns = NULL_TREE;
6951 for (z_candidate *cand = bad_cands; cand; cand = cand->next)
6952 {
6953 tree fn = cand->fn;
6954 if (tree ti = cand->template_decl)
6955 fn = TI_TEMPLATE (ti);
6956 fns = ovl_make (fn, fns);
6957 }
6958 shortcut_bad_convs = false;
6959 bad_cands = nullptr;
6960 goto again;
6961 }
6962
6963 if (complain & tf_error)
6964 {
6965 /* Remember any omitted candidates; we may want to print all candidates
6966 as part of overload resolution failure diagnostics. */
6967 for (z_candidate *omitted_cands : { ignored_template_cands, bad_cands })
6968 {
6969 z_candidate **omitted_cands_tail = &omitted_cands;
6970 while (*omitted_cands_tail)
6971 omitted_cands_tail = &(*omitted_cands_tail)->next;
6972 *omitted_cands_tail = *candidates;
6973 *candidates = omitted_cands;
6974 }
6975 }
6976 }
6977
6978 /* Returns 1 if P0145R2 says that the LHS of operator CODE is evaluated first,
6979 -1 if the RHS is evaluated first, or 0 if the order is unspecified. */
6980
6981 static int
6982 op_is_ordered (tree_code code)
6983 {
6984 switch (code)
6985 {
6986 // 5. b @= a
6987 case MODIFY_EXPR:
6988 return (flag_strong_eval_order > 1 ? -1 : 0);
6989
6990 // 6. a[b]
6991 case ARRAY_REF:
6992 return (flag_strong_eval_order > 1 ? 1 : 0);
6993
6994 // 1. a.b
6995 // Not overloadable (yet).
6996 // 2. a->b
6997 // Only one argument.
6998 // 3. a->*b
6999 case MEMBER_REF:
7000 // 7. a << b
7001 case LSHIFT_EXPR:
7002 // 8. a >> b
7003 case RSHIFT_EXPR:
7004 // a && b
7005 // Predates P0145R3.
7006 case TRUTH_ANDIF_EXPR:
7007 // a || b
7008 // Predates P0145R3.
7009 case TRUTH_ORIF_EXPR:
7010 // a , b
7011 // Predates P0145R3.
7012 case COMPOUND_EXPR:
7013 return (flag_strong_eval_order ? 1 : 0);
7014
7015 default:
7016 return 0;
7017 }
7018 }
7019
7020 /* Subroutine of build_new_op: Add to CANDIDATES all candidates for the
7021 operator indicated by CODE/CODE2. This function calls itself recursively to
7022 handle C++20 rewritten comparison operator candidates. Returns NULL_TREE
7023 upon success, and error_mark_node if something went wrong that prevented
7024 us from performing overload resolution (e.g. ambiguous member name lookup).
7025
7026 LOOKUPS, if non-NULL, is the set of pertinent namespace-scope operator
7027 overloads to consider. This parameter is used when instantiating a
7028 dependent operator expression and has the same structure as
7029 DEPENDENT_OPERATOR_TYPE_SAVED_LOOKUPS. */
7030
7031 static tree
7032 add_operator_candidates (z_candidate **candidates,
7033 tree_code code, tree_code code2,
7034 vec<tree, va_gc> *arglist, tree lookups,
7035 int flags, tsubst_flags_t complain)
7036 {
7037 z_candidate *start_candidates = *candidates;
7038 bool ismodop = code2 != ERROR_MARK;
7039 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
7040
7041 /* LOOKUP_REWRITTEN is set when we're looking for the == or <=> operator to
7042 rewrite from, and also when we're looking for the e.g. < operator to use
7043 on the result of <=>. In the latter case, we don't want the flag set in
7044 the candidate, we just want to suppress looking for rewrites. */
7045 bool rewritten = (flags & LOOKUP_REWRITTEN);
7046 if (rewritten && code != EQ_EXPR && code != SPACESHIP_EXPR)
7047 flags &= ~LOOKUP_REWRITTEN;
7048
7049 bool memonly = false;
7050 switch (code)
7051 {
7052 /* =, ->, [], () must be non-static member functions. */
7053 case MODIFY_EXPR:
7054 if (code2 != NOP_EXPR)
7055 break;
7056 /* FALLTHRU */
7057 case COMPONENT_REF:
7058 case ARRAY_REF:
7059 memonly = true;
7060 break;
7061
7062 default:
7063 break;
7064 }
7065
7066 /* Add namespace-scope operators to the list of functions to
7067 consider. */
7068 if (!memonly)
7069 {
7070 tree fns;
7071 if (!lookups)
7072 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
7073 /* If LOOKUPS is non-NULL, then we're instantiating a dependent operator
7074 expression, and LOOKUPS is the result of stage 1 name lookup. */
7075 else if (tree found = purpose_member (fnname, lookups))
7076 fns = TREE_VALUE (found);
7077 else
7078 fns = NULL_TREE;
7079 fns = lookup_arg_dependent (fnname, fns, arglist);
7080 add_candidates (fns, NULL_TREE, arglist, NULL_TREE,
7081 NULL_TREE, false, NULL_TREE, NULL_TREE,
7082 flags, candidates, complain);
7083 }
7084
7085 /* Add class-member operators to the candidate set. */
7086 tree arg1_type = TREE_TYPE ((*arglist)[0]);
7087 unsigned nargs = arglist->length () > 1 ? 2 : 1;
7088 tree arg2_type = nargs > 1 ? TREE_TYPE ((*arglist)[1]) : NULL_TREE;
7089 if (CLASS_TYPE_P (arg1_type))
7090 {
7091 tree fns = lookup_fnfields (arg1_type, fnname, 1, complain);
7092 if (fns == error_mark_node)
7093 return error_mark_node;
7094 if (fns)
7095 {
7096 if (code == ARRAY_REF)
7097 {
7098 vec<tree,va_gc> *restlist = make_tree_vector ();
7099 for (unsigned i = 1; i < nargs; ++i)
7100 vec_safe_push (restlist, (*arglist)[i]);
7101 z_candidate *save_cand = *candidates;
7102 add_candidates (BASELINK_FUNCTIONS (fns),
7103 (*arglist)[0], restlist, NULL_TREE,
7104 NULL_TREE, false,
7105 BASELINK_BINFO (fns),
7106 BASELINK_ACCESS_BINFO (fns),
7107 flags, candidates, complain);
7108 /* Release the vec if we didn't add a candidate that uses it. */
7109 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
7110 if (c->args == restlist)
7111 {
7112 restlist = NULL;
7113 break;
7114 }
7115 release_tree_vector (restlist);
7116 }
7117 else
7118 add_candidates (BASELINK_FUNCTIONS (fns),
7119 NULL_TREE, arglist, NULL_TREE,
7120 NULL_TREE, false,
7121 BASELINK_BINFO (fns),
7122 BASELINK_ACCESS_BINFO (fns),
7123 flags, candidates, complain);
7124 }
7125 }
7126 /* Per [over.match.oper]3.2, if no operand has a class type, then
7127 only non-member functions that have type T1 or reference to
7128 cv-qualified-opt T1 for the first argument, if the first argument
7129 has an enumeration type, or T2 or reference to cv-qualified-opt
7130 T2 for the second argument, if the second argument has an
7131 enumeration type. Filter out those that don't match. */
7132 else if (! arg2_type || ! CLASS_TYPE_P (arg2_type))
7133 {
7134 struct z_candidate **candp, **next;
7135
7136 for (candp = candidates; *candp != start_candidates; candp = next)
7137 {
7138 unsigned i;
7139 z_candidate *cand = *candp;
7140 next = &cand->next;
7141
7142 tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
7143
7144 for (i = 0; i < nargs; ++i)
7145 {
7146 tree parmtype = TREE_VALUE (parmlist);
7147 tree argtype = unlowered_expr_type ((*arglist)[i]);
7148
7149 if (TYPE_REF_P (parmtype))
7150 parmtype = TREE_TYPE (parmtype);
7151 if (TREE_CODE (argtype) == ENUMERAL_TYPE
7152 && (same_type_ignoring_top_level_qualifiers_p
7153 (argtype, parmtype)))
7154 break;
7155
7156 parmlist = TREE_CHAIN (parmlist);
7157 }
7158
7159 /* No argument has an appropriate type, so remove this
7160 candidate function from the list. */
7161 if (i == nargs)
7162 {
7163 *candp = cand->next;
7164 next = candp;
7165 }
7166 }
7167 }
7168
7169 if (!rewritten)
7170 {
7171 /* The standard says to rewrite built-in candidates, too,
7172 but there's no point. */
7173 add_builtin_candidates (candidates, code, code2, fnname, arglist,
7174 flags, complain);
7175
7176 /* Maybe add C++20 rewritten comparison candidates. */
7177 tree_code rewrite_code = ERROR_MARK;
7178 if (cxx_dialect >= cxx20
7179 && nargs == 2
7180 && (OVERLOAD_TYPE_P (arg1_type) || OVERLOAD_TYPE_P (arg2_type)))
7181 switch (code)
7182 {
7183 case LT_EXPR:
7184 case LE_EXPR:
7185 case GT_EXPR:
7186 case GE_EXPR:
7187 case SPACESHIP_EXPR:
7188 rewrite_code = SPACESHIP_EXPR;
7189 break;
7190
7191 case NE_EXPR:
7192 case EQ_EXPR:
7193 rewrite_code = EQ_EXPR;
7194 break;
7195
7196 default:;
7197 }
7198
7199 if (rewrite_code)
7200 {
7201 tree r;
7202 flags |= LOOKUP_REWRITTEN;
7203 if (rewrite_code != code)
7204 {
7205 /* Add rewritten candidates in same order. */
7206 r = add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
7207 arglist, lookups, flags, complain);
7208 if (r == error_mark_node)
7209 return error_mark_node;
7210 }
7211
7212 z_candidate *save_cand = *candidates;
7213
7214 /* Add rewritten candidates in reverse order. */
7215 flags |= LOOKUP_REVERSED;
7216 vec<tree,va_gc> *revlist = make_tree_vector ();
7217 revlist->quick_push ((*arglist)[1]);
7218 revlist->quick_push ((*arglist)[0]);
7219 r = add_operator_candidates (candidates, rewrite_code, ERROR_MARK,
7220 revlist, lookups, flags, complain);
7221 if (r == error_mark_node)
7222 return error_mark_node;
7223
7224 /* Release the vec if we didn't add a candidate that uses it. */
7225 for (z_candidate *c = *candidates; c != save_cand; c = c->next)
7226 if (c->args == revlist)
7227 {
7228 revlist = NULL;
7229 break;
7230 }
7231 release_tree_vector (revlist);
7232 }
7233 }
7234
7235 return NULL_TREE;
7236 }
7237
7238 tree
7239 build_new_op (const op_location_t &loc, enum tree_code code, int flags,
7240 tree arg1, tree arg2, tree arg3, tree lookups,
7241 tree *overload, tsubst_flags_t complain)
7242 {
7243 struct z_candidate *candidates = 0, *cand;
7244 releasing_vec arglist;
7245 tree result = NULL_TREE;
7246 bool result_valid_p = false;
7247 enum tree_code code2 = ERROR_MARK;
7248 enum tree_code code_orig_arg1 = ERROR_MARK;
7249 enum tree_code code_orig_arg2 = ERROR_MARK;
7250 bool strict_p;
7251 bool any_viable_p;
7252
7253 auto_cond_timevar tv (TV_OVERLOAD);
7254
7255 if (error_operand_p (arg1)
7256 || error_operand_p (arg2)
7257 || error_operand_p (arg3))
7258 return error_mark_node;
7259
7260 conversion_obstack_sentinel cos;
7261
7262 bool ismodop = code == MODIFY_EXPR;
7263 if (ismodop)
7264 {
7265 code2 = TREE_CODE (arg3);
7266 arg3 = NULL_TREE;
7267 }
7268
7269 tree arg1_type = unlowered_expr_type (arg1);
7270 tree arg2_type = arg2 ? unlowered_expr_type (arg2) : NULL_TREE;
7271
7272 arg1 = prep_operand (arg1);
7273
7274 switch (code)
7275 {
7276 case NEW_EXPR:
7277 case VEC_NEW_EXPR:
7278 case VEC_DELETE_EXPR:
7279 case DELETE_EXPR:
7280 /* Use build_operator_new_call and build_op_delete_call instead. */
7281 gcc_unreachable ();
7282
7283 case CALL_EXPR:
7284 /* Use build_op_call instead. */
7285 gcc_unreachable ();
7286
7287 case TRUTH_ORIF_EXPR:
7288 case TRUTH_ANDIF_EXPR:
7289 case TRUTH_AND_EXPR:
7290 case TRUTH_OR_EXPR:
7291 /* These are saved for the sake of warn_logical_operator. */
7292 code_orig_arg1 = TREE_CODE (arg1);
7293 code_orig_arg2 = TREE_CODE (arg2);
7294 break;
7295 case GT_EXPR:
7296 case LT_EXPR:
7297 case GE_EXPR:
7298 case LE_EXPR:
7299 case EQ_EXPR:
7300 case NE_EXPR:
7301 /* These are saved for the sake of maybe_warn_bool_compare. */
7302 code_orig_arg1 = TREE_CODE (arg1_type);
7303 code_orig_arg2 = TREE_CODE (arg2_type);
7304 break;
7305
7306 default:
7307 break;
7308 }
7309
7310 arg2 = prep_operand (arg2);
7311 arg3 = prep_operand (arg3);
7312
7313 if (code == COND_EXPR)
7314 /* Use build_conditional_expr instead. */
7315 gcc_unreachable ();
7316 else if (! OVERLOAD_TYPE_P (arg1_type)
7317 && (! arg2 || ! OVERLOAD_TYPE_P (arg2_type)))
7318 goto builtin;
7319
7320 if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
7321 {
7322 arg2 = integer_zero_node;
7323 arg2_type = integer_type_node;
7324 }
7325
7326 arglist->quick_push (arg1);
7327 if (arg2 != NULL_TREE)
7328 arglist->quick_push (arg2);
7329 if (arg3 != NULL_TREE)
7330 arglist->quick_push (arg3);
7331
7332 result = add_operator_candidates (&candidates, code, code2, arglist,
7333 lookups, flags, complain);
7334 if (result == error_mark_node)
7335 return error_mark_node;
7336
7337 switch (code)
7338 {
7339 case COMPOUND_EXPR:
7340 case ADDR_EXPR:
7341 /* For these, the built-in candidates set is empty
7342 [over.match.oper]/3. We don't want non-strict matches
7343 because exact matches are always possible with built-in
7344 operators. The built-in candidate set for COMPONENT_REF
7345 would be empty too, but since there are no such built-in
7346 operators, we accept non-strict matches for them. */
7347 strict_p = true;
7348 break;
7349
7350 default:
7351 strict_p = false;
7352 break;
7353 }
7354
7355 candidates = splice_viable (candidates, strict_p, &any_viable_p);
7356 if (!any_viable_p)
7357 {
7358 switch (code)
7359 {
7360 case POSTINCREMENT_EXPR:
7361 case POSTDECREMENT_EXPR:
7362 /* Don't try anything fancy if we're not allowed to produce
7363 errors. */
7364 if (!(complain & tf_error))
7365 return error_mark_node;
7366
7367 /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
7368 distinguish between prefix and postfix ++ and
7369 operator++() was used for both, so we allow this with
7370 -fpermissive. */
7371 else
7372 {
7373 tree fnname = ovl_op_identifier (ismodop, ismodop ? code2 : code);
7374 const char *msg = (flag_permissive)
7375 ? G_("no %<%D(int)%> declared for postfix %qs,"
7376 " trying prefix operator instead")
7377 : G_("no %<%D(int)%> declared for postfix %qs");
7378 permerror (loc, msg, fnname, OVL_OP_INFO (false, code)->name);
7379 }
7380
7381 if (!flag_permissive)
7382 return error_mark_node;
7383
7384 if (code == POSTINCREMENT_EXPR)
7385 code = PREINCREMENT_EXPR;
7386 else
7387 code = PREDECREMENT_EXPR;
7388 result = build_new_op (loc, code, flags, arg1, NULL_TREE,
7389 NULL_TREE, lookups, overload, complain);
7390 break;
7391
7392 /* The caller will deal with these. */
7393 case ADDR_EXPR:
7394 case COMPOUND_EXPR:
7395 case COMPONENT_REF:
7396 case CO_AWAIT_EXPR:
7397 result = NULL_TREE;
7398 result_valid_p = true;
7399 break;
7400
7401 default:
7402 if (complain & tf_error)
7403 {
7404 /* If one of the arguments of the operator represents
7405 an invalid use of member function pointer, try to report
7406 a meaningful error ... */
7407 if (invalid_nonstatic_memfn_p (loc, arg1, tf_error)
7408 || invalid_nonstatic_memfn_p (loc, arg2, tf_error)
7409 || invalid_nonstatic_memfn_p (loc, arg3, tf_error))
7410 /* We displayed the error message. */;
7411 else
7412 {
7413 /* ... Otherwise, report the more generic
7414 "no matching operator found" error */
7415 auto_diagnostic_group d;
7416 op_error (loc, code, code2, arg1, arg2, arg3, false);
7417 print_z_candidates (loc, candidates);
7418 }
7419 }
7420 result = error_mark_node;
7421 break;
7422 }
7423 }
7424 else
7425 {
7426 cand = tourney (candidates, complain);
7427 if (cand == 0)
7428 {
7429 if (complain & tf_error)
7430 {
7431 auto_diagnostic_group d;
7432 op_error (loc, code, code2, arg1, arg2, arg3, true);
7433 print_z_candidates (loc, candidates);
7434 }
7435 result = error_mark_node;
7436 if (overload)
7437 *overload = error_mark_node;
7438 }
7439 else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
7440 {
7441 if (overload)
7442 *overload = cand->fn;
7443
7444 if (resolve_args (arglist, complain) == NULL)
7445 result = error_mark_node;
7446 else
7447 {
7448 tsubst_flags_t ocomplain = complain;
7449 if (cand->rewritten ())
7450 /* We'll wrap this call in another one. */
7451 ocomplain &= ~tf_decltype;
7452 if (cand->reversed ())
7453 {
7454 /* We swapped these in add_candidate, swap them back now. */
7455 std::swap (cand->convs[0], cand->convs[1]);
7456 if (cand->fn == current_function_decl)
7457 warning_at (loc, 0, "in C++20 this comparison calls the "
7458 "current function recursively with reversed "
7459 "arguments");
7460 }
7461 result = build_over_call (cand, LOOKUP_NORMAL, ocomplain);
7462 }
7463
7464 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7465 /* There won't be a CALL_EXPR. */;
7466 else if (result && result != error_mark_node)
7467 {
7468 tree call = extract_call_expr (result);
7469 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7470
7471 /* Specify evaluation order as per P0145R2. */
7472 CALL_EXPR_ORDERED_ARGS (call) = false;
7473 switch (op_is_ordered (code))
7474 {
7475 case -1:
7476 CALL_EXPR_REVERSE_ARGS (call) = true;
7477 break;
7478
7479 case 1:
7480 CALL_EXPR_ORDERED_ARGS (call) = true;
7481 break;
7482
7483 default:
7484 break;
7485 }
7486 }
7487
7488 /* If this was a C++20 rewritten comparison, adjust the result. */
7489 if (cand->rewritten ())
7490 {
7491 /* FIXME build_min_non_dep_op_overload can't handle rewrites. */
7492 if (overload)
7493 *overload = NULL_TREE;
7494 switch (code)
7495 {
7496 case EQ_EXPR:
7497 gcc_checking_assert (cand->reversed ());
7498 gcc_fallthrough ();
7499 case NE_EXPR:
7500 if (result == error_mark_node)
7501 ;
7502 /* If a rewritten operator== candidate is selected by
7503 overload resolution for an operator @, its return type
7504 shall be cv bool.... */
7505 else if (TREE_CODE (TREE_TYPE (result)) != BOOLEAN_TYPE)
7506 {
7507 if (complain & tf_error)
7508 {
7509 auto_diagnostic_group d;
7510 error_at (loc, "return type of %qD is not %qs",
7511 cand->fn, "bool");
7512 inform (loc, "used as rewritten candidate for "
7513 "comparison of %qT and %qT",
7514 arg1_type, arg2_type);
7515 }
7516 result = error_mark_node;
7517 }
7518 else if (code == NE_EXPR)
7519 /* !(y == x) or !(x == y) */
7520 result = build1_loc (loc, TRUTH_NOT_EXPR,
7521 boolean_type_node, result);
7522 break;
7523
7524 /* If a rewritten operator<=> candidate is selected by
7525 overload resolution for an operator @, x @ y is
7526 interpreted as 0 @ (y <=> x) if the selected candidate is
7527 a synthesized candidate with reversed order of parameters,
7528 or (x <=> y) @ 0 otherwise, using the selected rewritten
7529 operator<=> candidate. */
7530 case SPACESHIP_EXPR:
7531 if (!cand->reversed ())
7532 /* We're in the build_new_op call below for an outer
7533 reversed call; we don't need to do anything more. */
7534 break;
7535 gcc_fallthrough ();
7536 case LT_EXPR:
7537 case LE_EXPR:
7538 case GT_EXPR:
7539 case GE_EXPR:
7540 {
7541 tree lhs = result;
7542 tree rhs = integer_zero_node;
7543 if (cand->reversed ())
7544 std::swap (lhs, rhs);
7545 warning_sentinel ws (warn_zero_as_null_pointer_constant);
7546 result = build_new_op (loc, code,
7547 LOOKUP_NORMAL|LOOKUP_REWRITTEN,
7548 lhs, rhs, NULL_TREE, lookups,
7549 NULL, complain);
7550 }
7551 break;
7552
7553 default:
7554 gcc_unreachable ();
7555 }
7556 }
7557
7558 /* In an expression of the form `a[]' where cand->fn
7559 which is operator[] turns out to be a static member function,
7560 `a' is none-the-less evaluated. */
7561 if (code == ARRAY_REF)
7562 result = keep_unused_object_arg (result, arg1, cand->fn);
7563 }
7564 else
7565 {
7566 /* Give any warnings we noticed during overload resolution. */
7567 if (cand->warnings && (complain & tf_warning))
7568 {
7569 struct candidate_warning *w;
7570 for (w = cand->warnings; w; w = w->next)
7571 joust (cand, w->loser, 1, complain);
7572 }
7573
7574 /* Check for comparison of different enum types. */
7575 switch (code)
7576 {
7577 case GT_EXPR:
7578 case LT_EXPR:
7579 case GE_EXPR:
7580 case LE_EXPR:
7581 case EQ_EXPR:
7582 case NE_EXPR:
7583 if (TREE_CODE (arg1_type) == ENUMERAL_TYPE
7584 && TREE_CODE (arg2_type) == ENUMERAL_TYPE
7585 && (TYPE_MAIN_VARIANT (arg1_type)
7586 != TYPE_MAIN_VARIANT (arg2_type)))
7587 {
7588 if (cxx_dialect >= cxx26
7589 && (complain & tf_warning_or_error) == 0)
7590 result = error_mark_node;
7591 else if (cxx_dialect >= cxx26 || (complain & tf_warning))
7592 emit_diagnostic (cxx_dialect >= cxx26
7593 ? DK_PEDWARN : DK_WARNING,
7594 loc, OPT_Wenum_compare,
7595 "comparison between %q#T and %q#T",
7596 arg1_type, arg2_type);
7597 }
7598 break;
7599 default:
7600 break;
7601 }
7602
7603 /* "If a built-in candidate is selected by overload resolution, the
7604 operands of class type are converted to the types of the
7605 corresponding parameters of the selected operation function,
7606 except that the second standard conversion sequence of a
7607 user-defined conversion sequence (12.3.3.1.2) is not applied." */
7608 conversion *conv = cand->convs[0];
7609 if (conv->user_conv_p)
7610 {
7611 conv = strip_standard_conversion (conv);
7612 arg1 = convert_like (conv, arg1, complain);
7613 }
7614
7615 if (arg2)
7616 {
7617 conv = cand->convs[1];
7618 if (conv->user_conv_p)
7619 {
7620 conv = strip_standard_conversion (conv);
7621 arg2 = convert_like (conv, arg2, complain);
7622 }
7623 }
7624
7625 if (arg3)
7626 {
7627 conv = cand->convs[2];
7628 if (conv->user_conv_p)
7629 {
7630 conv = strip_standard_conversion (conv);
7631 arg3 = convert_like (conv, arg3, complain);
7632 }
7633 }
7634 }
7635 }
7636
7637 if (result || result_valid_p)
7638 return result;
7639
7640 builtin:
7641 switch (code)
7642 {
7643 case MODIFY_EXPR:
7644 return cp_build_modify_expr (loc, arg1, code2, arg2, complain);
7645
7646 case INDIRECT_REF:
7647 return cp_build_indirect_ref (loc, arg1, RO_UNARY_STAR, complain);
7648
7649 case TRUTH_ANDIF_EXPR:
7650 case TRUTH_ORIF_EXPR:
7651 case TRUTH_AND_EXPR:
7652 case TRUTH_OR_EXPR:
7653 if ((complain & tf_warning) && !processing_template_decl)
7654 warn_logical_operator (loc, code, boolean_type_node,
7655 code_orig_arg1, arg1,
7656 code_orig_arg2, arg2);
7657 /* Fall through. */
7658 case GT_EXPR:
7659 case LT_EXPR:
7660 case GE_EXPR:
7661 case LE_EXPR:
7662 case EQ_EXPR:
7663 case NE_EXPR:
7664 if ((complain & tf_warning)
7665 && ((code_orig_arg1 == BOOLEAN_TYPE)
7666 ^ (code_orig_arg2 == BOOLEAN_TYPE)))
7667 maybe_warn_bool_compare (loc, code, arg1, arg2);
7668 if (complain & tf_warning && warn_tautological_compare)
7669 warn_tautological_cmp (loc, code, arg1, arg2);
7670 /* Fall through. */
7671 case SPACESHIP_EXPR:
7672 case PLUS_EXPR:
7673 case MINUS_EXPR:
7674 case MULT_EXPR:
7675 case TRUNC_DIV_EXPR:
7676 case MAX_EXPR:
7677 case MIN_EXPR:
7678 case LSHIFT_EXPR:
7679 case RSHIFT_EXPR:
7680 case TRUNC_MOD_EXPR:
7681 case BIT_AND_EXPR:
7682 case BIT_IOR_EXPR:
7683 case BIT_XOR_EXPR:
7684 return cp_build_binary_op (loc, code, arg1, arg2, complain);
7685
7686 case UNARY_PLUS_EXPR:
7687 case NEGATE_EXPR:
7688 case BIT_NOT_EXPR:
7689 case TRUTH_NOT_EXPR:
7690 case PREINCREMENT_EXPR:
7691 case POSTINCREMENT_EXPR:
7692 case PREDECREMENT_EXPR:
7693 case POSTDECREMENT_EXPR:
7694 case REALPART_EXPR:
7695 case IMAGPART_EXPR:
7696 case ABS_EXPR:
7697 case CO_AWAIT_EXPR:
7698 return cp_build_unary_op (code, arg1, false, complain);
7699
7700 case ARRAY_REF:
7701 return cp_build_array_ref (input_location, arg1, arg2, complain);
7702
7703 case MEMBER_REF:
7704 return build_m_component_ref (cp_build_indirect_ref (loc, arg1,
7705 RO_ARROW_STAR,
7706 complain),
7707 arg2, complain);
7708
7709 /* The caller will deal with these. */
7710 case ADDR_EXPR:
7711 case COMPONENT_REF:
7712 case COMPOUND_EXPR:
7713 return NULL_TREE;
7714
7715 default:
7716 gcc_unreachable ();
7717 }
7718 return NULL_TREE;
7719 }
7720
7721 /* Build a new call to operator[]. This may change ARGS. */
7722
7723 tree
7724 build_op_subscript (const op_location_t &loc, tree obj,
7725 vec<tree, va_gc> **args, tree *overload,
7726 tsubst_flags_t complain)
7727 {
7728 struct z_candidate *candidates = 0, *cand;
7729 tree fns, first_mem_arg = NULL_TREE;
7730 bool any_viable_p;
7731 tree result = NULL_TREE;
7732
7733 auto_cond_timevar tv (TV_OVERLOAD);
7734
7735 obj = mark_lvalue_use (obj);
7736
7737 if (error_operand_p (obj))
7738 return error_mark_node;
7739
7740 tree type = TREE_TYPE (obj);
7741
7742 obj = prep_operand (obj);
7743
7744 if (TYPE_BINFO (type))
7745 {
7746 fns = lookup_fnfields (TYPE_BINFO (type), ovl_op_identifier (ARRAY_REF),
7747 1, complain);
7748 if (fns == error_mark_node)
7749 return error_mark_node;
7750 }
7751 else
7752 fns = NULL_TREE;
7753
7754 if (args != NULL && *args != NULL)
7755 {
7756 *args = resolve_args (*args, complain);
7757 if (*args == NULL)
7758 return error_mark_node;
7759 }
7760
7761 conversion_obstack_sentinel cos;
7762
7763 if (fns)
7764 {
7765 first_mem_arg = obj;
7766
7767 add_candidates (BASELINK_FUNCTIONS (fns),
7768 first_mem_arg, *args, NULL_TREE,
7769 NULL_TREE, false,
7770 BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
7771 LOOKUP_NORMAL, &candidates, complain);
7772 }
7773
7774 /* Be strict here because if we choose a bad conversion candidate, the
7775 errors we get won't mention the call context. */
7776 candidates = splice_viable (candidates, true, &any_viable_p);
7777 if (!any_viable_p)
7778 {
7779 if (complain & tf_error)
7780 {
7781 auto_diagnostic_group d;
7782 error ("no match for call to %<%T::operator[] (%A)%>",
7783 TREE_TYPE (obj), build_tree_list_vec (*args));
7784 print_z_candidates (loc, candidates);
7785 }
7786 result = error_mark_node;
7787 }
7788 else
7789 {
7790 cand = tourney (candidates, complain);
7791 if (cand == 0)
7792 {
7793 if (complain & tf_error)
7794 {
7795 auto_diagnostic_group d;
7796 error ("call of %<%T::operator[] (%A)%> is ambiguous",
7797 TREE_TYPE (obj), build_tree_list_vec (*args));
7798 print_z_candidates (loc, candidates);
7799 }
7800 result = error_mark_node;
7801 }
7802 else if (TREE_CODE (cand->fn) == FUNCTION_DECL
7803 && DECL_OVERLOADED_OPERATOR_P (cand->fn)
7804 && DECL_OVERLOADED_OPERATOR_IS (cand->fn, ARRAY_REF))
7805 {
7806 if (overload)
7807 *overload = cand->fn;
7808 result = build_over_call (cand, LOOKUP_NORMAL, complain);
7809 if (trivial_fn_p (cand->fn) || DECL_IMMEDIATE_FUNCTION_P (cand->fn))
7810 /* There won't be a CALL_EXPR. */;
7811 else if (result && result != error_mark_node)
7812 {
7813 tree call = extract_call_expr (result);
7814 CALL_EXPR_OPERATOR_SYNTAX (call) = true;
7815
7816 /* Specify evaluation order as per P0145R2. */
7817 CALL_EXPR_ORDERED_ARGS (call) = op_is_ordered (ARRAY_REF) == 1;
7818 }
7819
7820 /* In an expression of the form `a[]' where cand->fn
7821 which is operator[] turns out to be a static member function,
7822 `a' is none-the-less evaluated. */
7823 result = keep_unused_object_arg (result, obj, cand->fn);
7824 }
7825 else
7826 gcc_unreachable ();
7827 }
7828
7829 return result;
7830 }
7831
7832 /* CALL was returned by some call-building function; extract the actual
7833 CALL_EXPR from any bits that have been tacked on, e.g. by
7834 convert_from_reference. */
7835
7836 tree
7837 extract_call_expr (tree call)
7838 {
7839 while (TREE_CODE (call) == COMPOUND_EXPR)
7840 call = TREE_OPERAND (call, 1);
7841 if (REFERENCE_REF_P (call))
7842 call = TREE_OPERAND (call, 0);
7843 if (TREE_CODE (call) == TARGET_EXPR)
7844 call = TARGET_EXPR_INITIAL (call);
7845 if (cxx_dialect >= cxx20)
7846 switch (TREE_CODE (call))
7847 {
7848 /* C++20 rewritten comparison operators. */
7849 case TRUTH_NOT_EXPR:
7850 call = TREE_OPERAND (call, 0);
7851 break;
7852 case LT_EXPR:
7853 case LE_EXPR:
7854 case GT_EXPR:
7855 case GE_EXPR:
7856 case SPACESHIP_EXPR:
7857 {
7858 tree op0 = TREE_OPERAND (call, 0);
7859 if (integer_zerop (op0))
7860 call = TREE_OPERAND (call, 1);
7861 else
7862 call = op0;
7863 }
7864 break;
7865 default:;
7866 }
7867
7868 if (TREE_CODE (call) != CALL_EXPR
7869 && TREE_CODE (call) != AGGR_INIT_EXPR
7870 && call != error_mark_node)
7871 return NULL_TREE;
7872 return call;
7873 }
7874
7875 /* Returns true if FN has two parameters, of which the second has type
7876 size_t. */
7877
7878 static bool
7879 second_parm_is_size_t (tree fn)
7880 {
7881 tree t = FUNCTION_ARG_CHAIN (fn);
7882 if (!t || !same_type_p (TREE_VALUE (t), size_type_node))
7883 return false;
7884 t = TREE_CHAIN (t);
7885 if (t == void_list_node)
7886 return true;
7887 return false;
7888 }
7889
7890 /* True if T, an allocation function, has std::align_val_t as its second
7891 argument. */
7892
7893 bool
7894 aligned_allocation_fn_p (tree t)
7895 {
7896 if (!aligned_new_threshold)
7897 return false;
7898
7899 tree a = FUNCTION_ARG_CHAIN (t);
7900 return (a && same_type_p (TREE_VALUE (a), align_type_node));
7901 }
7902
7903 /* True if T is std::destroying_delete_t. */
7904
7905 static bool
7906 std_destroying_delete_t_p (tree t)
7907 {
7908 return (TYPE_CONTEXT (t) == std_node
7909 && id_equal (TYPE_IDENTIFIER (t), "destroying_delete_t"));
7910 }
7911
7912 /* A deallocation function with at least two parameters whose second parameter
7913 type is of type std::destroying_delete_t is a destroying operator delete. A
7914 destroying operator delete shall be a class member function named operator
7915 delete. [ Note: Array deletion cannot use a destroying operator
7916 delete. --end note ] */
7917
7918 tree
7919 destroying_delete_p (tree t)
7920 {
7921 tree a = TYPE_ARG_TYPES (TREE_TYPE (t));
7922 if (!a || !TREE_CHAIN (a))
7923 return NULL_TREE;
7924 tree type = TREE_VALUE (TREE_CHAIN (a));
7925 return std_destroying_delete_t_p (type) ? type : NULL_TREE;
7926 }
7927
7928 struct dealloc_info
7929 {
7930 bool sized;
7931 bool aligned;
7932 tree destroying;
7933 };
7934
7935 /* Returns true iff T, an element of an OVERLOAD chain, is a usual deallocation
7936 function (3.7.4.2 [basic.stc.dynamic.deallocation]). If so, and DI is
7937 non-null, also set *DI. */
7938
7939 static bool
7940 usual_deallocation_fn_p (tree t, dealloc_info *di)
7941 {
7942 if (di) *di = dealloc_info();
7943
7944 /* A template instance is never a usual deallocation function,
7945 regardless of its signature. */
7946 if (TREE_CODE (t) == TEMPLATE_DECL
7947 || primary_template_specialization_p (t))
7948 return false;
7949
7950 /* A usual deallocation function is a deallocation function whose parameters
7951 after the first are
7952 - optionally, a parameter of type std::destroying_delete_t, then
7953 - optionally, a parameter of type std::size_t, then
7954 - optionally, a parameter of type std::align_val_t. */
7955 bool global = DECL_NAMESPACE_SCOPE_P (t);
7956 tree chain = FUNCTION_ARG_CHAIN (t);
7957 if (chain && destroying_delete_p (t))
7958 {
7959 if (di) di->destroying = TREE_VALUE (chain);
7960 chain = TREE_CHAIN (chain);
7961 }
7962 if (chain
7963 && (!global || flag_sized_deallocation)
7964 && same_type_p (TREE_VALUE (chain), size_type_node))
7965 {
7966 if (di) di->sized = true;
7967 chain = TREE_CHAIN (chain);
7968 }
7969 if (chain && aligned_new_threshold
7970 && same_type_p (TREE_VALUE (chain), align_type_node))
7971 {
7972 if (di) di->aligned = true;
7973 chain = TREE_CHAIN (chain);
7974 }
7975 return (chain == void_list_node);
7976 }
7977
7978 /* Just return whether FN is a usual deallocation function. */
7979
7980 bool
7981 usual_deallocation_fn_p (tree fn)
7982 {
7983 return usual_deallocation_fn_p (fn, NULL);
7984 }
7985
7986 /* Build a call to operator delete. This has to be handled very specially,
7987 because the restrictions on what signatures match are different from all
7988 other call instances. For a normal delete, only a delete taking (void *)
7989 or (void *, size_t) is accepted. For a placement delete, only an exact
7990 match with the placement new is accepted.
7991
7992 CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
7993 ADDR is the pointer to be deleted.
7994 SIZE is the size of the memory block to be deleted.
7995 GLOBAL_P is true if the delete-expression should not consider
7996 class-specific delete operators.
7997 CORO_P is true if the allocation is for a coroutine, where the two argument
7998 usual deallocation should be chosen in preference to the single argument
7999 version in a class context.
8000 PLACEMENT is the corresponding placement new call, or NULL_TREE.
8001
8002 If this call to "operator delete" is being generated as part to
8003 deallocate memory allocated via a new-expression (as per [expr.new]
8004 which requires that if the initialization throws an exception then
8005 we call a deallocation function), then ALLOC_FN is the allocation
8006 function. */
8007
8008 static tree
8009 build_op_delete_call_1 (enum tree_code code, tree addr, tree size,
8010 bool global_p, bool coro_p, tree placement,
8011 tree alloc_fn, tsubst_flags_t complain)
8012 {
8013 tree fn = NULL_TREE;
8014 tree fns, fnname, type, t;
8015 dealloc_info di_fn = { };
8016
8017 if (addr == error_mark_node)
8018 return error_mark_node;
8019
8020 type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
8021
8022 fnname = ovl_op_identifier (false, code);
8023
8024 if (CLASS_TYPE_P (type)
8025 && COMPLETE_TYPE_P (complete_type (type))
8026 && !global_p)
8027 /* In [class.free]
8028
8029 If the result of the lookup is ambiguous or inaccessible, or if
8030 the lookup selects a placement deallocation function, the
8031 program is ill-formed.
8032
8033 Therefore, we ask lookup_fnfields to complain about ambiguity. */
8034 {
8035 fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1, complain);
8036 if (fns == error_mark_node)
8037 return error_mark_node;
8038 }
8039 else
8040 fns = NULL_TREE;
8041
8042 if (fns == NULL_TREE)
8043 fns = lookup_name (fnname, LOOK_where::BLOCK_NAMESPACE);
8044
8045 /* Strip const and volatile from addr. */
8046 tree oaddr = addr;
8047 addr = cp_convert (ptr_type_node, addr, complain);
8048
8049 tree excluded_destroying = NULL_TREE;
8050
8051 if (placement)
8052 {
8053 /* "A declaration of a placement deallocation function matches the
8054 declaration of a placement allocation function if it has the same
8055 number of parameters and, after parameter transformations (8.3.5),
8056 all parameter types except the first are identical."
8057
8058 So we build up the function type we want and ask instantiate_type
8059 to get it for us. */
8060 t = FUNCTION_ARG_CHAIN (alloc_fn);
8061 t = tree_cons (NULL_TREE, ptr_type_node, t);
8062 t = build_function_type (void_type_node, t);
8063
8064 fn = instantiate_type (t, fns, tf_none);
8065 if (fn == error_mark_node)
8066 return NULL_TREE;
8067
8068 fn = MAYBE_BASELINK_FUNCTIONS (fn);
8069
8070 /* "If the lookup finds the two-parameter form of a usual deallocation
8071 function (3.7.4.2) and that function, considered as a placement
8072 deallocation function, would have been selected as a match for the
8073 allocation function, the program is ill-formed." */
8074 if (second_parm_is_size_t (fn))
8075 {
8076 const char *const msg1
8077 = G_("exception cleanup for this placement new selects "
8078 "non-placement %<operator delete%>");
8079 const char *const msg2
8080 = G_("%qD is a usual (non-placement) deallocation "
8081 "function in C++14 (or with %<-fsized-deallocation%>)");
8082
8083 /* But if the class has an operator delete (void *), then that is
8084 the usual deallocation function, so we shouldn't complain
8085 about using the operator delete (void *, size_t). */
8086 if (DECL_CLASS_SCOPE_P (fn))
8087 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
8088 {
8089 if (usual_deallocation_fn_p (elt)
8090 && FUNCTION_ARG_CHAIN (elt) == void_list_node)
8091 goto ok;
8092 }
8093 /* Before C++14 a two-parameter global deallocation function is
8094 always a placement deallocation function, but warn if
8095 -Wc++14-compat. */
8096 else if (!flag_sized_deallocation)
8097 {
8098 if (complain & tf_warning)
8099 {
8100 auto_diagnostic_group d;
8101 if (warning (OPT_Wc__14_compat, msg1))
8102 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
8103 }
8104 goto ok;
8105 }
8106
8107 if (complain & tf_warning_or_error)
8108 {
8109 auto_diagnostic_group d;
8110 if (permerror (input_location, msg1))
8111 {
8112 /* Only mention C++14 for namespace-scope delete. */
8113 if (DECL_NAMESPACE_SCOPE_P (fn))
8114 inform (DECL_SOURCE_LOCATION (fn), msg2, fn);
8115 else
8116 inform (DECL_SOURCE_LOCATION (fn),
8117 "%qD is a usual (non-placement) deallocation "
8118 "function", fn);
8119 }
8120 }
8121 else
8122 return error_mark_node;
8123 ok:;
8124 }
8125 }
8126 else
8127 /* "Any non-placement deallocation function matches a non-placement
8128 allocation function. If the lookup finds a single matching
8129 deallocation function, that function will be called; otherwise, no
8130 deallocation function will be called." */
8131 for (tree elt : lkp_range (MAYBE_BASELINK_FUNCTIONS (fns)))
8132 {
8133 dealloc_info di_elt;
8134 if (usual_deallocation_fn_p (elt, &di_elt))
8135 {
8136 /* If we're called for an EH cleanup in a new-expression, we can't
8137 use a destroying delete; the exception was thrown before the
8138 object was constructed. */
8139 if (alloc_fn && di_elt.destroying)
8140 {
8141 excluded_destroying = elt;
8142 continue;
8143 }
8144
8145 if (!fn)
8146 {
8147 fn = elt;
8148 di_fn = di_elt;
8149 continue;
8150 }
8151
8152 /* -- If any of the deallocation functions is a destroying
8153 operator delete, all deallocation functions that are not
8154 destroying operator deletes are eliminated from further
8155 consideration. */
8156 if (di_elt.destroying != di_fn.destroying)
8157 {
8158 if (di_elt.destroying)
8159 {
8160 fn = elt;
8161 di_fn = di_elt;
8162 }
8163 continue;
8164 }
8165
8166 /* -- If the type has new-extended alignment, a function with a
8167 parameter of type std::align_val_t is preferred; otherwise a
8168 function without such a parameter is preferred. If exactly one
8169 preferred function is found, that function is selected and the
8170 selection process terminates. If more than one preferred
8171 function is found, all non-preferred functions are eliminated
8172 from further consideration. */
8173 if (aligned_new_threshold)
8174 {
8175 bool want_align = type_has_new_extended_alignment (type);
8176 if (di_elt.aligned != di_fn.aligned)
8177 {
8178 if (want_align == di_elt.aligned)
8179 {
8180 fn = elt;
8181 di_fn = di_elt;
8182 }
8183 continue;
8184 }
8185 }
8186
8187 /* -- If the deallocation functions have class scope, the one
8188 without a parameter of type std::size_t is selected. */
8189 bool want_size;
8190 if (DECL_CLASS_SCOPE_P (fn) && !coro_p)
8191 want_size = false;
8192
8193 /* -- If the type is complete and if, for the second alternative
8194 (delete array) only, the operand is a pointer to a class type
8195 with a non-trivial destructor or a (possibly multi-dimensional)
8196 array thereof, the function with a parameter of type std::size_t
8197 is selected.
8198
8199 -- Otherwise, it is unspecified whether a deallocation function
8200 with a parameter of type std::size_t is selected. */
8201 else
8202 {
8203 want_size = COMPLETE_TYPE_P (type);
8204 if (code == VEC_DELETE_EXPR
8205 && !TYPE_VEC_NEW_USES_COOKIE (type))
8206 /* We need a cookie to determine the array size. */
8207 want_size = false;
8208 }
8209 gcc_assert (di_fn.sized != di_elt.sized);
8210 if (want_size == di_elt.sized)
8211 {
8212 fn = elt;
8213 di_fn = di_elt;
8214 }
8215 }
8216 }
8217
8218 /* If we have a matching function, call it. */
8219 if (fn)
8220 {
8221 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
8222
8223 /* If the FN is a member function, make sure that it is
8224 accessible. */
8225 if (BASELINK_P (fns))
8226 perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn,
8227 complain);
8228
8229 /* Core issue 901: It's ok to new a type with deleted delete. */
8230 if (DECL_DELETED_FN (fn) && alloc_fn)
8231 return NULL_TREE;
8232
8233 tree ret;
8234 if (placement)
8235 {
8236 /* The placement args might not be suitable for overload
8237 resolution at this point, so build the call directly. */
8238 int nargs = call_expr_nargs (placement);
8239 tree *argarray = XALLOCAVEC (tree, nargs);
8240 int i;
8241 argarray[0] = addr;
8242 for (i = 1; i < nargs; i++)
8243 argarray[i] = CALL_EXPR_ARG (placement, i);
8244 if (!mark_used (fn, complain) && !(complain & tf_error))
8245 return error_mark_node;
8246 ret = build_cxx_call (fn, nargs, argarray, complain);
8247 }
8248 else
8249 {
8250 tree destroying = di_fn.destroying;
8251 if (destroying)
8252 {
8253 /* Strip const and volatile from addr but retain the type of the
8254 object. */
8255 tree rtype = TREE_TYPE (TREE_TYPE (oaddr));
8256 rtype = cv_unqualified (rtype);
8257 rtype = TYPE_POINTER_TO (rtype);
8258 addr = cp_convert (rtype, oaddr, complain);
8259 destroying = build_functional_cast (input_location,
8260 destroying, NULL_TREE,
8261 complain);
8262 }
8263
8264 releasing_vec args;
8265 args->quick_push (addr);
8266 if (destroying)
8267 args->quick_push (destroying);
8268 if (di_fn.sized)
8269 args->quick_push (size);
8270 if (di_fn.aligned)
8271 {
8272 tree al = build_int_cst (align_type_node, TYPE_ALIGN_UNIT (type));
8273 args->quick_push (al);
8274 }
8275 ret = cp_build_function_call_vec (fn, &args, complain);
8276 }
8277
8278 /* Set this flag for all callers of this function. In addition to
8279 delete-expressions, this is called for deallocating coroutine state;
8280 treat that as an implicit delete-expression. This is also called for
8281 the delete if the constructor throws in a new-expression, and for a
8282 deleting destructor (which implements a delete-expression). */
8283 /* But leave this flag off for destroying delete to avoid wrong
8284 assumptions in the optimizers. */
8285 tree call = extract_call_expr (ret);
8286 if (TREE_CODE (call) == CALL_EXPR && !destroying_delete_p (fn))
8287 CALL_FROM_NEW_OR_DELETE_P (call) = 1;
8288
8289 return ret;
8290 }
8291
8292 /* If there's only a destroying delete that we can't use because the
8293 object isn't constructed yet, and we used global new, use global
8294 delete as well. */
8295 if (excluded_destroying
8296 && DECL_NAMESPACE_SCOPE_P (alloc_fn))
8297 return build_op_delete_call (code, addr, size, true, placement,
8298 alloc_fn, complain);
8299
8300 /* [expr.new]
8301
8302 If no unambiguous matching deallocation function can be found,
8303 propagating the exception does not cause the object's memory to
8304 be freed. */
8305 if (alloc_fn)
8306 {
8307 if ((complain & tf_warning)
8308 && !placement)
8309 {
8310 bool w = warning (0,
8311 "no corresponding deallocation function for %qD",
8312 alloc_fn);
8313 if (w && excluded_destroying)
8314 inform (DECL_SOURCE_LOCATION (excluded_destroying), "destroying "
8315 "delete %qD cannot be used to release the allocated memory"
8316 " if the initialization throws because the object is not "
8317 "constructed yet", excluded_destroying);
8318 }
8319 return NULL_TREE;
8320 }
8321
8322 if (complain & tf_error)
8323 error ("no suitable %<operator %s%> for %qT",
8324 OVL_OP_INFO (false, code)->name, type);
8325 return error_mark_node;
8326 }
8327
8328 /* Arguments as per build_op_delete_call_1 (). */
8329
8330 tree
8331 build_op_delete_call (enum tree_code code, tree addr, tree size, bool global_p,
8332 tree placement, tree alloc_fn, tsubst_flags_t complain)
8333 {
8334 return build_op_delete_call_1 (code, addr, size, global_p, /*coro_p*/false,
8335 placement, alloc_fn, complain);
8336 }
8337
8338 /* Arguments as per build_op_delete_call_1 (). */
8339
8340 tree
8341 build_coroutine_op_delete_call (enum tree_code code, tree addr, tree size,
8342 bool global_p, tree placement, tree alloc_fn,
8343 tsubst_flags_t complain)
8344 {
8345 return build_op_delete_call_1 (code, addr, size, global_p, /*coro_p*/true,
8346 placement, alloc_fn, complain);
8347 }
8348
8349 /* Issue diagnostics about a disallowed access of DECL, using DIAG_DECL
8350 in the diagnostics.
8351
8352 If ISSUE_ERROR is true, then issue an error about the access, followed
8353 by a note showing the declaration. Otherwise, just show the note.
8354
8355 DIAG_DECL and DIAG_LOCATION will almost always be the same.
8356 DIAG_LOCATION is just another DECL. NO_ACCESS_REASON is an optional
8357 parameter used to specify why DECL wasn't accessible (e.g. ak_private
8358 would be because DECL was private). If not using NO_ACCESS_REASON,
8359 then it must be ak_none, and the access failure reason will be
8360 figured out by looking at the protection of DECL. */
8361
8362 void
8363 complain_about_access (tree decl, tree diag_decl, tree diag_location,
8364 bool issue_error, access_kind no_access_reason)
8365 {
8366 /* If we have not already figured out why DECL is inaccessible... */
8367 if (no_access_reason == ak_none)
8368 {
8369 /* Examine the access of DECL to find out why. */
8370 if (TREE_PRIVATE (decl))
8371 no_access_reason = ak_private;
8372 else if (TREE_PROTECTED (decl))
8373 no_access_reason = ak_protected;
8374 }
8375
8376 /* Now generate an error message depending on calculated access. */
8377 if (no_access_reason == ak_private)
8378 {
8379 if (issue_error)
8380 error ("%q#D is private within this context", diag_decl);
8381 inform (DECL_SOURCE_LOCATION (diag_location), "declared private here");
8382 }
8383 else if (no_access_reason == ak_protected)
8384 {
8385 if (issue_error)
8386 error ("%q#D is protected within this context", diag_decl);
8387 inform (DECL_SOURCE_LOCATION (diag_location), "declared protected here");
8388 }
8389 /* Couldn't figure out why DECL is inaccesible, so just say it's
8390 inaccessible. */
8391 else
8392 {
8393 if (issue_error)
8394 error ("%q#D is inaccessible within this context", diag_decl);
8395 inform (DECL_SOURCE_LOCATION (diag_decl), "declared here");
8396 }
8397 }
8398
8399 /* Initialize a temporary of type TYPE with EXPR. The FLAGS are a
8400 bitwise or of LOOKUP_* values. If any errors are warnings are
8401 generated, set *DIAGNOSTIC_FN to "error" or "warning",
8402 respectively. If no diagnostics are generated, set *DIAGNOSTIC_FN
8403 to NULL. */
8404
8405 static tree
8406 build_temp (tree expr, tree type, int flags,
8407 diagnostic_t *diagnostic_kind, tsubst_flags_t complain)
8408 {
8409 int savew, savee;
8410
8411 *diagnostic_kind = DK_UNSPECIFIED;
8412
8413 /* If the source is a packed field, calling the copy constructor will require
8414 binding the field to the reference parameter to the copy constructor, and
8415 we'll end up with an infinite loop. If we can use a bitwise copy, then
8416 do that now. */
8417 if ((lvalue_kind (expr) & clk_packed)
8418 && CLASS_TYPE_P (TREE_TYPE (expr))
8419 && !type_has_nontrivial_copy_init (TREE_TYPE (expr)))
8420 return get_target_expr (expr, complain);
8421
8422 /* In decltype, we might have decided not to wrap this call in a TARGET_EXPR.
8423 But it turns out to be a subexpression, so perform temporary
8424 materialization now. */
8425 if (TREE_CODE (expr) == CALL_EXPR
8426 && CLASS_TYPE_P (type)
8427 && same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
8428 expr = build_cplus_new (type, expr, complain);
8429
8430 savew = warningcount + werrorcount, savee = errorcount;
8431 releasing_vec args (make_tree_vector_single (expr));
8432 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
8433 &args, type, flags, complain);
8434 if (warningcount + werrorcount > savew)
8435 *diagnostic_kind = DK_WARNING;
8436 else if (errorcount > savee)
8437 *diagnostic_kind = DK_ERROR;
8438 return expr;
8439 }
8440
8441 /* Get any location for EXPR, falling back to input_location.
8442
8443 If the result is in a system header and is the virtual location for
8444 a token coming from the expansion of a macro, unwind it to the
8445 location of the expansion point of the macro (e.g. to avoid the
8446 diagnostic being suppressed for expansions of NULL where "NULL" is
8447 in a system header). */
8448
8449 static location_t
8450 get_location_for_expr_unwinding_for_system_header (tree expr)
8451 {
8452 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
8453 loc = expansion_point_location_if_in_system_header (loc);
8454 return loc;
8455 }
8456
8457 /* Perform warnings about peculiar, but valid, conversions from/to NULL.
8458 Also handle a subset of zero as null warnings.
8459 EXPR is implicitly converted to type TOTYPE.
8460 FN and ARGNUM are used for diagnostics. */
8461
8462 static void
8463 conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
8464 {
8465 /* Issue warnings about peculiar, but valid, uses of NULL. */
8466 if (TREE_CODE (totype) != BOOLEAN_TYPE
8467 && ARITHMETIC_TYPE_P (totype)
8468 && null_node_p (expr))
8469 {
8470 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8471 if (fn)
8472 {
8473 auto_diagnostic_group d;
8474 if (warning_at (loc, OPT_Wconversion_null,
8475 "passing NULL to non-pointer argument %P of %qD",
8476 argnum, fn))
8477 inform (get_fndecl_argument_location (fn, argnum),
8478 "declared here");
8479 }
8480 else
8481 warning_at (loc, OPT_Wconversion_null,
8482 "converting to non-pointer type %qT from NULL", totype);
8483 }
8484
8485 /* Issue warnings if "false" is converted to a NULL pointer */
8486 else if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
8487 && TYPE_PTR_P (totype))
8488 {
8489 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8490 if (fn)
8491 {
8492 auto_diagnostic_group d;
8493 if (warning_at (loc, OPT_Wconversion_null,
8494 "converting %<false%> to pointer type for argument "
8495 "%P of %qD", argnum, fn))
8496 inform (get_fndecl_argument_location (fn, argnum),
8497 "declared here");
8498 }
8499 else
8500 warning_at (loc, OPT_Wconversion_null,
8501 "converting %<false%> to pointer type %qT", totype);
8502 }
8503 /* Handle zero as null pointer warnings for cases other
8504 than EQ_EXPR and NE_EXPR */
8505 else if ((TYPE_PTR_OR_PTRMEM_P (totype) || NULLPTR_TYPE_P (totype))
8506 && null_ptr_cst_p (expr))
8507 {
8508 location_t loc = get_location_for_expr_unwinding_for_system_header (expr);
8509 maybe_warn_zero_as_null_pointer_constant (expr, loc);
8510 }
8511 }
8512
8513 /* We gave a diagnostic during a conversion. If this was in the second
8514 standard conversion sequence of a user-defined conversion sequence, say
8515 which user-defined conversion. */
8516
8517 static void
8518 maybe_print_user_conv_context (conversion *convs)
8519 {
8520 if (convs->user_conv_p)
8521 for (conversion *t = convs; t; t = next_conversion (t))
8522 if (t->kind == ck_user)
8523 {
8524 print_z_candidate (0, N_(" after user-defined conversion:"),
8525 t->cand);
8526 break;
8527 }
8528 }
8529
8530 /* Locate the parameter with the given index within FNDECL.
8531 ARGNUM is zero based, -1 indicates the `this' argument of a method.
8532 Return the location of the FNDECL itself if there are problems. */
8533
8534 location_t
8535 get_fndecl_argument_location (tree fndecl, int argnum)
8536 {
8537 /* The locations of implicitly-declared functions are likely to be
8538 more meaningful than those of their parameters. */
8539 if (DECL_ARTIFICIAL (fndecl))
8540 return DECL_SOURCE_LOCATION (fndecl);
8541
8542 int i;
8543 tree param;
8544
8545 /* Locate param by index within DECL_ARGUMENTS (fndecl). */
8546 for (i = 0, param = FUNCTION_FIRST_USER_PARM (fndecl);
8547 i < argnum && param;
8548 i++, param = TREE_CHAIN (param))
8549 ;
8550
8551 /* If something went wrong (e.g. if we have a builtin and thus no arguments),
8552 return the location of FNDECL. */
8553 if (param == NULL)
8554 return DECL_SOURCE_LOCATION (fndecl);
8555
8556 return DECL_SOURCE_LOCATION (param);
8557 }
8558
8559 /* If FNDECL is non-NULL, issue a note highlighting ARGNUM
8560 within its declaration (or the fndecl itself if something went
8561 wrong). */
8562
8563 void
8564 maybe_inform_about_fndecl_for_bogus_argument_init (tree fn, int argnum,
8565 const char *highlight_color)
8566 {
8567 if (fn)
8568 {
8569 gcc_rich_location richloc (get_fndecl_argument_location (fn, argnum));
8570 richloc.set_highlight_color (highlight_color);
8571 inform (&richloc,
8572 "initializing argument %P of %qD", argnum, fn);
8573 }
8574 }
8575
8576 /* Maybe warn about C++20 Conversions to arrays of unknown bound. C is
8577 the conversion, EXPR is the expression we're converting. */
8578
8579 static void
8580 maybe_warn_array_conv (location_t loc, conversion *c, tree expr)
8581 {
8582 if (cxx_dialect >= cxx20)
8583 return;
8584
8585 tree type = TREE_TYPE (expr);
8586 type = strip_pointer_operator (type);
8587
8588 if (TREE_CODE (type) != ARRAY_TYPE
8589 || TYPE_DOMAIN (type) == NULL_TREE)
8590 return;
8591
8592 if (pedantic && conv_binds_to_array_of_unknown_bound (c))
8593 pedwarn (loc, OPT_Wc__20_extensions,
8594 "conversions to arrays of unknown bound "
8595 "are only available with %<-std=c++20%> or %<-std=gnu++20%>");
8596 }
8597
8598 /* We call this recursively in convert_like_internal. */
8599 static tree convert_like (conversion *, tree, tree, int, bool, bool, bool,
8600 tsubst_flags_t);
8601
8602 /* Adjust the result EXPR of a conversion to the expected type TOTYPE, which
8603 must be equivalent but might be a typedef. */
8604
8605 static tree
8606 maybe_adjust_type_name (tree type, tree expr, conversion_kind kind)
8607 {
8608 if (expr == error_mark_node
8609 || processing_template_decl)
8610 return expr;
8611
8612 tree etype = TREE_TYPE (expr);
8613 if (etype == type)
8614 return expr;
8615
8616 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p (etype, type)
8617 || is_bitfield_expr_with_lowered_type (expr)
8618 || seen_error ());
8619
8620 if (SCALAR_TYPE_P (type)
8621 && (kind == ck_rvalue
8622 /* ??? We should be able to do this for ck_identity of more prvalue
8623 expressions, but checking !obvalue_p here breaks, so for now let's
8624 just handle NON_LVALUE_EXPR (such as the location wrapper for a
8625 literal). Maybe we want to express already-rvalue in the
8626 conversion somehow? */
8627 || TREE_CODE (expr) == NON_LVALUE_EXPR))
8628 expr = build_nop (type, expr);
8629
8630 return expr;
8631 }
8632
8633 /* Perform the conversions in CONVS on the expression EXPR. FN and
8634 ARGNUM are used for diagnostics. ARGNUM is zero based, -1
8635 indicates the `this' argument of a method. INNER is nonzero when
8636 being called to continue a conversion chain. It is negative when a
8637 reference binding will be applied, positive otherwise. If
8638 ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
8639 conversions will be emitted if appropriate. If C_CAST_P is true,
8640 this conversion is coming from a C-style cast; in that case,
8641 conversions to inaccessible bases are permitted. */
8642
8643 static tree
8644 convert_like_internal (conversion *convs, tree expr, tree fn, int argnum,
8645 bool issue_conversion_warnings, bool c_cast_p,
8646 bool nested_p, tsubst_flags_t complain)
8647 {
8648 tree totype = convs->type;
8649 diagnostic_t diag_kind;
8650 int flags;
8651 location_t loc = cp_expr_loc_or_input_loc (expr);
8652
8653 if (convs->bad_p && !(complain & tf_error))
8654 return error_mark_node;
8655
8656 gcc_checking_assert (!TYPE_REF_P (TREE_TYPE (expr)));
8657
8658 if (convs->bad_p
8659 && convs->kind != ck_user
8660 && convs->kind != ck_list
8661 && convs->kind != ck_ambig
8662 && (convs->kind != ck_ref_bind
8663 || (convs->user_conv_p && next_conversion (convs)->bad_p))
8664 && (convs->kind != ck_rvalue
8665 || SCALAR_TYPE_P (totype))
8666 && convs->kind != ck_base)
8667 {
8668 int complained = 0;
8669 conversion *t = convs;
8670
8671 /* Give a helpful error if this is bad because of excess braces. */
8672 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8673 && SCALAR_TYPE_P (totype)
8674 && CONSTRUCTOR_NELTS (expr) > 0
8675 && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
8676 {
8677 complained = permerror (loc, "too many braces around initializer "
8678 "for %qT", totype);
8679 while (BRACE_ENCLOSED_INITIALIZER_P (expr)
8680 && CONSTRUCTOR_NELTS (expr) == 1)
8681 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8682 }
8683
8684 /* Give a helpful error if this is bad because a conversion to bool
8685 from std::nullptr_t requires direct-initialization. */
8686 if (NULLPTR_TYPE_P (TREE_TYPE (expr))
8687 && TREE_CODE (totype) == BOOLEAN_TYPE)
8688 complained = permerror (loc, "converting to %qH from %qI requires "
8689 "direct-initialization",
8690 totype, TREE_TYPE (expr));
8691
8692 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (expr))
8693 && SCALAR_FLOAT_TYPE_P (totype)
8694 && (extended_float_type_p (TREE_TYPE (expr))
8695 || extended_float_type_p (totype)))
8696 switch (cp_compare_floating_point_conversion_ranks (TREE_TYPE (expr),
8697 totype))
8698 {
8699 case 2:
8700 if (pedwarn (loc, OPT_Wnarrowing, "ISO C++ does not allow "
8701 "converting to %qH from %qI with greater "
8702 "conversion rank", totype, TREE_TYPE (expr)))
8703 complained = 1;
8704 else if (!complained)
8705 complained = -1;
8706 break;
8707 case 3:
8708 if (pedwarn (loc, OPT_Wnarrowing, "ISO C++ does not allow "
8709 "converting to %qH from %qI with unordered "
8710 "conversion rank", totype, TREE_TYPE (expr)))
8711 complained = 1;
8712 else if (!complained)
8713 complained = -1;
8714 break;
8715 default:
8716 break;
8717 }
8718
8719 for (; t ; t = next_conversion (t))
8720 {
8721 if (t->kind == ck_user && t->cand->reason)
8722 {
8723 auto_diagnostic_group d;
8724 complained = permerror (loc, "invalid user-defined conversion "
8725 "from %qH to %qI", TREE_TYPE (expr),
8726 totype);
8727 if (complained)
8728 print_z_candidate (loc, N_("candidate is:"), t->cand);
8729 expr = convert_like (t, expr, fn, argnum,
8730 /*issue_conversion_warnings=*/false,
8731 /*c_cast_p=*/false, /*nested_p=*/true,
8732 complain);
8733 break;
8734 }
8735 else if (t->kind == ck_user || !t->bad_p)
8736 {
8737 expr = convert_like (t, expr, fn, argnum,
8738 /*issue_conversion_warnings=*/false,
8739 /*c_cast_p=*/false, /*nested_p=*/true,
8740 complain);
8741 if (t->bad_p)
8742 complained = 1;
8743 break;
8744 }
8745 else if (t->kind == ck_ambig)
8746 return convert_like (t, expr, fn, argnum,
8747 /*issue_conversion_warnings=*/false,
8748 /*c_cast_p=*/false, /*nested_p=*/true,
8749 complain);
8750 else if (t->kind == ck_identity)
8751 break;
8752 }
8753 if (!complained && expr != error_mark_node)
8754 {
8755 range_label_for_type_mismatch label (TREE_TYPE (expr), totype);
8756 gcc_rich_location richloc (loc, &label, highlight_colors::percent_h);
8757 complained = permerror (&richloc,
8758 "invalid conversion from %qH to %qI",
8759 TREE_TYPE (expr), totype);
8760 if (complained)
8761 maybe_emit_indirection_note (loc, expr, totype);
8762 }
8763 if (convs->kind == ck_ref_bind)
8764 expr = convert_to_reference (totype, expr, CONV_IMPLICIT,
8765 LOOKUP_NORMAL, NULL_TREE,
8766 complain);
8767 else
8768 expr = cp_convert (totype, expr, complain);
8769 if (complained == 1)
8770 maybe_inform_about_fndecl_for_bogus_argument_init
8771 (fn, argnum, highlight_colors::percent_i);
8772 return expr;
8773 }
8774
8775 if (issue_conversion_warnings && (complain & tf_warning))
8776 conversion_null_warnings (totype, expr, fn, argnum);
8777
8778 switch (convs->kind)
8779 {
8780 case ck_user:
8781 {
8782 struct z_candidate *cand = convs->cand;
8783
8784 if (cand == NULL)
8785 /* We chose the surrogate function from add_conv_candidate, now we
8786 actually need to build the conversion. */
8787 cand = build_user_type_conversion_1 (totype, expr,
8788 LOOKUP_NO_CONVERSION, complain);
8789
8790 tree convfn = cand->fn;
8791
8792 /* When converting from an init list we consider explicit
8793 constructors, but actually trying to call one is an error. */
8794 if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn)
8795 && BRACE_ENCLOSED_INITIALIZER_P (expr)
8796 /* Unless this is for direct-list-initialization. */
8797 && (!CONSTRUCTOR_IS_DIRECT_INIT (expr) || convs->need_temporary_p)
8798 /* And in C++98 a default constructor can't be explicit. */
8799 && cxx_dialect >= cxx11)
8800 {
8801 if (!(complain & tf_error))
8802 return error_mark_node;
8803 location_t loc = location_of (expr);
8804 if (CONSTRUCTOR_NELTS (expr) == 0
8805 && FUNCTION_FIRST_USER_PARMTYPE (convfn) != void_list_node)
8806 {
8807 auto_diagnostic_group d;
8808 if (pedwarn (loc, 0, "converting to %qT from initializer list "
8809 "would use explicit constructor %qD",
8810 totype, convfn))
8811 {
8812 inform (DECL_SOURCE_LOCATION (convfn), "%qD declared here",
8813 convfn);
8814 inform (loc, "in C++11 and above a default constructor "
8815 "can be explicit");
8816 }
8817 }
8818 else
8819 {
8820 auto_diagnostic_group d;
8821 error ("converting to %qT from initializer list would use "
8822 "explicit constructor %qD", totype, convfn);
8823 inform (DECL_SOURCE_LOCATION (convfn), "%qD declared here",
8824 convfn);
8825 }
8826 }
8827
8828 /* If we're initializing from {}, it's value-initialization. */
8829 if (BRACE_ENCLOSED_INITIALIZER_P (expr)
8830 && CONSTRUCTOR_NELTS (expr) == 0
8831 && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype)
8832 && !processing_template_decl)
8833 {
8834 if (abstract_virtuals_error (NULL_TREE, totype, complain))
8835 return error_mark_node;
8836 expr = build_value_init (totype, complain);
8837 expr = get_target_expr (expr, complain);
8838 if (expr != error_mark_node)
8839 TARGET_EXPR_LIST_INIT_P (expr) = true;
8840 return expr;
8841 }
8842
8843 /* We don't know here whether EXPR is being used as an lvalue or
8844 rvalue, but we know it's read. */
8845 mark_exp_read (expr);
8846
8847 /* Give the conversion call the location of EXPR rather than the
8848 location of the context that caused the conversion. */
8849 iloc_sentinel ils (loc);
8850
8851 /* Pass LOOKUP_NO_CONVERSION so rvalue/base handling knows not to allow
8852 any more UDCs. */
8853 expr = build_over_call (cand, LOOKUP_NORMAL|LOOKUP_NO_CONVERSION,
8854 complain);
8855
8856 /* If this is a constructor or a function returning an aggr type,
8857 we need to build up a TARGET_EXPR. */
8858 if (DECL_CONSTRUCTOR_P (convfn))
8859 {
8860 expr = build_cplus_new (totype, expr, complain);
8861
8862 /* Remember that this was list-initialization. */
8863 if (convs->check_narrowing && expr != error_mark_node)
8864 TARGET_EXPR_LIST_INIT_P (expr) = true;
8865 }
8866
8867 return expr;
8868 }
8869 case ck_identity:
8870 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
8871 {
8872 int nelts = CONSTRUCTOR_NELTS (expr);
8873 if (nelts == 0)
8874 expr = build_value_init (totype, complain);
8875 else if (nelts == 1)
8876 expr = CONSTRUCTOR_ELT (expr, 0)->value;
8877 else
8878 gcc_unreachable ();
8879 }
8880 expr = mark_use (expr, /*rvalue_p=*/!convs->rvaluedness_matches_p,
8881 /*read_p=*/true, UNKNOWN_LOCATION,
8882 /*reject_builtin=*/true);
8883
8884 if (type_unknown_p (expr))
8885 expr = instantiate_type (totype, expr, complain);
8886 if (!nested_p && TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
8887 expr = cp_convert (totype, TREE_OPERAND (expr, 0), complain);
8888 if (expr == null_node
8889 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
8890 /* If __null has been converted to an integer type, we do not want to
8891 continue to warn about uses of EXPR as an integer, rather than as a
8892 pointer. */
8893 expr = build_int_cst (totype, 0);
8894 return maybe_adjust_type_name (totype, expr, convs->kind);
8895 case ck_ambig:
8896 /* We leave bad_p off ck_ambig because overload resolution considers
8897 it valid, it just fails when we try to perform it. So we need to
8898 check complain here, too. */
8899 if (complain & tf_error)
8900 {
8901 /* Call build_user_type_conversion again for the error. */
8902 int flags = (convs->need_temporary_p
8903 ? LOOKUP_IMPLICIT : LOOKUP_NORMAL);
8904 build_user_type_conversion (totype, convs->u.expr, flags, complain);
8905 gcc_assert (seen_error ());
8906 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
8907 }
8908 return error_mark_node;
8909
8910 case ck_list:
8911 {
8912 /* Conversion to std::initializer_list<T>. */
8913 tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
8914 unsigned HOST_WIDE_INT len = CONSTRUCTOR_NELTS (expr);
8915 tree array;
8916
8917 if (tree init = maybe_init_list_as_array (elttype, expr))
8918 {
8919 elttype
8920 = cp_build_qualified_type (elttype, (cp_type_quals (elttype)
8921 | TYPE_QUAL_CONST));
8922 tree index_type = TYPE_DOMAIN (TREE_TYPE (init));
8923 array = build_cplus_array_type (elttype, index_type);
8924 len = TREE_INT_CST_LOW (TYPE_MAX_VALUE (index_type)) + 1;
8925 array = build_vec_init_expr (array, init, complain);
8926 array = get_target_expr (array);
8927 array = cp_build_addr_expr (array, complain);
8928 }
8929 else if (len)
8930 {
8931 tree val;
8932 unsigned ix;
8933 tree new_ctor = build_constructor (init_list_type_node, NULL);
8934
8935 /* Convert all the elements. */
8936 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
8937 {
8938 if (TREE_CODE (val) == RAW_DATA_CST)
8939 {
8940 /* For conversion to initializer_list<unsigned char> or
8941 initializer_list<char> or initializer_list<signed char>
8942 we can optimize and keep RAW_DATA_CST with adjusted
8943 type if we report narrowing errors if needed, for
8944 others this converts each element separately. */
8945 if (convs->u.list[ix]->kind == ck_std)
8946 {
8947 tree et = convs->u.list[ix]->type;
8948 conversion *next = next_conversion (convs->u.list[ix]);
8949 gcc_assert (et
8950 && (TREE_CODE (et) == INTEGER_TYPE
8951 || is_byte_access_type (et))
8952 && TYPE_PRECISION (et) == CHAR_BIT
8953 && next
8954 && next->kind == ck_identity);
8955 if (!TYPE_UNSIGNED (et)
8956 /* For RAW_DATA_CST, TREE_TYPE (val) can be
8957 either integer_type_node (when it has been
8958 created by the lexer from CPP_EMBED) or
8959 after digestion/conversion some integral
8960 type with CHAR_BIT precision. For int with
8961 precision higher than CHAR_BIT or unsigned char
8962 diagnose narrowing conversions from
8963 that int/unsigned char to signed char if any
8964 byte has most significant bit set. */
8965 && (TYPE_UNSIGNED (TREE_TYPE (val))
8966 || (TYPE_PRECISION (TREE_TYPE (val))
8967 > CHAR_BIT)))
8968 for (int i = 0; i < RAW_DATA_LENGTH (val); ++i)
8969 {
8970 if (RAW_DATA_SCHAR_ELT (val, i) >= 0)
8971 continue;
8972 else if (complain & tf_error)
8973 {
8974 location_t loc
8975 = cp_expr_loc_or_input_loc (val);
8976 int savederrorcount = errorcount;
8977 permerror_opt (loc, OPT_Wnarrowing,
8978 "narrowing conversion of "
8979 "%qd from %qH to %qI",
8980 RAW_DATA_UCHAR_ELT (val, i),
8981 TREE_TYPE (val), et);
8982 if (errorcount != savederrorcount)
8983 return error_mark_node;
8984 }
8985 else
8986 return error_mark_node;
8987 }
8988 tree sub = copy_node (val);
8989 TREE_TYPE (sub) = et;
8990 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor),
8991 NULL_TREE, sub);
8992 }
8993 else
8994 {
8995 conversion *conv = convs->u.list[ix];
8996 gcc_assert (conv->kind == ck_list);
8997 for (int i = 0; i < RAW_DATA_LENGTH (val); ++i)
8998 {
8999 tree elt
9000 = build_int_cst (TREE_TYPE (val),
9001 RAW_DATA_UCHAR_ELT (val, i));
9002 tree sub
9003 = convert_like (conv->u.list[i], elt,
9004 fn, argnum, false, false,
9005 /*nested_p=*/true, complain);
9006 if (sub == error_mark_node)
9007 return sub;
9008 if (!check_narrowing (TREE_TYPE (sub), elt,
9009 complain))
9010 return error_mark_node;
9011 tree nc = new_ctor;
9012 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (nc),
9013 NULL_TREE, sub);
9014 if (!TREE_CONSTANT (sub))
9015 TREE_CONSTANT (new_ctor) = false;
9016 }
9017 }
9018 len += RAW_DATA_LENGTH (val) - 1;
9019 continue;
9020 }
9021 tree sub = convert_like (convs->u.list[ix], val, fn,
9022 argnum, false, false,
9023 /*nested_p=*/true, complain);
9024 if (sub == error_mark_node)
9025 return sub;
9026 if (!BRACE_ENCLOSED_INITIALIZER_P (val)
9027 && !check_narrowing (TREE_TYPE (sub), val, complain))
9028 return error_mark_node;
9029 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor),
9030 NULL_TREE, sub);
9031 if (!TREE_CONSTANT (sub))
9032 TREE_CONSTANT (new_ctor) = false;
9033 }
9034 /* Build up the array. */
9035 elttype
9036 = cp_build_qualified_type (elttype, (cp_type_quals (elttype)
9037 | TYPE_QUAL_CONST));
9038 array = build_array_of_n_type (elttype, len);
9039 array = finish_compound_literal (array, new_ctor, complain);
9040 /* This is dubious now, should be blessed by P2752. */
9041 DECL_MERGEABLE (TARGET_EXPR_SLOT (array)) = true;
9042 array = cp_build_addr_expr (array, complain);
9043 }
9044 else
9045 array = nullptr_node;
9046
9047 array = cp_convert (build_pointer_type (elttype), array, complain);
9048 if (array == error_mark_node)
9049 return error_mark_node;
9050
9051 /* Build up the initializer_list object. Note: fail gracefully
9052 if the object cannot be completed because, for example, no
9053 definition is provided (c++/80956). */
9054 totype = complete_type_or_maybe_complain (totype, NULL_TREE, complain);
9055 if (!totype)
9056 return error_mark_node;
9057 tree field = next_aggregate_field (TYPE_FIELDS (totype));
9058 vec<constructor_elt, va_gc> *vec = NULL;
9059 CONSTRUCTOR_APPEND_ELT (vec, field, array);
9060 field = next_aggregate_field (DECL_CHAIN (field));
9061 CONSTRUCTOR_APPEND_ELT (vec, field, size_int (len));
9062 tree new_ctor = build_constructor (totype, vec);
9063 return get_target_expr (new_ctor, complain);
9064 }
9065
9066 case ck_aggr:
9067 if (TREE_CODE (totype) == COMPLEX_TYPE)
9068 {
9069 tree real = CONSTRUCTOR_ELT (expr, 0)->value;
9070 tree imag = CONSTRUCTOR_ELT (expr, 1)->value;
9071 real = perform_implicit_conversion (TREE_TYPE (totype),
9072 real, complain);
9073 imag = perform_implicit_conversion (TREE_TYPE (totype),
9074 imag, complain);
9075 expr = build2 (COMPLEX_EXPR, totype, real, imag);
9076 return expr;
9077 }
9078 expr = reshape_init (totype, expr, complain);
9079 expr = get_target_expr (digest_init (totype, expr, complain),
9080 complain);
9081 if (expr != error_mark_node)
9082 TARGET_EXPR_LIST_INIT_P (expr) = true;
9083 return expr;
9084
9085 default:
9086 break;
9087 };
9088
9089 conversion *nc = next_conversion (convs);
9090 if (convs->kind == ck_ref_bind && nc->kind == ck_qual
9091 && !convs->need_temporary_p)
9092 /* direct_reference_binding might have inserted a ck_qual under
9093 this ck_ref_bind for the benefit of conversion sequence ranking.
9094 Don't actually perform that conversion. */
9095 nc = next_conversion (nc);
9096
9097 expr = convert_like (nc, expr, fn, argnum,
9098 convs->kind == ck_ref_bind
9099 ? issue_conversion_warnings : false,
9100 c_cast_p, /*nested_p=*/true, complain & ~tf_no_cleanup);
9101 if (expr == error_mark_node)
9102 return error_mark_node;
9103
9104 switch (convs->kind)
9105 {
9106 case ck_rvalue:
9107 expr = decay_conversion (expr, complain);
9108 if (expr == error_mark_node)
9109 {
9110 if (complain & tf_error)
9111 {
9112 auto_diagnostic_group d;
9113 maybe_print_user_conv_context (convs);
9114 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
9115 }
9116 return error_mark_node;
9117 }
9118
9119 if ((complain & tf_warning) && fn
9120 && warn_suggest_attribute_format)
9121 {
9122 tree rhstype = TREE_TYPE (expr);
9123 const enum tree_code coder = TREE_CODE (rhstype);
9124 const enum tree_code codel = TREE_CODE (totype);
9125 if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
9126 && coder == codel
9127 && check_missing_format_attribute (totype, rhstype))
9128 warning (OPT_Wsuggest_attribute_format,
9129 "argument of function call might be a candidate "
9130 "for a format attribute");
9131 }
9132
9133 if (! MAYBE_CLASS_TYPE_P (totype))
9134 return maybe_adjust_type_name (totype, expr, convs->kind);
9135
9136 /* Don't introduce copies when passing arguments along to the inherited
9137 constructor. */
9138 if (current_function_decl
9139 && flag_new_inheriting_ctors
9140 && DECL_INHERITED_CTOR (current_function_decl))
9141 return expr;
9142
9143 if (TREE_CODE (expr) == TARGET_EXPR
9144 && TARGET_EXPR_LIST_INIT_P (expr))
9145 /* Copy-list-initialization doesn't actually involve a copy. */
9146 return expr;
9147
9148 /* Fall through. */
9149 case ck_base:
9150 if (convs->kind == ck_base && !convs->need_temporary_p)
9151 {
9152 /* We are going to bind a reference directly to a base-class
9153 subobject of EXPR. */
9154 /* Build an expression for `*((base*) &expr)'. */
9155 expr = convert_to_base (expr, totype,
9156 !c_cast_p, /*nonnull=*/true, complain);
9157 return expr;
9158 }
9159
9160 /* Copy-initialization where the cv-unqualified version of the source
9161 type is the same class as, or a derived class of, the class of the
9162 destination [is treated as direct-initialization]. [dcl.init] */
9163 flags = LOOKUP_NORMAL;
9164 /* This conversion is being done in the context of a user-defined
9165 conversion (i.e. the second step of copy-initialization), so
9166 don't allow any more. */
9167 if (convs->user_conv_p)
9168 flags |= LOOKUP_NO_CONVERSION;
9169 /* We might be performing a conversion of the argument
9170 to the user-defined conversion, i.e., not a conversion of the
9171 result of the user-defined conversion. In which case we skip
9172 explicit constructors. */
9173 if (convs->copy_init_p)
9174 flags |= LOOKUP_ONLYCONVERTING;
9175 expr = build_temp (expr, totype, flags, &diag_kind, complain);
9176 if (diag_kind && complain)
9177 {
9178 auto_diagnostic_group d;
9179 maybe_print_user_conv_context (convs);
9180 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
9181 }
9182
9183 return build_cplus_new (totype, expr, complain);
9184
9185 case ck_ref_bind:
9186 {
9187 tree ref_type = totype;
9188
9189 if (convs->bad_p && !next_conversion (convs)->bad_p)
9190 {
9191 tree extype = TREE_TYPE (expr);
9192 auto_diagnostic_group d;
9193 if (TYPE_REF_IS_RVALUE (ref_type)
9194 && lvalue_p (expr))
9195 error_at (loc, "cannot bind rvalue reference of type %qH to "
9196 "lvalue of type %qI", totype, extype);
9197 else if (!TYPE_REF_IS_RVALUE (ref_type) && !lvalue_p (expr)
9198 && !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (ref_type)))
9199 {
9200 conversion *next = next_conversion (convs);
9201 if (next->kind == ck_std)
9202 {
9203 next = next_conversion (next);
9204 error_at (loc, "cannot bind non-const lvalue reference of "
9205 "type %qH to a value of type %qI",
9206 totype, next->type);
9207 }
9208 else if (!CP_TYPE_CONST_P (TREE_TYPE (ref_type)))
9209 error_at (loc, "cannot bind non-const lvalue reference of "
9210 "type %qH to an rvalue of type %qI", totype, extype);
9211 else // extype is volatile
9212 error_at (loc, "cannot bind lvalue reference of type "
9213 "%qH to an rvalue of type %qI", totype,
9214 extype);
9215 }
9216 else if (!reference_compatible_p (TREE_TYPE (totype), extype))
9217 {
9218 /* If we're converting from T[] to T[N], don't talk
9219 about discarding qualifiers. (Converting from T[N] to
9220 T[] is allowed by P0388R4.) */
9221 if (TREE_CODE (extype) == ARRAY_TYPE
9222 && TYPE_DOMAIN (extype) == NULL_TREE
9223 && TREE_CODE (TREE_TYPE (totype)) == ARRAY_TYPE
9224 && TYPE_DOMAIN (TREE_TYPE (totype)) != NULL_TREE)
9225 error_at (loc, "cannot bind reference of type %qH to %qI "
9226 "due to different array bounds", totype, extype);
9227 else
9228 error_at (loc, "binding reference of type %qH to %qI "
9229 "discards qualifiers", totype, extype);
9230 }
9231 else
9232 gcc_unreachable ();
9233 maybe_print_user_conv_context (convs);
9234 maybe_inform_about_fndecl_for_bogus_argument_init (fn, argnum);
9235
9236 return error_mark_node;
9237 }
9238 else if (complain & tf_warning)
9239 maybe_warn_array_conv (loc, convs, expr);
9240
9241 /* If necessary, create a temporary.
9242
9243 VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
9244 that need temporaries, even when their types are reference
9245 compatible with the type of reference being bound, so the
9246 upcoming call to cp_build_addr_expr doesn't fail. */
9247 if (convs->need_temporary_p
9248 || TREE_CODE (expr) == CONSTRUCTOR
9249 || TREE_CODE (expr) == VA_ARG_EXPR)
9250 {
9251 /* Otherwise, a temporary of type "cv1 T1" is created and
9252 initialized from the initializer expression using the rules
9253 for a non-reference copy-initialization (8.5). */
9254
9255 tree type = TREE_TYPE (ref_type);
9256 cp_lvalue_kind lvalue = lvalue_kind (expr);
9257
9258 gcc_assert (similar_type_p (type, next_conversion (convs)->type));
9259 if (!CP_TYPE_CONST_NON_VOLATILE_P (type)
9260 && !TYPE_REF_IS_RVALUE (ref_type))
9261 {
9262 /* If the reference is volatile or non-const, we
9263 cannot create a temporary. */
9264 if (complain & tf_error)
9265 {
9266 if (lvalue & clk_bitfield)
9267 error_at (loc, "cannot bind bit-field %qE to %qT",
9268 expr, ref_type);
9269 else if (lvalue & clk_packed)
9270 error_at (loc, "cannot bind packed field %qE to %qT",
9271 expr, ref_type);
9272 else
9273 error_at (loc, "cannot bind rvalue %qE to %qT",
9274 expr, ref_type);
9275 }
9276 return error_mark_node;
9277 }
9278 /* If the source is a packed field, and we must use a copy
9279 constructor, then building the target expr will require
9280 binding the field to the reference parameter to the
9281 copy constructor, and we'll end up with an infinite
9282 loop. If we can use a bitwise copy, then we'll be
9283 OK. */
9284 if ((lvalue & clk_packed)
9285 && CLASS_TYPE_P (type)
9286 && type_has_nontrivial_copy_init (type))
9287 {
9288 error_at (loc, "cannot bind packed field %qE to %qT",
9289 expr, ref_type);
9290 return error_mark_node;
9291 }
9292 if (lvalue & clk_bitfield)
9293 {
9294 expr = convert_bitfield_to_declared_type (expr);
9295 expr = fold_convert (type, expr);
9296 }
9297
9298 /* Creating &TARGET_EXPR<> in a template would break when
9299 tsubsting the expression, so use an IMPLICIT_CONV_EXPR
9300 instead. This can happen even when there's no class
9301 involved, e.g., when converting an integer to a reference
9302 type. */
9303 if (processing_template_decl)
9304 return build1 (IMPLICIT_CONV_EXPR, totype, expr);
9305 expr = build_target_expr_with_type (expr, type, complain);
9306 }
9307
9308 /* Take the address of the thing to which we will bind the
9309 reference. */
9310 expr = cp_build_addr_expr (expr, complain);
9311 if (expr == error_mark_node)
9312 return error_mark_node;
9313
9314 /* Convert it to a pointer to the type referred to by the
9315 reference. This will adjust the pointer if a derived to
9316 base conversion is being performed. */
9317 expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
9318 expr, complain);
9319 /* Convert the pointer to the desired reference type. */
9320 return build_nop (ref_type, expr);
9321 }
9322
9323 case ck_lvalue:
9324 return decay_conversion (expr, complain);
9325
9326 case ck_fnptr:
9327 /* ??? Should the address of a transaction-safe pointer point to the TM
9328 clone, and this conversion look up the primary function? */
9329 return build_nop (totype, expr);
9330
9331 case ck_qual:
9332 /* Warn about deprecated conversion if appropriate. */
9333 if (complain & tf_warning)
9334 {
9335 string_conv_p (totype, expr, 1);
9336 maybe_warn_array_conv (loc, convs, expr);
9337 }
9338 break;
9339
9340 case ck_ptr:
9341 if (convs->base_p)
9342 expr = convert_to_base (expr, totype, !c_cast_p,
9343 /*nonnull=*/false, complain);
9344 return build_nop (totype, expr);
9345
9346 case ck_pmem:
9347 return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
9348 c_cast_p, complain);
9349
9350 default:
9351 break;
9352 }
9353
9354 if (convs->check_narrowing
9355 && !check_narrowing (totype, expr, complain,
9356 convs->check_narrowing_const_only))
9357 return error_mark_node;
9358
9359 warning_sentinel w (warn_zero_as_null_pointer_constant);
9360 if (issue_conversion_warnings)
9361 expr = cp_convert_and_check (totype, expr, complain);
9362 else
9363 {
9364 if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
9365 expr = TREE_OPERAND (expr, 0);
9366 expr = cp_convert (totype, expr, complain);
9367 }
9368
9369 return expr;
9370 }
9371
9372 /* Return true if converting FROM to TO is unsafe in a template. */
9373
9374 static bool
9375 conv_unsafe_in_template_p (tree to, tree from)
9376 {
9377 /* Converting classes involves TARGET_EXPR. */
9378 if (CLASS_TYPE_P (to) || CLASS_TYPE_P (from))
9379 return true;
9380
9381 /* Converting real to integer produces FIX_TRUNC_EXPR which tsubst
9382 doesn't handle. */
9383 if (SCALAR_FLOAT_TYPE_P (from) && INTEGRAL_OR_ENUMERATION_TYPE_P (to))
9384 return true;
9385
9386 /* Converting integer to real isn't a trivial conversion, either. */
9387 if (INTEGRAL_OR_ENUMERATION_TYPE_P (from) && SCALAR_FLOAT_TYPE_P (to))
9388 return true;
9389
9390 return false;
9391 }
9392
9393 /* Wrapper for convert_like_internal that handles creating
9394 IMPLICIT_CONV_EXPR. */
9395
9396 static tree
9397 convert_like (conversion *convs, tree expr, tree fn, int argnum,
9398 bool issue_conversion_warnings, bool c_cast_p, bool nested_p,
9399 tsubst_flags_t complain)
9400 {
9401 /* Creating &TARGET_EXPR<> in a template breaks when substituting,
9402 and creating a CALL_EXPR in a template breaks in finish_call_expr
9403 so use an IMPLICIT_CONV_EXPR for this conversion. We would have
9404 created such codes e.g. when calling a user-defined conversion
9405 function. */
9406 tree conv_expr = NULL_TREE;
9407 if (processing_template_decl
9408 && convs->kind != ck_identity
9409 && conv_unsafe_in_template_p (convs->type, TREE_TYPE (expr)))
9410 {
9411 conv_expr = build1 (IMPLICIT_CONV_EXPR, convs->type, expr);
9412 if (convs->kind != ck_ref_bind)
9413 conv_expr = convert_from_reference (conv_expr);
9414 if (!convs->bad_p)
9415 return conv_expr;
9416 /* Do the normal processing to give the bad_p errors. But we still
9417 need to return the IMPLICIT_CONV_EXPR, unless we're returning
9418 error_mark_node. */
9419 }
9420 expr = convert_like_internal (convs, expr, fn, argnum,
9421 issue_conversion_warnings, c_cast_p,
9422 nested_p, complain);
9423 if (expr == error_mark_node)
9424 return error_mark_node;
9425 return conv_expr ? conv_expr : expr;
9426 }
9427
9428 /* Convenience wrapper for convert_like. */
9429
9430 static inline tree
9431 convert_like (conversion *convs, tree expr, tsubst_flags_t complain)
9432 {
9433 return convert_like (convs, expr, NULL_TREE, 0,
9434 /*issue_conversion_warnings=*/true,
9435 /*c_cast_p=*/false, /*nested_p=*/false, complain);
9436 }
9437
9438 /* Convenience wrapper for convert_like. */
9439
9440 static inline tree
9441 convert_like_with_context (conversion *convs, tree expr, tree fn, int argnum,
9442 tsubst_flags_t complain)
9443 {
9444 return convert_like (convs, expr, fn, argnum,
9445 /*issue_conversion_warnings=*/true,
9446 /*c_cast_p=*/false, /*nested_p=*/false, complain);
9447 }
9448
9449 /* ARG is being passed to a varargs function. Perform any conversions
9450 required. Return the converted value. */
9451
9452 tree
9453 convert_arg_to_ellipsis (tree arg, tsubst_flags_t complain)
9454 {
9455 tree arg_type = TREE_TYPE (arg);
9456 location_t loc = cp_expr_loc_or_input_loc (arg);
9457
9458 /* [expr.call]
9459
9460 If the argument has integral or enumeration type that is subject
9461 to the integral promotions (_conv.prom_), or a floating-point
9462 type that is subject to the floating-point promotion
9463 (_conv.fpprom_), the value of the argument is converted to the
9464 promoted type before the call. */
9465 if (SCALAR_FLOAT_TYPE_P (arg_type)
9466 && (TYPE_PRECISION (arg_type)
9467 < TYPE_PRECISION (double_type_node))
9468 && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (arg_type))
9469 && !extended_float_type_p (arg_type))
9470 {
9471 if ((complain & tf_warning)
9472 && warn_double_promotion && !c_inhibit_evaluation_warnings)
9473 warning_at (loc, OPT_Wdouble_promotion,
9474 "implicit conversion from %qH to %qI when passing "
9475 "argument to function",
9476 arg_type, double_type_node);
9477 if (TREE_CODE (arg) == EXCESS_PRECISION_EXPR)
9478 arg = TREE_OPERAND (arg, 0);
9479 arg = mark_rvalue_use (arg);
9480 arg = convert_to_real_nofold (double_type_node, arg);
9481 }
9482 else if (NULLPTR_TYPE_P (arg_type))
9483 {
9484 arg = mark_rvalue_use (arg);
9485 if (TREE_SIDE_EFFECTS (arg))
9486 {
9487 warning_sentinel w(warn_unused_result);
9488 arg = cp_build_compound_expr (arg, null_pointer_node, complain);
9489 }
9490 else
9491 arg = null_pointer_node;
9492 }
9493 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (arg_type))
9494 {
9495 if (SCOPED_ENUM_P (arg_type))
9496 {
9497 tree prom = cp_convert (ENUM_UNDERLYING_TYPE (arg_type), arg,
9498 complain);
9499 prom = cp_perform_integral_promotions (prom, complain);
9500 if (abi_version_crosses (6)
9501 && TYPE_MODE (TREE_TYPE (prom)) != TYPE_MODE (arg_type)
9502 && (complain & tf_warning))
9503 warning_at (loc, OPT_Wabi, "scoped enum %qT passed through %<...%>"
9504 " as %qT before %<-fabi-version=6%>, %qT after",
9505 arg_type,
9506 TREE_TYPE (prom), ENUM_UNDERLYING_TYPE (arg_type));
9507 if (!abi_version_at_least (6))
9508 arg = prom;
9509 }
9510 else
9511 arg = cp_perform_integral_promotions (arg, complain);
9512 }
9513 else
9514 /* [expr.call]
9515
9516 The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
9517 standard conversions are performed. */
9518 arg = decay_conversion (arg, complain);
9519
9520 arg = require_complete_type (arg, complain);
9521 arg_type = TREE_TYPE (arg);
9522
9523 if (arg != error_mark_node
9524 /* In a template (or ill-formed code), we can have an incomplete type
9525 even after require_complete_type, in which case we don't know
9526 whether it has trivial copy or not. */
9527 && COMPLETE_TYPE_P (arg_type)
9528 && !cp_unevaluated_operand)
9529 {
9530 /* [expr.call] 5.2.2/7:
9531 Passing a potentially-evaluated argument of class type (Clause 9)
9532 with a non-trivial copy constructor or a non-trivial destructor
9533 with no corresponding parameter is conditionally-supported, with
9534 implementation-defined semantics.
9535
9536 We support it as pass-by-invisible-reference, just like a normal
9537 value parameter.
9538
9539 If the call appears in the context of a sizeof expression,
9540 it is not potentially-evaluated. */
9541 if (type_has_nontrivial_copy_init (arg_type)
9542 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (arg_type))
9543 {
9544 arg = force_rvalue (arg, complain);
9545 if (complain & tf_warning)
9546 warning (OPT_Wconditionally_supported,
9547 "passing objects of non-trivially-copyable "
9548 "type %q#T through %<...%> is conditionally supported",
9549 arg_type);
9550 return build1 (ADDR_EXPR, build_reference_type (arg_type), arg);
9551 }
9552 /* Build up a real lvalue-to-rvalue conversion in case the
9553 copy constructor is trivial but not callable. */
9554 else if (CLASS_TYPE_P (arg_type))
9555 force_rvalue (arg, complain);
9556
9557 }
9558
9559 return arg;
9560 }
9561
9562 /* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused. */
9563
9564 tree
9565 build_x_va_arg (location_t loc, tree expr, tree type)
9566 {
9567 if (processing_template_decl)
9568 {
9569 tree r = build_min (VA_ARG_EXPR, type, expr);
9570 SET_EXPR_LOCATION (r, loc);
9571 return r;
9572 }
9573
9574 type = complete_type_or_else (type, NULL_TREE);
9575
9576 if (expr == error_mark_node || !type)
9577 return error_mark_node;
9578
9579 expr = mark_lvalue_use (expr);
9580
9581 if (TYPE_REF_P (type))
9582 {
9583 error ("cannot receive reference type %qT through %<...%>", type);
9584 return error_mark_node;
9585 }
9586
9587 if (type_has_nontrivial_copy_init (type)
9588 || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
9589 {
9590 /* conditionally-supported behavior [expr.call] 5.2.2/7. Let's treat
9591 it as pass by invisible reference. */
9592 warning_at (loc, OPT_Wconditionally_supported,
9593 "receiving objects of non-trivially-copyable type %q#T "
9594 "through %<...%> is conditionally-supported", type);
9595
9596 tree ref = cp_build_reference_type (type, false);
9597 expr = build_va_arg (loc, expr, ref);
9598 return convert_from_reference (expr);
9599 }
9600
9601 tree ret = build_va_arg (loc, expr, type);
9602 if (CLASS_TYPE_P (type))
9603 /* Wrap the VA_ARG_EXPR in a TARGET_EXPR now so other code doesn't need to
9604 know how to handle it. */
9605 ret = get_target_expr (ret);
9606 return ret;
9607 }
9608
9609 /* TYPE has been given to va_arg. Apply the default conversions which
9610 would have happened when passed via ellipsis. Return the promoted
9611 type, or the passed type if there is no change. */
9612
9613 tree
9614 cxx_type_promotes_to (tree type)
9615 {
9616 tree promote;
9617
9618 /* Perform the array-to-pointer and function-to-pointer
9619 conversions. */
9620 type = type_decays_to (type);
9621
9622 promote = type_promotes_to (type);
9623 if (same_type_p (type, promote))
9624 promote = type;
9625
9626 return promote;
9627 }
9628
9629 /* ARG is a default argument expression being passed to a parameter of
9630 the indicated TYPE, which is a parameter to FN. PARMNUM is the
9631 zero-based argument number. Do any required conversions. Return
9632 the converted value. */
9633
9634 static GTY(()) vec<tree, va_gc> *default_arg_context;
9635 void
9636 push_defarg_context (tree fn)
9637 { vec_safe_push (default_arg_context, fn); }
9638
9639 void
9640 pop_defarg_context (void)
9641 { default_arg_context->pop (); }
9642
9643 tree
9644 convert_default_arg (tree type, tree arg, tree fn, int parmnum,
9645 tsubst_flags_t complain)
9646 {
9647 int i;
9648 tree t;
9649
9650 /* See through clones. */
9651 fn = DECL_ORIGIN (fn);
9652 /* And inheriting ctors. */
9653 if (flag_new_inheriting_ctors)
9654 fn = strip_inheriting_ctors (fn);
9655
9656 /* Detect recursion. */
9657 FOR_EACH_VEC_SAFE_ELT (default_arg_context, i, t)
9658 if (t == fn)
9659 {
9660 if (complain & tf_error)
9661 error ("recursive evaluation of default argument for %q#D", fn);
9662 return error_mark_node;
9663 }
9664
9665 /* If the ARG is an unparsed default argument expression, the
9666 conversion cannot be performed. */
9667 if (TREE_CODE (arg) == DEFERRED_PARSE)
9668 {
9669 if (complain & tf_error)
9670 error ("call to %qD uses the default argument for parameter %P, which "
9671 "is not yet defined", fn, parmnum);
9672 return error_mark_node;
9673 }
9674
9675 push_defarg_context (fn);
9676
9677 if (fn && DECL_TEMPLATE_INFO (fn))
9678 arg = tsubst_default_argument (fn, parmnum, type, arg, complain);
9679
9680 /* Due to:
9681
9682 [dcl.fct.default]
9683
9684 The names in the expression are bound, and the semantic
9685 constraints are checked, at the point where the default
9686 expressions appears.
9687
9688 we must not perform access checks here. */
9689 push_deferring_access_checks (dk_no_check);
9690 /* We must make a copy of ARG, in case subsequent processing
9691 alters any part of it. */
9692 arg = break_out_target_exprs (arg, /*clear location*/true);
9693
9694 arg = convert_for_initialization (0, type, arg, LOOKUP_IMPLICIT,
9695 ICR_DEFAULT_ARGUMENT, fn, parmnum,
9696 complain);
9697 arg = convert_for_arg_passing (type, arg, complain);
9698 pop_deferring_access_checks();
9699
9700 pop_defarg_context ();
9701
9702 return arg;
9703 }
9704
9705 /* Returns the type which will really be used for passing an argument of
9706 type TYPE. */
9707
9708 tree
9709 type_passed_as (tree type)
9710 {
9711 /* Pass classes with copy ctors by invisible reference. */
9712 if (TREE_ADDRESSABLE (type))
9713 type = build_reference_type (type);
9714 else if (targetm.calls.promote_prototypes (NULL_TREE)
9715 && INTEGRAL_TYPE_P (type)
9716 && COMPLETE_TYPE_P (type)
9717 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9718 type = integer_type_node;
9719
9720 return type;
9721 }
9722
9723 /* Actually perform the appropriate conversion. */
9724
9725 tree
9726 convert_for_arg_passing (tree type, tree val, tsubst_flags_t complain)
9727 {
9728 tree bitfield_type;
9729
9730 /* If VAL is a bitfield, then -- since it has already been converted
9731 to TYPE -- it cannot have a precision greater than TYPE.
9732
9733 If it has a smaller precision, we must widen it here. For
9734 example, passing "int f:3;" to a function expecting an "int" will
9735 not result in any conversion before this point.
9736
9737 If the precision is the same we must not risk widening. For
9738 example, the COMPONENT_REF for a 32-bit "long long" bitfield will
9739 often have type "int", even though the C++ type for the field is
9740 "long long". If the value is being passed to a function
9741 expecting an "int", then no conversions will be required. But,
9742 if we call convert_bitfield_to_declared_type, the bitfield will
9743 be converted to "long long". */
9744 bitfield_type = is_bitfield_expr_with_lowered_type (val);
9745 if (bitfield_type
9746 && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
9747 val = convert_to_integer_nofold (TYPE_MAIN_VARIANT (bitfield_type), val);
9748
9749 if (val == error_mark_node)
9750 ;
9751 /* Pass classes with copy ctors by invisible reference. */
9752 else if (TREE_ADDRESSABLE (type))
9753 val = build1 (ADDR_EXPR, build_reference_type (type), val);
9754 else if (targetm.calls.promote_prototypes (NULL_TREE)
9755 && INTEGRAL_TYPE_P (type)
9756 && COMPLETE_TYPE_P (type)
9757 && tree_int_cst_lt (TYPE_SIZE (type), TYPE_SIZE (integer_type_node)))
9758 val = cp_perform_integral_promotions (val, complain);
9759 if (complain & tf_warning)
9760 maybe_warn_parm_abi (type, cp_expr_loc_or_input_loc (val));
9761
9762 if (complain & tf_warning)
9763 warn_for_address_of_packed_member (type, val);
9764
9765 /* gimplify_arg elides TARGET_EXPRs that initialize a function argument,
9766 unless the initializer is a CONSTRUCTOR. In that case, we fail to
9767 elide the copy anyway. See that function for more information. */
9768 if (SIMPLE_TARGET_EXPR_P (val)
9769 && TREE_CODE (TARGET_EXPR_INITIAL (val)) != CONSTRUCTOR)
9770 set_target_expr_eliding (val);
9771
9772 return val;
9773 }
9774
9775 /* Returns non-zero iff FN is a function with magic varargs, i.e. ones for
9776 which just decay_conversion or no conversions at all should be done.
9777 This is true for some builtins which don't act like normal functions.
9778 Return 2 if just decay_conversion and removal of excess precision should
9779 be done, 1 if just decay_conversion. Return 3 for special treatment of
9780 the 3rd argument for __builtin_*_overflow_p. Return 4 for special
9781 treatment of the 1st argument for
9782 __builtin_{clz,ctz,clrsb,ffs,parity,popcount}g. */
9783
9784 int
9785 magic_varargs_p (tree fn)
9786 {
9787 if (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
9788 switch (DECL_FUNCTION_CODE (fn))
9789 {
9790 case BUILT_IN_CLASSIFY_TYPE:
9791 case BUILT_IN_CONSTANT_P:
9792 case BUILT_IN_NEXT_ARG:
9793 case BUILT_IN_VA_START:
9794 return 1;
9795
9796 case BUILT_IN_ADD_OVERFLOW_P:
9797 case BUILT_IN_SUB_OVERFLOW_P:
9798 case BUILT_IN_MUL_OVERFLOW_P:
9799 return 3;
9800
9801 case BUILT_IN_ISFINITE:
9802 case BUILT_IN_ISINF:
9803 case BUILT_IN_ISINF_SIGN:
9804 case BUILT_IN_ISNAN:
9805 case BUILT_IN_ISNORMAL:
9806 case BUILT_IN_FPCLASSIFY:
9807 return 2;
9808
9809 case BUILT_IN_CLZG:
9810 case BUILT_IN_CTZG:
9811 case BUILT_IN_CLRSBG:
9812 case BUILT_IN_FFSG:
9813 case BUILT_IN_PARITYG:
9814 case BUILT_IN_POPCOUNTG:
9815 return 4;
9816
9817 default:
9818 return lookup_attribute ("type generic",
9819 TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
9820 }
9821
9822 return 0;
9823 }
9824
9825 /* Returns the decl of the dispatcher function if FN is a function version. */
9826
9827 tree
9828 get_function_version_dispatcher (tree fn)
9829 {
9830 tree dispatcher_decl = NULL;
9831
9832 if (DECL_LOCAL_DECL_P (fn))
9833 fn = DECL_LOCAL_DECL_ALIAS (fn);
9834
9835 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
9836 && DECL_FUNCTION_VERSIONED (fn));
9837
9838 gcc_assert (targetm.get_function_versions_dispatcher);
9839 dispatcher_decl = targetm.get_function_versions_dispatcher (fn);
9840
9841 if (dispatcher_decl == NULL)
9842 {
9843 error_at (input_location, "use of multiversioned function "
9844 "without a default");
9845 return NULL;
9846 }
9847
9848 retrofit_lang_decl (dispatcher_decl);
9849 gcc_assert (dispatcher_decl != NULL);
9850 return dispatcher_decl;
9851 }
9852
9853 /* fn is a function version dispatcher that is marked used. Mark all the
9854 semantically identical function versions it will dispatch as used. */
9855
9856 void
9857 mark_versions_used (tree fn)
9858 {
9859 struct cgraph_node *node;
9860 struct cgraph_function_version_info *node_v;
9861 struct cgraph_function_version_info *it_v;
9862
9863 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
9864
9865 node = cgraph_node::get (fn);
9866 if (node == NULL)
9867 return;
9868
9869 gcc_assert (node->dispatcher_function);
9870
9871 node_v = node->function_version ();
9872 if (node_v == NULL)
9873 return;
9874
9875 /* All semantically identical versions are chained. Traverse and mark each
9876 one of them as used. */
9877 it_v = node_v->next;
9878 while (it_v != NULL)
9879 {
9880 mark_used (it_v->this_node->decl);
9881 it_v = it_v->next;
9882 }
9883 }
9884
9885 /* Build a call to "the copy constructor" for the type of A, even if it
9886 wouldn't be selected by normal overload resolution. Used for
9887 diagnostics. */
9888
9889 static tree
9890 call_copy_ctor (tree a, tsubst_flags_t complain)
9891 {
9892 tree ctype = TYPE_MAIN_VARIANT (TREE_TYPE (a));
9893 tree binfo = TYPE_BINFO (ctype);
9894 tree copy = get_copy_ctor (ctype, complain);
9895 copy = build_baselink (binfo, binfo, copy, NULL_TREE);
9896 tree ob = build_dummy_object (ctype);
9897 releasing_vec args (make_tree_vector_single (a));
9898 tree r = build_new_method_call (ob, copy, &args, NULL_TREE,
9899 LOOKUP_NORMAL, NULL, complain);
9900 return r;
9901 }
9902
9903 /* Return the base constructor corresponding to COMPLETE_CTOR or NULL_TREE. */
9904
9905 static tree
9906 base_ctor_for (tree complete_ctor)
9907 {
9908 tree clone;
9909 FOR_EACH_CLONE (clone, DECL_CLONED_FUNCTION (complete_ctor))
9910 if (DECL_BASE_CONSTRUCTOR_P (clone))
9911 return clone;
9912 return NULL_TREE;
9913 }
9914
9915 /* Try to make EXP suitable to be used as the initializer for a base subobject,
9916 and return whether we were successful. EXP must have already been cleared
9917 by unsafe_copy_elision_p{,_opt}. */
9918
9919 static bool
9920 make_base_init_ok (tree exp)
9921 {
9922 if (TREE_CODE (exp) == TARGET_EXPR)
9923 exp = TARGET_EXPR_INITIAL (exp);
9924 while (TREE_CODE (exp) == COMPOUND_EXPR)
9925 exp = TREE_OPERAND (exp, 1);
9926 if (TREE_CODE (exp) == COND_EXPR)
9927 {
9928 bool ret = make_base_init_ok (TREE_OPERAND (exp, 2));
9929 if (tree op1 = TREE_OPERAND (exp, 1))
9930 {
9931 bool r1 = make_base_init_ok (op1);
9932 /* If unsafe_copy_elision_p was false, the arms should match. */
9933 gcc_assert (r1 == ret);
9934 }
9935 return ret;
9936 }
9937 if (TREE_CODE (exp) != AGGR_INIT_EXPR)
9938 /* A trivial copy is OK. */
9939 return true;
9940 if (!AGGR_INIT_VIA_CTOR_P (exp))
9941 /* unsafe_copy_elision_p_opt must have said this is OK. */
9942 return true;
9943 tree fn = cp_get_callee_fndecl_nofold (exp);
9944 if (DECL_BASE_CONSTRUCTOR_P (fn))
9945 return true;
9946 gcc_assert (DECL_COMPLETE_CONSTRUCTOR_P (fn));
9947 fn = base_ctor_for (fn);
9948 if (!fn || DECL_HAS_VTT_PARM_P (fn))
9949 /* The base constructor has more parameters, so we can't just change the
9950 call target. It would be possible to splice in the appropriate
9951 arguments, but probably not worth the complexity. */
9952 return false;
9953 mark_used (fn);
9954 AGGR_INIT_EXPR_FN (exp) = build_address (fn);
9955 return true;
9956 }
9957
9958 /* Return 2 if T refers to a base, 1 if a potentially-overlapping field,
9959 neither of which can be used for return by invisible reference. We avoid
9960 doing C++17 mandatory copy elision for either of these cases.
9961
9962 This returns non-zero even if the type of T has no tail padding that other
9963 data could be allocated into, because that depends on the particular ABI.
9964 unsafe_copy_elision_p_opt does consider whether there is padding. */
9965
9966 int
9967 unsafe_return_slot_p (tree t)
9968 {
9969 /* Check empty bases separately, they don't have fields. */
9970 if (is_empty_base_ref (t))
9971 return 2;
9972
9973 /* A delegating constructor might be used to initialize a base. */
9974 if (current_function_decl
9975 && DECL_CONSTRUCTOR_P (current_function_decl)
9976 && (t == current_class_ref
9977 || tree_strip_nop_conversions (t) == current_class_ptr))
9978 return 2;
9979
9980 STRIP_NOPS (t);
9981 if (TREE_CODE (t) == ADDR_EXPR)
9982 t = TREE_OPERAND (t, 0);
9983 if (TREE_CODE (t) == COMPONENT_REF)
9984 t = TREE_OPERAND (t, 1);
9985 if (TREE_CODE (t) != FIELD_DECL)
9986 return false;
9987 if (!CLASS_TYPE_P (TREE_TYPE (t)))
9988 /* The middle-end will do the right thing for scalar types. */
9989 return false;
9990 if (DECL_FIELD_IS_BASE (t))
9991 return 2;
9992 if (lookup_attribute ("no_unique_address", DECL_ATTRIBUTES (t)))
9993 return 1;
9994 return 0;
9995 }
9996
9997 /* True IFF EXP is a prvalue that represents return by invisible reference. */
9998
9999 static bool
10000 init_by_return_slot_p (tree exp)
10001 {
10002 /* Copy elision only happens with a TARGET_EXPR. */
10003 if (TREE_CODE (exp) != TARGET_EXPR)
10004 return false;
10005 tree init = TARGET_EXPR_INITIAL (exp);
10006 /* build_compound_expr pushes COMPOUND_EXPR inside TARGET_EXPR. */
10007 while (TREE_CODE (init) == COMPOUND_EXPR)
10008 init = TREE_OPERAND (init, 1);
10009 if (TREE_CODE (init) == COND_EXPR)
10010 {
10011 /* We'll end up copying from each of the arms of the COND_EXPR directly
10012 into the target, so look at them. */
10013 if (tree op = TREE_OPERAND (init, 1))
10014 if (init_by_return_slot_p (op))
10015 return true;
10016 return init_by_return_slot_p (TREE_OPERAND (init, 2));
10017 }
10018 return (TREE_CODE (init) == AGGR_INIT_EXPR
10019 && !AGGR_INIT_VIA_CTOR_P (init));
10020 }
10021
10022 /* We can't elide a copy from a function returning by value to a
10023 potentially-overlapping subobject, as the callee might clobber tail padding.
10024 Return true iff this could be that case.
10025
10026 Places that use this function (or _opt) to decide to elide a copy should
10027 probably use make_safe_copy_elision instead. */
10028
10029 bool
10030 unsafe_copy_elision_p (tree target, tree exp)
10031 {
10032 return unsafe_return_slot_p (target) && init_by_return_slot_p (exp);
10033 }
10034
10035 /* As above, but for optimization allow more cases that are actually safe. */
10036
10037 static bool
10038 unsafe_copy_elision_p_opt (tree target, tree exp)
10039 {
10040 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (exp));
10041 /* It's safe to elide the copy for a class with no tail padding. */
10042 if (!is_empty_class (type)
10043 && tree_int_cst_equal (TYPE_SIZE (type), CLASSTYPE_SIZE (type)))
10044 return false;
10045 return unsafe_copy_elision_p (target, exp);
10046 }
10047
10048 /* Try to make EXP suitable to be used as the initializer for TARGET,
10049 and return whether we were successful. */
10050
10051 bool
10052 make_safe_copy_elision (tree target, tree exp)
10053 {
10054 int uns = unsafe_return_slot_p (target);
10055 if (!uns)
10056 return true;
10057 if (init_by_return_slot_p (exp))
10058 return false;
10059 if (uns == 1)
10060 return true;
10061 return make_base_init_ok (exp);
10062 }
10063
10064 /* True IFF the result of the conversion C is a prvalue. */
10065
10066 static bool
10067 conv_is_prvalue (conversion *c)
10068 {
10069 if (c->kind == ck_rvalue)
10070 return true;
10071 if (c->kind == ck_base && c->need_temporary_p)
10072 return true;
10073 if (c->kind == ck_user && !TYPE_REF_P (c->type))
10074 return true;
10075 if (c->kind == ck_identity && c->u.expr
10076 && TREE_CODE (c->u.expr) == TARGET_EXPR)
10077 return true;
10078
10079 return false;
10080 }
10081
10082 /* True iff C is a conversion that binds a reference to a prvalue. */
10083
10084 static bool
10085 conv_binds_ref_to_prvalue (conversion *c)
10086 {
10087 if (c->kind != ck_ref_bind)
10088 return false;
10089 if (c->need_temporary_p)
10090 return true;
10091
10092 return conv_is_prvalue (next_conversion (c));
10093 }
10094
10095 /* True iff EXPR represents a (subobject of a) temporary. */
10096
10097 static bool
10098 expr_represents_temporary_p (tree expr)
10099 {
10100 while (handled_component_p (expr))
10101 expr = TREE_OPERAND (expr, 0);
10102 return TREE_CODE (expr) == TARGET_EXPR;
10103 }
10104
10105 /* True iff C is a conversion that binds a reference to a temporary.
10106 This is a superset of conv_binds_ref_to_prvalue: here we're also
10107 interested in xvalues. */
10108
10109 static bool
10110 conv_binds_ref_to_temporary (conversion *c)
10111 {
10112 if (conv_binds_ref_to_prvalue (c))
10113 return true;
10114 if (c->kind != ck_ref_bind)
10115 return false;
10116 c = next_conversion (c);
10117 /* This is the case for
10118 struct Base {};
10119 struct Derived : Base {};
10120 const Base& b(Derived{});
10121 where we bind 'b' to the Base subobject of a temporary object of type
10122 Derived. The subobject is an xvalue; the whole object is a prvalue.
10123
10124 The ck_base doesn't have to be present for cases like X{}.m. */
10125 if (c->kind == ck_base)
10126 c = next_conversion (c);
10127 if (c->kind == ck_identity && c->u.expr
10128 && expr_represents_temporary_p (c->u.expr))
10129 return true;
10130 return false;
10131 }
10132
10133 /* Return tristate::TS_TRUE if converting EXPR to a reference type TYPE binds
10134 the reference to a temporary. Return tristate::TS_FALSE if converting
10135 EXPR to a reference type TYPE doesn't bind the reference to a temporary. If
10136 the conversion is invalid or bad, return tristate::TS_UNKNOWN. DIRECT_INIT_P
10137 says whether the conversion should be done in direct- or copy-initialization
10138 context. */
10139
10140 tristate
10141 ref_conv_binds_to_temporary (tree type, tree expr, bool direct_init_p/*=false*/)
10142 {
10143 gcc_assert (TYPE_REF_P (type));
10144
10145 conversion_obstack_sentinel cos;
10146
10147 const int flags = direct_init_p ? LOOKUP_NORMAL : LOOKUP_IMPLICIT;
10148 conversion *conv = implicit_conversion (type, TREE_TYPE (expr), expr,
10149 /*c_cast_p=*/false, flags, tf_none);
10150 if (!conv || conv->bad_p)
10151 return tristate::unknown ();
10152
10153 if (conv_binds_ref_to_temporary (conv))
10154 {
10155 /* Actually perform the conversion to check access control. */
10156 if (convert_like (conv, expr, tf_none) != error_mark_node)
10157 return tristate (true);
10158 else
10159 return tristate::unknown ();
10160 }
10161
10162 return tristate (false);
10163 }
10164
10165 /* Call the trivial destructor for INSTANCE, which can be either an lvalue of
10166 class type or a pointer to class type. If NO_PTR_DEREF is true and
10167 INSTANCE has pointer type, clobber the pointer rather than what it points
10168 to. */
10169
10170 tree
10171 build_trivial_dtor_call (tree instance, bool no_ptr_deref)
10172 {
10173 gcc_assert (!is_dummy_object (instance));
10174
10175 if (!flag_lifetime_dse)
10176 {
10177 no_clobber:
10178 return fold_convert (void_type_node, instance);
10179 }
10180
10181 if (INDIRECT_TYPE_P (TREE_TYPE (instance))
10182 && (!no_ptr_deref || TYPE_REF_P (TREE_TYPE (instance))))
10183 {
10184 if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (instance))))
10185 goto no_clobber;
10186 instance = cp_build_fold_indirect_ref (instance);
10187 }
10188
10189 /* A trivial destructor should still clobber the object. */
10190 tree clobber = build_clobber (TREE_TYPE (instance), CLOBBER_OBJECT_END);
10191 return build2 (MODIFY_EXPR, void_type_node,
10192 instance, clobber);
10193 }
10194
10195 /* Return true if in an immediate function context, or an unevaluated operand,
10196 or a default argument/member initializer, or a subexpression of an immediate
10197 invocation. */
10198
10199 bool
10200 in_immediate_context ()
10201 {
10202 return (cp_unevaluated_operand != 0
10203 || (current_function_decl != NULL_TREE
10204 && DECL_IMMEDIATE_FUNCTION_P (current_function_decl))
10205 /* DR 2631: default args and DMI aren't immediately evaluated.
10206 Return true here so immediate_invocation_p returns false. */
10207 || current_binding_level->kind == sk_function_parms
10208 || current_binding_level->kind == sk_template_parms
10209 || parsing_nsdmi ()
10210 || in_consteval_if_p);
10211 }
10212
10213 /* Return true if a call to FN with number of arguments NARGS
10214 is an immediate invocation. */
10215
10216 bool
10217 immediate_invocation_p (tree fn)
10218 {
10219 return (TREE_CODE (fn) == FUNCTION_DECL
10220 && DECL_IMMEDIATE_FUNCTION_P (fn)
10221 && !in_immediate_context ());
10222 }
10223
10224 /* Subroutine of the various build_*_call functions. Overload resolution
10225 has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
10226 ARGS is a TREE_LIST of the unconverted arguments to the call. FLAGS is a
10227 bitmask of various LOOKUP_* flags which apply to the call itself. */
10228
10229 static tree
10230 build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
10231 {
10232 tree fn = cand->fn;
10233 const vec<tree, va_gc> *args = cand->args;
10234 tree first_arg = cand->first_arg;
10235 conversion **convs = cand->convs;
10236 tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
10237 int parmlen;
10238 tree val;
10239 int nargs;
10240 tree *argarray;
10241 bool already_used = false;
10242
10243 /* In a template, there is no need to perform all of the work that
10244 is normally done. We are only interested in the type of the call
10245 expression, i.e., the return type of the function. Any semantic
10246 errors will be deferred until the template is instantiated. */
10247 if (processing_template_decl)
10248 {
10249 if (undeduced_auto_decl (fn))
10250 mark_used (fn, complain);
10251 else
10252 /* Otherwise set TREE_USED for the benefit of -Wunused-function.
10253 See PR80598. */
10254 TREE_USED (fn) = 1;
10255
10256 tree return_type = TREE_TYPE (TREE_TYPE (fn));
10257 tree callee;
10258 if (first_arg == NULL_TREE)
10259 {
10260 callee = build_addr_func (fn, complain);
10261 if (callee == error_mark_node)
10262 return error_mark_node;
10263 }
10264 else
10265 {
10266 callee = build_baselink (cand->conversion_path, cand->access_path,
10267 fn, NULL_TREE);
10268 callee = build_min (COMPONENT_REF, TREE_TYPE (fn),
10269 first_arg, callee, NULL_TREE);
10270 }
10271
10272 tree expr = build_call_vec (return_type, callee, args);
10273 SET_EXPR_LOCATION (expr, input_location);
10274 if (TREE_THIS_VOLATILE (fn) && cfun)
10275 current_function_returns_abnormally = 1;
10276 if (TREE_DEPRECATED (fn)
10277 && warning_suppressed_at (input_location,
10278 OPT_Wdeprecated_declarations))
10279 /* Make the expr consistent with the location. */
10280 TREE_NO_WARNING (expr) = true;
10281 if (immediate_invocation_p (fn))
10282 {
10283 tree obj_arg = NULL_TREE;
10284 if (DECL_CONSTRUCTOR_P (fn))
10285 obj_arg = first_arg;
10286 /* Look through *(const T *)&obj. */
10287 if (obj_arg && INDIRECT_REF_P (obj_arg))
10288 {
10289 tree addr = TREE_OPERAND (obj_arg, 0);
10290 STRIP_NOPS (addr);
10291 if (TREE_CODE (addr) == ADDR_EXPR)
10292 {
10293 tree typeo = TREE_TYPE (obj_arg);
10294 tree typei = TREE_TYPE (TREE_OPERAND (addr, 0));
10295 if (same_type_ignoring_top_level_qualifiers_p (typeo, typei))
10296 obj_arg = TREE_OPERAND (addr, 0);
10297 }
10298 }
10299 fold_non_dependent_expr (expr, complain,
10300 /*manifestly_const_eval=*/true,
10301 obj_arg);
10302 }
10303 return convert_from_reference (expr);
10304 }
10305
10306 /* Give any warnings we noticed during overload resolution. */
10307 if (cand->warnings && (complain & tf_warning))
10308 {
10309 struct candidate_warning *w;
10310 for (w = cand->warnings; w; w = w->next)
10311 joust (cand, w->loser, 1, complain);
10312 }
10313
10314 /* Core issue 2327: P0135 doesn't say how to handle the case where the
10315 argument to the copy constructor ends up being a prvalue after
10316 conversion. Let's do the normal processing, but pretend we aren't
10317 actually using the copy constructor. */
10318 bool force_elide = false;
10319 if (cxx_dialect >= cxx17
10320 && cand->num_convs == 1
10321 && DECL_COMPLETE_CONSTRUCTOR_P (fn)
10322 && (DECL_COPY_CONSTRUCTOR_P (fn)
10323 || DECL_MOVE_CONSTRUCTOR_P (fn))
10324 && !unsafe_return_slot_p (first_arg)
10325 && conv_binds_ref_to_prvalue (convs[0]))
10326 {
10327 force_elide = true;
10328 goto not_really_used;
10329 }
10330
10331 /* OK, we're actually calling this inherited constructor; set its deletedness
10332 appropriately. We can get away with doing this here because calling is
10333 the only way to refer to a constructor. */
10334 if (DECL_INHERITED_CTOR (fn)
10335 && !deduce_inheriting_ctor (fn))
10336 {
10337 if (complain & tf_error)
10338 mark_used (fn);
10339 return error_mark_node;
10340 }
10341
10342 /* Make =delete work with SFINAE. */
10343 if (DECL_DELETED_FN (fn))
10344 {
10345 if (complain & tf_error)
10346 {
10347 mark_used (fn);
10348 if (cand->next)
10349 {
10350 if (flag_diagnostics_all_candidates)
10351 print_z_candidates (input_location, cand, /*only_viable_p=*/false);
10352 else
10353 inform (input_location,
10354 "use %<-fdiagnostics-all-candidates%> to display "
10355 "considered candidates");
10356 }
10357 }
10358 return error_mark_node;
10359 }
10360
10361 if (DECL_FUNCTION_MEMBER_P (fn))
10362 {
10363 tree access_fn;
10364 /* If FN is a template function, two cases must be considered.
10365 For example:
10366
10367 struct A {
10368 protected:
10369 template <class T> void f();
10370 };
10371 template <class T> struct B {
10372 protected:
10373 void g();
10374 };
10375 struct C : A, B<int> {
10376 using A::f; // #1
10377 using B<int>::g; // #2
10378 };
10379
10380 In case #1 where `A::f' is a member template, DECL_ACCESS is
10381 recorded in the primary template but not in its specialization.
10382 We check access of FN using its primary template.
10383
10384 In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
10385 because it is a member of class template B, DECL_ACCESS is
10386 recorded in the specialization `B<int>::g'. We cannot use its
10387 primary template because `B<T>::g' and `B<int>::g' may have
10388 different access. */
10389 if (DECL_TEMPLATE_INFO (fn)
10390 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
10391 access_fn = DECL_TI_TEMPLATE (fn);
10392 else
10393 access_fn = fn;
10394 if (!perform_or_defer_access_check (cand->access_path, access_fn,
10395 fn, complain))
10396 return error_mark_node;
10397 }
10398
10399 /* If we're checking for implicit delete, don't bother with argument
10400 conversions. */
10401 if (flags & LOOKUP_SPECULATIVE)
10402 {
10403 if (cand->viable == 1)
10404 return fn;
10405 else if (!(complain & tf_error))
10406 /* Reject bad conversions now. */
10407 return error_mark_node;
10408 /* else continue to get conversion error. */
10409 }
10410
10411 not_really_used:
10412
10413 /* N3276 magic doesn't apply to nested calls. */
10414 tsubst_flags_t decltype_flag = (complain & tf_decltype);
10415 complain &= ~tf_decltype;
10416 /* No-Cleanup doesn't apply to nested calls either. */
10417 tsubst_flags_t no_cleanup_complain = complain;
10418 complain &= ~tf_no_cleanup;
10419
10420 /* Find maximum size of vector to hold converted arguments. */
10421 parmlen = list_length (parm);
10422 nargs = vec_safe_length (args) + (first_arg != NULL_TREE ? 1 : 0);
10423 if (parmlen > nargs)
10424 nargs = parmlen;
10425 argarray = XALLOCAVEC (tree, nargs);
10426
10427 in_consteval_if_p_temp_override icip;
10428 /* If the call is immediate function invocation, make sure
10429 taking address of immediate functions is allowed in its arguments. */
10430 if (immediate_invocation_p (STRIP_TEMPLATE (fn)))
10431 in_consteval_if_p = true;
10432
10433 int argarray_size = 0;
10434 unsigned int arg_index = 0;
10435 int conv_index = 0;
10436 int param_index = 0;
10437
10438 auto consume_object_arg = [&arg_index, &first_arg, args]()
10439 {
10440 if (!first_arg)
10441 return (*args)[arg_index++];
10442 tree object_arg = first_arg;
10443 first_arg = NULL_TREE;
10444 return object_arg;
10445 };
10446
10447 /* The implicit parameters to a constructor are not considered by overload
10448 resolution, and must be of the proper type. */
10449 if (DECL_CONSTRUCTOR_P (fn))
10450 {
10451 tree object_arg = consume_object_arg ();
10452 argarray[argarray_size++] = build_this (object_arg);
10453 parm = TREE_CHAIN (parm);
10454 /* We should never try to call the abstract constructor. */
10455 gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
10456
10457 if (DECL_HAS_VTT_PARM_P (fn))
10458 {
10459 argarray[argarray_size++] = (*args)[arg_index];
10460 ++arg_index;
10461 parm = TREE_CHAIN (parm);
10462 }
10463 }
10464 /* Bypass access control for 'this' parameter. */
10465 else if (DECL_IOBJ_MEMBER_FUNCTION_P (fn))
10466 {
10467 tree arg = build_this (consume_object_arg ());
10468 tree argtype = TREE_TYPE (arg);
10469
10470 if (arg == error_mark_node)
10471 return error_mark_node;
10472 if (convs[conv_index++]->bad_p)
10473 {
10474 if (complain & tf_error)
10475 {
10476 auto_diagnostic_group d;
10477 if (permerror (input_location, "passing %qT as %<this%> "
10478 "argument discards qualifiers",
10479 TREE_TYPE (argtype)))
10480 inform (DECL_SOURCE_LOCATION (fn), " in call to %qD", fn);
10481 }
10482 else
10483 return error_mark_node;
10484 }
10485
10486 /* The class where FN is defined. */
10487 tree ctx = DECL_CONTEXT (fn);
10488
10489 /* See if the function member or the whole class type is declared
10490 final and the call can be devirtualized. */
10491 if (DECL_FINAL_P (fn) || CLASSTYPE_FINAL (ctx))
10492 flags |= LOOKUP_NONVIRTUAL;
10493
10494 /* [class.mfct.non-static]: If a non-static member function of a class
10495 X is called for an object that is not of type X, or of a type
10496 derived from X, the behavior is undefined.
10497
10498 So we can assume that anything passed as 'this' is non-null, and
10499 optimize accordingly. */
10500 /* Check that the base class is accessible. */
10501 if (!accessible_base_p (TREE_TYPE (argtype),
10502 BINFO_TYPE (cand->conversion_path), true))
10503 {
10504 if (complain & tf_error)
10505 error ("%qT is not an accessible base of %qT",
10506 BINFO_TYPE (cand->conversion_path),
10507 TREE_TYPE (argtype));
10508 else
10509 return error_mark_node;
10510 }
10511 /* If fn was found by a using declaration, the conversion path
10512 will be to the derived class, not the base declaring fn. We
10513 must convert to the base. */
10514 tree base_binfo = cand->conversion_path;
10515 if (BINFO_TYPE (base_binfo) != ctx)
10516 {
10517 base_binfo = lookup_base (base_binfo, ctx, ba_unique, NULL, complain);
10518 if (base_binfo == error_mark_node)
10519 return error_mark_node;
10520 }
10521
10522 /* If we know the dynamic type of the object, look up the final overrider
10523 in the BINFO. */
10524 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0
10525 && resolves_to_fixed_type_p (arg))
10526 {
10527 tree ov = lookup_vfn_in_binfo (DECL_VINDEX (fn), base_binfo);
10528
10529 /* And unwind base_binfo to match. If we don't find the type we're
10530 looking for in BINFO_INHERITANCE_CHAIN, we're looking at diamond
10531 inheritance; for now do a normal virtual call in that case. */
10532 tree octx = DECL_CONTEXT (ov);
10533 tree obinfo = base_binfo;
10534 while (obinfo && !SAME_BINFO_TYPE_P (BINFO_TYPE (obinfo), octx))
10535 obinfo = BINFO_INHERITANCE_CHAIN (obinfo);
10536 if (obinfo)
10537 {
10538 fn = ov;
10539 base_binfo = obinfo;
10540 flags |= LOOKUP_NONVIRTUAL;
10541 }
10542 }
10543
10544 tree converted_arg = build_base_path (PLUS_EXPR, arg,
10545 base_binfo, 1, complain);
10546
10547 argarray[argarray_size++] = converted_arg;
10548 parm = TREE_CHAIN (parm);
10549 }
10550
10551 auto handle_arg = [fn, flags](tree type,
10552 tree arg,
10553 int const param_index,
10554 conversion *conv,
10555 tsubst_flags_t const arg_complain)
10556 {
10557 /* Set user_conv_p on the argument conversions, so rvalue/base handling
10558 knows not to allow any more UDCs. This needs to happen after we
10559 process cand->warnings. */
10560 if (flags & LOOKUP_NO_CONVERSION)
10561 conv->user_conv_p = true;
10562
10563 if (arg_complain & tf_warning)
10564 maybe_warn_pessimizing_move (arg, type, /*return_p=*/false);
10565
10566 tree val = convert_like_with_context (conv, arg, fn,
10567 param_index, arg_complain);
10568 val = convert_for_arg_passing (type, val, arg_complain);
10569 return val;
10570 };
10571
10572 if (DECL_XOBJ_MEMBER_FUNCTION_P (fn))
10573 {
10574 gcc_assert (cand->num_convs > 0);
10575 tree object_arg = consume_object_arg ();
10576 val = handle_arg (TREE_VALUE (parm),
10577 object_arg,
10578 param_index++,
10579 convs[conv_index++],
10580 complain);
10581
10582 if (val == error_mark_node)
10583 return error_mark_node;
10584 else
10585 argarray[argarray_size++] = val;
10586 parm = TREE_CHAIN (parm);
10587 }
10588
10589 gcc_assert (first_arg == NULL_TREE);
10590 for (; arg_index < vec_safe_length (args) && parm;
10591 parm = TREE_CHAIN (parm), ++arg_index, ++param_index, ++conv_index)
10592 {
10593 tree current_arg = (*args)[arg_index];
10594
10595 /* If the argument is NULL and used to (implicitly) instantiate a
10596 template function (and bind one of the template arguments to
10597 the type of 'long int'), we don't want to warn about passing NULL
10598 to non-pointer argument.
10599 For example, if we have this template function:
10600
10601 template<typename T> void func(T x) {}
10602
10603 we want to warn (when -Wconversion is enabled) in this case:
10604
10605 void foo() {
10606 func<int>(NULL);
10607 }
10608
10609 but not in this case:
10610
10611 void foo() {
10612 func(NULL);
10613 }
10614 */
10615 bool const conversion_warning = !(null_node_p (current_arg)
10616 && DECL_TEMPLATE_INFO (fn)
10617 && cand->template_decl
10618 && !cand->explicit_targs);
10619
10620 tsubst_flags_t const arg_complain
10621 = conversion_warning ? complain : complain & ~tf_warning;
10622
10623 val = handle_arg (TREE_VALUE (parm),
10624 current_arg,
10625 param_index,
10626 convs[conv_index],
10627 arg_complain);
10628
10629 if (val == error_mark_node)
10630 return error_mark_node;
10631 else
10632 argarray[argarray_size++] = val;
10633 }
10634
10635 /* Default arguments */
10636 for (; parm && parm != void_list_node;
10637 parm = TREE_CHAIN (parm), param_index++)
10638 {
10639 if (TREE_VALUE (parm) == error_mark_node)
10640 return error_mark_node;
10641 val = convert_default_arg (TREE_VALUE (parm),
10642 TREE_PURPOSE (parm),
10643 fn, param_index,
10644 complain);
10645 if (val == error_mark_node)
10646 return error_mark_node;
10647 argarray[argarray_size++] = val;
10648 }
10649
10650 /* Ellipsis */
10651 int magic = magic_varargs_p (fn);
10652 for (; arg_index < vec_safe_length (args); ++arg_index)
10653 {
10654 tree a = (*args)[arg_index];
10655 if ((magic == 3 && arg_index == 2) || (magic == 4 && arg_index == 0))
10656 {
10657 /* Do no conversions for certain magic varargs. */
10658 a = mark_type_use (a);
10659 if (TREE_CODE (a) == FUNCTION_DECL && reject_gcc_builtin (a))
10660 return error_mark_node;
10661 }
10662 else if (magic != 0)
10663 {
10664 /* Don't truncate excess precision to the semantic type. */
10665 if (magic == 1 && TREE_CODE (a) == EXCESS_PRECISION_EXPR)
10666 a = TREE_OPERAND (a, 0);
10667 /* For other magic varargs only do decay_conversion. */
10668 a = decay_conversion (a, complain);
10669 }
10670 else if (DECL_CONSTRUCTOR_P (fn)
10671 && vec_safe_length (args) == 1
10672 && same_type_ignoring_top_level_qualifiers_p (DECL_CONTEXT (fn),
10673 TREE_TYPE (a)))
10674 {
10675 /* Avoid infinite recursion trying to call A(...). */
10676 if (complain & tf_error)
10677 /* Try to call the actual copy constructor for a good error. */
10678 call_copy_ctor (a, complain);
10679 return error_mark_node;
10680 }
10681 else
10682 a = convert_arg_to_ellipsis (a, complain);
10683 if (a == error_mark_node)
10684 return error_mark_node;
10685 argarray[argarray_size++] = a;
10686 }
10687
10688 gcc_assert (argarray_size <= nargs);
10689 nargs = argarray_size;
10690 icip.reset ();
10691
10692 /* Avoid performing argument transformation if warnings are disabled.
10693 When tf_warning is set and at least one of the warnings is active
10694 the check_function_arguments function might warn about something. */
10695
10696 bool warned_p = false;
10697 if ((complain & tf_warning)
10698 && (warn_nonnull
10699 || warn_format
10700 || warn_suggest_attribute_format
10701 || warn_restrict))
10702 {
10703 tree *fargs = (!nargs ? argarray
10704 : (tree *) alloca (nargs * sizeof (tree)));
10705 for (int j = 0; j < nargs; j++)
10706 {
10707 /* For -Wformat undo the implicit passing by hidden reference
10708 done by convert_arg_to_ellipsis. */
10709 if (TREE_CODE (argarray[j]) == ADDR_EXPR
10710 && TYPE_REF_P (TREE_TYPE (argarray[j])))
10711 fargs[j] = TREE_OPERAND (argarray[j], 0);
10712 else
10713 fargs[j] = argarray[j];
10714 }
10715
10716 warned_p = check_function_arguments (input_location, fn, TREE_TYPE (fn),
10717 nargs, fargs, NULL,
10718 cp_comp_parm_types);
10719 }
10720
10721 if (DECL_INHERITED_CTOR (fn))
10722 {
10723 /* Check for passing ellipsis arguments to an inherited constructor. We
10724 could handle this by open-coding the inherited constructor rather than
10725 defining it, but let's not bother now. */
10726 if (!cp_unevaluated_operand
10727 && cand->num_convs
10728 && cand->convs[cand->num_convs-1]->ellipsis_p)
10729 {
10730 if (complain & tf_error)
10731 {
10732 sorry ("passing arguments to ellipsis of inherited constructor "
10733 "%qD", cand->fn);
10734 inform (DECL_SOURCE_LOCATION (cand->fn), "declared here");
10735 }
10736 return error_mark_node;
10737 }
10738
10739 /* A base constructor inheriting from a virtual base doesn't get the
10740 inherited arguments, just this and __vtt. */
10741 if (ctor_omit_inherited_parms (fn))
10742 nargs = 2;
10743 }
10744
10745 /* Avoid actually calling copy constructors and copy assignment operators,
10746 if possible. */
10747
10748 if (!force_elide
10749 && (!flag_elide_constructors
10750 /* It's unsafe to elide the operation when handling
10751 a noexcept-expression, it may evaluate to the wrong
10752 value (c++/53025, c++/96090). */
10753 || cp_noexcept_operand != 0))
10754 /* Do things the hard way. */;
10755 else if (cand->num_convs == 1
10756 && (DECL_COPY_CONSTRUCTOR_P (fn)
10757 || DECL_MOVE_CONSTRUCTOR_P (fn)))
10758 {
10759 tree targ;
10760 tree arg = argarray[num_artificial_parms_for (fn)];
10761 tree fa = argarray[0];
10762 bool trivial = trivial_fn_p (fn);
10763
10764 /* Pull out the real argument, disregarding const-correctness. */
10765 targ = arg;
10766 /* Strip the reference binding for the constructor parameter. */
10767 if (CONVERT_EXPR_P (targ)
10768 && TYPE_REF_P (TREE_TYPE (targ)))
10769 targ = TREE_OPERAND (targ, 0);
10770 /* But don't strip any other reference bindings; binding a temporary to a
10771 reference prevents copy elision. */
10772 while ((CONVERT_EXPR_P (targ)
10773 && !TYPE_REF_P (TREE_TYPE (targ)))
10774 || TREE_CODE (targ) == NON_LVALUE_EXPR)
10775 targ = TREE_OPERAND (targ, 0);
10776 if (TREE_CODE (targ) == ADDR_EXPR)
10777 {
10778 targ = TREE_OPERAND (targ, 0);
10779 if (!same_type_ignoring_top_level_qualifiers_p
10780 (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
10781 targ = NULL_TREE;
10782 }
10783 else
10784 targ = NULL_TREE;
10785
10786 if (targ)
10787 arg = targ;
10788 else
10789 arg = cp_build_fold_indirect_ref (arg);
10790
10791 /* In C++17 we shouldn't be copying a TARGET_EXPR except into a
10792 potentially-overlapping subobject. */
10793 if (CHECKING_P && cxx_dialect >= cxx17)
10794 gcc_assert (TREE_CODE (arg) != TARGET_EXPR
10795 || force_elide
10796 /* It's from binding the ref parm to a packed field. */
10797 || convs[0]->need_temporary_p
10798 || seen_error ()
10799 /* See unsafe_copy_elision_p. */
10800 || unsafe_return_slot_p (fa));
10801
10802 bool unsafe = unsafe_copy_elision_p_opt (fa, arg);
10803 bool eliding_temp = (TREE_CODE (arg) == TARGET_EXPR && !unsafe);
10804
10805 /* [class.copy]: the copy constructor is implicitly defined even if the
10806 implementation elided its use. But don't warn about deprecation when
10807 eliding a temporary, as then no copy is actually performed. */
10808 warning_sentinel s (warn_deprecated_copy, eliding_temp);
10809 if (force_elide)
10810 /* The language says this isn't called. */;
10811 else if (!trivial)
10812 {
10813 if (!mark_used (fn, complain) && !(complain & tf_error))
10814 return error_mark_node;
10815 already_used = true;
10816 }
10817 else
10818 cp_handle_deprecated_or_unavailable (fn, complain);
10819
10820 if (eliding_temp && DECL_BASE_CONSTRUCTOR_P (fn)
10821 && !make_base_init_ok (arg))
10822 unsafe = true;
10823
10824 /* If we're creating a temp and we already have one, don't create a
10825 new one. If we're not creating a temp but we get one, use
10826 INIT_EXPR to collapse the temp into our target. Otherwise, if the
10827 ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
10828 temp or an INIT_EXPR otherwise. */
10829 if (is_dummy_object (fa))
10830 {
10831 if (TREE_CODE (arg) == TARGET_EXPR)
10832 return arg;
10833 else if (trivial)
10834 return force_target_expr (DECL_CONTEXT (fn), arg, complain);
10835 }
10836 else if ((trivial || TREE_CODE (arg) == TARGET_EXPR)
10837 && !unsafe)
10838 {
10839 tree to = cp_build_fold_indirect_ref (fa);
10840 val = cp_build_init_expr (to, arg);
10841 return val;
10842 }
10843 }
10844 else if (DECL_ASSIGNMENT_OPERATOR_P (fn)
10845 && DECL_OVERLOADED_OPERATOR_IS (fn, NOP_EXPR)
10846 && trivial_fn_p (fn))
10847 {
10848 tree to = cp_build_fold_indirect_ref (argarray[0]);
10849 tree type = TREE_TYPE (to);
10850 tree as_base = CLASSTYPE_AS_BASE (type);
10851 tree arg = argarray[1];
10852 location_t loc = cp_expr_loc_or_input_loc (arg);
10853
10854 if (is_really_empty_class (type, /*ignore_vptr*/true))
10855 {
10856 /* Avoid copying empty classes, but ensure op= returns an lvalue even
10857 if the object argument isn't one. */
10858 to = force_lvalue (to, complain);
10859 val = build2 (COMPOUND_EXPR, type, arg, to);
10860 suppress_warning (val, OPT_Wunused);
10861 }
10862 else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
10863 {
10864 if (is_std_init_list (type)
10865 && conv_binds_ref_to_prvalue (convs[1]))
10866 warning_at (loc, OPT_Winit_list_lifetime,
10867 "assignment from temporary %<initializer_list%> does "
10868 "not extend the lifetime of the underlying array");
10869 arg = cp_build_fold_indirect_ref (arg);
10870 val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
10871 }
10872 else
10873 {
10874 /* We must only copy the non-tail padding parts. */
10875 tree arg0, arg2, t;
10876 tree array_type, alias_set;
10877
10878 arg2 = TYPE_SIZE_UNIT (as_base);
10879 /* Ensure op= returns an lvalue even if the object argument isn't
10880 one. */
10881 to = force_lvalue (to, complain);
10882 to = cp_stabilize_reference (to);
10883 arg0 = cp_build_addr_expr (to, complain);
10884
10885 array_type = build_array_type (unsigned_char_type_node,
10886 build_index_type
10887 (size_binop (MINUS_EXPR,
10888 arg2, size_int (1))));
10889 alias_set = build_int_cst (build_pointer_type (type), 0);
10890 t = build2 (MODIFY_EXPR, void_type_node,
10891 build2 (MEM_REF, array_type, arg0, alias_set),
10892 build2 (MEM_REF, array_type, arg, alias_set));
10893 val = build2 (COMPOUND_EXPR, TREE_TYPE (to), t, to);
10894 suppress_warning (val, OPT_Wunused);
10895 }
10896
10897 cp_handle_deprecated_or_unavailable (fn, complain);
10898
10899 return val;
10900 }
10901 else if (trivial_fn_p (fn))
10902 {
10903 if (DECL_DESTRUCTOR_P (fn))
10904 return build_trivial_dtor_call (argarray[0]);
10905 else if (default_ctor_p (fn))
10906 {
10907 if (is_dummy_object (argarray[0]))
10908 return force_target_expr (DECL_CONTEXT (fn), void_node,
10909 no_cleanup_complain);
10910 else
10911 return cp_build_fold_indirect_ref (argarray[0]);
10912 }
10913 }
10914
10915 gcc_assert (!force_elide);
10916
10917 if (!already_used
10918 && !mark_used (fn, complain))
10919 return error_mark_node;
10920
10921 /* Warn if the built-in writes to an object of a non-trivial type. */
10922 if (warn_class_memaccess
10923 && vec_safe_length (args) >= 2
10924 && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
10925 maybe_warn_class_memaccess (input_location, fn, args);
10926
10927 if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
10928 {
10929 tree t;
10930 tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
10931 DECL_CONTEXT (fn),
10932 ba_any, NULL, complain);
10933 gcc_assert (binfo && binfo != error_mark_node);
10934
10935 argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1,
10936 complain);
10937 if (TREE_SIDE_EFFECTS (argarray[0]))
10938 argarray[0] = save_expr (argarray[0]);
10939 t = build_pointer_type (TREE_TYPE (fn));
10940 fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
10941 TREE_TYPE (fn) = t;
10942 }
10943 else
10944 {
10945 /* If FN is marked deprecated or unavailable, then we've already
10946 issued a diagnostic from mark_used above, so avoid redundantly
10947 issuing another one from build_addr_func. */
10948 auto w = make_temp_override (deprecated_state,
10949 UNAVAILABLE_DEPRECATED_SUPPRESS);
10950
10951 fn = build_addr_func (fn, complain);
10952 if (fn == error_mark_node)
10953 return error_mark_node;
10954
10955 /* We're actually invoking the function. (Immediate functions get an
10956 & when invoking it even though the user didn't use &.) */
10957 ADDR_EXPR_DENOTES_CALL_P (fn) = true;
10958 }
10959
10960 tree call = build_cxx_call (fn, nargs, argarray, complain|decltype_flag);
10961 if (call == error_mark_node)
10962 return call;
10963 if (cand->flags & LOOKUP_LIST_INIT_CTOR)
10964 {
10965 tree c = extract_call_expr (call);
10966 /* build_new_op will clear this when appropriate. */
10967 CALL_EXPR_ORDERED_ARGS (c) = true;
10968 }
10969 if (warned_p)
10970 {
10971 tree c = extract_call_expr (call);
10972 if (TREE_CODE (c) == CALL_EXPR)
10973 suppress_warning (c /* Suppress all warnings. */);
10974 }
10975 else if (TREE_DEPRECATED (fn)
10976 && warning_suppressed_at (input_location,
10977 OPT_Wdeprecated_declarations))
10978 {
10979 tree c = extract_call_expr (call);
10980 if (TREE_CODE (c) == CALL_EXPR)
10981 TREE_NO_WARNING (c) = true;
10982 }
10983
10984 return call;
10985 }
10986
10987 namespace
10988 {
10989
10990 /* Return the DECL of the first non-static subobject of class TYPE
10991 that satisfies the predicate PRED or null if none can be found. */
10992
10993 template <class Predicate>
10994 tree
10995 first_non_static_field (tree type, Predicate pred)
10996 {
10997 if (!type || !CLASS_TYPE_P (type))
10998 return NULL_TREE;
10999
11000 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
11001 {
11002 if (TREE_CODE (field) != FIELD_DECL)
11003 continue;
11004 if (TREE_STATIC (field))
11005 continue;
11006 if (pred (field))
11007 return field;
11008 }
11009
11010 int i = 0;
11011
11012 for (tree base_binfo, binfo = TYPE_BINFO (type);
11013 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
11014 {
11015 tree base = TREE_TYPE (base_binfo);
11016 if (pred (base))
11017 return base;
11018 if (tree field = first_non_static_field (base, pred))
11019 return field;
11020 }
11021
11022 return NULL_TREE;
11023 }
11024
11025 struct NonPublicField
11026 {
11027 bool operator() (const_tree t) const
11028 {
11029 return DECL_P (t) && (TREE_PRIVATE (t) || TREE_PROTECTED (t));
11030 }
11031 };
11032
11033 /* Return the DECL of the first non-public subobject of class TYPE
11034 or null if none can be found. */
11035
11036 static inline tree
11037 first_non_public_field (tree type)
11038 {
11039 return first_non_static_field (type, NonPublicField ());
11040 }
11041
11042 struct NonTrivialField
11043 {
11044 bool operator() (const_tree t) const
11045 {
11046 return !trivial_type_p (DECL_P (t) ? TREE_TYPE (t) : t);
11047 }
11048 };
11049
11050 /* Return the DECL of the first non-trivial subobject of class TYPE
11051 or null if none can be found. */
11052
11053 static inline tree
11054 first_non_trivial_field (tree type)
11055 {
11056 return first_non_static_field (type, NonTrivialField ());
11057 }
11058
11059 } /* unnamed namespace */
11060
11061 /* Return true if all copy and move assignment operator overloads for
11062 class TYPE are trivial and at least one of them is not deleted and,
11063 when ACCESS is set, accessible. Return false otherwise. Set
11064 HASASSIGN to true when the TYPE has a (not necessarily trivial)
11065 copy or move assignment. */
11066
11067 static bool
11068 has_trivial_copy_assign_p (tree type, bool access, bool *hasassign)
11069 {
11070 tree fns = get_class_binding (type, assign_op_identifier);
11071 bool all_trivial = true;
11072
11073 /* Iterate over overloads of the assignment operator, checking
11074 accessible copy assignments for triviality. */
11075
11076 for (tree f : ovl_range (fns))
11077 {
11078 /* Skip operators that aren't copy assignments. */
11079 if (!copy_fn_p (f))
11080 continue;
11081
11082 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
11083 || accessible_p (TYPE_BINFO (type), f, true));
11084
11085 /* Skip template assignment operators and deleted functions. */
11086 if (TREE_CODE (f) != FUNCTION_DECL || DECL_DELETED_FN (f))
11087 continue;
11088
11089 if (accessible)
11090 *hasassign = true;
11091
11092 if (!accessible || !trivial_fn_p (f))
11093 all_trivial = false;
11094
11095 /* Break early when both properties have been determined. */
11096 if (*hasassign && !all_trivial)
11097 break;
11098 }
11099
11100 /* Return true if they're all trivial and one of the expressions
11101 TYPE() = TYPE() or TYPE() = (TYPE&)() is valid. */
11102 tree ref = cp_build_reference_type (type, false);
11103 return (all_trivial
11104 && (is_trivially_xible (MODIFY_EXPR, type, type)
11105 || is_trivially_xible (MODIFY_EXPR, type, ref)));
11106 }
11107
11108 /* Return true if all copy and move ctor overloads for class TYPE are
11109 trivial and at least one of them is not deleted and, when ACCESS is
11110 set, accessible. Return false otherwise. Set each element of HASCTOR[]
11111 to true when the TYPE has a (not necessarily trivial) default and copy
11112 (or move) ctor, respectively. */
11113
11114 static bool
11115 has_trivial_copy_p (tree type, bool access, bool hasctor[2])
11116 {
11117 tree fns = get_class_binding (type, complete_ctor_identifier);
11118 bool all_trivial = true;
11119
11120 for (tree f : ovl_range (fns))
11121 {
11122 /* Skip template constructors. */
11123 if (TREE_CODE (f) != FUNCTION_DECL)
11124 continue;
11125
11126 bool cpy_or_move_ctor_p = copy_fn_p (f);
11127
11128 /* Skip ctors other than default, copy, and move. */
11129 if (!cpy_or_move_ctor_p && !default_ctor_p (f))
11130 continue;
11131
11132 if (DECL_DELETED_FN (f))
11133 continue;
11134
11135 bool accessible = (!access || !(TREE_PRIVATE (f) || TREE_PROTECTED (f))
11136 || accessible_p (TYPE_BINFO (type), f, true));
11137
11138 if (accessible)
11139 hasctor[cpy_or_move_ctor_p] = true;
11140
11141 if (cpy_or_move_ctor_p && (!accessible || !trivial_fn_p (f)))
11142 all_trivial = false;
11143
11144 /* Break early when both properties have been determined. */
11145 if (hasctor[0] && hasctor[1] && !all_trivial)
11146 break;
11147 }
11148
11149 return all_trivial;
11150 }
11151
11152 /* Issue a warning on a call to the built-in function FNDECL if it is
11153 a raw memory write whose destination is not an object of (something
11154 like) trivial or standard layout type with a non-deleted assignment
11155 and copy ctor. Detects const correctness violations, corrupting
11156 references, virtual table pointers, and bypassing non-trivial
11157 assignments. */
11158
11159 static void
11160 maybe_warn_class_memaccess (location_t loc, tree fndecl,
11161 const vec<tree, va_gc> *args)
11162 {
11163 /* Except for bcopy where it's second, the destination pointer is
11164 the first argument for all functions handled here. Compute
11165 the index of the destination and source arguments. */
11166 unsigned dstidx = DECL_FUNCTION_CODE (fndecl) == BUILT_IN_BCOPY;
11167 unsigned srcidx = !dstidx;
11168
11169 tree dest = (*args)[dstidx];
11170 if (!TREE_TYPE (dest)
11171 || (TREE_CODE (TREE_TYPE (dest)) != ARRAY_TYPE
11172 && !INDIRECT_TYPE_P (TREE_TYPE (dest))))
11173 return;
11174
11175 tree srctype = NULL_TREE;
11176
11177 /* Determine the type of the pointed-to object and whether it's
11178 a complete class type. */
11179 tree desttype = TREE_TYPE (TREE_TYPE (dest));
11180
11181 if (!desttype || !COMPLETE_TYPE_P (desttype) || !CLASS_TYPE_P (desttype))
11182 return;
11183
11184 /* Check to see if the raw memory call is made by a non-static member
11185 function with THIS as the destination argument for the destination
11186 type. If so, and if the class has no non-trivial bases or members,
11187 be more permissive. */
11188 if (current_function_decl
11189 && DECL_OBJECT_MEMBER_FUNCTION_P (current_function_decl)
11190 && is_object_parameter (tree_strip_nop_conversions (dest)))
11191 {
11192 tree ctx = DECL_CONTEXT (current_function_decl);
11193 bool special = same_type_ignoring_top_level_qualifiers_p (ctx, desttype);
11194 tree binfo = TYPE_BINFO (ctx);
11195
11196 if (special
11197 && !BINFO_VTABLE (binfo)
11198 && !first_non_trivial_field (desttype))
11199 return;
11200 }
11201
11202 /* True if the class is trivial. */
11203 bool trivial = trivial_type_p (desttype);
11204
11205 /* Set to true if DESTYPE has an accessible copy assignment. */
11206 bool hasassign = false;
11207 /* True if all of the class' overloaded copy assignment operators
11208 are all trivial (and not deleted) and at least one of them is
11209 accessible. */
11210 bool trivassign = has_trivial_copy_assign_p (desttype, true, &hasassign);
11211
11212 /* Set to true if DESTTYPE has an accessible default and copy ctor,
11213 respectively. */
11214 bool hasctors[2] = { false, false };
11215
11216 /* True if all of the class' overloaded copy constructors are all
11217 trivial (and not deleted) and at least one of them is accessible. */
11218 bool trivcopy = has_trivial_copy_p (desttype, true, hasctors);
11219
11220 /* Set FLD to the first private/protected member of the class. */
11221 tree fld = trivial ? first_non_public_field (desttype) : NULL_TREE;
11222
11223 /* The warning format string. */
11224 const char *warnfmt = NULL;
11225 /* A suggested alternative to offer instead of the raw memory call.
11226 Empty string when none can be come up with. */
11227 const char *suggest = "";
11228 bool warned = false;
11229
11230 switch (DECL_FUNCTION_CODE (fndecl))
11231 {
11232 case BUILT_IN_MEMSET:
11233 if (!integer_zerop (maybe_constant_value ((*args)[1])))
11234 {
11235 /* Diagnose setting non-copy-assignable or non-trivial types,
11236 or types with a private member, to (potentially) non-zero
11237 bytes. Since the value of the bytes being written is unknown,
11238 suggest using assignment instead (if one exists). Also warn
11239 for writes into objects for which zero-initialization doesn't
11240 mean all bits clear (pointer-to-member data, where null is all
11241 bits set). Since the value being written is (most likely)
11242 non-zero, simply suggest assignment (but not copy assignment). */
11243 suggest = "; use assignment instead";
11244 if (!trivassign)
11245 warnfmt = G_("%qD writing to an object of type %#qT with "
11246 "no trivial copy-assignment");
11247 else if (!trivial)
11248 warnfmt = G_("%qD writing to an object of non-trivial type %#qT%s");
11249 else if (fld)
11250 {
11251 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
11252 warned = warning_at (loc, OPT_Wclass_memaccess,
11253 "%qD writing to an object of type %#qT with "
11254 "%qs member %qD",
11255 fndecl, desttype, access, fld);
11256 }
11257 else if (!zero_init_p (desttype))
11258 warnfmt = G_("%qD writing to an object of type %#qT containing "
11259 "a pointer to data member%s");
11260
11261 break;
11262 }
11263 /* Fall through. */
11264
11265 case BUILT_IN_BZERO:
11266 /* Similarly to the above, diagnose clearing non-trivial or non-
11267 standard layout objects, or objects of types with no assignmenmt.
11268 Since the value being written is known to be zero, suggest either
11269 copy assignment, copy ctor, or default ctor as an alternative,
11270 depending on what's available. */
11271
11272 if (hasassign && hasctors[0])
11273 suggest = G_("; use assignment or value-initialization instead");
11274 else if (hasassign)
11275 suggest = G_("; use assignment instead");
11276 else if (hasctors[0])
11277 suggest = G_("; use value-initialization instead");
11278
11279 if (!trivassign)
11280 warnfmt = G_("%qD clearing an object of type %#qT with "
11281 "no trivial copy-assignment%s");
11282 else if (!trivial)
11283 warnfmt = G_("%qD clearing an object of non-trivial type %#qT%s");
11284 else if (!zero_init_p (desttype))
11285 warnfmt = G_("%qD clearing an object of type %#qT containing "
11286 "a pointer-to-member%s");
11287 break;
11288
11289 case BUILT_IN_BCOPY:
11290 case BUILT_IN_MEMCPY:
11291 case BUILT_IN_MEMMOVE:
11292 case BUILT_IN_MEMPCPY:
11293 /* Determine the type of the source object. */
11294 srctype = TREE_TYPE ((*args)[srcidx]);
11295 if (!srctype || !INDIRECT_TYPE_P (srctype))
11296 srctype = void_type_node;
11297 else
11298 srctype = TREE_TYPE (srctype);
11299
11300 /* Since it's impossible to determine wheter the byte copy is
11301 being used in place of assignment to an existing object or
11302 as a substitute for initialization, assume it's the former.
11303 Determine the best alternative to use instead depending on
11304 what's not deleted. */
11305 if (hasassign && hasctors[1])
11306 suggest = G_("; use copy-assignment or copy-initialization instead");
11307 else if (hasassign)
11308 suggest = G_("; use copy-assignment instead");
11309 else if (hasctors[1])
11310 suggest = G_("; use copy-initialization instead");
11311
11312 if (!trivassign)
11313 warnfmt = G_("%qD writing to an object of type %#qT with no trivial "
11314 "copy-assignment%s");
11315 else if (!trivially_copyable_p (desttype))
11316 warnfmt = G_("%qD writing to an object of non-trivially copyable "
11317 "type %#qT%s");
11318 else if (!trivcopy)
11319 warnfmt = G_("%qD writing to an object with a deleted copy constructor");
11320
11321 else if (!trivial
11322 && !VOID_TYPE_P (srctype)
11323 && !is_byte_access_type (srctype)
11324 && !same_type_ignoring_top_level_qualifiers_p (desttype,
11325 srctype))
11326 {
11327 /* Warn when copying into a non-trivial object from an object
11328 of a different type other than void or char. */
11329 warned = warning_at (loc, OPT_Wclass_memaccess,
11330 "%qD copying an object of non-trivial type "
11331 "%#qT from an array of %#qT",
11332 fndecl, desttype, srctype);
11333 }
11334 else if (fld
11335 && !VOID_TYPE_P (srctype)
11336 && !is_byte_access_type (srctype)
11337 && !same_type_ignoring_top_level_qualifiers_p (desttype,
11338 srctype))
11339 {
11340 const char *access = TREE_PRIVATE (fld) ? "private" : "protected";
11341 warned = warning_at (loc, OPT_Wclass_memaccess,
11342 "%qD copying an object of type %#qT with "
11343 "%qs member %qD from an array of %#qT; use "
11344 "assignment or copy-initialization instead",
11345 fndecl, desttype, access, fld, srctype);
11346 }
11347 else if (!trivial && vec_safe_length (args) > 2)
11348 {
11349 tree sz = maybe_constant_value ((*args)[2]);
11350 if (!tree_fits_uhwi_p (sz))
11351 break;
11352
11353 /* Finally, warn on partial copies. */
11354 unsigned HOST_WIDE_INT typesize
11355 = tree_to_uhwi (TYPE_SIZE_UNIT (desttype));
11356 if (typesize == 0)
11357 break;
11358 if (unsigned HOST_WIDE_INT partial = tree_to_uhwi (sz) % typesize)
11359 warned = warning_at (loc, OPT_Wclass_memaccess,
11360 (typesize - partial > 1
11361 ? G_("%qD writing to an object of "
11362 "a non-trivial type %#qT leaves %wu "
11363 "bytes unchanged")
11364 : G_("%qD writing to an object of "
11365 "a non-trivial type %#qT leaves %wu "
11366 "byte unchanged")),
11367 fndecl, desttype, typesize - partial);
11368 }
11369 break;
11370
11371 case BUILT_IN_REALLOC:
11372
11373 if (!trivially_copyable_p (desttype))
11374 warnfmt = G_("%qD moving an object of non-trivially copyable type "
11375 "%#qT; use %<new%> and %<delete%> instead");
11376 else if (!trivcopy)
11377 warnfmt = G_("%qD moving an object of type %#qT with deleted copy "
11378 "constructor; use %<new%> and %<delete%> instead");
11379 else if (!get_dtor (desttype, tf_none))
11380 warnfmt = G_("%qD moving an object of type %#qT with deleted "
11381 "destructor");
11382 else if (!trivial)
11383 {
11384 tree sz = maybe_constant_value ((*args)[1]);
11385 if (TREE_CODE (sz) == INTEGER_CST
11386 && tree_int_cst_lt (sz, TYPE_SIZE_UNIT (desttype)))
11387 /* Finally, warn on reallocation into insufficient space. */
11388 warned = warning_at (loc, OPT_Wclass_memaccess,
11389 "%qD moving an object of non-trivial type "
11390 "%#qT and size %E into a region of size %E",
11391 fndecl, desttype, TYPE_SIZE_UNIT (desttype),
11392 sz);
11393 }
11394 break;
11395
11396 default:
11397 return;
11398 }
11399
11400 if (warnfmt)
11401 {
11402 if (suggest)
11403 warned = warning_at (loc, OPT_Wclass_memaccess,
11404 warnfmt, fndecl, desttype, suggest);
11405 else
11406 warned = warning_at (loc, OPT_Wclass_memaccess,
11407 warnfmt, fndecl, desttype);
11408 }
11409
11410 if (warned)
11411 inform (location_of (desttype), "%#qT declared here", desttype);
11412 }
11413
11414 /* Build and return a call to FN, using NARGS arguments in ARGARRAY.
11415 If FN is the result of resolving an overloaded target built-in,
11416 ORIG_FNDECL is the original function decl, otherwise it is null.
11417 This function performs no overload resolution, conversion, or other
11418 high-level operations. */
11419
11420 tree
11421 build_cxx_call (tree fn, int nargs, tree *argarray,
11422 tsubst_flags_t complain, tree orig_fndecl)
11423 {
11424 tree fndecl;
11425
11426 /* Remember roughly where this call is. */
11427 location_t loc = cp_expr_loc_or_input_loc (fn);
11428 fn = build_call_a (fn, nargs, argarray);
11429 SET_EXPR_LOCATION (fn, loc);
11430
11431 fndecl = get_callee_fndecl (fn);
11432 if (!orig_fndecl)
11433 orig_fndecl = fndecl;
11434
11435 /* Check that arguments to builtin functions match the expectations. */
11436 if (fndecl
11437 && !processing_template_decl
11438 && fndecl_built_in_p (fndecl))
11439 {
11440 int i;
11441
11442 /* We need to take care that values to BUILT_IN_NORMAL
11443 are reduced. */
11444 for (i = 0; i < nargs; i++)
11445 argarray[i] = maybe_constant_value (argarray[i]);
11446
11447 if (!check_builtin_function_arguments (EXPR_LOCATION (fn), vNULL, fndecl,
11448 orig_fndecl, nargs, argarray,
11449 complain & tf_error))
11450 return error_mark_node;
11451 else if (fndecl_built_in_p (fndecl, BUILT_IN_CLEAR_PADDING))
11452 {
11453 tree arg0 = argarray[0];
11454 STRIP_NOPS (arg0);
11455 if (TREE_CODE (arg0) == ADDR_EXPR
11456 && DECL_P (TREE_OPERAND (arg0, 0))
11457 && same_type_ignoring_top_level_qualifiers_p
11458 (TREE_TYPE (TREE_TYPE (argarray[0])),
11459 TREE_TYPE (TREE_TYPE (arg0))))
11460 /* For __builtin_clear_padding (&var) we know the type
11461 is for a complete object, so there is no risk in clearing
11462 padding that is reused in some derived class member. */;
11463 else if (!trivially_copyable_p (TREE_TYPE (TREE_TYPE (argarray[0]))))
11464 {
11465 error_at (EXPR_LOC_OR_LOC (argarray[0], input_location),
11466 "argument %u in call to function %qE "
11467 "has pointer to a non-trivially-copyable type (%qT)",
11468 1, fndecl, TREE_TYPE (argarray[0]));
11469 return error_mark_node;
11470 }
11471 }
11472 }
11473
11474 if (VOID_TYPE_P (TREE_TYPE (fn)))
11475 return fn;
11476
11477 /* 5.2.2/11: If a function call is a prvalue of object type: if the
11478 function call is either the operand of a decltype-specifier or the
11479 right operand of a comma operator that is the operand of a
11480 decltype-specifier, a temporary object is not introduced for the
11481 prvalue. The type of the prvalue may be incomplete. */
11482 if (!(complain & tf_decltype))
11483 {
11484 fn = require_complete_type (fn, complain);
11485 if (fn == error_mark_node)
11486 return error_mark_node;
11487
11488 if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
11489 {
11490 fn = build_cplus_new (TREE_TYPE (fn), fn, complain);
11491 maybe_warn_parm_abi (TREE_TYPE (fn), loc);
11492 }
11493 }
11494 return convert_from_reference (fn);
11495 }
11496
11497 /* Returns the value to use for the in-charge parameter when making a
11498 call to a function with the indicated NAME.
11499
11500 FIXME:Can't we find a neater way to do this mapping? */
11501
11502 tree
11503 in_charge_arg_for_name (tree name)
11504 {
11505 if (IDENTIFIER_CTOR_P (name))
11506 {
11507 if (name == complete_ctor_identifier)
11508 return integer_one_node;
11509 gcc_checking_assert (name == base_ctor_identifier);
11510 }
11511 else
11512 {
11513 if (name == complete_dtor_identifier)
11514 return integer_two_node;
11515 else if (name == deleting_dtor_identifier)
11516 /* The deleting dtor should now be handled by
11517 build_delete_destructor_body. */
11518 gcc_unreachable ();
11519 gcc_checking_assert (name == base_dtor_identifier);
11520 }
11521
11522 return integer_zero_node;
11523 }
11524
11525 /* We've built up a constructor call RET. Complain if it delegates to the
11526 constructor we're currently compiling. */
11527
11528 static void
11529 check_self_delegation (tree ret)
11530 {
11531 if (TREE_CODE (ret) == TARGET_EXPR)
11532 ret = TARGET_EXPR_INITIAL (ret);
11533 tree fn = cp_get_callee_fndecl_nofold (ret);
11534 if (fn && DECL_ABSTRACT_ORIGIN (fn) == current_function_decl)
11535 error ("constructor delegates to itself");
11536 }
11537
11538 /* Build a call to a constructor, destructor, or an assignment
11539 operator for INSTANCE, an expression with class type. NAME
11540 indicates the special member function to call; *ARGS are the
11541 arguments. ARGS may be NULL. This may change ARGS. BINFO
11542 indicates the base of INSTANCE that is to be passed as the `this'
11543 parameter to the member function called.
11544
11545 FLAGS are the LOOKUP_* flags to use when processing the call.
11546
11547 If NAME indicates a complete object constructor, INSTANCE may be
11548 NULL_TREE. In this case, the caller will call build_cplus_new to
11549 store the newly constructed object into a VAR_DECL. */
11550
11551 tree
11552 build_special_member_call (tree instance, tree name, vec<tree, va_gc> **args,
11553 tree binfo, int flags, tsubst_flags_t complain)
11554 {
11555 tree fns;
11556 /* The type of the subobject to be constructed or destroyed. */
11557 tree class_type;
11558 vec<tree, va_gc> *allocated = NULL;
11559 tree ret;
11560
11561 gcc_assert (IDENTIFIER_CDTOR_P (name) || name == assign_op_identifier);
11562
11563 if (error_operand_p (instance))
11564 return error_mark_node;
11565
11566 if (IDENTIFIER_DTOR_P (name))
11567 {
11568 gcc_assert (args == NULL || vec_safe_is_empty (*args));
11569 if (!type_build_dtor_call (TREE_TYPE (instance)))
11570 /* Shortcut to avoid lazy destructor declaration. */
11571 return build_trivial_dtor_call (instance);
11572 }
11573
11574 if (TYPE_P (binfo))
11575 {
11576 /* Resolve the name. */
11577 if (!complete_type_or_maybe_complain (binfo, NULL_TREE, complain))
11578 return error_mark_node;
11579
11580 binfo = TYPE_BINFO (binfo);
11581 }
11582
11583 gcc_assert (binfo != NULL_TREE);
11584
11585 class_type = BINFO_TYPE (binfo);
11586
11587 /* Handle the special case where INSTANCE is NULL_TREE. */
11588 if (name == complete_ctor_identifier && !instance)
11589 instance = build_dummy_object (class_type);
11590 else
11591 {
11592 /* Convert to the base class, if necessary. */
11593 if (!same_type_ignoring_top_level_qualifiers_p
11594 (TREE_TYPE (instance), BINFO_TYPE (binfo)))
11595 {
11596 if (IDENTIFIER_CDTOR_P (name))
11597 /* For constructors and destructors, either the base is
11598 non-virtual, or it is virtual but we are doing the
11599 conversion from a constructor or destructor for the
11600 complete object. In either case, we can convert
11601 statically. */
11602 instance = convert_to_base_statically (instance, binfo);
11603 else
11604 {
11605 /* However, for assignment operators, we must convert
11606 dynamically if the base is virtual. */
11607 gcc_checking_assert (name == assign_op_identifier);
11608 instance = build_base_path (PLUS_EXPR, instance,
11609 binfo, /*nonnull=*/1, complain);
11610 }
11611 }
11612 }
11613
11614 gcc_assert (instance != NULL_TREE);
11615
11616 /* In C++17, "If the initializer expression is a prvalue and the
11617 cv-unqualified version of the source type is the same class as the class
11618 of the destination, the initializer expression is used to initialize the
11619 destination object." Handle that here to avoid doing overload
11620 resolution. */
11621 if (cxx_dialect >= cxx17
11622 && args && vec_safe_length (*args) == 1
11623 && !unsafe_return_slot_p (instance))
11624 {
11625 tree arg = (**args)[0];
11626
11627 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
11628 && !TYPE_HAS_LIST_CTOR (class_type)
11629 && !CONSTRUCTOR_IS_DESIGNATED_INIT (arg)
11630 && CONSTRUCTOR_NELTS (arg) == 1)
11631 arg = CONSTRUCTOR_ELT (arg, 0)->value;
11632
11633 if ((TREE_CODE (arg) == TARGET_EXPR
11634 || TREE_CODE (arg) == CONSTRUCTOR)
11635 && (same_type_ignoring_top_level_qualifiers_p
11636 (class_type, TREE_TYPE (arg))))
11637 {
11638 if (is_dummy_object (instance))
11639 return arg;
11640 else if (TREE_CODE (arg) == TARGET_EXPR)
11641 TARGET_EXPR_DIRECT_INIT_P (arg) = true;
11642
11643 if ((complain & tf_error)
11644 && (flags & LOOKUP_DELEGATING_CONS))
11645 check_self_delegation (arg);
11646 /* Avoid change of behavior on Wunused-var-2.C. */
11647 instance = mark_lvalue_use (instance);
11648 return cp_build_init_expr (instance, arg);
11649 }
11650 }
11651
11652 fns = lookup_fnfields (binfo, name, 1, complain);
11653
11654 /* When making a call to a constructor or destructor for a subobject
11655 that uses virtual base classes, pass down a pointer to a VTT for
11656 the subobject. */
11657 if ((name == base_ctor_identifier
11658 || name == base_dtor_identifier)
11659 && CLASSTYPE_VBASECLASSES (class_type))
11660 {
11661 tree vtt;
11662 tree sub_vtt;
11663
11664 /* If the current function is a complete object constructor
11665 or destructor, then we fetch the VTT directly.
11666 Otherwise, we look it up using the VTT we were given. */
11667 vtt = DECL_CHAIN (CLASSTYPE_VTABLES (current_class_type));
11668 vtt = decay_conversion (vtt, complain);
11669 if (vtt == error_mark_node)
11670 return error_mark_node;
11671 vtt = build_if_in_charge (vtt, current_vtt_parm);
11672 if (BINFO_SUBVTT_INDEX (binfo))
11673 sub_vtt = fold_build_pointer_plus (vtt, BINFO_SUBVTT_INDEX (binfo));
11674 else
11675 sub_vtt = vtt;
11676
11677 if (args == NULL)
11678 {
11679 allocated = make_tree_vector ();
11680 args = &allocated;
11681 }
11682
11683 vec_safe_insert (*args, 0, sub_vtt);
11684 }
11685
11686 ret = build_new_method_call (instance, fns, args,
11687 TYPE_BINFO (BINFO_TYPE (binfo)),
11688 flags, /*fn=*/NULL,
11689 complain);
11690
11691 if (allocated != NULL)
11692 release_tree_vector (allocated);
11693
11694 if ((complain & tf_error)
11695 && (flags & LOOKUP_DELEGATING_CONS)
11696 && name == complete_ctor_identifier)
11697 check_self_delegation (ret);
11698
11699 return ret;
11700 }
11701
11702 /* Return the NAME, as a C string. The NAME indicates a function that
11703 is a member of TYPE. *FREE_P is set to true if the caller must
11704 free the memory returned.
11705
11706 Rather than go through all of this, we should simply set the names
11707 of constructors and destructors appropriately, and dispense with
11708 ctor_identifier, dtor_identifier, etc. */
11709
11710 static char *
11711 name_as_c_string (tree name, tree type, bool *free_p)
11712 {
11713 const char *pretty_name;
11714
11715 /* Assume that we will not allocate memory. */
11716 *free_p = false;
11717 /* Constructors and destructors are special. */
11718 if (IDENTIFIER_CDTOR_P (name))
11719 {
11720 pretty_name
11721 = identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type)));
11722 /* For a destructor, add the '~'. */
11723 if (IDENTIFIER_DTOR_P (name))
11724 {
11725 pretty_name = concat ("~", pretty_name, NULL);
11726 /* Remember that we need to free the memory allocated. */
11727 *free_p = true;
11728 }
11729 }
11730 else if (IDENTIFIER_CONV_OP_P (name))
11731 {
11732 pretty_name = concat ("operator ",
11733 type_as_string_translate (TREE_TYPE (name),
11734 TFF_PLAIN_IDENTIFIER),
11735 NULL);
11736 /* Remember that we need to free the memory allocated. */
11737 *free_p = true;
11738 }
11739 else
11740 pretty_name = identifier_to_locale (IDENTIFIER_POINTER (name));
11741
11742 return CONST_CAST (char *, pretty_name);
11743 }
11744
11745 /* If CANDIDATES contains exactly one candidate, return it, otherwise
11746 return NULL. */
11747
11748 static z_candidate *
11749 single_z_candidate (z_candidate *candidates)
11750 {
11751 if (candidates == NULL)
11752 return NULL;
11753
11754 if (candidates->next)
11755 return NULL;
11756
11757 return candidates;
11758 }
11759
11760 /* If CANDIDATE is invalid due to a bad argument type, return the
11761 pertinent conversion_info.
11762
11763 Otherwise, return NULL. */
11764
11765 static const conversion_info *
11766 maybe_get_bad_conversion_for_unmatched_call (const z_candidate *candidate)
11767 {
11768 /* Must be an rr_arg_conversion or rr_bad_arg_conversion. */
11769 rejection_reason *r = candidate->reason;
11770
11771 if (r == NULL)
11772 return NULL;
11773
11774 switch (r->code)
11775 {
11776 default:
11777 return NULL;
11778
11779 case rr_arg_conversion:
11780 return &r->u.conversion;
11781
11782 case rr_bad_arg_conversion:
11783 return &r->u.bad_conversion;
11784 }
11785 }
11786
11787 /* Issue an error and note complaining about a bad argument type at a
11788 callsite with a single candidate FNDECL.
11789
11790 ARG_LOC is the location of the argument (or UNKNOWN_LOCATION, in which
11791 case input_location is used).
11792 FROM_TYPE is the type of the actual argument; TO_TYPE is the type of
11793 the formal parameter. */
11794
11795 void
11796 complain_about_bad_argument (location_t arg_loc,
11797 tree from_type, tree to_type,
11798 tree fndecl, int parmnum)
11799 {
11800 auto_diagnostic_group d;
11801 range_label_for_type_mismatch rhs_label (from_type, to_type);
11802 range_label *label = &rhs_label;
11803 if (arg_loc == UNKNOWN_LOCATION)
11804 {
11805 arg_loc = input_location;
11806 label = NULL;
11807 }
11808 gcc_rich_location richloc (arg_loc, label, highlight_colors::percent_h);
11809 error_at (&richloc,
11810 "cannot convert %qH to %qI",
11811 from_type, to_type);
11812 maybe_inform_about_fndecl_for_bogus_argument_init
11813 (fndecl,
11814 parmnum,
11815 highlight_colors::percent_i);
11816 }
11817
11818 /* Subroutine of build_new_method_call_1, for where there are no viable
11819 candidates for the call. */
11820
11821 static void
11822 complain_about_no_candidates_for_method_call (tree instance,
11823 z_candidate *candidates,
11824 tree explicit_targs,
11825 tree basetype,
11826 tree optype, tree name,
11827 bool skip_first_for_error,
11828 vec<tree, va_gc> *user_args)
11829 {
11830 auto_diagnostic_group d;
11831 if (!COMPLETE_OR_OPEN_TYPE_P (basetype))
11832 cxx_incomplete_type_error (instance, basetype);
11833 else if (optype)
11834 error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
11835 basetype, optype, build_tree_list_vec (user_args),
11836 TREE_TYPE (instance));
11837 else
11838 {
11839 /* Special-case for when there's a single candidate that's failing
11840 due to a bad argument type. */
11841 if (z_candidate *candidate = single_z_candidate (candidates))
11842 if (const conversion_info *conv
11843 = maybe_get_bad_conversion_for_unmatched_call (candidate))
11844 {
11845 tree from_type = conv->from;
11846 if (!TYPE_P (conv->from))
11847 from_type = lvalue_type (conv->from);
11848 complain_about_bad_argument (conv->loc,
11849 from_type, conv->to_type,
11850 candidate->fn, conv->n_arg);
11851 return;
11852 }
11853
11854 tree arglist = build_tree_list_vec (user_args);
11855 tree errname = name;
11856 bool twiddle = false;
11857 if (IDENTIFIER_CDTOR_P (errname))
11858 {
11859 twiddle = IDENTIFIER_DTOR_P (errname);
11860 errname = constructor_name (basetype);
11861 }
11862 if (explicit_targs)
11863 errname = lookup_template_function (errname, explicit_targs);
11864 if (skip_first_for_error)
11865 arglist = TREE_CHAIN (arglist);
11866 error ("no matching function for call to %<%T::%s%E(%A)%#V%>",
11867 basetype, &"~"[!twiddle], errname, arglist,
11868 TREE_TYPE (instance));
11869 }
11870 print_z_candidates (location_of (name), candidates);
11871 }
11872
11873 /* Build a call to "INSTANCE.FN (ARGS)". If FN_P is non-NULL, it will
11874 be set, upon return, to the function called. ARGS may be NULL.
11875 This may change ARGS. */
11876
11877 tree
11878 build_new_method_call (tree instance, tree fns, vec<tree, va_gc> **args,
11879 tree conversion_path, int flags,
11880 tree *fn_p, tsubst_flags_t complain)
11881 {
11882 struct z_candidate *candidates = 0, *cand;
11883 tree explicit_targs = NULL_TREE;
11884 tree basetype = NULL_TREE;
11885 tree access_binfo;
11886 tree optype;
11887 tree first_mem_arg = NULL_TREE;
11888 tree name;
11889 bool skip_first_for_error;
11890 vec<tree, va_gc> *user_args;
11891 tree call;
11892 tree fn;
11893 int template_only = 0;
11894 bool any_viable_p;
11895 tree orig_instance;
11896 tree orig_fns;
11897 vec<tree, va_gc> *orig_args = NULL;
11898
11899 auto_cond_timevar tv (TV_OVERLOAD);
11900
11901 gcc_assert (instance != NULL_TREE);
11902
11903 /* We don't know what function we're going to call, yet. */
11904 if (fn_p)
11905 *fn_p = NULL_TREE;
11906
11907 if (error_operand_p (instance)
11908 || !fns || error_operand_p (fns))
11909 return error_mark_node;
11910
11911 if (!BASELINK_P (fns))
11912 {
11913 if (complain & tf_error)
11914 error ("call to non-function %qD", fns);
11915 return error_mark_node;
11916 }
11917
11918 orig_instance = instance;
11919 orig_fns = fns;
11920
11921 /* Dismantle the baselink to collect all the information we need. */
11922 if (!conversion_path)
11923 conversion_path = BASELINK_BINFO (fns);
11924 access_binfo = BASELINK_ACCESS_BINFO (fns);
11925 optype = BASELINK_OPTYPE (fns);
11926 fns = BASELINK_FUNCTIONS (fns);
11927 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11928 {
11929 explicit_targs = TREE_OPERAND (fns, 1);
11930 fns = TREE_OPERAND (fns, 0);
11931 template_only = 1;
11932 }
11933 gcc_assert (OVL_P (fns));
11934 fn = OVL_FIRST (fns);
11935 name = DECL_NAME (fn);
11936
11937 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
11938 gcc_assert (CLASS_TYPE_P (basetype));
11939
11940 user_args = args == NULL ? NULL : *args;
11941 /* Under DR 147 A::A() is an invalid constructor call,
11942 not a functional cast. */
11943 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
11944 {
11945 if (! (complain & tf_error))
11946 return error_mark_node;
11947
11948 basetype = DECL_CONTEXT (fn);
11949 name = constructor_name (basetype);
11950 auto_diagnostic_group d;
11951 if (permerror (input_location,
11952 "cannot call constructor %<%T::%D%> directly",
11953 basetype, name))
11954 inform (input_location, "for a function-style cast, remove the "
11955 "redundant %<::%D%>", name);
11956 call = build_functional_cast (input_location, basetype,
11957 build_tree_list_vec (user_args),
11958 complain);
11959 return call;
11960 }
11961
11962 if (processing_template_decl)
11963 orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
11964
11965 /* Process the argument list. */
11966 if (args != NULL && *args != NULL)
11967 {
11968 *args = resolve_args (*args, complain);
11969 if (*args == NULL)
11970 return error_mark_node;
11971 user_args = *args;
11972 }
11973
11974 /* Consider the object argument to be used even if we end up selecting a
11975 static member function. */
11976 instance = mark_type_use (instance);
11977
11978 /* Figure out whether to skip the first argument for the error
11979 message we will display to users if an error occurs. We don't
11980 want to display any compiler-generated arguments. The "this"
11981 pointer hasn't been added yet. However, we must remove the VTT
11982 pointer if this is a call to a base-class constructor or
11983 destructor. */
11984 skip_first_for_error = false;
11985 if (IDENTIFIER_CDTOR_P (name))
11986 {
11987 /* Callers should explicitly indicate whether they want to ctor
11988 the complete object or just the part without virtual bases. */
11989 gcc_assert (name != ctor_identifier);
11990
11991 /* Remove the VTT pointer, if present. */
11992 if ((name == base_ctor_identifier || name == base_dtor_identifier)
11993 && CLASSTYPE_VBASECLASSES (basetype))
11994 skip_first_for_error = true;
11995
11996 /* It's OK to call destructors and constructors on cv-qualified
11997 objects. Therefore, convert the INSTANCE to the unqualified
11998 type, if necessary. */
11999 if (!same_type_p (basetype, TREE_TYPE (instance)))
12000 {
12001 instance = build_this (instance);
12002 instance = build_nop (build_pointer_type (basetype), instance);
12003 instance = build_fold_indirect_ref (instance);
12004 }
12005 }
12006 else
12007 gcc_assert (!DECL_DESTRUCTOR_P (fn) && !DECL_CONSTRUCTOR_P (fn));
12008
12009 /* For the overload resolution we need to find the actual `this`
12010 that would be captured if the call turns out to be to a
12011 non-static member function. Do not actually capture it at this
12012 point. */
12013 if (DECL_CONSTRUCTOR_P (fn))
12014 /* Constructors don't use the enclosing 'this'. */
12015 first_mem_arg = instance;
12016 else
12017 first_mem_arg = maybe_resolve_dummy (instance, false);
12018
12019 conversion_obstack_sentinel cos;
12020
12021 /* The number of arguments artificial parms in ARGS; we subtract one because
12022 there's no 'this' in ARGS. */
12023 unsigned skip = num_artificial_parms_for (fn) - 1;
12024
12025 /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
12026 initializer, not T({ }). */
12027 if (DECL_CONSTRUCTOR_P (fn)
12028 && vec_safe_length (user_args) > skip
12029 && DIRECT_LIST_INIT_P ((*user_args)[skip]))
12030 {
12031 tree init_list = (*user_args)[skip];
12032 tree init = NULL_TREE;
12033
12034 gcc_assert (user_args->length () == skip + 1
12035 && !(flags & LOOKUP_ONLYCONVERTING));
12036
12037 /* If the initializer list has no elements and T is a class type with
12038 a default constructor, the object is value-initialized. Handle
12039 this here so we don't need to handle it wherever we use
12040 build_special_member_call. */
12041 if (CONSTRUCTOR_NELTS (init_list) == 0
12042 && TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
12043 /* For a user-provided default constructor, use the normal
12044 mechanisms so that protected access works. */
12045 && type_has_non_user_provided_default_constructor (basetype)
12046 && !processing_template_decl)
12047 init = build_value_init (basetype, complain);
12048
12049 /* If BASETYPE is an aggregate, we need to do aggregate
12050 initialization. */
12051 else if (CP_AGGREGATE_TYPE_P (basetype))
12052 {
12053 init = reshape_init (basetype, init_list, complain);
12054 init = digest_init (basetype, init, complain);
12055 }
12056
12057 if (init)
12058 {
12059 if (is_dummy_object (instance))
12060 return get_target_expr (init, complain);
12061 return cp_build_init_expr (instance, init);
12062 }
12063
12064 /* Otherwise go ahead with overload resolution. */
12065 add_list_candidates (fns, first_mem_arg, user_args,
12066 basetype, explicit_targs, template_only,
12067 conversion_path, access_binfo, flags,
12068 &candidates, complain);
12069 }
12070 else
12071 add_candidates (fns, first_mem_arg, user_args, optype,
12072 explicit_targs, template_only, conversion_path,
12073 access_binfo, flags, &candidates, complain);
12074
12075 any_viable_p = false;
12076 candidates = splice_viable (candidates, false, &any_viable_p);
12077
12078 if (!any_viable_p)
12079 {
12080 /* [dcl.init], 17.6.2.2:
12081
12082 Otherwise, if no constructor is viable, the destination type is
12083 a (possibly cv-qualified) aggregate class A, and the initializer
12084 is a parenthesized expression-list, the object is initialized as
12085 follows...
12086
12087 We achieve this by building up a CONSTRUCTOR, as for list-init,
12088 and setting CONSTRUCTOR_IS_PAREN_INIT to distinguish between
12089 the two. */
12090 if (DECL_CONSTRUCTOR_P (fn)
12091 && !(flags & LOOKUP_ONLYCONVERTING)
12092 && cxx_dialect >= cxx20
12093 && CP_AGGREGATE_TYPE_P (basetype)
12094 && !vec_safe_is_empty (user_args))
12095 {
12096 /* Create a CONSTRUCTOR from ARGS, e.g. {1, 2} from <1, 2>. */
12097 tree ctor = build_constructor_from_vec (init_list_type_node,
12098 user_args);
12099 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
12100 CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
12101 if (is_dummy_object (instance))
12102 return ctor;
12103 else
12104 {
12105 ctor = digest_init (basetype, ctor, complain);
12106 if (ctor == error_mark_node)
12107 return error_mark_node;
12108 return cp_build_init_expr (instance, ctor);
12109 }
12110 }
12111 if (complain & tf_error)
12112 complain_about_no_candidates_for_method_call (instance, candidates,
12113 explicit_targs, basetype,
12114 optype, name,
12115 skip_first_for_error,
12116 user_args);
12117 call = error_mark_node;
12118 }
12119 else
12120 {
12121 cand = tourney (candidates, complain);
12122 if (cand == 0)
12123 {
12124 char *pretty_name;
12125 bool free_p;
12126 tree arglist;
12127
12128 if (complain & tf_error)
12129 {
12130 pretty_name = name_as_c_string (name, basetype, &free_p);
12131 arglist = build_tree_list_vec (user_args);
12132 if (skip_first_for_error)
12133 arglist = TREE_CHAIN (arglist);
12134 auto_diagnostic_group d;
12135 if (!any_strictly_viable (candidates))
12136 error ("no matching function for call to %<%s(%A)%>",
12137 pretty_name, arglist);
12138 else
12139 error ("call of overloaded %<%s(%A)%> is ambiguous",
12140 pretty_name, arglist);
12141 print_z_candidates (location_of (name), candidates);
12142 if (free_p)
12143 free (pretty_name);
12144 }
12145 call = error_mark_node;
12146 if (fn_p)
12147 *fn_p = error_mark_node;
12148 }
12149 else
12150 {
12151 fn = cand->fn;
12152 call = NULL_TREE;
12153
12154 if (!(flags & LOOKUP_NONVIRTUAL)
12155 && DECL_PURE_VIRTUAL_P (fn)
12156 && instance == current_class_ref
12157 && (complain & tf_warning))
12158 {
12159 /* This is not an error, it is runtime undefined
12160 behavior. */
12161 if (!current_function_decl)
12162 warning (0, "pure virtual %q#D called from "
12163 "non-static data member initializer", fn);
12164 else if (DECL_CONSTRUCTOR_P (current_function_decl)
12165 || DECL_DESTRUCTOR_P (current_function_decl))
12166 warning (0, (DECL_CONSTRUCTOR_P (current_function_decl)
12167 ? G_("pure virtual %q#D called from constructor")
12168 : G_("pure virtual %q#D called from destructor")),
12169 fn);
12170 }
12171
12172 if (DECL_OBJECT_MEMBER_FUNCTION_P (fn)
12173 && !DECL_CONSTRUCTOR_P (fn)
12174 && is_dummy_object (instance))
12175 {
12176 instance = maybe_resolve_dummy (instance, true);
12177 if (instance == error_mark_node)
12178 call = error_mark_node;
12179 else if (!is_dummy_object (instance))
12180 {
12181 /* We captured 'this' in the current lambda now that
12182 we know we really need it. */
12183 cand->first_arg = instance;
12184 }
12185 else if (current_class_ptr && any_dependent_bases_p ())
12186 /* We can't tell until instantiation time whether we can use
12187 *this as the implicit object argument. */;
12188 else
12189 {
12190 if (complain & tf_error)
12191 error ("cannot call member function %qD without object",
12192 fn);
12193 call = error_mark_node;
12194 }
12195 }
12196
12197 if (call != error_mark_node)
12198 {
12199 /* Now we know what function is being called. */
12200 if (fn_p)
12201 *fn_p = fn;
12202 /* Build the actual CALL_EXPR. */
12203 call = build_over_call (cand, flags, complain);
12204
12205 /* Suppress warnings for if (my_struct.operator= (x)) where
12206 my_struct is implicitly converted to bool. */
12207 if (TREE_CODE (call) == MODIFY_EXPR)
12208 suppress_warning (call, OPT_Wparentheses);
12209
12210 /* In an expression of the form `a->f()' where `f' turns
12211 out to be a static member function, `a' is
12212 none-the-less evaluated. */
12213 if (!is_dummy_object (instance))
12214 call = keep_unused_object_arg (call, instance, fn);
12215 if (call != error_mark_node
12216 && DECL_DESTRUCTOR_P (cand->fn)
12217 && !VOID_TYPE_P (TREE_TYPE (call)))
12218 /* An explicit call of the form "x->~X()" has type
12219 "void". However, on platforms where destructors
12220 return "this" (i.e., those where
12221 targetm.cxx.cdtor_returns_this is true), such calls
12222 will appear to have a return value of pointer type
12223 to the low-level call machinery. We do not want to
12224 change the low-level machinery, since we want to be
12225 able to optimize "delete f()" on such platforms as
12226 "operator delete(~X(f()))" (rather than generating
12227 "t = f(), ~X(t), operator delete (t)"). */
12228 call = build_nop (void_type_node, call);
12229 }
12230 }
12231 }
12232
12233 if (processing_template_decl && call != error_mark_node)
12234 {
12235 bool cast_to_void = false;
12236
12237 if (TREE_CODE (call) == COMPOUND_EXPR)
12238 call = TREE_OPERAND (call, 1);
12239 else if (TREE_CODE (call) == NOP_EXPR)
12240 {
12241 cast_to_void = true;
12242 call = TREE_OPERAND (call, 0);
12243 }
12244 if (INDIRECT_REF_P (call))
12245 call = TREE_OPERAND (call, 0);
12246
12247 /* Prune all but the selected function from the original overload
12248 set so that we can avoid some duplicate work at instantiation time. */
12249 if (really_overloaded_fn (fns))
12250 {
12251 if (DECL_TEMPLATE_INFO (fn)
12252 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
12253 {
12254 /* Use the selected template, not the specialization, so that
12255 this looks like an actual lookup result for sake of
12256 filter_memfn_lookup. */
12257
12258 if (OVL_SINGLE_P (fns))
12259 /* If the original overload set consists of a single function
12260 template, this isn't beneficial. */
12261 goto skip_prune;
12262
12263 fn = ovl_make (DECL_TI_TEMPLATE (fn));
12264 if (template_only)
12265 fn = lookup_template_function (fn, explicit_targs);
12266 }
12267 orig_fns = copy_node (orig_fns);
12268 BASELINK_FUNCTIONS (orig_fns) = fn;
12269 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (orig_fns) = true;
12270 }
12271
12272 skip_prune:
12273 call = (build_min_non_dep_call_vec
12274 (call,
12275 build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
12276 orig_instance, orig_fns, NULL_TREE),
12277 orig_args));
12278 SET_EXPR_LOCATION (call, input_location);
12279 call = convert_from_reference (call);
12280 if (cast_to_void)
12281 call = build_nop (void_type_node, call);
12282 }
12283
12284 if (orig_args != NULL)
12285 release_tree_vector (orig_args);
12286
12287 return call;
12288 }
12289
12290 /* Returns true iff standard conversion sequence ICS1 is a proper
12291 subsequence of ICS2. */
12292
12293 static bool
12294 is_subseq (conversion *ics1, conversion *ics2)
12295 {
12296 /* We can assume that a conversion of the same code
12297 between the same types indicates a subsequence since we only get
12298 here if the types we are converting from are the same. */
12299
12300 while (ics1->kind == ck_rvalue
12301 || ics1->kind == ck_lvalue)
12302 ics1 = next_conversion (ics1);
12303
12304 while (1)
12305 {
12306 while (ics2->kind == ck_rvalue
12307 || ics2->kind == ck_lvalue)
12308 ics2 = next_conversion (ics2);
12309
12310 if (ics2->kind == ck_user
12311 || !has_next (ics2->kind))
12312 /* At this point, ICS1 cannot be a proper subsequence of
12313 ICS2. We can get a USER_CONV when we are comparing the
12314 second standard conversion sequence of two user conversion
12315 sequences. */
12316 return false;
12317
12318 ics2 = next_conversion (ics2);
12319
12320 while (ics2->kind == ck_rvalue
12321 || ics2->kind == ck_lvalue)
12322 ics2 = next_conversion (ics2);
12323
12324 if (ics2->kind == ics1->kind
12325 && same_type_p (ics2->type, ics1->type)
12326 && (ics1->kind == ck_identity
12327 || same_type_p (next_conversion (ics2)->type,
12328 next_conversion (ics1)->type)))
12329 return true;
12330 }
12331 }
12332
12333 /* Returns nonzero iff DERIVED is derived from BASE. The inputs may
12334 be any _TYPE nodes. */
12335
12336 bool
12337 is_properly_derived_from (tree derived, tree base)
12338 {
12339 if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
12340 return false;
12341
12342 /* We only allow proper derivation here. The DERIVED_FROM_P macro
12343 considers every class derived from itself. */
12344 return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
12345 && DERIVED_FROM_P (base, derived));
12346 }
12347
12348 /* We build the ICS for an implicit object parameter as a pointer
12349 conversion sequence. However, such a sequence should be compared
12350 as if it were a reference conversion sequence. If ICS is the
12351 implicit conversion sequence for an implicit object parameter,
12352 modify it accordingly. */
12353
12354 static void
12355 maybe_handle_implicit_object (conversion **ics)
12356 {
12357 if ((*ics)->this_p)
12358 {
12359 /* [over.match.funcs]
12360
12361 For non-static member functions, the type of the
12362 implicit object parameter is "reference to cv X"
12363 where X is the class of which the function is a
12364 member and cv is the cv-qualification on the member
12365 function declaration. */
12366 conversion *t = *ics;
12367 tree reference_type;
12368
12369 /* The `this' parameter is a pointer to a class type. Make the
12370 implicit conversion talk about a reference to that same class
12371 type. */
12372 reference_type = TREE_TYPE (t->type);
12373 reference_type = build_reference_type (reference_type);
12374
12375 if (t->kind == ck_qual)
12376 t = next_conversion (t);
12377 if (t->kind == ck_ptr)
12378 t = next_conversion (t);
12379 t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
12380 t = direct_reference_binding (reference_type, t);
12381 t->this_p = 1;
12382 t->rvaluedness_matches_p = 0;
12383 *ics = t;
12384 }
12385 }
12386
12387 /* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
12388 and return the initial reference binding conversion. Otherwise,
12389 leave *ICS unchanged and return NULL. */
12390
12391 static conversion *
12392 maybe_handle_ref_bind (conversion **ics)
12393 {
12394 if ((*ics)->kind == ck_ref_bind)
12395 {
12396 conversion *old_ics = *ics;
12397 *ics = next_conversion (old_ics);
12398 (*ics)->user_conv_p = old_ics->user_conv_p;
12399 return old_ics;
12400 }
12401
12402 return NULL;
12403 }
12404
12405 /* Get the expression at the beginning of the conversion chain C. */
12406
12407 static tree
12408 conv_get_original_expr (conversion *c)
12409 {
12410 for (; c; c = next_conversion (c))
12411 if (c->kind == ck_identity || c->kind == ck_ambig || c->kind == ck_aggr)
12412 return c->u.expr;
12413 return NULL_TREE;
12414 }
12415
12416 /* Return a tree representing the number of elements initialized by the
12417 list-initialization C. The caller must check that C converts to an
12418 array type. */
12419
12420 static tree
12421 nelts_initialized_by_list_init (conversion *c)
12422 {
12423 /* If the array we're converting to has a dimension, we'll use that. */
12424 if (TYPE_DOMAIN (c->type))
12425 return array_type_nelts_top (c->type);
12426 else
12427 {
12428 /* Otherwise, we look at how many elements the constructor we're
12429 initializing from has. */
12430 tree ctor = conv_get_original_expr (c);
12431 return size_int (CONSTRUCTOR_NELTS (ctor));
12432 }
12433 }
12434
12435 /* True iff C is a conversion that binds a reference or a pointer to
12436 an array of unknown bound. */
12437
12438 static inline bool
12439 conv_binds_to_array_of_unknown_bound (conversion *c)
12440 {
12441 /* ck_ref_bind won't have the reference stripped. */
12442 tree type = non_reference (c->type);
12443 /* ck_qual won't have the pointer stripped. */
12444 type = strip_pointer_operator (type);
12445 return (TREE_CODE (type) == ARRAY_TYPE
12446 && TYPE_DOMAIN (type) == NULL_TREE);
12447 }
12448
12449 /* Compare two implicit conversion sequences according to the rules set out in
12450 [over.ics.rank]. Return values:
12451
12452 1: ics1 is better than ics2
12453 -1: ics2 is better than ics1
12454 0: ics1 and ics2 are indistinguishable */
12455
12456 static int
12457 compare_ics (conversion *ics1, conversion *ics2)
12458 {
12459 tree from_type1;
12460 tree from_type2;
12461 tree to_type1;
12462 tree to_type2;
12463 tree deref_from_type1 = NULL_TREE;
12464 tree deref_from_type2 = NULL_TREE;
12465 tree deref_to_type1 = NULL_TREE;
12466 tree deref_to_type2 = NULL_TREE;
12467 conversion_rank rank1, rank2;
12468
12469 /* REF_BINDING is nonzero if the result of the conversion sequence
12470 is a reference type. In that case REF_CONV is the reference
12471 binding conversion. */
12472 conversion *ref_conv1;
12473 conversion *ref_conv2;
12474
12475 /* Compare badness before stripping the reference conversion. */
12476 if (ics1->bad_p > ics2->bad_p)
12477 return -1;
12478 else if (ics1->bad_p < ics2->bad_p)
12479 return 1;
12480
12481 /* Handle implicit object parameters. */
12482 maybe_handle_implicit_object (&ics1);
12483 maybe_handle_implicit_object (&ics2);
12484
12485 /* Handle reference parameters. */
12486 ref_conv1 = maybe_handle_ref_bind (&ics1);
12487 ref_conv2 = maybe_handle_ref_bind (&ics2);
12488
12489 /* List-initialization sequence L1 is a better conversion sequence than
12490 list-initialization sequence L2 if L1 converts to
12491 std::initializer_list<X> for some X and L2 does not. */
12492 if (ics1->kind == ck_list && ics2->kind != ck_list)
12493 return 1;
12494 if (ics2->kind == ck_list && ics1->kind != ck_list)
12495 return -1;
12496
12497 /* [over.ics.rank]
12498
12499 When comparing the basic forms of implicit conversion sequences (as
12500 defined in _over.best.ics_)
12501
12502 --a standard conversion sequence (_over.ics.scs_) is a better
12503 conversion sequence than a user-defined conversion sequence
12504 or an ellipsis conversion sequence, and
12505
12506 --a user-defined conversion sequence (_over.ics.user_) is a
12507 better conversion sequence than an ellipsis conversion sequence
12508 (_over.ics.ellipsis_). */
12509 /* Use BAD_CONVERSION_RANK because we already checked for a badness
12510 mismatch. If both ICS are bad, we try to make a decision based on
12511 what would have happened if they'd been good. This is not an
12512 extension, we'll still give an error when we build up the call; this
12513 just helps us give a more helpful error message. */
12514 rank1 = BAD_CONVERSION_RANK (ics1);
12515 rank2 = BAD_CONVERSION_RANK (ics2);
12516
12517 if (rank1 > rank2)
12518 return -1;
12519 else if (rank1 < rank2)
12520 return 1;
12521
12522 if (ics1->ellipsis_p)
12523 /* Both conversions are ellipsis conversions. */
12524 return 0;
12525
12526 /* User-defined conversion sequence U1 is a better conversion sequence
12527 than another user-defined conversion sequence U2 if they contain the
12528 same user-defined conversion operator or constructor and if the sec-
12529 ond standard conversion sequence of U1 is better than the second
12530 standard conversion sequence of U2. */
12531
12532 /* Handle list-conversion with the same code even though it isn't always
12533 ranked as a user-defined conversion and it doesn't have a second
12534 standard conversion sequence; it will still have the desired effect.
12535 Specifically, we need to do the reference binding comparison at the
12536 end of this function. */
12537
12538 if (ics1->user_conv_p || ics1->kind == ck_list
12539 || ics1->kind == ck_aggr || ics2->kind == ck_aggr)
12540 {
12541 conversion *t1 = strip_standard_conversion (ics1);
12542 conversion *t2 = strip_standard_conversion (ics2);
12543
12544 if (!t1 || !t2 || t1->kind != t2->kind)
12545 return 0;
12546 else if (t1->kind == ck_user)
12547 {
12548 tree f1 = t1->cand ? t1->cand->fn : t1->type;
12549 tree f2 = t2->cand ? t2->cand->fn : t2->type;
12550 if (f1 != f2)
12551 return 0;
12552 }
12553 /* List-initialization sequence L1 is a better conversion sequence than
12554 list-initialization sequence L2 if
12555
12556 -- L1 and L2 convert to arrays of the same element type, and either
12557 the number of elements n1 initialized by L1 is less than the number
12558 of elements n2 initialized by L2, or n1=n2 and L2 converts to an array
12559 of unknown bound and L1 does not. (Added in CWG 1307 and extended by
12560 P0388R4.) */
12561 else if (t1->kind == ck_aggr
12562 && TREE_CODE (t1->type) == ARRAY_TYPE
12563 && TREE_CODE (t2->type) == ARRAY_TYPE
12564 && same_type_p (TREE_TYPE (t1->type), TREE_TYPE (t2->type)))
12565 {
12566 tree n1 = nelts_initialized_by_list_init (t1);
12567 tree n2 = nelts_initialized_by_list_init (t2);
12568 if (tree_int_cst_lt (n1, n2))
12569 return 1;
12570 else if (tree_int_cst_lt (n2, n1))
12571 return -1;
12572 /* The n1 == n2 case. */
12573 bool c1 = conv_binds_to_array_of_unknown_bound (t1);
12574 bool c2 = conv_binds_to_array_of_unknown_bound (t2);
12575 if (c1 && !c2)
12576 return -1;
12577 else if (!c1 && c2)
12578 return 1;
12579 else
12580 return 0;
12581 }
12582 else
12583 {
12584 /* For ambiguous or aggregate conversions, use the target type as
12585 a proxy for the conversion function. */
12586 if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
12587 return 0;
12588 }
12589
12590 /* We can just fall through here, after setting up
12591 FROM_TYPE1 and FROM_TYPE2. */
12592 from_type1 = t1->type;
12593 from_type2 = t2->type;
12594 }
12595 else
12596 {
12597 conversion *t1;
12598 conversion *t2;
12599
12600 /* We're dealing with two standard conversion sequences.
12601
12602 [over.ics.rank]
12603
12604 Standard conversion sequence S1 is a better conversion
12605 sequence than standard conversion sequence S2 if
12606
12607 --S1 is a proper subsequence of S2 (comparing the conversion
12608 sequences in the canonical form defined by _over.ics.scs_,
12609 excluding any Lvalue Transformation; the identity
12610 conversion sequence is considered to be a subsequence of
12611 any non-identity conversion sequence */
12612
12613 t1 = ics1;
12614 while (t1->kind != ck_identity)
12615 t1 = next_conversion (t1);
12616 from_type1 = t1->type;
12617
12618 t2 = ics2;
12619 while (t2->kind != ck_identity)
12620 t2 = next_conversion (t2);
12621 from_type2 = t2->type;
12622 }
12623
12624 /* One sequence can only be a subsequence of the other if they start with
12625 the same type. They can start with different types when comparing the
12626 second standard conversion sequence in two user-defined conversion
12627 sequences. */
12628 if (same_type_p (from_type1, from_type2))
12629 {
12630 if (is_subseq (ics1, ics2))
12631 return 1;
12632 if (is_subseq (ics2, ics1))
12633 return -1;
12634 }
12635
12636 /* [over.ics.rank]
12637
12638 Or, if not that,
12639
12640 --the rank of S1 is better than the rank of S2 (by the rules
12641 defined below):
12642
12643 Standard conversion sequences are ordered by their ranks: an Exact
12644 Match is a better conversion than a Promotion, which is a better
12645 conversion than a Conversion.
12646
12647 Two conversion sequences with the same rank are indistinguishable
12648 unless one of the following rules applies:
12649
12650 --A conversion that does not a convert a pointer, pointer to member,
12651 or std::nullptr_t to bool is better than one that does.
12652
12653 The ICS_STD_RANK automatically handles the pointer-to-bool rule,
12654 so that we do not have to check it explicitly. */
12655 if (ics1->rank < ics2->rank)
12656 return 1;
12657 else if (ics2->rank < ics1->rank)
12658 return -1;
12659
12660 to_type1 = ics1->type;
12661 to_type2 = ics2->type;
12662
12663 /* A conversion from scalar arithmetic type to complex is worse than a
12664 conversion between scalar arithmetic types. */
12665 if (same_type_p (from_type1, from_type2)
12666 && ARITHMETIC_TYPE_P (from_type1)
12667 && ARITHMETIC_TYPE_P (to_type1)
12668 && ARITHMETIC_TYPE_P (to_type2)
12669 && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
12670 != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
12671 {
12672 if (TREE_CODE (to_type1) == COMPLEX_TYPE)
12673 return -1;
12674 else
12675 return 1;
12676 }
12677
12678 {
12679 /* A conversion in either direction between floating-point type FP1 and
12680 floating-point type FP2 is better than a conversion in the same
12681 direction between FP1 and arithmetic type T3 if
12682 - the floating-point conversion rank of FP1 is equal to the rank of
12683 FP2, and
12684 - T3 is not a floating-point type, or T3 is a floating-point type
12685 whose rank is not equal to the rank of FP1, or the floating-point
12686 conversion subrank of FP2 is greater than the subrank of T3. */
12687 tree fp1 = from_type1;
12688 tree fp2 = to_type1;
12689 tree fp3 = from_type2;
12690 tree t3 = to_type2;
12691 int ret = 1;
12692 if (TYPE_MAIN_VARIANT (fp2) == TYPE_MAIN_VARIANT (t3))
12693 {
12694 std::swap (fp1, fp2);
12695 std::swap (fp3, t3);
12696 }
12697 if (TYPE_MAIN_VARIANT (fp1) == TYPE_MAIN_VARIANT (fp3)
12698 && SCALAR_FLOAT_TYPE_P (fp1)
12699 /* Only apply this rule if at least one of the 3 types is
12700 extended floating-point type, otherwise keep them as
12701 before for compatibility reasons with types like __float128.
12702 float, double and long double alone have different conversion
12703 ranks and so when just those 3 types are involved, this
12704 rule doesn't trigger. */
12705 && (extended_float_type_p (fp1)
12706 || (SCALAR_FLOAT_TYPE_P (fp2) && extended_float_type_p (fp2))
12707 || (SCALAR_FLOAT_TYPE_P (t3) && extended_float_type_p (t3))))
12708 {
12709 if (TREE_CODE (fp2) != REAL_TYPE)
12710 {
12711 ret = -ret;
12712 std::swap (fp2, t3);
12713 }
12714 if (SCALAR_FLOAT_TYPE_P (fp2))
12715 {
12716 /* cp_compare_floating_point_conversion_ranks returns -1, 0 or 1
12717 if the conversion rank is equal (-1 or 1 if the subrank is
12718 different). */
12719 if (IN_RANGE (cp_compare_floating_point_conversion_ranks (fp1,
12720 fp2),
12721 -1, 1))
12722 {
12723 /* Conversion ranks of FP1 and FP2 are equal. */
12724 if (TREE_CODE (t3) != REAL_TYPE
12725 || !IN_RANGE (cp_compare_floating_point_conversion_ranks
12726 (fp1, t3),
12727 -1, 1))
12728 /* FP1 <-> FP2 conversion is better. */
12729 return ret;
12730 int c = cp_compare_floating_point_conversion_ranks (fp2, t3);
12731 gcc_assert (IN_RANGE (c, -1, 1));
12732 if (c == 1)
12733 /* Conversion subrank of FP2 is greater than subrank of T3.
12734 FP1 <-> FP2 conversion is better. */
12735 return ret;
12736 else if (c == -1)
12737 /* Conversion subrank of FP2 is less than subrank of T3.
12738 FP1 <-> T3 conversion is better. */
12739 return -ret;
12740 }
12741 else if (SCALAR_FLOAT_TYPE_P (t3)
12742 && IN_RANGE (cp_compare_floating_point_conversion_ranks
12743 (fp1, t3),
12744 -1, 1))
12745 /* Conversion ranks of FP1 and FP2 are not equal, conversion
12746 ranks of FP1 and T3 are equal.
12747 FP1 <-> T3 conversion is better. */
12748 return -ret;
12749 }
12750 }
12751 }
12752
12753 if (TYPE_PTR_P (from_type1)
12754 && TYPE_PTR_P (from_type2)
12755 && TYPE_PTR_P (to_type1)
12756 && TYPE_PTR_P (to_type2))
12757 {
12758 deref_from_type1 = TREE_TYPE (from_type1);
12759 deref_from_type2 = TREE_TYPE (from_type2);
12760 deref_to_type1 = TREE_TYPE (to_type1);
12761 deref_to_type2 = TREE_TYPE (to_type2);
12762 }
12763 /* The rules for pointers to members A::* are just like the rules
12764 for pointers A*, except opposite: if B is derived from A then
12765 A::* converts to B::*, not vice versa. For that reason, we
12766 switch the from_ and to_ variables here. */
12767 else if ((TYPE_PTRDATAMEM_P (from_type1) && TYPE_PTRDATAMEM_P (from_type2)
12768 && TYPE_PTRDATAMEM_P (to_type1) && TYPE_PTRDATAMEM_P (to_type2))
12769 || (TYPE_PTRMEMFUNC_P (from_type1)
12770 && TYPE_PTRMEMFUNC_P (from_type2)
12771 && TYPE_PTRMEMFUNC_P (to_type1)
12772 && TYPE_PTRMEMFUNC_P (to_type2)))
12773 {
12774 deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
12775 deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
12776 deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
12777 deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
12778 }
12779
12780 if (deref_from_type1 != NULL_TREE
12781 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
12782 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
12783 {
12784 /* This was one of the pointer or pointer-like conversions.
12785
12786 [over.ics.rank]
12787
12788 --If class B is derived directly or indirectly from class A,
12789 conversion of B* to A* is better than conversion of B* to
12790 void*, and conversion of A* to void* is better than
12791 conversion of B* to void*. */
12792 if (VOID_TYPE_P (deref_to_type1)
12793 && VOID_TYPE_P (deref_to_type2))
12794 {
12795 if (is_properly_derived_from (deref_from_type1,
12796 deref_from_type2))
12797 return -1;
12798 else if (is_properly_derived_from (deref_from_type2,
12799 deref_from_type1))
12800 return 1;
12801 }
12802 else if (VOID_TYPE_P (deref_to_type1)
12803 || VOID_TYPE_P (deref_to_type2))
12804 {
12805 if (same_type_p (deref_from_type1, deref_from_type2))
12806 {
12807 if (VOID_TYPE_P (deref_to_type2))
12808 {
12809 if (is_properly_derived_from (deref_from_type1,
12810 deref_to_type1))
12811 return 1;
12812 }
12813 /* We know that DEREF_TO_TYPE1 is `void' here. */
12814 else if (is_properly_derived_from (deref_from_type1,
12815 deref_to_type2))
12816 return -1;
12817 }
12818 }
12819 else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
12820 && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
12821 {
12822 /* [over.ics.rank]
12823
12824 --If class B is derived directly or indirectly from class A
12825 and class C is derived directly or indirectly from B,
12826
12827 --conversion of C* to B* is better than conversion of C* to
12828 A*,
12829
12830 --conversion of B* to A* is better than conversion of C* to
12831 A* */
12832 if (same_type_p (deref_from_type1, deref_from_type2))
12833 {
12834 if (is_properly_derived_from (deref_to_type1,
12835 deref_to_type2))
12836 return 1;
12837 else if (is_properly_derived_from (deref_to_type2,
12838 deref_to_type1))
12839 return -1;
12840 }
12841 else if (same_type_p (deref_to_type1, deref_to_type2))
12842 {
12843 if (is_properly_derived_from (deref_from_type2,
12844 deref_from_type1))
12845 return 1;
12846 else if (is_properly_derived_from (deref_from_type1,
12847 deref_from_type2))
12848 return -1;
12849 }
12850 }
12851 }
12852 else if (CLASS_TYPE_P (non_reference (from_type1))
12853 && same_type_p (from_type1, from_type2))
12854 {
12855 tree from = non_reference (from_type1);
12856
12857 /* [over.ics.rank]
12858
12859 --binding of an expression of type C to a reference of type
12860 B& is better than binding an expression of type C to a
12861 reference of type A&
12862
12863 --conversion of C to B is better than conversion of C to A, */
12864 if (is_properly_derived_from (from, to_type1)
12865 && is_properly_derived_from (from, to_type2))
12866 {
12867 if (is_properly_derived_from (to_type1, to_type2))
12868 return 1;
12869 else if (is_properly_derived_from (to_type2, to_type1))
12870 return -1;
12871 }
12872 }
12873 else if (CLASS_TYPE_P (non_reference (to_type1))
12874 && same_type_p (to_type1, to_type2))
12875 {
12876 tree to = non_reference (to_type1);
12877
12878 /* [over.ics.rank]
12879
12880 --binding of an expression of type B to a reference of type
12881 A& is better than binding an expression of type C to a
12882 reference of type A&,
12883
12884 --conversion of B to A is better than conversion of C to A */
12885 if (is_properly_derived_from (from_type1, to)
12886 && is_properly_derived_from (from_type2, to))
12887 {
12888 if (is_properly_derived_from (from_type2, from_type1))
12889 return 1;
12890 else if (is_properly_derived_from (from_type1, from_type2))
12891 return -1;
12892 }
12893 }
12894
12895 /* [over.ics.rank]
12896
12897 --S1 and S2 differ only in their qualification conversion and yield
12898 similar types T1 and T2 (_conv.qual_), respectively, and the cv-
12899 qualification signature of type T1 is a proper subset of the cv-
12900 qualification signature of type T2 */
12901 if (ics1->kind == ck_qual
12902 && ics2->kind == ck_qual
12903 && same_type_p (from_type1, from_type2))
12904 {
12905 int result = comp_cv_qual_signature (to_type1, to_type2);
12906 if (result != 0)
12907 return result;
12908 }
12909
12910 /* [over.ics.rank]
12911
12912 --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
12913 to an implicit object parameter of a non-static member function
12914 declared without a ref-qualifier, and either S1 binds an lvalue
12915 reference to an lvalue and S2 binds an rvalue reference or S1 binds an
12916 rvalue reference to an rvalue and S2 binds an lvalue reference (C++0x
12917 draft standard, 13.3.3.2)
12918
12919 --S1 and S2 are reference bindings (_dcl.init.ref_), and the
12920 types to which the references refer are the same type except for
12921 top-level cv-qualifiers, and the type to which the reference
12922 initialized by S2 refers is more cv-qualified than the type to
12923 which the reference initialized by S1 refers.
12924
12925 DR 1328 [over.match.best]: the context is an initialization by
12926 conversion function for direct reference binding (13.3.1.6) of a
12927 reference to function type, the return type of F1 is the same kind of
12928 reference (i.e. lvalue or rvalue) as the reference being initialized,
12929 and the return type of F2 is not. */
12930
12931 if (ref_conv1 && ref_conv2)
12932 {
12933 if (!ref_conv1->this_p && !ref_conv2->this_p
12934 && (ref_conv1->rvaluedness_matches_p
12935 != ref_conv2->rvaluedness_matches_p)
12936 && (same_type_p (ref_conv1->type, ref_conv2->type)
12937 || (TYPE_REF_IS_RVALUE (ref_conv1->type)
12938 != TYPE_REF_IS_RVALUE (ref_conv2->type))))
12939 {
12940 if (ref_conv1->bad_p
12941 && !same_type_p (TREE_TYPE (ref_conv1->type),
12942 TREE_TYPE (ref_conv2->type)))
12943 /* Don't prefer a bad conversion that drops cv-quals to a bad
12944 conversion with the wrong rvalueness. */
12945 return 0;
12946 return (ref_conv1->rvaluedness_matches_p
12947 - ref_conv2->rvaluedness_matches_p);
12948 }
12949
12950 if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
12951 {
12952 /* Per P0388R4:
12953
12954 void f (int(&)[]), // (1)
12955 f (int(&)[1]), // (2)
12956 f (int*); // (3)
12957
12958 (2) is better than (1), but (3) should be equal to (1) and to
12959 (2). For that reason we don't use ck_qual for (1) which would
12960 give it the cr_exact rank while (3) remains ck_identity.
12961 Therefore we compare (1) and (2) here. For (1) we'll have
12962
12963 ck_ref_bind <- ck_identity
12964 int[] & int[1]
12965
12966 so to handle this we must look at ref_conv. */
12967 bool c1 = conv_binds_to_array_of_unknown_bound (ref_conv1);
12968 bool c2 = conv_binds_to_array_of_unknown_bound (ref_conv2);
12969 if (c1 && !c2)
12970 return -1;
12971 else if (!c1 && c2)
12972 return 1;
12973
12974 int q1 = cp_type_quals (TREE_TYPE (ref_conv1->type));
12975 int q2 = cp_type_quals (TREE_TYPE (ref_conv2->type));
12976 if (ref_conv1->bad_p)
12977 {
12978 /* Prefer the one that drops fewer cv-quals. */
12979 tree ftype = next_conversion (ref_conv1)->type;
12980 int fquals = cp_type_quals (ftype);
12981 q1 ^= fquals;
12982 q2 ^= fquals;
12983 }
12984 return comp_cv_qualification (q2, q1);
12985 }
12986 }
12987
12988 /* [over.ics.rank]
12989
12990 Per CWG 1601:
12991 -- A conversion that promotes an enumeration whose underlying type
12992 is fixed to its underlying type is better than one that promotes to
12993 the promoted underlying type, if the two are different. */
12994 if (ics1->rank == cr_promotion
12995 && ics2->rank == cr_promotion
12996 && UNSCOPED_ENUM_P (from_type1)
12997 && ENUM_FIXED_UNDERLYING_TYPE_P (from_type1)
12998 && same_type_p (from_type1, from_type2))
12999 {
13000 tree utype = ENUM_UNDERLYING_TYPE (from_type1);
13001 tree prom = type_promotes_to (from_type1);
13002 if (!same_type_p (utype, prom))
13003 {
13004 if (same_type_p (to_type1, utype)
13005 && same_type_p (to_type2, prom))
13006 return 1;
13007 else if (same_type_p (to_type2, utype)
13008 && same_type_p (to_type1, prom))
13009 return -1;
13010 }
13011 }
13012
13013 /* Neither conversion sequence is better than the other. */
13014 return 0;
13015 }
13016
13017 /* The source type for this standard conversion sequence. */
13018
13019 static tree
13020 source_type (conversion *t)
13021 {
13022 return strip_standard_conversion (t)->type;
13023 }
13024
13025 /* Note a warning about preferring WINNER to LOSER. We do this by storing
13026 a pointer to LOSER and re-running joust to produce the warning if WINNER
13027 is actually used. */
13028
13029 static void
13030 add_warning (struct z_candidate *winner, struct z_candidate *loser)
13031 {
13032 candidate_warning *cw = (candidate_warning *)
13033 conversion_obstack_alloc (sizeof (candidate_warning));
13034 cw->loser = loser;
13035 cw->next = winner->warnings;
13036 winner->warnings = cw;
13037 }
13038
13039 /* CAND is a constructor candidate in joust in C++17 and up. If it copies a
13040 prvalue returned from a conversion function, return true. Otherwise, return
13041 false. */
13042
13043 static bool
13044 joust_maybe_elide_copy (z_candidate *cand)
13045 {
13046 tree fn = cand->fn;
13047 if (!DECL_COPY_CONSTRUCTOR_P (fn) && !DECL_MOVE_CONSTRUCTOR_P (fn))
13048 return false;
13049 conversion *conv = cand->convs[0];
13050 if (conv->kind == ck_ambig)
13051 return false;
13052 gcc_checking_assert (conv->kind == ck_ref_bind);
13053 conv = next_conversion (conv);
13054 if (conv->kind == ck_user && !TYPE_REF_P (conv->type))
13055 {
13056 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
13057 (conv->type, DECL_CONTEXT (fn)));
13058 z_candidate *uc = conv->cand;
13059 if (DECL_CONV_FN_P (uc->fn))
13060 return true;
13061 }
13062 return false;
13063 }
13064
13065 /* Return the class that CAND's implicit object parameter refers to. */
13066
13067 static tree
13068 class_of_implicit_object (z_candidate *cand)
13069 {
13070 if (!DECL_IOBJ_MEMBER_FUNCTION_P (cand->fn))
13071 return NULL_TREE;
13072
13073 /* "For conversion functions that are implicit object member functions,
13074 the function is considered to be a member of the class of the implied
13075 object argument for the purpose of defining the type of the implicit
13076 object parameter." */
13077 if (DECL_CONV_FN_P (cand->fn))
13078 return TYPE_MAIN_VARIANT (TREE_TYPE (cand->first_arg));
13079
13080 /* "For non-conversion functions that are implicit object member
13081 functions nominated by a using-declaration in a derived class, the
13082 function is considered to be a member of the derived class for the
13083 purpose of defining the type of the implicit object parameter."
13084
13085 That derived class is reflected in the conversion_path binfo. */
13086 return BINFO_TYPE (cand->conversion_path);
13087 }
13088
13089 /* Return whether the first parameter of C1 matches the second parameter
13090 of C2. */
13091
13092 static bool
13093 reversed_match (z_candidate *c1, z_candidate *c2)
13094 {
13095 tree fn1 = c1->fn;
13096 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (c2->fn));
13097 tree parm2 = TREE_VALUE (TREE_CHAIN (parms2));
13098 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn1))
13099 {
13100 tree ctx = class_of_implicit_object (c1);
13101 return iobj_parm_corresponds_to (fn1, parm2, ctx);
13102 }
13103 else
13104 {
13105 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
13106 tree parm1 = TREE_VALUE (parms1);
13107 return same_type_p (parm1, parm2);
13108 }
13109 }
13110
13111 /* True if the defining declarations of the two candidates have equivalent
13112 parameters. MATCH_KIND controls whether we're trying to compare the
13113 original declarations (for a warning) or the actual candidates. */
13114
13115 enum class pmatch { original, current };
13116
13117 static bool
13118 cand_parms_match (z_candidate *c1, z_candidate *c2, pmatch match_kind)
13119 {
13120 tree fn1 = c1->fn;
13121 tree fn2 = c2->fn;
13122 bool reversed = (match_kind == pmatch::current
13123 && c1->reversed () != c2->reversed ());
13124 if (fn1 == fn2 && !reversed)
13125 return true;
13126 if (identifier_p (fn1) || identifier_p (fn2))
13127 return false;
13128 if (match_kind == pmatch::original)
13129 {
13130 /* We don't look at c1->template_decl because that's only set for
13131 primary templates, not e.g. non-template member functions of
13132 class templates. */
13133 tree t1 = most_general_template (fn1);
13134 tree t2 = most_general_template (fn2);
13135 if (t1 || t2)
13136 {
13137 if (!t1 || !t2)
13138 return false;
13139 if (t1 == t2)
13140 return true;
13141 fn1 = DECL_TEMPLATE_RESULT (t1);
13142 fn2 = DECL_TEMPLATE_RESULT (t2);
13143 }
13144 }
13145
13146 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn1));
13147 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (fn2));
13148
13149 if (DECL_FUNCTION_MEMBER_P (fn1)
13150 && DECL_FUNCTION_MEMBER_P (fn2))
13151 {
13152 tree base1 = DECL_CONTEXT (strip_inheriting_ctors (fn1));
13153 tree base2 = DECL_CONTEXT (strip_inheriting_ctors (fn2));
13154 if (base1 != base2)
13155 return false;
13156
13157 if (reversed)
13158 return (reversed_match (c1, c2)
13159 && reversed_match (c2, c1));
13160
13161 /* Use object_parms_correspond to simplify comparing iobj/xobj/static
13162 member functions. */
13163 if (!object_parms_correspond (fn1, fn2, base1))
13164 return false;
13165
13166 /* We just compared the object parameters, if they don't correspond
13167 we already returned false. */
13168 auto skip_parms = [] (tree fn, tree parms)
13169 {
13170 if (DECL_XOBJ_MEMBER_FUNCTION_P (fn))
13171 return TREE_CHAIN (parms);
13172 else
13173 return skip_artificial_parms_for (fn, parms);
13174 };
13175 parms1 = skip_parms (fn1, parms1);
13176 parms2 = skip_parms (fn2, parms2);
13177 }
13178 else if (reversed)
13179 return (reversed_match (c1, c2)
13180 && reversed_match (c2, c1));
13181 return compparms (parms1, parms2);
13182 }
13183
13184 /* True iff FN is a copy or move constructor or assignment operator. */
13185
13186 static bool
13187 sfk_copy_or_move (tree fn)
13188 {
13189 if (TREE_CODE (fn) != FUNCTION_DECL)
13190 return false;
13191 special_function_kind sfk = special_function_p (fn);
13192 return sfk >= sfk_copy_constructor && sfk <= sfk_move_assignment;
13193 }
13194
13195 /* Compare two candidates for overloading as described in
13196 [over.match.best]. Return values:
13197
13198 1: cand1 is better than cand2
13199 -1: cand2 is better than cand1
13200 0: cand1 and cand2 are indistinguishable */
13201
13202 static int
13203 joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn,
13204 tsubst_flags_t complain)
13205 {
13206 int winner = 0;
13207 int off1 = 0, off2 = 0;
13208 size_t i;
13209 size_t len;
13210
13211 /* Candidates that involve bad conversions are always worse than those
13212 that don't. */
13213 if (cand1->viable > cand2->viable)
13214 return 1;
13215 if (cand1->viable < cand2->viable)
13216 return -1;
13217
13218 /* If we have two pseudo-candidates for conversions to the same type,
13219 or two candidates for the same function, arbitrarily pick one. */
13220 if (cand1->fn == cand2->fn
13221 && cand1->reversed () == cand2->reversed ()
13222 && (IS_TYPE_OR_DECL_P (cand1->fn)))
13223 return 1;
13224
13225 /* Prefer a non-deleted function over an implicitly deleted move
13226 constructor or assignment operator. This differs slightly from the
13227 wording for issue 1402 (which says the move op is ignored by overload
13228 resolution), but this way produces better error messages. */
13229 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
13230 && TREE_CODE (cand2->fn) == FUNCTION_DECL
13231 && DECL_DELETED_FN (cand1->fn) != DECL_DELETED_FN (cand2->fn))
13232 {
13233 if (DECL_DELETED_FN (cand1->fn) && DECL_DEFAULTED_FN (cand1->fn)
13234 && move_fn_p (cand1->fn))
13235 return -1;
13236 if (DECL_DELETED_FN (cand2->fn) && DECL_DEFAULTED_FN (cand2->fn)
13237 && move_fn_p (cand2->fn))
13238 return 1;
13239 }
13240
13241 /* a viable function F1
13242 is defined to be a better function than another viable function F2 if
13243 for all arguments i, ICSi(F1) is not a worse conversion sequence than
13244 ICSi(F2), and then */
13245
13246 /* for some argument j, ICSj(F1) is a better conversion sequence than
13247 ICSj(F2) */
13248
13249 /* For comparing static and non-static member functions, we ignore
13250 the implicit object parameter of the non-static function. The
13251 standard says to pretend that the static function has an object
13252 parm, but that won't work with operator overloading. */
13253 len = cand1->num_convs;
13254 if (len != cand2->num_convs)
13255 {
13256 int static_1 = (TREE_CODE (cand1->fn) == FUNCTION_DECL
13257 && DECL_STATIC_FUNCTION_P (cand1->fn));
13258 int static_2 = (TREE_CODE (cand2->fn) == FUNCTION_DECL
13259 && DECL_STATIC_FUNCTION_P (cand2->fn));
13260
13261 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
13262 && TREE_CODE (cand2->fn) == FUNCTION_DECL
13263 && DECL_CONSTRUCTOR_P (cand1->fn)
13264 && is_list_ctor (cand1->fn) != is_list_ctor (cand2->fn))
13265 /* We're comparing a near-match list constructor and a near-match
13266 non-list constructor. Just treat them as unordered. */
13267 return 0;
13268
13269 gcc_assert (static_1 != static_2);
13270
13271 if (static_1)
13272 {
13273 /* C++23 [over.best.ics.general] says:
13274 When the parameter is the implicit object parameter of a static
13275 member function, the implicit conversion sequence is a standard
13276 conversion sequence that is neither better nor worse than any
13277 other standard conversion sequence. */
13278 if (CONVERSION_RANK (cand2->convs[0]) >= cr_user)
13279 winner = 1;
13280 off2 = 1;
13281 }
13282 else
13283 {
13284 if (CONVERSION_RANK (cand1->convs[0]) >= cr_user)
13285 winner = -1;
13286 off1 = 1;
13287 --len;
13288 }
13289 }
13290
13291 for (i = 0; i < len; ++i)
13292 {
13293 conversion *t1 = cand1->convs[i + off1];
13294 conversion *t2 = cand2->convs[i + off2];
13295 int comp = compare_ics (t1, t2);
13296
13297 if (comp != 0)
13298 {
13299 if ((complain & tf_warning)
13300 && warn_sign_promo
13301 && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
13302 == cr_std + cr_promotion)
13303 && t1->kind == ck_std
13304 && t2->kind == ck_std
13305 && TREE_CODE (t1->type) == INTEGER_TYPE
13306 && TREE_CODE (t2->type) == INTEGER_TYPE
13307 && (TYPE_PRECISION (t1->type)
13308 == TYPE_PRECISION (t2->type))
13309 && (TYPE_UNSIGNED (next_conversion (t1)->type)
13310 || (TREE_CODE (next_conversion (t1)->type)
13311 == ENUMERAL_TYPE)))
13312 {
13313 tree type = next_conversion (t1)->type;
13314 tree type1, type2;
13315 struct z_candidate *w, *l;
13316 if (comp > 0)
13317 type1 = t1->type, type2 = t2->type,
13318 w = cand1, l = cand2;
13319 else
13320 type1 = t2->type, type2 = t1->type,
13321 w = cand2, l = cand1;
13322
13323 if (warn)
13324 {
13325 warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
13326 type, type1, type2);
13327 warning (OPT_Wsign_promo, " in call to %qD", w->fn);
13328 }
13329 else
13330 add_warning (w, l);
13331 }
13332
13333 if (winner && comp != winner)
13334 {
13335 /* Ambiguity between normal and reversed comparison operators
13336 with the same parameter types. P2468 decided not to go with
13337 this approach to resolving the ambiguity, so pedwarn. */
13338 if ((complain & tf_warning_or_error)
13339 && (cand1->reversed () != cand2->reversed ())
13340 && cand_parms_match (cand1, cand2, pmatch::original))
13341 {
13342 struct z_candidate *w, *l;
13343 if (cand2->reversed ())
13344 winner = 1, w = cand1, l = cand2;
13345 else
13346 winner = -1, w = cand2, l = cand1;
13347 if (warn)
13348 {
13349 auto_diagnostic_group d;
13350 if (pedwarn (input_location, 0,
13351 "C++20 says that these are ambiguous, "
13352 "even though the second is reversed:"))
13353 {
13354 print_z_candidate (input_location,
13355 N_("candidate 1:"), w);
13356 print_z_candidate (input_location,
13357 N_("candidate 2:"), l);
13358 if (w->fn == l->fn
13359 && DECL_IOBJ_MEMBER_FUNCTION_P (w->fn)
13360 && (type_memfn_quals (TREE_TYPE (w->fn))
13361 & TYPE_QUAL_CONST) == 0)
13362 {
13363 /* Suggest adding const to
13364 struct A { bool operator==(const A&); }; */
13365 tree parmtype
13366 = FUNCTION_FIRST_USER_PARMTYPE (w->fn);
13367 parmtype = TREE_VALUE (parmtype);
13368 if (TYPE_REF_P (parmtype)
13369 && TYPE_READONLY (TREE_TYPE (parmtype))
13370 && (same_type_ignoring_top_level_qualifiers_p
13371 (TREE_TYPE (parmtype),
13372 DECL_CONTEXT (w->fn))))
13373 inform (DECL_SOURCE_LOCATION (w->fn),
13374 "try making the operator a %<const%> "
13375 "member function");
13376 }
13377 }
13378 }
13379 else
13380 add_warning (w, l);
13381 return winner;
13382 }
13383
13384 winner = 0;
13385 goto tweak;
13386 }
13387 winner = comp;
13388 }
13389 }
13390
13391 /* warn about confusing overload resolution for user-defined conversions,
13392 either between a constructor and a conversion op, or between two
13393 conversion ops. */
13394 if ((complain & tf_warning)
13395 /* In C++17, the constructor might have been elided, which means that
13396 an originally null ->second_conv could become non-null. */
13397 && winner && warn_conversion && cand1->second_conv && cand2->second_conv
13398 && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
13399 && winner != compare_ics (cand1->second_conv, cand2->second_conv))
13400 {
13401 struct z_candidate *w, *l;
13402 bool give_warning = false;
13403
13404 if (winner == 1)
13405 w = cand1, l = cand2;
13406 else
13407 w = cand2, l = cand1;
13408
13409 /* We don't want to complain about `X::operator T1 ()'
13410 beating `X::operator T2 () const', when T2 is a no less
13411 cv-qualified version of T1. */
13412 if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
13413 && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
13414 {
13415 tree t = TREE_TYPE (TREE_TYPE (l->fn));
13416 tree f = TREE_TYPE (TREE_TYPE (w->fn));
13417
13418 if (TREE_CODE (t) == TREE_CODE (f) && INDIRECT_TYPE_P (t))
13419 {
13420 t = TREE_TYPE (t);
13421 f = TREE_TYPE (f);
13422 }
13423 if (!comp_ptr_ttypes (t, f))
13424 give_warning = true;
13425 }
13426 else
13427 give_warning = true;
13428
13429 if (!give_warning)
13430 /*NOP*/;
13431 else if (warn)
13432 {
13433 tree source = source_type (w->convs[0]);
13434 if (INDIRECT_TYPE_P (source))
13435 source = TREE_TYPE (source);
13436 auto_diagnostic_group d;
13437 if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
13438 && warning (OPT_Wconversion, " for conversion from %qH to %qI",
13439 source, w->second_conv->type))
13440 {
13441 inform (input_location, " because conversion sequence "
13442 "for the argument is better");
13443 }
13444 }
13445 else
13446 add_warning (w, l);
13447 }
13448
13449 if (winner)
13450 return winner;
13451
13452 /* DR 495 moved this tiebreaker above the template ones. */
13453 /* or, if not that,
13454 the context is an initialization by user-defined conversion (see
13455 _dcl.init_ and _over.match.user_) and the standard conversion
13456 sequence from the return type of F1 to the destination type (i.e.,
13457 the type of the entity being initialized) is a better conversion
13458 sequence than the standard conversion sequence from the return type
13459 of F2 to the destination type. */
13460
13461 if (cand1->second_conv)
13462 {
13463 winner = compare_ics (cand1->second_conv, cand2->second_conv);
13464 if (winner)
13465 return winner;
13466 }
13467
13468 /* CWG2735 (PR109247): A copy/move ctor/op= for which its operand uses an
13469 explicit conversion (due to list-initialization) is worse. */
13470 {
13471 z_candidate *sp = nullptr;
13472 if (sfk_copy_or_move (cand1->fn))
13473 sp = cand1;
13474 if (sfk_copy_or_move (cand2->fn))
13475 sp = sp ? nullptr : cand2;
13476 if (sp)
13477 {
13478 conversion *conv = sp->convs[!DECL_CONSTRUCTOR_P (sp->fn)];
13479 if (conv->user_conv_p)
13480 for (; conv; conv = next_conversion (conv))
13481 if (conv->kind == ck_user
13482 && DECL_P (conv->cand->fn)
13483 && DECL_NONCONVERTING_P (conv->cand->fn))
13484 return (sp == cand1) ? -1 : 1;
13485 }
13486 }
13487
13488 /* DR2327: C++17 copy elision in [over.match.ctor] (direct-init) context.
13489 The standard currently says that only constructors are candidates, but if
13490 one copies a prvalue returned by a conversion function we prefer that.
13491
13492 Clang does something similar, as discussed at
13493 http://lists.isocpp.org/core/2017/10/3166.php
13494 http://lists.isocpp.org/core/2019/03/5721.php */
13495 if (len == 1 && cxx_dialect >= cxx17
13496 && DECL_P (cand1->fn)
13497 && DECL_COMPLETE_CONSTRUCTOR_P (cand1->fn)
13498 && !(cand1->flags & LOOKUP_ONLYCONVERTING))
13499 {
13500 bool elided1 = joust_maybe_elide_copy (cand1);
13501 bool elided2 = joust_maybe_elide_copy (cand2);
13502 winner = elided1 - elided2;
13503 if (winner)
13504 return winner;
13505 }
13506
13507 /* or, if not that,
13508 F1 is a non-template function and F2 is a template function
13509 specialization. */
13510
13511 if (!cand1->template_decl && cand2->template_decl)
13512 return 1;
13513 else if (cand1->template_decl && !cand2->template_decl)
13514 return -1;
13515
13516 /* or, if not that,
13517 F1 and F2 are template functions and the function template for F1 is
13518 more specialized than the template for F2 according to the partial
13519 ordering rules. */
13520
13521 if (cand1->template_decl && cand2->template_decl)
13522 {
13523 winner = more_specialized_fn
13524 (TI_TEMPLATE (cand1->template_decl),
13525 TI_TEMPLATE (cand2->template_decl),
13526 /* [temp.func.order]: The presence of unused ellipsis and default
13527 arguments has no effect on the partial ordering of function
13528 templates. add_function_candidate() will not have
13529 counted the "this" argument for constructors. */
13530 cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
13531 if (winner)
13532 return winner;
13533 }
13534
13535 /* F1 and F2 are non-template functions and
13536 - they have the same non-object-parameter-type-lists ([dcl.fct]), and
13537 - if they are member functions, both are direct members of the same
13538 class, and
13539 - if both are non-static member functions, they have the same types for
13540 their object parameters, and
13541 - F1 is more constrained than F2 according to the partial ordering of
13542 constraints described in [temp.constr.order]. */
13543 if (flag_concepts && DECL_P (cand1->fn) && DECL_P (cand2->fn)
13544 && !cand1->template_decl && !cand2->template_decl
13545 && cand_parms_match (cand1, cand2, pmatch::current))
13546 {
13547 winner = more_constrained (cand1->fn, cand2->fn);
13548 if (winner)
13549 return winner;
13550 }
13551
13552 /* F2 is a rewritten candidate (12.4.1.2) and F1 is not, or F1 and F2 are
13553 rewritten candidates, and F2 is a synthesized candidate with reversed
13554 order of parameters and F1 is not. */
13555 if (cand1->rewritten ())
13556 {
13557 if (!cand2->rewritten ())
13558 return -1;
13559 if (!cand1->reversed () && cand2->reversed ())
13560 return 1;
13561 if (cand1->reversed () && !cand2->reversed ())
13562 return -1;
13563 }
13564 else if (cand2->rewritten ())
13565 return 1;
13566
13567 if (deduction_guide_p (cand1->fn))
13568 {
13569 gcc_assert (deduction_guide_p (cand2->fn));
13570
13571 /* F1 and F2 are generated from class template argument deduction for a
13572 class D, and F2 is generated from inheriting constructors from a base
13573 class of D while F1 is not, and for each explicit function argument,
13574 the corresponding parameters of F1 and F2 are either both ellipses or
13575 have the same type. */
13576 bool inherited1 = inherited_guide_p (cand1->fn);
13577 bool inherited2 = inherited_guide_p (cand2->fn);
13578 if (int diff = inherited2 - inherited1)
13579 {
13580 for (i = 0; i < len; ++i)
13581 {
13582 conversion *t1 = cand1->convs[i + off1];
13583 conversion *t2 = cand2->convs[i + off2];
13584 /* ??? It seems the ellipses part of this tiebreaker isn't
13585 needed since a mismatch should have broken the tie earlier
13586 during ICS comparison. */
13587 gcc_checking_assert (t1->ellipsis_p == t2->ellipsis_p);
13588 if (!same_type_p (t1->type, t2->type))
13589 break;
13590 }
13591 if (i == len)
13592 return diff;
13593 }
13594
13595 /* F1 is generated from a deduction-guide (13.3.1.8) and F2 is not */
13596 /* We distinguish between candidates from an explicit deduction guide and
13597 candidates built from a constructor based on DECL_ARTIFICIAL. */
13598 int art1 = DECL_ARTIFICIAL (cand1->fn);
13599 int art2 = DECL_ARTIFICIAL (cand2->fn);
13600 if (art1 != art2)
13601 return art2 - art1;
13602
13603 if (art1)
13604 {
13605 /* Prefer the special copy guide over a declared copy/move
13606 constructor. */
13607 if (copy_guide_p (cand1->fn))
13608 return 1;
13609 if (copy_guide_p (cand2->fn))
13610 return -1;
13611
13612 /* Prefer a candidate generated from a non-template constructor. */
13613 int tg1 = template_guide_p (cand1->fn);
13614 int tg2 = template_guide_p (cand2->fn);
13615 if (tg1 != tg2)
13616 return tg2 - tg1;
13617 }
13618 }
13619
13620 /* F1 is a constructor for a class D, F2 is a constructor for a base class B
13621 of D, and for all arguments the corresponding parameters of F1 and F2 have
13622 the same type (CWG 2273/2277). */
13623 if (DECL_INHERITED_CTOR (cand1->fn) || DECL_INHERITED_CTOR (cand2->fn))
13624 {
13625 tree base1 = DECL_CONTEXT (strip_inheriting_ctors (cand1->fn));
13626 tree base2 = DECL_CONTEXT (strip_inheriting_ctors (cand2->fn));
13627
13628 bool used1 = false;
13629 bool used2 = false;
13630 if (base1 == base2)
13631 /* No difference. */;
13632 else if (DERIVED_FROM_P (base1, base2))
13633 used1 = true;
13634 else if (DERIVED_FROM_P (base2, base1))
13635 used2 = true;
13636
13637 if (int diff = used2 - used1)
13638 {
13639 for (i = 0; i < len; ++i)
13640 {
13641 conversion *t1 = cand1->convs[i + off1];
13642 conversion *t2 = cand2->convs[i + off2];
13643 if (!same_type_p (t1->type, t2->type))
13644 break;
13645 }
13646 if (i == len)
13647 return diff;
13648 }
13649 }
13650
13651 /* Check whether we can discard a builtin candidate, either because we
13652 have two identical ones or matching builtin and non-builtin candidates.
13653
13654 (Pedantically in the latter case the builtin which matched the user
13655 function should not be added to the overload set, but we spot it here.
13656
13657 [over.match.oper]
13658 ... the builtin candidates include ...
13659 - do not have the same parameter type list as any non-template
13660 non-member candidate. */
13661
13662 if (identifier_p (cand1->fn) || identifier_p (cand2->fn))
13663 {
13664 for (i = 0; i < len; ++i)
13665 if (!same_type_p (cand1->convs[i]->type,
13666 cand2->convs[i]->type))
13667 break;
13668 if (i == cand1->num_convs)
13669 {
13670 if (cand1->fn == cand2->fn)
13671 /* Two built-in candidates; arbitrarily pick one. */
13672 return 1;
13673 else if (identifier_p (cand1->fn))
13674 /* cand1 is built-in; prefer cand2. */
13675 return -1;
13676 else
13677 /* cand2 is built-in; prefer cand1. */
13678 return 1;
13679 }
13680 }
13681
13682 /* For candidates of a multi-versioned function, make the version with
13683 the highest priority win. This version will be checked for dispatching
13684 first. If this version can be inlined into the caller, the front-end
13685 will simply make a direct call to this function. */
13686
13687 if (TREE_CODE (cand1->fn) == FUNCTION_DECL
13688 && DECL_FUNCTION_VERSIONED (cand1->fn)
13689 && TREE_CODE (cand2->fn) == FUNCTION_DECL
13690 && DECL_FUNCTION_VERSIONED (cand2->fn))
13691 {
13692 tree f1 = TREE_TYPE (cand1->fn);
13693 tree f2 = TREE_TYPE (cand2->fn);
13694 tree p1 = TYPE_ARG_TYPES (f1);
13695 tree p2 = TYPE_ARG_TYPES (f2);
13696
13697 /* Check if cand1->fn and cand2->fn are versions of the same function. It
13698 is possible that cand1->fn and cand2->fn are function versions but of
13699 different functions. Check types to see if they are versions of the same
13700 function. */
13701 if (compparms (p1, p2)
13702 && same_type_p (TREE_TYPE (f1), TREE_TYPE (f2)))
13703 {
13704 /* Always make the version with the higher priority, more
13705 specialized, win. */
13706 gcc_assert (targetm.compare_version_priority);
13707 if (targetm.compare_version_priority (cand1->fn, cand2->fn) >= 0)
13708 return 1;
13709 else
13710 return -1;
13711 }
13712 }
13713
13714 /* If the two function declarations represent the same function (this can
13715 happen with declarations in multiple scopes and arg-dependent lookup),
13716 arbitrarily choose one. But first make sure the default args we're
13717 using match. */
13718 if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
13719 && equal_functions (cand1->fn, cand2->fn))
13720 {
13721 tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
13722 tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
13723
13724 gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
13725
13726 for (i = 0; i < len; ++i)
13727 {
13728 /* Don't crash if the fn is variadic. */
13729 if (!parms1)
13730 break;
13731 parms1 = TREE_CHAIN (parms1);
13732 parms2 = TREE_CHAIN (parms2);
13733 }
13734
13735 if (off1)
13736 parms1 = TREE_CHAIN (parms1);
13737 else if (off2)
13738 parms2 = TREE_CHAIN (parms2);
13739
13740 for (; parms1; ++i)
13741 {
13742 if (!cp_tree_equal (TREE_PURPOSE (parms1),
13743 TREE_PURPOSE (parms2)))
13744 {
13745 if (warn)
13746 {
13747 if (complain & tf_error)
13748 {
13749 auto_diagnostic_group d;
13750 if (permerror (input_location,
13751 "default argument mismatch in "
13752 "overload resolution"))
13753 {
13754 inform (DECL_SOURCE_LOCATION (cand1->fn),
13755 " candidate 1: %q#F", cand1->fn);
13756 inform (DECL_SOURCE_LOCATION (cand2->fn),
13757 " candidate 2: %q#F", cand2->fn);
13758 }
13759 }
13760 else
13761 return 0;
13762 }
13763 else
13764 add_warning (cand1, cand2);
13765 break;
13766 }
13767 parms1 = TREE_CHAIN (parms1);
13768 parms2 = TREE_CHAIN (parms2);
13769 }
13770
13771 return 1;
13772 }
13773
13774 tweak:
13775
13776 /* Extension: If the worst conversion for one candidate is better than the
13777 worst conversion for the other, take the first. */
13778 if (!pedantic && (complain & tf_warning_or_error))
13779 {
13780 conversion_rank rank1 = cr_identity, rank2 = cr_identity;
13781 struct z_candidate *w = 0, *l = 0;
13782
13783 for (i = 0; i < len; ++i)
13784 {
13785 if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
13786 rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
13787 if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
13788 rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
13789 }
13790 if (rank1 < rank2)
13791 winner = 1, w = cand1, l = cand2;
13792 if (rank1 > rank2)
13793 winner = -1, w = cand2, l = cand1;
13794 if (winner)
13795 {
13796 /* Don't choose a deleted function over ambiguity. */
13797 if (DECL_P (w->fn) && DECL_DELETED_FN (w->fn))
13798 return 0;
13799 if (warn)
13800 {
13801 auto_diagnostic_group d;
13802 if (pedwarn (input_location, 0,
13803 "ISO C++ says that these are ambiguous, even "
13804 "though the worst conversion for the first is "
13805 "better than the worst conversion for the second:"))
13806 {
13807 print_z_candidate (input_location, N_("candidate 1:"), w);
13808 print_z_candidate (input_location, N_("candidate 2:"), l);
13809 }
13810 }
13811 else
13812 add_warning (w, l);
13813 return winner;
13814 }
13815 }
13816
13817 gcc_assert (!winner);
13818 return 0;
13819 }
13820
13821 /* Given a list of candidates for overloading, find the best one, if any.
13822 This algorithm has a worst case of O(2n) (winner is last), and a best
13823 case of O(n/2) (totally ambiguous); much better than a sorting
13824 algorithm. The candidates list is assumed to be sorted according
13825 to viability (via splice_viable). */
13826
13827 static struct z_candidate *
13828 tourney (struct z_candidate *candidates, tsubst_flags_t complain)
13829 {
13830 struct z_candidate **champ = &candidates, **challenger;
13831 int fate;
13832 struct z_candidate *previous_worse_champ = nullptr;
13833
13834 /* Walk through the list once, comparing each current champ to the next
13835 candidate, knocking out a candidate or two with each comparison. */
13836
13837 for (challenger = &candidates->next; *challenger && (*challenger)->viable; )
13838 {
13839 fate = joust (*champ, *challenger, 0, complain);
13840 if (fate == 1)
13841 challenger = &(*challenger)->next;
13842 else if (fate == -1)
13843 {
13844 previous_worse_champ = *champ;
13845 champ = challenger;
13846 challenger = &(*challenger)->next;
13847 }
13848 else
13849 {
13850 previous_worse_champ = nullptr;
13851 champ = &(*challenger)->next;
13852 if (!*champ || !(*champ)->viable
13853 || (*champ)->viable < (*challenger)->viable)
13854 {
13855 champ = nullptr;
13856 break;
13857 }
13858 challenger = &(*champ)->next;
13859 }
13860 }
13861
13862 /* Make sure the champ is better than all the candidates it hasn't yet
13863 been compared to. */
13864
13865 if (champ)
13866 for (challenger = &candidates;
13867 challenger != champ;
13868 challenger = &(*challenger)->next)
13869 {
13870 if (*challenger == previous_worse_champ)
13871 /* We already know this candidate is worse than the champ. */
13872 continue;
13873 fate = joust (*champ, *challenger, 0, complain);
13874 if (fate != 1)
13875 {
13876 champ = nullptr;
13877 break;
13878 }
13879 }
13880
13881 if (!champ)
13882 return nullptr;
13883
13884 /* Move the champ to the front of the candidate list. */
13885
13886 if (champ != &candidates)
13887 {
13888 z_candidate *saved_champ = *champ;
13889 *champ = saved_champ->next;
13890 saved_champ->next = candidates;
13891 candidates = saved_champ;
13892 }
13893
13894 return candidates;
13895 }
13896
13897 /* Returns nonzero if things of type FROM can be converted to TO. */
13898
13899 bool
13900 can_convert (tree to, tree from, tsubst_flags_t complain)
13901 {
13902 tree arg = NULL_TREE;
13903 /* implicit_conversion only considers user-defined conversions
13904 if it has an expression for the call argument list. */
13905 if (CLASS_TYPE_P (from) || CLASS_TYPE_P (to))
13906 arg = build_stub_object (from);
13907 return can_convert_arg (to, from, arg, LOOKUP_IMPLICIT, complain);
13908 }
13909
13910 /* Returns nonzero if things of type FROM can be converted to TO with a
13911 standard conversion. */
13912
13913 bool
13914 can_convert_standard (tree to, tree from, tsubst_flags_t complain)
13915 {
13916 return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT, complain);
13917 }
13918
13919 /* Returns nonzero if ARG (of type FROM) can be converted to TO. */
13920
13921 bool
13922 can_convert_arg (tree to, tree from, tree arg, int flags,
13923 tsubst_flags_t complain)
13924 {
13925 conversion *t;
13926 bool ok_p;
13927
13928 conversion_obstack_sentinel cos;
13929 /* We want to discard any access checks done for this test,
13930 as we might not be in the appropriate access context and
13931 we'll do the check again when we actually perform the
13932 conversion. */
13933 push_deferring_access_checks (dk_deferred);
13934
13935 /* Handle callers like check_local_shadow forgetting to
13936 convert_from_reference. */
13937 if (TYPE_REF_P (from) && arg)
13938 {
13939 arg = convert_from_reference (arg);
13940 from = TREE_TYPE (arg);
13941 }
13942
13943 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
13944 flags, complain);
13945 ok_p = (t && !t->bad_p);
13946
13947 /* Discard the access checks now. */
13948 pop_deferring_access_checks ();
13949
13950 return ok_p;
13951 }
13952
13953 /* Like can_convert_arg, but allows dubious conversions as well. */
13954
13955 bool
13956 can_convert_arg_bad (tree to, tree from, tree arg, int flags,
13957 tsubst_flags_t complain)
13958 {
13959 conversion *t;
13960
13961 conversion_obstack_sentinel cos;
13962 /* Try to perform the conversion. */
13963 t = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
13964 flags, complain);
13965
13966 return t != NULL;
13967 }
13968
13969 /* Return an IMPLICIT_CONV_EXPR from EXPR to TYPE with bits set from overload
13970 resolution FLAGS. */
13971
13972 tree
13973 build_implicit_conv_flags (tree type, tree expr, int flags)
13974 {
13975 /* In a template, we are only concerned about determining the
13976 type of non-dependent expressions, so we do not have to
13977 perform the actual conversion. But for initializers, we
13978 need to be able to perform it at instantiation
13979 (or instantiate_non_dependent_expr) time. */
13980 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
13981 if (!(flags & LOOKUP_ONLYCONVERTING))
13982 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
13983 if (flags & LOOKUP_NO_NARROWING)
13984 IMPLICIT_CONV_EXPR_BRACED_INIT (expr) = true;
13985 return expr;
13986 }
13987
13988 /* Convert EXPR to TYPE. Return the converted expression.
13989
13990 Note that we allow bad conversions here because by the time we get to
13991 this point we are committed to doing the conversion. If we end up
13992 doing a bad conversion, convert_like will complain. */
13993
13994 tree
13995 perform_implicit_conversion_flags (tree type, tree expr,
13996 tsubst_flags_t complain, int flags)
13997 {
13998 conversion *conv;
13999 location_t loc = cp_expr_loc_or_input_loc (expr);
14000
14001 if (error_operand_p (expr))
14002 return error_mark_node;
14003
14004 conversion_obstack_sentinel cos;
14005
14006 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
14007 /*c_cast_p=*/false,
14008 flags, complain);
14009
14010 if (!conv)
14011 {
14012 if (complain & tf_error)
14013 implicit_conversion_error (loc, type, expr);
14014 expr = error_mark_node;
14015 }
14016 else if (processing_template_decl && conv->kind != ck_identity)
14017 expr = build_implicit_conv_flags (type, expr, flags);
14018 else
14019 {
14020 /* Give a conversion call the same location as expr. */
14021 iloc_sentinel il (loc);
14022 expr = convert_like (conv, expr, complain);
14023 }
14024
14025 return expr;
14026 }
14027
14028 tree
14029 perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
14030 {
14031 return perform_implicit_conversion_flags (type, expr, complain,
14032 LOOKUP_IMPLICIT);
14033 }
14034
14035 /* Convert EXPR to TYPE (as a direct-initialization) if that is
14036 permitted. If the conversion is valid, the converted expression is
14037 returned. Otherwise, NULL_TREE is returned, except in the case
14038 that TYPE is a class type; in that case, an error is issued. If
14039 C_CAST_P is true, then this direct-initialization is taking
14040 place as part of a static_cast being attempted as part of a C-style
14041 cast. */
14042
14043 tree
14044 perform_direct_initialization_if_possible (tree type,
14045 tree expr,
14046 bool c_cast_p,
14047 tsubst_flags_t complain)
14048 {
14049 conversion *conv;
14050
14051 if (type == error_mark_node || error_operand_p (expr))
14052 return error_mark_node;
14053 /* [dcl.init]
14054
14055 If the destination type is a (possibly cv-qualified) class type:
14056
14057 -- If the initialization is direct-initialization ...,
14058 constructors are considered.
14059
14060 -- If overload resolution is successful, the selected constructor
14061 is called to initialize the object, with the initializer expression
14062 or expression-list as its argument(s).
14063
14064 -- Otherwise, if no constructor is viable, the destination type is
14065 a (possibly cv-qualified) aggregate class A, and the initializer is
14066 a parenthesized expression-list, the object is initialized as
14067 follows... */
14068 if (CLASS_TYPE_P (type))
14069 {
14070 releasing_vec args (make_tree_vector_single (expr));
14071 expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
14072 &args, type, LOOKUP_NORMAL, complain);
14073 return build_cplus_new (type, expr, complain);
14074 }
14075
14076 conversion_obstack_sentinel cos;
14077
14078 conv = implicit_conversion (type, TREE_TYPE (expr), expr,
14079 c_cast_p,
14080 LOOKUP_NORMAL, complain);
14081 if (!conv || conv->bad_p)
14082 expr = NULL_TREE;
14083 else if (processing_template_decl && conv->kind != ck_identity)
14084 {
14085 /* In a template, we are only concerned about determining the
14086 type of non-dependent expressions, so we do not have to
14087 perform the actual conversion. But for initializers, we
14088 need to be able to perform it at instantiation
14089 (or instantiate_non_dependent_expr) time. */
14090 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
14091 IMPLICIT_CONV_EXPR_DIRECT_INIT (expr) = true;
14092 }
14093 else
14094 expr = convert_like (conv, expr, NULL_TREE, 0,
14095 /*issue_conversion_warnings=*/false,
14096 c_cast_p, /*nested_p=*/false, complain);
14097
14098 return expr;
14099 }
14100
14101 /* When initializing a reference that lasts longer than a full-expression,
14102 this special rule applies:
14103
14104 [class.temporary]
14105
14106 The temporary to which the reference is bound or the temporary
14107 that is the complete object to which the reference is bound
14108 persists for the lifetime of the reference.
14109
14110 The temporaries created during the evaluation of the expression
14111 initializing the reference, except the temporary to which the
14112 reference is bound, are destroyed at the end of the
14113 full-expression in which they are created.
14114
14115 In that case, we store the converted expression into a new
14116 VAR_DECL in a new scope.
14117
14118 However, we want to be careful not to create temporaries when
14119 they are not required. For example, given:
14120
14121 struct B {};
14122 struct D : public B {};
14123 D f();
14124 const B& b = f();
14125
14126 there is no need to copy the return value from "f"; we can just
14127 extend its lifetime. Similarly, given:
14128
14129 struct S {};
14130 struct T { operator S(); };
14131 T t;
14132 const S& s = t;
14133
14134 we can extend the lifetime of the return value of the conversion
14135 operator.
14136
14137 The next several functions are involved in this lifetime extension. */
14138
14139 /* DECL is a VAR_DECL or FIELD_DECL whose type is a REFERENCE_TYPE. The
14140 reference is being bound to a temporary. Create and return a new
14141 VAR_DECL with the indicated TYPE; this variable will store the value to
14142 which the reference is bound. */
14143
14144 tree
14145 make_temporary_var_for_ref_to_temp (tree decl, tree type)
14146 {
14147 tree var = create_temporary_var (type);
14148
14149 /* Register the variable. */
14150 if (VAR_P (decl)
14151 && (TREE_STATIC (decl) || CP_DECL_THREAD_LOCAL_P (decl)))
14152 {
14153 /* Namespace-scope or local static; give it a mangled name. */
14154
14155 /* If an initializer is visible to multiple translation units, those
14156 translation units must agree on the addresses of the
14157 temporaries. Therefore the temporaries must be given a consistent name
14158 and vague linkage. The mangled name of a temporary is the name of the
14159 non-temporary object in whose initializer they appear, prefixed with
14160 GR and suffixed with a sequence number mangled using the usual rules
14161 for a seq-id. Temporaries are numbered with a pre-order, depth-first,
14162 left-to-right walk of the complete initializer. */
14163 copy_linkage (var, decl);
14164
14165 tree name = mangle_ref_init_variable (decl);
14166 DECL_NAME (var) = name;
14167 SET_DECL_ASSEMBLER_NAME (var, name);
14168
14169 /* Set the context to make the variable mergeable in modules. */
14170 DECL_CONTEXT (var) = current_scope ();
14171 }
14172 else
14173 /* Create a new cleanup level if necessary. */
14174 maybe_push_cleanup_level (type);
14175
14176 return pushdecl (var);
14177 }
14178
14179 static tree extend_temps_r (tree *, int *, void *);
14180
14181 /* EXPR is the initializer for a variable DECL of reference or
14182 std::initializer_list type. Create, push and return a new VAR_DECL
14183 for the initializer so that it will live as long as DECL. Any
14184 cleanup for the new variable is returned through CLEANUP, and the
14185 code to initialize the new variable is returned through INITP. */
14186
14187 static tree
14188 set_up_extended_ref_temp (tree decl, tree expr, vec<tree, va_gc> **cleanups,
14189 tree *initp, tree *cond_guard,
14190 void *walk_data)
14191 {
14192 tree init;
14193 tree type;
14194 tree var;
14195
14196 /* Create the temporary variable. */
14197 type = TREE_TYPE (expr);
14198 var = make_temporary_var_for_ref_to_temp (decl, type);
14199 layout_decl (var, 0);
14200 /* If the rvalue is the result of a function call it will be
14201 a TARGET_EXPR. If it is some other construct (such as a
14202 member access expression where the underlying object is
14203 itself the result of a function call), turn it into a
14204 TARGET_EXPR here. It is important that EXPR be a
14205 TARGET_EXPR below since otherwise the INIT_EXPR will
14206 attempt to make a bitwise copy of EXPR to initialize
14207 VAR. */
14208 if (TREE_CODE (expr) != TARGET_EXPR)
14209 expr = get_target_expr (expr);
14210 else
14211 {
14212 if (TREE_ADDRESSABLE (expr))
14213 TREE_ADDRESSABLE (var) = 1;
14214 if (DECL_MERGEABLE (TARGET_EXPR_SLOT (expr)))
14215 DECL_MERGEABLE (var) = true;
14216 }
14217
14218 if (TREE_CODE (decl) == FIELD_DECL
14219 && extra_warnings && !warning_suppressed_p (decl))
14220 {
14221 warning (OPT_Wextra, "a temporary bound to %qD only persists "
14222 "until the constructor exits", decl);
14223 suppress_warning (decl);
14224 }
14225
14226 /* Recursively extend temps in this initializer. The recursion needs to come
14227 after creating the variable to conform to the mangling ABI, and before
14228 maybe_constant_init because the extension might change its result. */
14229 if (walk_data)
14230 cp_walk_tree (&TARGET_EXPR_INITIAL (expr), extend_temps_r,
14231 walk_data, nullptr);
14232 else
14233 TARGET_EXPR_INITIAL (expr)
14234 = extend_ref_init_temps (decl, TARGET_EXPR_INITIAL (expr), cleanups,
14235 cond_guard);
14236
14237 /* Any reference temp has a non-trivial initializer. */
14238 DECL_NONTRIVIALLY_INITIALIZED_P (var) = true;
14239
14240 /* If the initializer is constant, put it in DECL_INITIAL so we get
14241 static initialization and use in constant expressions. */
14242 init = maybe_constant_init (expr, var, /*manifestly_const_eval=*/true);
14243 /* As in store_init_value. */
14244 init = cp_fully_fold (init);
14245 if (TREE_CONSTANT (init))
14246 {
14247 if (literal_type_p (type)
14248 && CP_TYPE_CONST_NON_VOLATILE_P (type)
14249 && !TYPE_HAS_MUTABLE_P (type))
14250 {
14251 /* 5.19 says that a constant expression can include an
14252 lvalue-rvalue conversion applied to "a glvalue of literal type
14253 that refers to a non-volatile temporary object initialized
14254 with a constant expression". Rather than try to communicate
14255 that this VAR_DECL is a temporary, just mark it constexpr. */
14256 DECL_DECLARED_CONSTEXPR_P (var) = true;
14257 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var) = true;
14258 TREE_CONSTANT (var) = true;
14259 TREE_READONLY (var) = true;
14260 }
14261 DECL_INITIAL (var) = init;
14262 init = NULL_TREE;
14263 }
14264 else
14265 /* Create the INIT_EXPR that will initialize the temporary
14266 variable. */
14267 init = split_nonconstant_init (var, expr);
14268 if (at_function_scope_p ())
14269 {
14270 add_decl_expr (var);
14271
14272 if (TREE_STATIC (var))
14273 init = add_stmt_to_compound (init, register_dtor_fn (var));
14274 else
14275 {
14276 /* ??? Instead of rebuilding the cleanup, we could replace the slot
14277 with var in TARGET_EXPR_CLEANUP (expr). */
14278 tree cleanup = cxx_maybe_build_cleanup (var, tf_warning_or_error);
14279 if (cleanup)
14280 {
14281 if (cond_guard && cleanup != error_mark_node)
14282 {
14283 if (*cond_guard == NULL_TREE)
14284 {
14285 *cond_guard = build_local_temp (boolean_type_node);
14286 add_decl_expr (*cond_guard);
14287 tree set = cp_build_modify_expr (UNKNOWN_LOCATION,
14288 *cond_guard, NOP_EXPR,
14289 boolean_false_node,
14290 tf_warning_or_error);
14291 finish_expr_stmt (set);
14292 }
14293 cleanup = build3 (COND_EXPR, void_type_node,
14294 *cond_guard, cleanup, NULL_TREE);
14295 }
14296 if (flag_exceptions && TREE_CODE (TREE_TYPE (var)) != ARRAY_TYPE)
14297 {
14298 /* The normal cleanup for this extended variable isn't pushed
14299 until cp_finish_decl, so we need to retain a TARGET_EXPR
14300 to clean it up in case a later initializer throws
14301 (g++.dg/eh/ref-temp3.C).
14302
14303 We don't do this for array temporaries because they have
14304 the array cleanup region from build_vec_init.
14305
14306 Unlike maybe_push_temp_cleanup, we don't actually need a
14307 flag, but a TARGET_EXPR needs a TARGET_EXPR_SLOT.
14308 Perhaps this could use WITH_CLEANUP_EXPR instead, but
14309 gimplify.cc doesn't handle that, and front-end handling
14310 was removed in r8-1725 and r8-1818.
14311
14312 Alternately it might be preferable to flatten an
14313 initialization with extended temps into a sequence of
14314 (non-full-expression) statements, so we could immediately
14315 push_cleanup here for only a single cleanup region, but we
14316 don't have a mechanism for that in the front-end, only the
14317 gimplifier. */
14318 tree targ = get_internal_target_expr (boolean_true_node);
14319 TARGET_EXPR_CLEANUP (targ) = cleanup;
14320 CLEANUP_EH_ONLY (targ) = true;
14321 /* Don't actually initialize the bool. */
14322 init = (!init ? void_node
14323 : convert_to_void (init, ICV_STATEMENT, tf_none));
14324 TARGET_EXPR_INITIAL (targ) = init;
14325 init = targ;
14326 }
14327 vec_safe_push (*cleanups, cleanup);
14328 }
14329 }
14330
14331 /* We must be careful to destroy the temporary only
14332 after its initialization has taken place. If the
14333 initialization throws an exception, then the
14334 destructor should not be run. We cannot simply
14335 transform INIT into something like:
14336
14337 (INIT, ({ CLEANUP_STMT; }))
14338
14339 because emit_local_var always treats the
14340 initializer as a full-expression. Thus, the
14341 destructor would run too early; it would run at the
14342 end of initializing the reference variable, rather
14343 than at the end of the block enclosing the
14344 reference variable.
14345
14346 The solution is to pass back a cleanup expression
14347 which the caller is responsible for attaching to
14348 the statement tree. */
14349 }
14350 else
14351 {
14352 rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
14353 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
14354 {
14355 if (CP_DECL_THREAD_LOCAL_P (var))
14356 tls_aggregates = tree_cons (NULL_TREE, var,
14357 tls_aggregates);
14358 else
14359 static_aggregates = tree_cons (NULL_TREE, var,
14360 static_aggregates);
14361 }
14362 else
14363 /* Check whether the dtor is callable. */
14364 cxx_maybe_build_cleanup (var, tf_warning_or_error);
14365 }
14366 /* Avoid -Wunused-variable warning (c++/38958). */
14367 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
14368 && VAR_P (decl))
14369 TREE_USED (decl) = DECL_READ_P (decl) = true;
14370
14371 *initp = init;
14372 return var;
14373 }
14374
14375 /* Convert EXPR to the indicated reference TYPE, in a way suitable for
14376 initializing a variable of that TYPE. */
14377
14378 tree
14379 initialize_reference (tree type, tree expr,
14380 int flags, tsubst_flags_t complain)
14381 {
14382 conversion *conv;
14383 location_t loc = cp_expr_loc_or_input_loc (expr);
14384
14385 if (type == error_mark_node || error_operand_p (expr))
14386 return error_mark_node;
14387
14388 conversion_obstack_sentinel cos;
14389
14390 conv = reference_binding (type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
14391 flags, complain);
14392 /* If this conversion failed, we're in C++20, and we have something like
14393 A& a(b) where A is an aggregate, try again, this time as A& a{b}. */
14394 if ((!conv || conv->bad_p)
14395 && (flags & LOOKUP_AGGREGATE_PAREN_INIT))
14396 {
14397 tree e = build_constructor_single (init_list_type_node, NULL_TREE, expr);
14398 CONSTRUCTOR_IS_DIRECT_INIT (e) = true;
14399 CONSTRUCTOR_IS_PAREN_INIT (e) = true;
14400 conversion *c = reference_binding (type, TREE_TYPE (e), e,
14401 /*c_cast_p=*/false, flags, complain);
14402 /* If this worked, use it. */
14403 if (c && !c->bad_p)
14404 expr = e, conv = c;
14405 }
14406 if (!conv || conv->bad_p)
14407 {
14408 if (complain & tf_error)
14409 {
14410 if (conv)
14411 convert_like (conv, expr, complain);
14412 else if (!CP_TYPE_CONST_P (TREE_TYPE (type))
14413 && !TYPE_REF_IS_RVALUE (type)
14414 && !lvalue_p (expr))
14415 error_at (loc, "invalid initialization of non-const reference of "
14416 "type %qH from an rvalue of type %qI",
14417 type, TREE_TYPE (expr));
14418 else
14419 error_at (loc, "invalid initialization of reference of type "
14420 "%qH from expression of type %qI", type,
14421 TREE_TYPE (expr));
14422 }
14423 return error_mark_node;
14424 }
14425
14426 if (conv->kind == ck_ref_bind)
14427 /* Perform the conversion. */
14428 expr = convert_like (conv, expr, complain);
14429 else if (conv->kind == ck_ambig)
14430 /* We gave an error in build_user_type_conversion_1. */
14431 expr = error_mark_node;
14432 else
14433 gcc_unreachable ();
14434
14435 return expr;
14436 }
14437
14438 /* Return true if T is std::pair<const T&, const T&>. */
14439
14440 static bool
14441 std_pair_ref_ref_p (tree t)
14442 {
14443 /* First, check if we have std::pair. */
14444 if (!NON_UNION_CLASS_TYPE_P (t)
14445 || !CLASSTYPE_TEMPLATE_INSTANTIATION (t))
14446 return false;
14447 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (t));
14448 if (!decl_in_std_namespace_p (tdecl))
14449 return false;
14450 tree name = DECL_NAME (tdecl);
14451 if (!name || !id_equal (name, "pair"))
14452 return false;
14453
14454 /* Now see if the template arguments are both const T&. */
14455 tree args = CLASSTYPE_TI_ARGS (t);
14456 if (TREE_VEC_LENGTH (args) != 2)
14457 return false;
14458 for (int i = 0; i < 2; i++)
14459 if (!TYPE_REF_OBJ_P (TREE_VEC_ELT (args, i))
14460 || !CP_TYPE_CONST_P (TREE_TYPE (TREE_VEC_ELT (args, i))))
14461 return false;
14462
14463 return true;
14464 }
14465
14466 /* Return true if a class T has a reference member. */
14467
14468 static bool
14469 class_has_reference_member_p (tree t)
14470 {
14471 for (tree fields = TYPE_FIELDS (t);
14472 fields;
14473 fields = DECL_CHAIN (fields))
14474 if (TREE_CODE (fields) == FIELD_DECL
14475 && !DECL_ARTIFICIAL (fields)
14476 && TYPE_REF_P (TREE_TYPE (fields)))
14477 return true;
14478 return false;
14479 }
14480
14481 /* A wrapper for the above suitable as a callback for dfs_walk_once. */
14482
14483 static tree
14484 class_has_reference_member_p_r (tree binfo, void *)
14485 {
14486 return (class_has_reference_member_p (BINFO_TYPE (binfo))
14487 ? integer_one_node : NULL_TREE);
14488 }
14489
14490
14491 /* Return true if T (either a class or a function) has been marked as
14492 not-dangling. */
14493
14494 static bool
14495 no_dangling_p (tree t)
14496 {
14497 t = lookup_attribute ("no_dangling", TYPE_ATTRIBUTES (t));
14498 if (!t)
14499 return false;
14500
14501 t = TREE_VALUE (t);
14502 if (!t)
14503 return true;
14504
14505 t = build_converted_constant_bool_expr (TREE_VALUE (t), tf_warning_or_error);
14506 t = cxx_constant_value (t);
14507 return t == boolean_true_node;
14508 }
14509
14510 /* Return true if a class CTYPE is either std::reference_wrapper or
14511 std::ref_view, or a reference wrapper class. We consider a class
14512 a reference wrapper class if it has a reference member. We no
14513 longer check that it has a constructor taking the same reference type
14514 since that approach still generated too many false positives. */
14515
14516 static bool
14517 reference_like_class_p (tree ctype)
14518 {
14519 if (!CLASS_TYPE_P (ctype))
14520 return false;
14521
14522 if (no_dangling_p (ctype))
14523 return true;
14524
14525 /* Also accept a std::pair<const T&, const T&>. */
14526 if (std_pair_ref_ref_p (ctype))
14527 return true;
14528
14529 tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
14530 if (decl_in_std_namespace_p (tdecl))
14531 {
14532 tree name = DECL_NAME (tdecl);
14533 if (name
14534 && (id_equal (name, "reference_wrapper")
14535 || id_equal (name, "span")
14536 || id_equal (name, "ref_view")))
14537 return true;
14538 }
14539
14540 /* Avoid warning if CTYPE looks like std::span: it has a T* member and
14541 a trivial destructor. For example,
14542
14543 template<typename T>
14544 struct Span {
14545 T* data_;
14546 std::size len_;
14547 };
14548
14549 is considered std::span-like. */
14550 if (NON_UNION_CLASS_TYPE_P (ctype) && TYPE_HAS_TRIVIAL_DESTRUCTOR (ctype))
14551 for (tree field = next_aggregate_field (TYPE_FIELDS (ctype));
14552 field; field = next_aggregate_field (DECL_CHAIN (field)))
14553 if (TYPE_PTR_P (TREE_TYPE (field)))
14554 return true;
14555
14556 /* Some classes, such as std::tuple, have the reference member in its
14557 (non-direct) base class. */
14558 if (dfs_walk_once (TYPE_BINFO (ctype), class_has_reference_member_p_r,
14559 nullptr, nullptr))
14560 return true;
14561
14562 return false;
14563 }
14564
14565 /* Helper for maybe_warn_dangling_reference to find a problematic temporary
14566 in EXPR (as outlined in maybe_warn_dangling_reference), or NULL_TREE
14567 if none found. For instance:
14568
14569 const S& s = S().self(); // S()
14570 const int& r = (42, f(1)); // temporary for passing 1 to f
14571 const int& t = b ? f(1) : f(2); // temporary for 1
14572 const int& u = b ? f(1) : f(g); // temporary for 1
14573 const int& v = b ? f(g) : f(2); // temporary for 2
14574 const int& w = b ? f(g) : f(g); // NULL_TREE
14575 const int& y = (f(1), 42); // NULL_TREE
14576 const int& z = f(f(1)); // temporary for 1
14577
14578 EXPR is the initializer. If ARG_P is true, we're processing an argument
14579 to a function; the point is to distinguish between, for example,
14580
14581 Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
14582
14583 where we shouldn't warn, and
14584
14585 Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
14586
14587 where we should warn (Ref is a reference_like_class_p so we see through
14588 it. */
14589
14590 static tree
14591 do_warn_dangling_reference (tree expr, bool arg_p)
14592 {
14593 STRIP_NOPS (expr);
14594
14595 if (arg_p && expr_represents_temporary_p (expr))
14596 {
14597 /* An attempt to reduce the number of -Wdangling-reference
14598 false positives concerning reference wrappers (c++/107532).
14599 When we encounter a reference_like_class_p, we don't warn
14600 just yet; instead, we keep recursing to see if there were
14601 any temporaries behind the reference-wrapper class. */
14602 tree e = expr;
14603 while (handled_component_p (e))
14604 e = TREE_OPERAND (e, 0);
14605 tree type = TREE_TYPE (e);
14606 /* If the temporary represents a lambda, we don't really know
14607 what's going on here. */
14608 if (!reference_like_class_p (type) && !LAMBDA_TYPE_P (type))
14609 return expr;
14610 }
14611
14612 switch (TREE_CODE (expr))
14613 {
14614 case CALL_EXPR:
14615 {
14616 tree fndecl = cp_get_callee_fndecl_nofold (expr);
14617 if (!fndecl
14618 || warning_suppressed_p (fndecl, OPT_Wdangling_reference)
14619 || !warning_enabled_at (DECL_SOURCE_LOCATION (fndecl),
14620 OPT_Wdangling_reference)
14621 /* Don't emit a false positive for:
14622 std::vector<int> v = ...;
14623 std::vector<int>::const_iterator it = v.begin();
14624 const int &r = *it++;
14625 because R refers to one of the int elements of V, not to
14626 a temporary object. Member operator* may return a reference
14627 but probably not to one of its arguments. */
14628 || (DECL_OBJECT_MEMBER_FUNCTION_P (fndecl)
14629 && DECL_OVERLOADED_OPERATOR_P (fndecl)
14630 && DECL_OVERLOADED_OPERATOR_IS (fndecl, INDIRECT_REF))
14631 || no_dangling_p (TREE_TYPE (fndecl)))
14632 return NULL_TREE;
14633
14634 tree rettype = TREE_TYPE (TREE_TYPE (fndecl));
14635 /* If the function doesn't return a reference, don't warn. This
14636 can be e.g.
14637 const int& z = std::min({1, 2, 3, 4, 5, 6, 7});
14638 which doesn't dangle: std::min here returns an int.
14639
14640 If the function returns a std::pair<const T&, const T&>, we
14641 warn, to detect e.g.
14642 std::pair<const int&, const int&> v = std::minmax(1, 2);
14643 which also creates a dangling reference, because std::minmax
14644 returns std::pair<const T&, const T&>(b, a). */
14645 if (!(TYPE_REF_OBJ_P (rettype) || reference_like_class_p (rettype)))
14646 return NULL_TREE;
14647
14648 /* Here we're looking to see if any of the arguments is a temporary
14649 initializing a reference parameter. */
14650 for (int i = 0; i < call_expr_nargs (expr); ++i)
14651 {
14652 tree arg = CALL_EXPR_ARG (expr, i);
14653 /* Check that this argument initializes a reference, except for
14654 the argument initializing the object of a member function. */
14655 if (!DECL_IOBJ_MEMBER_FUNCTION_P (fndecl)
14656 && !TYPE_REF_P (TREE_TYPE (arg)))
14657 continue;
14658 STRIP_NOPS (arg);
14659 if (TREE_CODE (arg) == ADDR_EXPR)
14660 arg = TREE_OPERAND (arg, 0);
14661 /* Recurse to see if the argument is a temporary. It could also
14662 be another call taking a temporary and returning it and
14663 initializing this reference parameter. */
14664 if ((arg = do_warn_dangling_reference (arg, /*arg_p=*/true)))
14665 {
14666 /* If we know the temporary could not bind to the return type,
14667 don't warn. This is for scalars and empty classes only
14668 because for other classes we can't be sure we are not
14669 returning its sub-object. */
14670 if ((SCALAR_TYPE_P (TREE_TYPE (arg))
14671 || is_empty_class (TREE_TYPE (arg)))
14672 && TYPE_REF_P (rettype)
14673 && !reference_related_p (TREE_TYPE (rettype),
14674 TREE_TYPE (arg)))
14675 continue;
14676 return arg;
14677 }
14678 /* Don't warn about member functions like:
14679 std::any a(...);
14680 S& s = a.emplace<S>({0}, 0);
14681 which construct a new object and return a reference to it, but
14682 we still want to detect:
14683 struct S { const S& self () { return *this; } };
14684 const S& s = S().self();
14685 where 's' dangles. If we've gotten here, the object this function
14686 is invoked on is not a temporary. */
14687 if (DECL_OBJECT_MEMBER_FUNCTION_P (fndecl))
14688 break;
14689 }
14690 return NULL_TREE;
14691 }
14692 case COMPOUND_EXPR:
14693 return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
14694 case COND_EXPR:
14695 if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
14696 return t;
14697 return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
14698 case PAREN_EXPR:
14699 return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
14700 case TARGET_EXPR:
14701 return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
14702 default:
14703 return NULL_TREE;
14704 }
14705 }
14706
14707 /* Implement -Wdangling-reference, to detect cases like
14708
14709 int n = 1;
14710 const int& r = std::max(n - 1, n + 1); // r is dangling
14711
14712 This creates temporaries from the arguments, returns a reference to
14713 one of the temporaries, but both temporaries are destroyed at the end
14714 of the full expression.
14715
14716 This works by checking if a reference is initialized with a function
14717 that returns a reference, and at least one parameter of the function
14718 is a reference that is bound to a temporary. It assumes that such a
14719 function actually returns one of its arguments.
14720
14721 DECL is the reference being initialized, INIT is the initializer. */
14722
14723 static void
14724 maybe_warn_dangling_reference (const_tree decl, tree init)
14725 {
14726 if (!warn_dangling_reference)
14727 return;
14728 tree type = TREE_TYPE (decl);
14729 /* Only warn if what we're initializing has type T&& or const T&, or
14730 std::pair<const T&, const T&>. (A non-const lvalue reference can't
14731 bind to a temporary.) */
14732 if (!((TYPE_REF_OBJ_P (type)
14733 && (TYPE_REF_IS_RVALUE (type)
14734 || CP_TYPE_CONST_P (TREE_TYPE (type))))
14735 || std_pair_ref_ref_p (type)))
14736 return;
14737 /* Don't suppress the diagnostic just because the call comes from
14738 a system header. If the DECL is not in a system header, or if
14739 -Wsystem-headers was provided, warn. */
14740 auto wsh
14741 = make_temp_override (global_dc->m_warn_system_headers,
14742 (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
14743 || global_dc->m_warn_system_headers));
14744 if (tree call = do_warn_dangling_reference (init, /*arg_p=*/false))
14745 {
14746 auto_diagnostic_group d;
14747 if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
14748 "possibly dangling reference to a temporary"))
14749 inform (EXPR_LOCATION (call), "%qT temporary created here",
14750 TREE_TYPE (call));
14751 }
14752 }
14753
14754 /* If *P is an xvalue expression, prevent temporary lifetime extension if it
14755 gets used to initialize a reference. */
14756
14757 static tree
14758 prevent_lifetime_extension (tree t)
14759 {
14760 tree *p = &t;
14761 while (TREE_CODE (*p) == COMPOUND_EXPR)
14762 p = &TREE_OPERAND (*p, 1);
14763 while (handled_component_p (*p))
14764 p = &TREE_OPERAND (*p, 0);
14765 /* Change a TARGET_EXPR from prvalue to xvalue. */
14766 if (TREE_CODE (*p) == TARGET_EXPR)
14767 *p = build2 (COMPOUND_EXPR, TREE_TYPE (*p), *p,
14768 move (TARGET_EXPR_SLOT (*p)));
14769 return t;
14770 }
14771
14772 /* Subroutine of extend_ref_init_temps. Possibly extend one initializer,
14773 which is bound either to a reference or a std::initializer_list. */
14774
14775 static tree
14776 extend_ref_init_temps_1 (tree decl, tree init, vec<tree, va_gc> **cleanups,
14777 tree *cond_guard)
14778 {
14779 /* CWG1299 (C++20): The temporary object to which the reference is bound or
14780 the temporary object that is the complete object of a subobject to which
14781 the reference is bound persists for the lifetime of the reference if the
14782 glvalue to which the reference is bound was obtained through one of the
14783 following:
14784 - a temporary materialization conversion ([conv.rval]),
14785 - ( expression ), where expression is one of these expressions,
14786 - subscripting ([expr.sub]) of an array operand, where that operand is one
14787 of these expressions,
14788 - a class member access ([expr.ref]) using the . operator where the left
14789 operand is one of these expressions and the right operand designates a
14790 non-static data member of non-reference type,
14791 - a pointer-to-member operation ([expr.mptr.oper]) using the .* operator
14792 where the left operand is one of these expressions and the right operand
14793 is a pointer to data member of non-reference type,
14794 - a const_cast ([expr.const.cast]), static_cast ([expr.static.cast]),
14795 dynamic_cast ([expr.dynamic.cast]), or reinterpret_cast
14796 ([expr.reinterpret.cast]) converting, without a user-defined conversion,
14797 a glvalue operand that is one of these expressions to a glvalue that
14798 refers to the object designated by the operand, or to its complete
14799 object or a subobject thereof,
14800 - a conditional expression ([expr.cond]) that is a glvalue where the
14801 second or third operand is one of these expressions, or
14802 - a comma expression ([expr.comma]) that is a glvalue where the right
14803 operand is one of these expressions. */
14804
14805 /* FIXME several cases are still handled wrong (101572, 81420). */
14806
14807 tree sub = init;
14808 tree *p;
14809 STRIP_NOPS (sub);
14810 if (TREE_CODE (sub) == COMPOUND_EXPR)
14811 {
14812 TREE_OPERAND (sub, 1)
14813 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14814 cond_guard);
14815 return init;
14816 }
14817 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
14818 && TYPE_PTRDATAMEM_P (TREE_TYPE (tree_strip_nop_conversions
14819 (TREE_OPERAND (sub, 1)))))
14820 {
14821 /* A pointer-to-member operation. */
14822 TREE_OPERAND (sub, 0)
14823 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 0), cleanups,
14824 cond_guard);
14825 return init;
14826 }
14827 if (TREE_CODE (sub) == COND_EXPR)
14828 {
14829 tree cur_cond_guard = NULL_TREE;
14830 if (TREE_OPERAND (sub, 1))
14831 TREE_OPERAND (sub, 1)
14832 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 1), cleanups,
14833 &cur_cond_guard);
14834 if (cur_cond_guard)
14835 {
14836 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14837 NOP_EXPR, boolean_true_node,
14838 tf_warning_or_error);
14839 TREE_OPERAND (sub, 1)
14840 = cp_build_compound_expr (set, TREE_OPERAND (sub, 1),
14841 tf_warning_or_error);
14842 }
14843 cur_cond_guard = NULL_TREE;
14844 if (TREE_OPERAND (sub, 2))
14845 TREE_OPERAND (sub, 2)
14846 = extend_ref_init_temps_1 (decl, TREE_OPERAND (sub, 2), cleanups,
14847 &cur_cond_guard);
14848 if (cur_cond_guard)
14849 {
14850 tree set = cp_build_modify_expr (UNKNOWN_LOCATION, cur_cond_guard,
14851 NOP_EXPR, boolean_true_node,
14852 tf_warning_or_error);
14853 TREE_OPERAND (sub, 2)
14854 = cp_build_compound_expr (set, TREE_OPERAND (sub, 2),
14855 tf_warning_or_error);
14856 }
14857 return init;
14858 }
14859 if (TREE_CODE (sub) != ADDR_EXPR)
14860 return init;
14861 /* Deal with binding to a subobject. */
14862 for (p = &TREE_OPERAND (sub, 0);
14863 TREE_CODE (*p) == COMPONENT_REF || TREE_CODE (*p) == ARRAY_REF; )
14864 p = &TREE_OPERAND (*p, 0);
14865 if (TREE_CODE (*p) == TARGET_EXPR)
14866 {
14867 tree subinit = NULL_TREE;
14868 *p = set_up_extended_ref_temp (decl, *p, cleanups, &subinit,
14869 cond_guard, nullptr);
14870 recompute_tree_invariant_for_addr_expr (sub);
14871 if (init != sub)
14872 init = fold_convert (TREE_TYPE (init), sub);
14873 if (subinit)
14874 init = build2 (COMPOUND_EXPR, TREE_TYPE (init), subinit, init);
14875 }
14876 return init;
14877 }
14878
14879 /* Data for extend_temps_r, mostly matching the parameters of
14880 extend_ref_init_temps. */
14881
14882 struct extend_temps_data
14883 {
14884 tree decl;
14885 tree init;
14886 vec<tree, va_gc> **cleanups;
14887 tree* cond_guard;
14888 hash_set<tree> *pset; // For avoiding redundant walk_tree.
14889 hash_map<tree, tree> *var_map; // For remapping extended temps.
14890 };
14891
14892 /* Tree walk function for extend_all_temps. Generally parallel to
14893 extend_ref_init_temps_1, but adapted for walk_tree. */
14894
14895 tree
14896 extend_temps_r (tree *tp, int *walk_subtrees, void *data)
14897 {
14898 extend_temps_data *d = (extend_temps_data *)data;
14899
14900 if (TREE_CODE (*tp) == VAR_DECL)
14901 {
14902 if (tree *r = d->var_map->get (*tp))
14903 *tp = *r;
14904 return NULL_TREE;
14905 }
14906
14907 if (TYPE_P (*tp) || TREE_CODE (*tp) == CLEANUP_POINT_EXPR
14908 || d->pset->add (*tp))
14909 {
14910 *walk_subtrees = 0;
14911 return NULL_TREE;
14912 }
14913
14914 if (TREE_CODE (*tp) == COND_EXPR)
14915 {
14916 cp_walk_tree (&TREE_OPERAND (*tp, 0), extend_temps_r, d, nullptr);
14917
14918 auto walk_arm = [d](tree &op)
14919 {
14920 tree cur_cond_guard = NULL_TREE;
14921 auto ov = make_temp_override (d->cond_guard, &cur_cond_guard);
14922 cp_walk_tree (&op, extend_temps_r, d, nullptr);
14923 if (cur_cond_guard)
14924 {
14925 tree set = build2 (MODIFY_EXPR, boolean_type_node,
14926 cur_cond_guard, boolean_true_node);
14927 op = cp_build_compound_expr (set, op, tf_none);
14928 }
14929 };
14930 walk_arm (TREE_OPERAND (*tp, 1));
14931 walk_arm (TREE_OPERAND (*tp, 2));
14932
14933 *walk_subtrees = 0;
14934 return NULL_TREE;
14935 }
14936
14937 tree *p = tp;
14938
14939 if (TREE_CODE (*tp) == ADDR_EXPR)
14940 for (p = &TREE_OPERAND (*tp, 0);
14941 TREE_CODE (*p) == COMPONENT_REF || TREE_CODE (*p) == ARRAY_REF; )
14942 p = &TREE_OPERAND (*p, 0);
14943
14944 if (TREE_CODE (*p) == TARGET_EXPR
14945 /* An eliding TARGET_EXPR isn't a temporary at all. */
14946 && !TARGET_EXPR_ELIDING_P (*p)
14947 /* A TARGET_EXPR with TARGET_EXPR_INTERNAL_P is an artificial variable
14948 used during initialization that need not be extended. */
14949 && !TARGET_EXPR_INTERNAL_P (*p))
14950 {
14951 /* A CLEANUP_EH_ONLY expr should also have TARGET_EXPR_INTERNAL_P. */
14952 gcc_checking_assert (!CLEANUP_EH_ONLY (*p));
14953
14954 tree subinit = NULL_TREE;
14955 tree slot = TARGET_EXPR_SLOT (*p);
14956 *p = set_up_extended_ref_temp (d->decl, *p, d->cleanups, &subinit,
14957 d->cond_guard, d);
14958 if (TREE_CODE (*tp) == ADDR_EXPR)
14959 recompute_tree_invariant_for_addr_expr (*tp);
14960 if (subinit)
14961 *tp = cp_build_compound_expr (subinit, *tp, tf_none);
14962 d->var_map->put (slot, *p);
14963 }
14964
14965 return NULL_TREE;
14966 }
14967
14968 /* Extend all the temporaries in a for-range-initializer. */
14969
14970 static tree
14971 extend_all_temps (tree decl, tree init, vec<tree, va_gc> **cleanups)
14972 {
14973 hash_set<tree> pset;
14974 hash_map<tree, tree> map;
14975 gcc_assert (!TREE_STATIC (decl));
14976 extend_temps_data d = { decl, init, cleanups, nullptr, &pset, &map };
14977 cp_walk_tree (&init, extend_temps_r, &d, nullptr);
14978 return init;
14979 }
14980
14981 /* INIT is part of the initializer for DECL. If there are any
14982 reference or initializer lists being initialized, extend their
14983 lifetime to match that of DECL. */
14984
14985 tree
14986 extend_ref_init_temps (tree decl, tree init, vec<tree, va_gc> **cleanups,
14987 tree *cond_guard)
14988 {
14989 tree type = TREE_TYPE (init);
14990 if (processing_template_decl)
14991 return init;
14992
14993 /* P2718R0 - in C++23 for-range-initializer, extend all temps. */
14994 if (DECL_NAME (decl) == for_range__identifier
14995 && flag_range_for_ext_temps)
14996 {
14997 gcc_checking_assert (!cond_guard);
14998 return extend_all_temps (decl, init, cleanups);
14999 }
15000
15001 maybe_warn_dangling_reference (decl, init);
15002
15003 if (TYPE_REF_P (type))
15004 init = extend_ref_init_temps_1 (decl, init, cleanups, cond_guard);
15005 else
15006 {
15007 tree ctor = init;
15008 if (TREE_CODE (ctor) == TARGET_EXPR)
15009 ctor = TARGET_EXPR_INITIAL (ctor);
15010 if (TREE_CODE (ctor) == CONSTRUCTOR)
15011 {
15012 /* [dcl.init] When initializing an aggregate from a parenthesized list
15013 of values... a temporary object bound to a reference does not have
15014 its lifetime extended. */
15015 if (CONSTRUCTOR_IS_PAREN_INIT (ctor))
15016 return init;
15017
15018 if (is_std_init_list (type))
15019 {
15020 /* The temporary array underlying a std::initializer_list
15021 is handled like a reference temporary. */
15022 tree array = CONSTRUCTOR_ELT (ctor, 0)->value;
15023 array = extend_ref_init_temps_1 (decl, array, cleanups,
15024 cond_guard);
15025 CONSTRUCTOR_ELT (ctor, 0)->value = array;
15026 }
15027 else
15028 {
15029 unsigned i;
15030 constructor_elt *p;
15031 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
15032 FOR_EACH_VEC_SAFE_ELT (elts, i, p)
15033 p->value = extend_ref_init_temps (decl, p->value, cleanups,
15034 cond_guard);
15035 }
15036 recompute_constructor_flags (ctor);
15037 if (decl_maybe_constant_var_p (decl) && TREE_CONSTANT (ctor))
15038 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
15039 }
15040 }
15041
15042 return init;
15043 }
15044
15045 /* Returns true iff an initializer for TYPE could contain temporaries that
15046 need to be extended because they are bound to references or
15047 std::initializer_list. */
15048
15049 bool
15050 type_has_extended_temps (tree type)
15051 {
15052 type = strip_array_types (type);
15053 if (TYPE_REF_P (type))
15054 return true;
15055 if (CLASS_TYPE_P (type))
15056 {
15057 if (is_std_init_list (type))
15058 return true;
15059 for (tree f = next_aggregate_field (TYPE_FIELDS (type));
15060 f; f = next_aggregate_field (DECL_CHAIN (f)))
15061 if (type_has_extended_temps (TREE_TYPE (f)))
15062 return true;
15063 }
15064 return false;
15065 }
15066
15067 /* Returns true iff TYPE is some variant of std::initializer_list. */
15068
15069 bool
15070 is_std_init_list (tree type)
15071 {
15072 if (!TYPE_P (type))
15073 return false;
15074 if (cxx_dialect == cxx98)
15075 return false;
15076 /* Look through typedefs. */
15077 type = TYPE_MAIN_VARIANT (type);
15078 return (CLASS_TYPE_P (type)
15079 && CP_TYPE_CONTEXT (type) == std_node
15080 && init_list_identifier == DECL_NAME (TYPE_NAME (type)));
15081 }
15082
15083 /* Returns true iff DECL is a list constructor: i.e. a constructor which
15084 will accept an argument list of a single std::initializer_list<T>. */
15085
15086 bool
15087 is_list_ctor (tree decl)
15088 {
15089 tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
15090 tree arg;
15091
15092 if (!args || args == void_list_node)
15093 return false;
15094
15095 arg = non_reference (TREE_VALUE (args));
15096 if (!is_std_init_list (arg))
15097 return false;
15098
15099 args = TREE_CHAIN (args);
15100
15101 if (args && args != void_list_node && !TREE_PURPOSE (args))
15102 /* There are more non-defaulted parms. */
15103 return false;
15104
15105 return true;
15106 }
15107
15108 /* We know that can_convert_arg_bad already said "no" when trying to convert
15109 FROM to TO with ARG and FLAGS. Try to figure out if it was because
15110 an explicit conversion function was skipped when looking for a way to
15111 perform the conversion. At this point we've already printed an error. */
15112
15113 void
15114 maybe_show_nonconverting_candidate (tree to, tree from, tree arg, int flags)
15115 {
15116 if (!(flags & LOOKUP_ONLYCONVERTING))
15117 return;
15118
15119 conversion_obstack_sentinel cos;
15120 conversion *c = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
15121 flags & ~LOOKUP_ONLYCONVERTING, tf_none);
15122 if (c && !c->bad_p && c->user_conv_p)
15123 /* Ay, the conversion would have worked in direct-init context. */
15124 for (; c; c = next_conversion (c))
15125 if (c->kind == ck_user
15126 && DECL_P (c->cand->fn)
15127 && DECL_NONCONVERTING_P (c->cand->fn))
15128 inform (DECL_SOURCE_LOCATION (c->cand->fn), "explicit conversion "
15129 "function was not considered");
15130 }
15131
15132 /* We're converting EXPR to TYPE. If that conversion involves a conversion
15133 function and we're binding EXPR to a reference parameter of that function,
15134 return true. */
15135
15136 bool
15137 conv_binds_to_reference_parm_p (tree type, tree expr)
15138 {
15139 conversion_obstack_sentinel cos;
15140 conversion *c = implicit_conversion (type, TREE_TYPE (expr), expr,
15141 /*c_cast_p=*/false, LOOKUP_NORMAL,
15142 tf_none);
15143 if (c && !c->bad_p && c->user_conv_p)
15144 for (; c; c = next_conversion (c))
15145 if (c->kind == ck_user)
15146 for (z_candidate *cand = c->cand; cand; cand = cand->next)
15147 if (cand->viable == 1)
15148 for (size_t i = 0; i < cand->num_convs; ++i)
15149 if (cand->convs[i]->kind == ck_ref_bind
15150 && conv_get_original_expr (cand->convs[i]) == expr)
15151 return true;
15152
15153 return false;
15154 }
15155
15156 #include "gt-cp-call.h"