OSDN Git Service

* call.c (convert_like_real): Give "initializing argument of"
[pf3gnuchains/gcc-fork.git] / gcc / cp / call.c
1 /* Functions related to invoking methods and overloaded functions.
2    Copyright (C) 1987, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
4    Free Software Foundation, Inc.
5    Contributed by Michael Tiemann (tiemann@cygnus.com) and
6    modified by Brendan Kehoe (brendan@cygnus.com).
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24
25 /* High-level class interface.  */
26
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "tm.h"
31 #include "tree.h"
32 #include "cp-tree.h"
33 #include "output.h"
34 #include "flags.h"
35 #include "toplev.h"
36 #include "diagnostic-core.h"
37 #include "intl.h"
38 #include "target.h"
39 #include "convert.h"
40 #include "langhooks.h"
41
42 /* The various kinds of conversion.  */
43
44 typedef enum conversion_kind {
45   ck_identity,
46   ck_lvalue,
47   ck_qual,
48   ck_std,
49   ck_ptr,
50   ck_pmem,
51   ck_base,
52   ck_ref_bind,
53   ck_user,
54   ck_ambig,
55   ck_list,
56   ck_aggr,
57   ck_rvalue
58 } conversion_kind;
59
60 /* The rank of the conversion.  Order of the enumerals matters; better
61    conversions should come earlier in the list.  */
62
63 typedef enum conversion_rank {
64   cr_identity,
65   cr_exact,
66   cr_promotion,
67   cr_std,
68   cr_pbool,
69   cr_user,
70   cr_ellipsis,
71   cr_bad
72 } conversion_rank;
73
74 /* An implicit conversion sequence, in the sense of [over.best.ics].
75    The first conversion to be performed is at the end of the chain.
76    That conversion is always a cr_identity conversion.  */
77
78 typedef struct conversion conversion;
79 struct conversion {
80   /* The kind of conversion represented by this step.  */
81   conversion_kind kind;
82   /* The rank of this conversion.  */
83   conversion_rank rank;
84   BOOL_BITFIELD user_conv_p : 1;
85   BOOL_BITFIELD ellipsis_p : 1;
86   BOOL_BITFIELD this_p : 1;
87   BOOL_BITFIELD bad_p : 1;
88   /* If KIND is ck_ref_bind ck_base_conv, true to indicate that a
89      temporary should be created to hold the result of the
90      conversion.  */
91   BOOL_BITFIELD need_temporary_p : 1;
92   /* If KIND is ck_ptr or ck_pmem, true to indicate that a conversion
93      from a pointer-to-derived to pointer-to-base is being performed.  */
94   BOOL_BITFIELD base_p : 1;
95   /* If KIND is ck_ref_bind, true when either an lvalue reference is
96      being bound to an lvalue expression or an rvalue reference is
97      being bound to an rvalue expression. */
98   BOOL_BITFIELD rvaluedness_matches_p: 1;
99   BOOL_BITFIELD check_narrowing: 1;
100   /* The type of the expression resulting from the conversion.  */
101   tree type;
102   union {
103     /* The next conversion in the chain.  Since the conversions are
104        arranged from outermost to innermost, the NEXT conversion will
105        actually be performed before this conversion.  This variant is
106        used only when KIND is neither ck_identity nor ck_ambig.  */
107     conversion *next;
108     /* The expression at the beginning of the conversion chain.  This
109        variant is used only if KIND is ck_identity or ck_ambig.  */
110     tree expr;
111     /* The array of conversions for an initializer_list.  */
112     conversion **list;
113   } u;
114   /* The function candidate corresponding to this conversion
115      sequence.  This field is only used if KIND is ck_user.  */
116   struct z_candidate *cand;
117 };
118
119 #define CONVERSION_RANK(NODE)                   \
120   ((NODE)->bad_p ? cr_bad                       \
121    : (NODE)->ellipsis_p ? cr_ellipsis           \
122    : (NODE)->user_conv_p ? cr_user              \
123    : (NODE)->rank)
124
125 static struct obstack conversion_obstack;
126 static bool conversion_obstack_initialized;
127
128 static struct z_candidate * tourney (struct z_candidate *);
129 static int equal_functions (tree, tree);
130 static int joust (struct z_candidate *, struct z_candidate *, bool);
131 static int compare_ics (conversion *, conversion *);
132 static tree build_over_call (struct z_candidate *, int, tsubst_flags_t);
133 static tree build_java_interface_fn_ref (tree, tree);
134 #define convert_like(CONV, EXPR, COMPLAIN)                      \
135   convert_like_real ((CONV), (EXPR), NULL_TREE, 0, 0,           \
136                      /*issue_conversion_warnings=*/true,        \
137                      /*c_cast_p=*/false, (COMPLAIN))
138 #define convert_like_with_context(CONV, EXPR, FN, ARGNO, COMPLAIN )     \
139   convert_like_real ((CONV), (EXPR), (FN), (ARGNO), 0,                  \
140                      /*issue_conversion_warnings=*/true,                \
141                      /*c_cast_p=*/false, (COMPLAIN))
142 static tree convert_like_real (conversion *, tree, tree, int, int, bool,
143                                bool, tsubst_flags_t);
144 static void op_error (enum tree_code, enum tree_code, tree, tree,
145                       tree, bool);
146 static VEC(tree,gc) *resolve_args (VEC(tree,gc) *);
147 static struct z_candidate *build_user_type_conversion_1 (tree, tree, int);
148 static void print_z_candidate (const char *, struct z_candidate *);
149 static void print_z_candidates (struct z_candidate *);
150 static tree build_this (tree);
151 static struct z_candidate *splice_viable (struct z_candidate *, bool, bool *);
152 static bool any_strictly_viable (struct z_candidate *);
153 static struct z_candidate *add_template_candidate
154         (struct z_candidate **, tree, tree, tree, tree, const VEC(tree,gc) *,
155          tree, tree, tree, int, unification_kind_t);
156 static struct z_candidate *add_template_candidate_real
157         (struct z_candidate **, tree, tree, tree, tree, const VEC(tree,gc) *,
158          tree, tree, tree, int, tree, unification_kind_t);
159 static struct z_candidate *add_template_conv_candidate
160         (struct z_candidate **, tree, tree, tree, const VEC(tree,gc) *, tree,
161          tree, tree);
162 static void add_builtin_candidates
163         (struct z_candidate **, enum tree_code, enum tree_code,
164          tree, tree *, int);
165 static void add_builtin_candidate
166         (struct z_candidate **, enum tree_code, enum tree_code,
167          tree, tree, tree, tree *, tree *, int);
168 static bool is_complete (tree);
169 static void build_builtin_candidate
170         (struct z_candidate **, tree, tree, tree, tree *, tree *,
171          int);
172 static struct z_candidate *add_conv_candidate
173         (struct z_candidate **, tree, tree, tree, const VEC(tree,gc) *, tree,
174          tree);
175 static struct z_candidate *add_function_candidate
176         (struct z_candidate **, tree, tree, tree, const VEC(tree,gc) *, tree,
177          tree, int);
178 static conversion *implicit_conversion (tree, tree, tree, bool, int);
179 static conversion *standard_conversion (tree, tree, tree, bool, int);
180 static conversion *reference_binding (tree, tree, tree, bool, int);
181 static conversion *build_conv (conversion_kind, tree, conversion *);
182 static conversion *build_list_conv (tree, tree, int);
183 static bool is_subseq (conversion *, conversion *);
184 static conversion *maybe_handle_ref_bind (conversion **);
185 static void maybe_handle_implicit_object (conversion **);
186 static struct z_candidate *add_candidate
187         (struct z_candidate **, tree, tree, const VEC(tree,gc) *, size_t,
188          conversion **, tree, tree, int);
189 static tree source_type (conversion *);
190 static void add_warning (struct z_candidate *, struct z_candidate *);
191 static bool reference_compatible_p (tree, tree);
192 static conversion *convert_class_to_reference (tree, tree, tree, int);
193 static conversion *direct_reference_binding (tree, conversion *);
194 static bool promoted_arithmetic_type_p (tree);
195 static conversion *conditional_conversion (tree, tree);
196 static char *name_as_c_string (tree, tree, bool *);
197 static tree prep_operand (tree);
198 static void add_candidates (tree, tree, const VEC(tree,gc) *, tree, tree, bool,
199                             tree, tree, int, struct z_candidate **);
200 static conversion *merge_conversion_sequences (conversion *, conversion *);
201 static bool magic_varargs_p (tree);
202 static tree build_temp (tree, tree, int, diagnostic_t *);
203
204 /* Returns nonzero iff the destructor name specified in NAME matches BASETYPE.
205    NAME can take many forms...  */
206
207 bool
208 check_dtor_name (tree basetype, tree name)
209 {
210   /* Just accept something we've already complained about.  */
211   if (name == error_mark_node)
212     return true;
213
214   if (TREE_CODE (name) == TYPE_DECL)
215     name = TREE_TYPE (name);
216   else if (TYPE_P (name))
217     /* OK */;
218   else if (TREE_CODE (name) == IDENTIFIER_NODE)
219     {
220       if ((MAYBE_CLASS_TYPE_P (basetype)
221            && name == constructor_name (basetype))
222           || (TREE_CODE (basetype) == ENUMERAL_TYPE
223               && name == TYPE_IDENTIFIER (basetype)))
224         return true;
225       else
226         name = get_type_value (name);
227     }
228   else
229     {
230       /* In the case of:
231
232          template <class T> struct S { ~S(); };
233          int i;
234          i.~S();
235
236          NAME will be a class template.  */
237       gcc_assert (DECL_CLASS_TEMPLATE_P (name));
238       return false;
239     }
240
241   if (!name || name == error_mark_node)
242     return false;
243   return same_type_p (TYPE_MAIN_VARIANT (basetype), TYPE_MAIN_VARIANT (name));
244 }
245
246 /* We want the address of a function or method.  We avoid creating a
247    pointer-to-member function.  */
248
249 tree
250 build_addr_func (tree function)
251 {
252   tree type = TREE_TYPE (function);
253
254   /* We have to do these by hand to avoid real pointer to member
255      functions.  */
256   if (TREE_CODE (type) == METHOD_TYPE)
257     {
258       if (TREE_CODE (function) == OFFSET_REF)
259         {
260           tree object = build_address (TREE_OPERAND (function, 0));
261           return get_member_function_from_ptrfunc (&object,
262                                                    TREE_OPERAND (function, 1));
263         }
264       function = build_address (function);
265     }
266   else
267     function = decay_conversion (function);
268
269   return function;
270 }
271
272 /* Build a CALL_EXPR, we can handle FUNCTION_TYPEs, METHOD_TYPEs, or
273    POINTER_TYPE to those.  Note, pointer to member function types
274    (TYPE_PTRMEMFUNC_P) must be handled by our callers.  There are
275    two variants.  build_call_a is the primitive taking an array of
276    arguments, while build_call_n is a wrapper that handles varargs.  */
277
278 tree
279 build_call_n (tree function, int n, ...)
280 {
281   if (n == 0)
282     return build_call_a (function, 0, NULL);
283   else
284     {
285       tree *argarray = XALLOCAVEC (tree, n);
286       va_list ap;
287       int i;
288
289       va_start (ap, n);
290       for (i = 0; i < n; i++)
291         argarray[i] = va_arg (ap, tree);
292       va_end (ap);
293       return build_call_a (function, n, argarray);
294     }
295 }
296
297 tree
298 build_call_a (tree function, int n, tree *argarray)
299 {
300   int is_constructor = 0;
301   int nothrow;
302   tree decl;
303   tree result_type;
304   tree fntype;
305   int i;
306
307   function = build_addr_func (function);
308
309   gcc_assert (TYPE_PTR_P (TREE_TYPE (function)));
310   fntype = TREE_TYPE (TREE_TYPE (function));
311   gcc_assert (TREE_CODE (fntype) == FUNCTION_TYPE
312               || TREE_CODE (fntype) == METHOD_TYPE);
313   result_type = TREE_TYPE (fntype);
314   /* An rvalue has no cv-qualifiers.  */
315   if (SCALAR_TYPE_P (result_type) || VOID_TYPE_P (result_type))
316     result_type = cv_unqualified (result_type);
317
318   if (TREE_CODE (function) == ADDR_EXPR
319       && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
320     {
321       decl = TREE_OPERAND (function, 0);
322       if (!TREE_USED (decl))
323         {
324           /* We invoke build_call directly for several library
325              functions.  These may have been declared normally if
326              we're building libgcc, so we can't just check
327              DECL_ARTIFICIAL.  */
328           gcc_assert (DECL_ARTIFICIAL (decl)
329                       || !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)),
330                                    "__", 2));
331           mark_used (decl);
332         }
333     }
334   else
335     decl = NULL_TREE;
336
337   /* We check both the decl and the type; a function may be known not to
338      throw without being declared throw().  */
339   nothrow = ((decl && TREE_NOTHROW (decl))
340              || TYPE_NOTHROW_P (TREE_TYPE (TREE_TYPE (function))));
341
342   if (decl && TREE_THIS_VOLATILE (decl) && cfun && cp_function_chain)
343     current_function_returns_abnormally = 1;
344
345   if (decl && TREE_DEPRECATED (decl))
346     warn_deprecated_use (decl, NULL_TREE);
347   require_complete_eh_spec_types (fntype, decl);
348
349   if (decl && DECL_CONSTRUCTOR_P (decl))
350     is_constructor = 1;
351
352   /* Don't pass empty class objects by value.  This is useful
353      for tags in STL, which are used to control overload resolution.
354      We don't need to handle other cases of copying empty classes.  */
355   if (! decl || ! DECL_BUILT_IN (decl))
356     for (i = 0; i < n; i++)
357       if (is_empty_class (TREE_TYPE (argarray[i]))
358           && ! TREE_ADDRESSABLE (TREE_TYPE (argarray[i])))
359         {
360           tree t = build0 (EMPTY_CLASS_EXPR, TREE_TYPE (argarray[i]));
361           argarray[i] = build2 (COMPOUND_EXPR, TREE_TYPE (t),
362                                 argarray[i], t);
363         }
364
365   function = build_call_array_loc (input_location,
366                                    result_type, function, n, argarray);
367   TREE_HAS_CONSTRUCTOR (function) = is_constructor;
368   TREE_NOTHROW (function) = nothrow;
369
370   return function;
371 }
372
373 /* Build something of the form ptr->method (args)
374    or object.method (args).  This can also build
375    calls to constructors, and find friends.
376
377    Member functions always take their class variable
378    as a pointer.
379
380    INSTANCE is a class instance.
381
382    NAME is the name of the method desired, usually an IDENTIFIER_NODE.
383
384    PARMS help to figure out what that NAME really refers to.
385
386    BASETYPE_PATH, if non-NULL, contains a chain from the type of INSTANCE
387    down to the real instance type to use for access checking.  We need this
388    information to get protected accesses correct.
389
390    FLAGS is the logical disjunction of zero or more LOOKUP_
391    flags.  See cp-tree.h for more info.
392
393    If this is all OK, calls build_function_call with the resolved
394    member function.
395
396    This function must also handle being called to perform
397    initialization, promotion/coercion of arguments, and
398    instantiation of default parameters.
399
400    Note that NAME may refer to an instance variable name.  If
401    `operator()()' is defined for the type of that field, then we return
402    that result.  */
403
404 /* New overloading code.  */
405
406 typedef struct z_candidate z_candidate;
407
408 typedef struct candidate_warning candidate_warning;
409 struct candidate_warning {
410   z_candidate *loser;
411   candidate_warning *next;
412 };
413
414 struct z_candidate {
415   /* The FUNCTION_DECL that will be called if this candidate is
416      selected by overload resolution.  */
417   tree fn;
418   /* If not NULL_TREE, the first argument to use when calling this
419      function.  */
420   tree first_arg;
421   /* The rest of the arguments to use when calling this function.  If
422      there are no further arguments this may be NULL or it may be an
423      empty vector.  */
424   const VEC(tree,gc) *args;
425   /* The implicit conversion sequences for each of the arguments to
426      FN.  */
427   conversion **convs;
428   /* The number of implicit conversion sequences.  */
429   size_t num_convs;
430   /* If FN is a user-defined conversion, the standard conversion
431      sequence from the type returned by FN to the desired destination
432      type.  */
433   conversion *second_conv;
434   int viable;
435   /* If FN is a member function, the binfo indicating the path used to
436      qualify the name of FN at the call site.  This path is used to
437      determine whether or not FN is accessible if it is selected by
438      overload resolution.  The DECL_CONTEXT of FN will always be a
439      (possibly improper) base of this binfo.  */
440   tree access_path;
441   /* If FN is a non-static member function, the binfo indicating the
442      subobject to which the `this' pointer should be converted if FN
443      is selected by overload resolution.  The type pointed to the by
444      the `this' pointer must correspond to the most derived class
445      indicated by the CONVERSION_PATH.  */
446   tree conversion_path;
447   tree template_decl;
448   tree explicit_targs;
449   candidate_warning *warnings;
450   z_candidate *next;
451 };
452
453 /* Returns true iff T is a null pointer constant in the sense of
454    [conv.ptr].  */
455
456 bool
457 null_ptr_cst_p (tree t)
458 {
459   /* [conv.ptr]
460
461      A null pointer constant is an integral constant expression
462      (_expr.const_) rvalue of integer type that evaluates to zero or
463      an rvalue of type std::nullptr_t. */
464   t = integral_constant_value (t);
465   if (t == null_node
466       || NULLPTR_TYPE_P (TREE_TYPE (t)))
467     return true;
468   if (CP_INTEGRAL_TYPE_P (TREE_TYPE (t)) && integer_zerop (t))
469     {
470       STRIP_NOPS (t);
471       if (!TREE_OVERFLOW (t))
472         return true;
473     }
474   return false;
475 }
476
477 /* Returns nonzero if PARMLIST consists of only default parms and/or
478    ellipsis.  */
479
480 bool
481 sufficient_parms_p (const_tree parmlist)
482 {
483   for (; parmlist && parmlist != void_list_node;
484        parmlist = TREE_CHAIN (parmlist))
485     if (!TREE_PURPOSE (parmlist))
486       return false;
487   return true;
488 }
489
490 /* Allocate N bytes of memory from the conversion obstack.  The memory
491    is zeroed before being returned.  */
492
493 static void *
494 conversion_obstack_alloc (size_t n)
495 {
496   void *p;
497   if (!conversion_obstack_initialized)
498     {
499       gcc_obstack_init (&conversion_obstack);
500       conversion_obstack_initialized = true;
501     }
502   p = obstack_alloc (&conversion_obstack, n);
503   memset (p, 0, n);
504   return p;
505 }
506
507 /* Dynamically allocate a conversion.  */
508
509 static conversion *
510 alloc_conversion (conversion_kind kind)
511 {
512   conversion *c;
513   c = (conversion *) conversion_obstack_alloc (sizeof (conversion));
514   c->kind = kind;
515   return c;
516 }
517
518 #ifdef ENABLE_CHECKING
519
520 /* Make sure that all memory on the conversion obstack has been
521    freed.  */
522
523 void
524 validate_conversion_obstack (void)
525 {
526   if (conversion_obstack_initialized)
527     gcc_assert ((obstack_next_free (&conversion_obstack)
528                  == obstack_base (&conversion_obstack)));
529 }
530
531 #endif /* ENABLE_CHECKING */
532
533 /* Dynamically allocate an array of N conversions.  */
534
535 static conversion **
536 alloc_conversions (size_t n)
537 {
538   return (conversion **) conversion_obstack_alloc (n * sizeof (conversion *));
539 }
540
541 static conversion *
542 build_conv (conversion_kind code, tree type, conversion *from)
543 {
544   conversion *t;
545   conversion_rank rank = CONVERSION_RANK (from);
546
547   /* Note that the caller is responsible for filling in t->cand for
548      user-defined conversions.  */
549   t = alloc_conversion (code);
550   t->type = type;
551   t->u.next = from;
552
553   switch (code)
554     {
555     case ck_ptr:
556     case ck_pmem:
557     case ck_base:
558     case ck_std:
559       if (rank < cr_std)
560         rank = cr_std;
561       break;
562
563     case ck_qual:
564       if (rank < cr_exact)
565         rank = cr_exact;
566       break;
567
568     default:
569       break;
570     }
571   t->rank = rank;
572   t->user_conv_p = (code == ck_user || from->user_conv_p);
573   t->bad_p = from->bad_p;
574   t->base_p = false;
575   return t;
576 }
577
578 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, a
579    specialization of std::initializer_list<T>, if such a conversion is
580    possible.  */
581
582 static conversion *
583 build_list_conv (tree type, tree ctor, int flags)
584 {
585   tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (type), 0);
586   unsigned len = CONSTRUCTOR_NELTS (ctor);
587   conversion **subconvs = alloc_conversions (len);
588   conversion *t;
589   unsigned i;
590   tree val;
591
592   /* Within a list-initialization we can have more user-defined
593      conversions.  */
594   flags &= ~LOOKUP_NO_CONVERSION;
595   /* But no narrowing conversions.  */
596   flags |= LOOKUP_NO_NARROWING;
597
598   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), i, val)
599     {
600       conversion *sub
601         = implicit_conversion (elttype, TREE_TYPE (val), val,
602                                false, flags);
603       if (sub == NULL)
604         return NULL;
605
606       subconvs[i] = sub;
607     }
608
609   t = alloc_conversion (ck_list);
610   t->type = type;
611   t->u.list = subconvs;
612   t->rank = cr_exact;
613
614   for (i = 0; i < len; ++i)
615     {
616       conversion *sub = subconvs[i];
617       if (sub->rank > t->rank)
618         t->rank = sub->rank;
619       if (sub->user_conv_p)
620         t->user_conv_p = true;
621       if (sub->bad_p)
622         t->bad_p = true;
623     }
624
625   return t;
626 }
627
628 /* Represent a conversion from CTOR, a braced-init-list, to TYPE, an
629    aggregate class, if such a conversion is possible.  */
630
631 static conversion *
632 build_aggr_conv (tree type, tree ctor, int flags)
633 {
634   unsigned HOST_WIDE_INT i = 0;
635   conversion *c;
636   tree field = next_initializable_field (TYPE_FIELDS (type));
637   tree empty_ctor = NULL_TREE;
638
639   for (; field; field = next_initializable_field (TREE_CHAIN (field)))
640     {
641       if (i < CONSTRUCTOR_NELTS (ctor))
642         {
643           constructor_elt *ce = CONSTRUCTOR_ELT (ctor, i);
644           if (!can_convert_arg (TREE_TYPE (field), TREE_TYPE (ce->value),
645                                 ce->value, flags))
646             return NULL;
647           ++i;
648           if (TREE_CODE (type) == UNION_TYPE)
649             break;
650         }
651       else
652         {
653           if (empty_ctor == NULL_TREE)
654             empty_ctor = build_constructor (init_list_type_node, NULL);
655           if (!can_convert_arg (TREE_TYPE (field), TREE_TYPE (empty_ctor),
656                                 empty_ctor, flags))
657             return NULL;
658         }
659     }
660
661   if (i < CONSTRUCTOR_NELTS (ctor))
662     return NULL;
663
664   c = alloc_conversion (ck_aggr);
665   c->type = type;
666   c->rank = cr_exact;
667   c->user_conv_p = true;
668   c->u.next = NULL;
669   return c;
670 }
671
672 /* Build a representation of the identity conversion from EXPR to
673    itself.  The TYPE should match the type of EXPR, if EXPR is non-NULL.  */
674
675 static conversion *
676 build_identity_conv (tree type, tree expr)
677 {
678   conversion *c;
679
680   c = alloc_conversion (ck_identity);
681   c->type = type;
682   c->u.expr = expr;
683
684   return c;
685 }
686
687 /* Converting from EXPR to TYPE was ambiguous in the sense that there
688    were multiple user-defined conversions to accomplish the job.
689    Build a conversion that indicates that ambiguity.  */
690
691 static conversion *
692 build_ambiguous_conv (tree type, tree expr)
693 {
694   conversion *c;
695
696   c = alloc_conversion (ck_ambig);
697   c->type = type;
698   c->u.expr = expr;
699
700   return c;
701 }
702
703 tree
704 strip_top_quals (tree t)
705 {
706   if (TREE_CODE (t) == ARRAY_TYPE)
707     return t;
708   return cp_build_qualified_type (t, 0);
709 }
710
711 /* Returns the standard conversion path (see [conv]) from type FROM to type
712    TO, if any.  For proper handling of null pointer constants, you must
713    also pass the expression EXPR to convert from.  If C_CAST_P is true,
714    this conversion is coming from a C-style cast.  */
715
716 static conversion *
717 standard_conversion (tree to, tree from, tree expr, bool c_cast_p,
718                      int flags)
719 {
720   enum tree_code fcode, tcode;
721   conversion *conv;
722   bool fromref = false;
723
724   to = non_reference (to);
725   if (TREE_CODE (from) == REFERENCE_TYPE)
726     {
727       fromref = true;
728       from = TREE_TYPE (from);
729     }
730   to = strip_top_quals (to);
731   from = strip_top_quals (from);
732
733   if ((TYPE_PTRFN_P (to) || TYPE_PTRMEMFUNC_P (to))
734       && expr && type_unknown_p (expr))
735     {
736       tsubst_flags_t tflags = tf_conv;
737       if (!(flags & LOOKUP_PROTECT))
738         tflags |= tf_no_access_control;
739       expr = instantiate_type (to, expr, tflags);
740       if (expr == error_mark_node)
741         return NULL;
742       from = TREE_TYPE (expr);
743     }
744
745   fcode = TREE_CODE (from);
746   tcode = TREE_CODE (to);
747
748   conv = build_identity_conv (from, expr);
749   if (fcode == FUNCTION_TYPE || fcode == ARRAY_TYPE)
750     {
751       from = type_decays_to (from);
752       fcode = TREE_CODE (from);
753       conv = build_conv (ck_lvalue, from, conv);
754     }
755   else if (fromref || (expr && lvalue_p (expr)))
756     {
757       if (expr)
758         {
759           tree bitfield_type;
760           bitfield_type = is_bitfield_expr_with_lowered_type (expr);
761           if (bitfield_type)
762             {
763               from = strip_top_quals (bitfield_type);
764               fcode = TREE_CODE (from);
765             }
766         }
767       conv = build_conv (ck_rvalue, from, conv);
768     }
769
770    /* Allow conversion between `__complex__' data types.  */
771   if (tcode == COMPLEX_TYPE && fcode == COMPLEX_TYPE)
772     {
773       /* The standard conversion sequence to convert FROM to TO is
774          the standard conversion sequence to perform componentwise
775          conversion.  */
776       conversion *part_conv = standard_conversion
777         (TREE_TYPE (to), TREE_TYPE (from), NULL_TREE, c_cast_p, flags);
778
779       if (part_conv)
780         {
781           conv = build_conv (part_conv->kind, to, conv);
782           conv->rank = part_conv->rank;
783         }
784       else
785         conv = NULL;
786
787       return conv;
788     }
789
790   if (same_type_p (from, to))
791     return conv;
792
793   /* [conv.ptr]
794      A null pointer constant can be converted to a pointer type; ... A
795      null pointer constant of integral type can be converted to an
796      rvalue of type std::nullptr_t. */
797   if ((tcode == POINTER_TYPE || TYPE_PTR_TO_MEMBER_P (to)
798        || NULLPTR_TYPE_P (to))
799       && expr && null_ptr_cst_p (expr))
800     conv = build_conv (ck_std, to, conv);
801   else if ((tcode == INTEGER_TYPE && fcode == POINTER_TYPE)
802            || (tcode == POINTER_TYPE && fcode == INTEGER_TYPE))
803     {
804       /* For backwards brain damage compatibility, allow interconversion of
805          pointers and integers with a pedwarn.  */
806       conv = build_conv (ck_std, to, conv);
807       conv->bad_p = true;
808     }
809   else if (UNSCOPED_ENUM_P (to) && fcode == INTEGER_TYPE)
810     {
811       /* For backwards brain damage compatibility, allow interconversion of
812          enums and integers with a pedwarn.  */
813       conv = build_conv (ck_std, to, conv);
814       conv->bad_p = true;
815     }
816   else if ((tcode == POINTER_TYPE && fcode == POINTER_TYPE)
817            || (TYPE_PTRMEM_P (to) && TYPE_PTRMEM_P (from)))
818     {
819       tree to_pointee;
820       tree from_pointee;
821
822       if (tcode == POINTER_TYPE
823           && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (from),
824                                                         TREE_TYPE (to)))
825         ;
826       else if (VOID_TYPE_P (TREE_TYPE (to))
827                && !TYPE_PTRMEM_P (from)
828                && TREE_CODE (TREE_TYPE (from)) != FUNCTION_TYPE)
829         {
830           from = build_pointer_type
831             (cp_build_qualified_type (void_type_node,
832                                       cp_type_quals (TREE_TYPE (from))));
833           conv = build_conv (ck_ptr, from, conv);
834         }
835       else if (TYPE_PTRMEM_P (from))
836         {
837           tree fbase = TYPE_PTRMEM_CLASS_TYPE (from);
838           tree tbase = TYPE_PTRMEM_CLASS_TYPE (to);
839
840           if (DERIVED_FROM_P (fbase, tbase)
841               && (same_type_ignoring_top_level_qualifiers_p
842                   (TYPE_PTRMEM_POINTED_TO_TYPE (from),
843                    TYPE_PTRMEM_POINTED_TO_TYPE (to))))
844             {
845               from = build_ptrmem_type (tbase,
846                                         TYPE_PTRMEM_POINTED_TO_TYPE (from));
847               conv = build_conv (ck_pmem, from, conv);
848             }
849           else if (!same_type_p (fbase, tbase))
850             return NULL;
851         }
852       else if (CLASS_TYPE_P (TREE_TYPE (from))
853                && CLASS_TYPE_P (TREE_TYPE (to))
854                /* [conv.ptr]
855
856                   An rvalue of type "pointer to cv D," where D is a
857                   class type, can be converted to an rvalue of type
858                   "pointer to cv B," where B is a base class (clause
859                   _class.derived_) of D.  If B is an inaccessible
860                   (clause _class.access_) or ambiguous
861                   (_class.member.lookup_) base class of D, a program
862                   that necessitates this conversion is ill-formed.
863                   Therefore, we use DERIVED_FROM_P, and do not check
864                   access or uniqueness.  */
865                && DERIVED_FROM_P (TREE_TYPE (to), TREE_TYPE (from)))
866         {
867           from =
868             cp_build_qualified_type (TREE_TYPE (to),
869                                      cp_type_quals (TREE_TYPE (from)));
870           from = build_pointer_type (from);
871           conv = build_conv (ck_ptr, from, conv);
872           conv->base_p = true;
873         }
874
875       if (tcode == POINTER_TYPE)
876         {
877           to_pointee = TREE_TYPE (to);
878           from_pointee = TREE_TYPE (from);
879         }
880       else
881         {
882           to_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (to);
883           from_pointee = TYPE_PTRMEM_POINTED_TO_TYPE (from);
884         }
885
886       if (same_type_p (from, to))
887         /* OK */;
888       else if (c_cast_p && comp_ptr_ttypes_const (to, from))
889         /* In a C-style cast, we ignore CV-qualification because we
890            are allowed to perform a static_cast followed by a
891            const_cast.  */
892         conv = build_conv (ck_qual, to, conv);
893       else if (!c_cast_p && comp_ptr_ttypes (to_pointee, from_pointee))
894         conv = build_conv (ck_qual, to, conv);
895       else if (expr && string_conv_p (to, expr, 0))
896         /* converting from string constant to char *.  */
897         conv = build_conv (ck_qual, to, conv);
898       else if (ptr_reasonably_similar (to_pointee, from_pointee))
899         {
900           conv = build_conv (ck_ptr, to, conv);
901           conv->bad_p = true;
902         }
903       else
904         return NULL;
905
906       from = to;
907     }
908   else if (TYPE_PTRMEMFUNC_P (to) && TYPE_PTRMEMFUNC_P (from))
909     {
910       tree fromfn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (from));
911       tree tofn = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (to));
912       tree fbase = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (fromfn)));
913       tree tbase = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (tofn)));
914
915       if (!DERIVED_FROM_P (fbase, tbase)
916           || !same_type_p (TREE_TYPE (fromfn), TREE_TYPE (tofn))
917           || !compparms (TREE_CHAIN (TYPE_ARG_TYPES (fromfn)),
918                          TREE_CHAIN (TYPE_ARG_TYPES (tofn)))
919           || cp_type_quals (fbase) != cp_type_quals (tbase))
920         return NULL;
921
922       from = build_memfn_type (fromfn, tbase, cp_type_quals (tbase));
923       from = build_ptrmemfunc_type (build_pointer_type (from));
924       conv = build_conv (ck_pmem, from, conv);
925       conv->base_p = true;
926     }
927   else if (tcode == BOOLEAN_TYPE)
928     {
929       /* [conv.bool]
930
931           An rvalue of arithmetic, unscoped enumeration, pointer, or
932           pointer to member type can be converted to an rvalue of type
933           bool. ... An rvalue of type std::nullptr_t can be converted
934           to an rvalue of type bool;  */
935       if (ARITHMETIC_TYPE_P (from)
936           || UNSCOPED_ENUM_P (from)
937           || fcode == POINTER_TYPE
938           || TYPE_PTR_TO_MEMBER_P (from)
939           || NULLPTR_TYPE_P (from))
940         {
941           conv = build_conv (ck_std, to, conv);
942           if (fcode == POINTER_TYPE
943               || TYPE_PTRMEM_P (from)
944               || (TYPE_PTRMEMFUNC_P (from)
945                   && conv->rank < cr_pbool)
946               || NULLPTR_TYPE_P (from))
947             conv->rank = cr_pbool;
948           return conv;
949         }
950
951       return NULL;
952     }
953   /* We don't check for ENUMERAL_TYPE here because there are no standard
954      conversions to enum type.  */
955   /* As an extension, allow conversion to complex type.  */
956   else if (ARITHMETIC_TYPE_P (to))
957     {
958       if (! (INTEGRAL_CODE_P (fcode) || fcode == REAL_TYPE)
959           || SCOPED_ENUM_P (from))
960         return NULL;
961       conv = build_conv (ck_std, to, conv);
962
963       /* Give this a better rank if it's a promotion.  */
964       if (same_type_p (to, type_promotes_to (from))
965           && conv->u.next->rank <= cr_promotion)
966         conv->rank = cr_promotion;
967     }
968   else if (fcode == VECTOR_TYPE && tcode == VECTOR_TYPE
969            && vector_types_convertible_p (from, to, false))
970     return build_conv (ck_std, to, conv);
971   else if (MAYBE_CLASS_TYPE_P (to) && MAYBE_CLASS_TYPE_P (from)
972            && is_properly_derived_from (from, to))
973     {
974       if (conv->kind == ck_rvalue)
975         conv = conv->u.next;
976       conv = build_conv (ck_base, to, conv);
977       /* The derived-to-base conversion indicates the initialization
978          of a parameter with base type from an object of a derived
979          type.  A temporary object is created to hold the result of
980          the conversion unless we're binding directly to a reference.  */
981       conv->need_temporary_p = !(flags & LOOKUP_NO_TEMP_BIND);
982     }
983   else
984     return NULL;
985
986   if (flags & LOOKUP_NO_NARROWING)
987     conv->check_narrowing = true;
988
989   return conv;
990 }
991
992 /* Returns nonzero if T1 is reference-related to T2.  */
993
994 bool
995 reference_related_p (tree t1, tree t2)
996 {
997   t1 = TYPE_MAIN_VARIANT (t1);
998   t2 = TYPE_MAIN_VARIANT (t2);
999
1000   /* [dcl.init.ref]
1001
1002      Given types "cv1 T1" and "cv2 T2," "cv1 T1" is reference-related
1003      to "cv2 T2" if T1 is the same type as T2, or T1 is a base class
1004      of T2.  */
1005   return (same_type_p (t1, t2)
1006           || (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
1007               && DERIVED_FROM_P (t1, t2)));
1008 }
1009
1010 /* Returns nonzero if T1 is reference-compatible with T2.  */
1011
1012 static bool
1013 reference_compatible_p (tree t1, tree t2)
1014 {
1015   /* [dcl.init.ref]
1016
1017      "cv1 T1" is reference compatible with "cv2 T2" if T1 is
1018      reference-related to T2 and cv1 is the same cv-qualification as,
1019      or greater cv-qualification than, cv2.  */
1020   return (reference_related_p (t1, t2)
1021           && at_least_as_qualified_p (t1, t2));
1022 }
1023
1024 /* Determine whether or not the EXPR (of class type S) can be
1025    converted to T as in [over.match.ref].  */
1026
1027 static conversion *
1028 convert_class_to_reference (tree reference_type, tree s, tree expr, int flags)
1029 {
1030   tree conversions;
1031   tree first_arg;
1032   conversion *conv;
1033   tree t;
1034   struct z_candidate *candidates;
1035   struct z_candidate *cand;
1036   bool any_viable_p;
1037
1038   conversions = lookup_conversions (s, /*lookup_template_convs_p=*/true);
1039   if (!conversions)
1040     return NULL;
1041
1042   /* [over.match.ref]
1043
1044      Assuming that "cv1 T" is the underlying type of the reference
1045      being initialized, and "cv S" is the type of the initializer
1046      expression, with S a class type, the candidate functions are
1047      selected as follows:
1048
1049      --The conversion functions of S and its base classes are
1050        considered.  Those that are not hidden within S and yield type
1051        "reference to cv2 T2", where "cv1 T" is reference-compatible
1052        (_dcl.init.ref_) with "cv2 T2", are candidate functions.
1053
1054      The argument list has one argument, which is the initializer
1055      expression.  */
1056
1057   candidates = 0;
1058
1059   /* Conceptually, we should take the address of EXPR and put it in
1060      the argument list.  Unfortunately, however, that can result in
1061      error messages, which we should not issue now because we are just
1062      trying to find a conversion operator.  Therefore, we use NULL,
1063      cast to the appropriate type.  */
1064   first_arg = build_int_cst (build_pointer_type (s), 0);
1065
1066   t = TREE_TYPE (reference_type);
1067
1068   /* We're performing a user-defined conversion to a desired type, so set
1069      this for the benefit of add_candidates.  */
1070   flags |= LOOKUP_NO_CONVERSION;
1071
1072   for (; conversions; conversions = TREE_CHAIN (conversions))
1073     {
1074       tree fns = TREE_VALUE (conversions);
1075       tree binfo = TREE_PURPOSE (conversions);
1076       struct z_candidate *old_candidates = candidates;;
1077
1078       add_candidates (fns, first_arg, NULL, reference_type,
1079                       NULL_TREE, false,
1080                       binfo, TYPE_BINFO (s),
1081                       flags, &candidates);
1082
1083       for (cand = candidates; cand != old_candidates; cand = cand->next)
1084         {
1085           /* Now, see if the conversion function really returns
1086              an lvalue of the appropriate type.  From the
1087              point of view of unification, simply returning an
1088              rvalue of the right type is good enough.  */
1089           tree f = cand->fn;
1090           tree t2 = TREE_TYPE (TREE_TYPE (f));
1091           if (TREE_CODE (t2) != REFERENCE_TYPE
1092               || !reference_compatible_p (t, TREE_TYPE (t2)))
1093             {
1094               cand->viable = 0;
1095             }
1096           else
1097             {
1098               conversion *identity_conv;
1099               /* Build a standard conversion sequence indicating the
1100                  binding from the reference type returned by the
1101                  function to the desired REFERENCE_TYPE.  */
1102               identity_conv
1103                 = build_identity_conv (TREE_TYPE (TREE_TYPE
1104                                                   (TREE_TYPE (cand->fn))),
1105                                        NULL_TREE);
1106               cand->second_conv
1107                 = (direct_reference_binding
1108                    (reference_type, identity_conv));
1109               cand->second_conv->rvaluedness_matches_p
1110                 = TYPE_REF_IS_RVALUE (TREE_TYPE (TREE_TYPE (cand->fn)))
1111                   == TYPE_REF_IS_RVALUE (reference_type);
1112               cand->second_conv->bad_p |= cand->convs[0]->bad_p;
1113
1114               /* Don't allow binding of lvalues to rvalue references.  */
1115               if (TYPE_REF_IS_RVALUE (reference_type)
1116                   && !TYPE_REF_IS_RVALUE (TREE_TYPE (TREE_TYPE (cand->fn))))
1117                 cand->second_conv->bad_p = true;
1118             }
1119         }
1120     }
1121
1122   candidates = splice_viable (candidates, pedantic, &any_viable_p);
1123   /* If none of the conversion functions worked out, let our caller
1124      know.  */
1125   if (!any_viable_p)
1126     return NULL;
1127
1128   cand = tourney (candidates);
1129   if (!cand)
1130     return NULL;
1131
1132   /* Now that we know that this is the function we're going to use fix
1133      the dummy first argument.  */
1134   gcc_assert (cand->first_arg == NULL_TREE
1135               || integer_zerop (cand->first_arg));
1136   cand->first_arg = build_this (expr);
1137
1138   /* Build a user-defined conversion sequence representing the
1139      conversion.  */
1140   conv = build_conv (ck_user,
1141                      TREE_TYPE (TREE_TYPE (cand->fn)),
1142                      build_identity_conv (TREE_TYPE (expr), expr));
1143   conv->cand = cand;
1144
1145   if (cand->viable == -1)
1146     conv->bad_p = true;
1147
1148   /* Merge it with the standard conversion sequence from the
1149      conversion function's return type to the desired type.  */
1150   cand->second_conv = merge_conversion_sequences (conv, cand->second_conv);
1151
1152   return cand->second_conv;
1153 }
1154
1155 /* A reference of the indicated TYPE is being bound directly to the
1156    expression represented by the implicit conversion sequence CONV.
1157    Return a conversion sequence for this binding.  */
1158
1159 static conversion *
1160 direct_reference_binding (tree type, conversion *conv)
1161 {
1162   tree t;
1163
1164   gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
1165   gcc_assert (TREE_CODE (conv->type) != REFERENCE_TYPE);
1166
1167   t = TREE_TYPE (type);
1168
1169   /* [over.ics.rank]
1170
1171      When a parameter of reference type binds directly
1172      (_dcl.init.ref_) to an argument expression, the implicit
1173      conversion sequence is the identity conversion, unless the
1174      argument expression has a type that is a derived class of the
1175      parameter type, in which case the implicit conversion sequence is
1176      a derived-to-base Conversion.
1177
1178      If the parameter binds directly to the result of applying a
1179      conversion function to the argument expression, the implicit
1180      conversion sequence is a user-defined conversion sequence
1181      (_over.ics.user_), with the second standard conversion sequence
1182      either an identity conversion or, if the conversion function
1183      returns an entity of a type that is a derived class of the
1184      parameter type, a derived-to-base conversion.  */
1185   if (!same_type_ignoring_top_level_qualifiers_p (t, conv->type))
1186     {
1187       /* Represent the derived-to-base conversion.  */
1188       conv = build_conv (ck_base, t, conv);
1189       /* We will actually be binding to the base-class subobject in
1190          the derived class, so we mark this conversion appropriately.
1191          That way, convert_like knows not to generate a temporary.  */
1192       conv->need_temporary_p = false;
1193     }
1194   return build_conv (ck_ref_bind, type, conv);
1195 }
1196
1197 /* Returns the conversion path from type FROM to reference type TO for
1198    purposes of reference binding.  For lvalue binding, either pass a
1199    reference type to FROM or an lvalue expression to EXPR.  If the
1200    reference will be bound to a temporary, NEED_TEMPORARY_P is set for
1201    the conversion returned.  If C_CAST_P is true, this
1202    conversion is coming from a C-style cast.  */
1203
1204 static conversion *
1205 reference_binding (tree rto, tree rfrom, tree expr, bool c_cast_p, int flags)
1206 {
1207   conversion *conv = NULL;
1208   tree to = TREE_TYPE (rto);
1209   tree from = rfrom;
1210   tree tfrom;
1211   bool related_p;
1212   bool compatible_p;
1213   cp_lvalue_kind is_lvalue = clk_none;
1214
1215   if (TREE_CODE (to) == FUNCTION_TYPE && expr && type_unknown_p (expr))
1216     {
1217       expr = instantiate_type (to, expr, tf_none);
1218       if (expr == error_mark_node)
1219         return NULL;
1220       from = TREE_TYPE (expr);
1221     }
1222
1223   if (TREE_CODE (from) == REFERENCE_TYPE)
1224     {
1225       /* Anything with reference type is an lvalue.  */
1226       is_lvalue = clk_ordinary;
1227       from = TREE_TYPE (from);
1228     }
1229
1230   if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1231     {
1232       maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
1233       conv = implicit_conversion (to, from, expr, c_cast_p,
1234                                   flags);
1235       if (!CLASS_TYPE_P (to)
1236           && CONSTRUCTOR_NELTS (expr) == 1)
1237         {
1238           expr = CONSTRUCTOR_ELT (expr, 0)->value;
1239           if (error_operand_p (expr))
1240             return NULL;
1241           from = TREE_TYPE (expr);
1242         }
1243     }
1244
1245   if (is_lvalue == clk_none && expr)
1246     is_lvalue = real_lvalue_p (expr);
1247
1248   tfrom = from;
1249   if ((is_lvalue & clk_bitfield) != 0)
1250     tfrom = unlowered_expr_type (expr);
1251
1252   /* Figure out whether or not the types are reference-related and
1253      reference compatible.  We have do do this after stripping
1254      references from FROM.  */
1255   related_p = reference_related_p (to, tfrom);
1256   /* If this is a C cast, first convert to an appropriately qualified
1257      type, so that we can later do a const_cast to the desired type.  */
1258   if (related_p && c_cast_p
1259       && !at_least_as_qualified_p (to, tfrom))
1260     to = cp_build_qualified_type (to, cp_type_quals (tfrom));
1261   compatible_p = reference_compatible_p (to, tfrom);
1262
1263   /* Directly bind reference when target expression's type is compatible with
1264      the reference and expression is an lvalue. In DR391, the wording in
1265      [8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
1266      const and rvalue references to rvalues of compatible class type.
1267      We should also do direct bindings for non-class "rvalues" derived from
1268      rvalue references.  */
1269   if (compatible_p
1270       && (is_lvalue
1271           || (((CP_TYPE_CONST_NON_VOLATILE_P (to)
1272                 && !(flags & LOOKUP_NO_TEMP_BIND))
1273                || TYPE_REF_IS_RVALUE (rto))
1274               && (CLASS_TYPE_P (from) || (expr && lvalue_p (expr))))))
1275     {
1276       /* [dcl.init.ref]
1277
1278          If the initializer expression
1279
1280          -- is an lvalue (but not an lvalue for a bit-field), and "cv1 T1"
1281             is reference-compatible with "cv2 T2,"
1282
1283          the reference is bound directly to the initializer expression
1284          lvalue.
1285
1286          [...]
1287          If the initializer expression is an rvalue, with T2 a class type,
1288          and "cv1 T1" is reference-compatible with "cv2 T2", the reference
1289          is bound to the object represented by the rvalue or to a sub-object
1290          within that object.  */
1291
1292       conv = build_identity_conv (tfrom, expr);
1293       conv = direct_reference_binding (rto, conv);
1294
1295       if (flags & LOOKUP_PREFER_RVALUE)
1296         /* The top-level caller requested that we pretend that the lvalue
1297            be treated as an rvalue.  */
1298         conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
1299       else
1300         conv->rvaluedness_matches_p 
1301           = (TYPE_REF_IS_RVALUE (rto) == !is_lvalue);
1302
1303       if ((is_lvalue & clk_bitfield) != 0
1304           || ((is_lvalue & clk_packed) != 0 && !TYPE_PACKED (to)))
1305         /* For the purposes of overload resolution, we ignore the fact
1306            this expression is a bitfield or packed field. (In particular,
1307            [over.ics.ref] says specifically that a function with a
1308            non-const reference parameter is viable even if the
1309            argument is a bitfield.)
1310
1311            However, when we actually call the function we must create
1312            a temporary to which to bind the reference.  If the
1313            reference is volatile, or isn't const, then we cannot make
1314            a temporary, so we just issue an error when the conversion
1315            actually occurs.  */
1316         conv->need_temporary_p = true;
1317
1318       /* Don't allow binding of lvalues to rvalue references.  */
1319       if (is_lvalue && TYPE_REF_IS_RVALUE (rto)
1320           && !(flags & LOOKUP_PREFER_RVALUE))
1321         conv->bad_p = true;
1322
1323       return conv;
1324     }
1325   /* [class.conv.fct] A conversion function is never used to convert a
1326      (possibly cv-qualified) object to the (possibly cv-qualified) same
1327      object type (or a reference to it), to a (possibly cv-qualified) base
1328      class of that type (or a reference to it).... */
1329   else if (CLASS_TYPE_P (from) && !related_p
1330            && !(flags & LOOKUP_NO_CONVERSION))
1331     {
1332       /* [dcl.init.ref]
1333
1334          If the initializer expression
1335
1336          -- has a class type (i.e., T2 is a class type) can be
1337             implicitly converted to an lvalue of type "cv3 T3," where
1338             "cv1 T1" is reference-compatible with "cv3 T3".  (this
1339             conversion is selected by enumerating the applicable
1340             conversion functions (_over.match.ref_) and choosing the
1341             best one through overload resolution.  (_over.match_).
1342
1343         the reference is bound to the lvalue result of the conversion
1344         in the second case.  */
1345       conv = convert_class_to_reference (rto, from, expr, flags);
1346       if (conv)
1347         return conv;
1348     }
1349
1350   /* From this point on, we conceptually need temporaries, even if we
1351      elide them.  Only the cases above are "direct bindings".  */
1352   if (flags & LOOKUP_NO_TEMP_BIND)
1353     return NULL;
1354
1355   /* [over.ics.rank]
1356
1357      When a parameter of reference type is not bound directly to an
1358      argument expression, the conversion sequence is the one required
1359      to convert the argument expression to the underlying type of the
1360      reference according to _over.best.ics_.  Conceptually, this
1361      conversion sequence corresponds to copy-initializing a temporary
1362      of the underlying type with the argument expression.  Any
1363      difference in top-level cv-qualification is subsumed by the
1364      initialization itself and does not constitute a conversion.  */
1365
1366   /* [dcl.init.ref]
1367
1368      Otherwise, the reference shall be to a non-volatile const type.
1369
1370      Under C++0x, [8.5.3/5 dcl.init.ref] it may also be an rvalue reference */
1371   if (!CP_TYPE_CONST_NON_VOLATILE_P (to) && !TYPE_REF_IS_RVALUE (rto))
1372     return NULL;
1373
1374   /* [dcl.init.ref]
1375
1376      Otherwise, a temporary of type "cv1 T1" is created and
1377      initialized from the initializer expression using the rules for a
1378      non-reference copy initialization.  If T1 is reference-related to
1379      T2, cv1 must be the same cv-qualification as, or greater
1380      cv-qualification than, cv2; otherwise, the program is ill-formed.  */
1381   if (related_p && !at_least_as_qualified_p (to, from))
1382     return NULL;
1383
1384   /* We're generating a temporary now, but don't bind any more in the
1385      conversion (specifically, don't slice the temporary returned by a
1386      conversion operator).  */
1387   flags |= LOOKUP_NO_TEMP_BIND;
1388
1389   /* Temporaries are copy-initialized, except for this hack to allow
1390      explicit conversion ops to the copy ctor.  See also
1391      add_function_candidate.  */
1392   if (!(flags & LOOKUP_COPY_PARM))
1393     flags |= LOOKUP_ONLYCONVERTING;
1394
1395   if (!conv)
1396     conv = implicit_conversion (to, from, expr, c_cast_p,
1397                                 flags);
1398   if (!conv)
1399     return NULL;
1400
1401   conv = build_conv (ck_ref_bind, rto, conv);
1402   /* This reference binding, unlike those above, requires the
1403      creation of a temporary.  */
1404   conv->need_temporary_p = true;
1405   conv->rvaluedness_matches_p = TYPE_REF_IS_RVALUE (rto);
1406
1407   return conv;
1408 }
1409
1410 /* Returns the implicit conversion sequence (see [over.ics]) from type
1411    FROM to type TO.  The optional expression EXPR may affect the
1412    conversion.  FLAGS are the usual overloading flags.  If C_CAST_P is
1413    true, this conversion is coming from a C-style cast.  */
1414
1415 static conversion *
1416 implicit_conversion (tree to, tree from, tree expr, bool c_cast_p,
1417                      int flags)
1418 {
1419   conversion *conv;
1420
1421   if (from == error_mark_node || to == error_mark_node
1422       || expr == error_mark_node)
1423     return NULL;
1424
1425   if (TREE_CODE (to) == REFERENCE_TYPE)
1426     conv = reference_binding (to, from, expr, c_cast_p, flags);
1427   else
1428     conv = standard_conversion (to, from, expr, c_cast_p, flags);
1429
1430   if (conv)
1431     return conv;
1432
1433   if (expr && BRACE_ENCLOSED_INITIALIZER_P (expr))
1434     {
1435       if (is_std_init_list (to))
1436         return build_list_conv (to, expr, flags);
1437
1438       /* Allow conversion from an initializer-list with one element to a
1439          scalar type.  */
1440       if (SCALAR_TYPE_P (to))
1441         {
1442           int nelts = CONSTRUCTOR_NELTS (expr);
1443           tree elt;
1444
1445           if (nelts == 0)
1446             elt = integer_zero_node;
1447           else if (nelts == 1)
1448             elt = CONSTRUCTOR_ELT (expr, 0)->value;
1449           else
1450             elt = error_mark_node;
1451
1452           conv = implicit_conversion (to, TREE_TYPE (elt), elt,
1453                                       c_cast_p, flags);
1454           if (conv)
1455             {
1456               conv->check_narrowing = true;
1457               if (BRACE_ENCLOSED_INITIALIZER_P (elt))
1458                 /* Too many levels of braces, i.e. '{{1}}'.  */
1459                 conv->bad_p = true;
1460               return conv;
1461             }
1462         }
1463     }
1464
1465   if (expr != NULL_TREE
1466       && (MAYBE_CLASS_TYPE_P (from)
1467           || MAYBE_CLASS_TYPE_P (to))
1468       && (flags & LOOKUP_NO_CONVERSION) == 0)
1469     {
1470       struct z_candidate *cand;
1471       int convflags = (flags & (LOOKUP_NO_TEMP_BIND|LOOKUP_ONLYCONVERTING
1472                                 |LOOKUP_NO_NARROWING));
1473
1474       if (CLASS_TYPE_P (to)
1475           && !CLASSTYPE_NON_AGGREGATE (complete_type (to))
1476           && BRACE_ENCLOSED_INITIALIZER_P (expr))
1477         return build_aggr_conv (to, expr, flags);
1478
1479       cand = build_user_type_conversion_1 (to, expr, convflags);
1480       if (cand)
1481         conv = cand->second_conv;
1482
1483       /* We used to try to bind a reference to a temporary here, but that
1484          is now handled after the recursive call to this function at the end
1485          of reference_binding.  */
1486       return conv;
1487     }
1488
1489   return NULL;
1490 }
1491
1492 /* Add a new entry to the list of candidates.  Used by the add_*_candidate
1493    functions.  ARGS will not be changed until a single candidate is
1494    selected.  */
1495
1496 static struct z_candidate *
1497 add_candidate (struct z_candidate **candidates,
1498                tree fn, tree first_arg, const VEC(tree,gc) *args,
1499                size_t num_convs, conversion **convs,
1500                tree access_path, tree conversion_path,
1501                int viable)
1502 {
1503   struct z_candidate *cand = (struct z_candidate *)
1504     conversion_obstack_alloc (sizeof (struct z_candidate));
1505
1506   cand->fn = fn;
1507   cand->first_arg = first_arg;
1508   cand->args = args;
1509   cand->convs = convs;
1510   cand->num_convs = num_convs;
1511   cand->access_path = access_path;
1512   cand->conversion_path = conversion_path;
1513   cand->viable = viable;
1514   cand->next = *candidates;
1515   *candidates = cand;
1516
1517   return cand;
1518 }
1519
1520 /* Create an overload candidate for the function or method FN called
1521    with the argument list FIRST_ARG/ARGS and add it to CANDIDATES.
1522    FLAGS is passed on to implicit_conversion.
1523
1524    This does not change ARGS.
1525
1526    CTYPE, if non-NULL, is the type we want to pretend this function
1527    comes from for purposes of overload resolution.  */
1528
1529 static struct z_candidate *
1530 add_function_candidate (struct z_candidate **candidates,
1531                         tree fn, tree ctype, tree first_arg,
1532                         const VEC(tree,gc) *args, tree access_path,
1533                         tree conversion_path, int flags)
1534 {
1535   tree parmlist = TYPE_ARG_TYPES (TREE_TYPE (fn));
1536   int i, len;
1537   conversion **convs;
1538   tree parmnode;
1539   tree orig_first_arg = first_arg;
1540   int skip;
1541   int viable = 1;
1542
1543   /* At this point we should not see any functions which haven't been
1544      explicitly declared, except for friend functions which will have
1545      been found using argument dependent lookup.  */
1546   gcc_assert (!DECL_ANTICIPATED (fn) || DECL_HIDDEN_FRIEND_P (fn));
1547
1548   /* The `this', `in_chrg' and VTT arguments to constructors are not
1549      considered in overload resolution.  */
1550   if (DECL_CONSTRUCTOR_P (fn))
1551     {
1552       parmlist = skip_artificial_parms_for (fn, parmlist);
1553       skip = num_artificial_parms_for (fn);
1554       if (skip > 0 && first_arg != NULL_TREE)
1555         {
1556           --skip;
1557           first_arg = NULL_TREE;
1558         }
1559     }
1560   else
1561     skip = 0;
1562
1563   len = VEC_length (tree, args) - skip + (first_arg != NULL_TREE ? 1 : 0);
1564   convs = alloc_conversions (len);
1565
1566   /* 13.3.2 - Viable functions [over.match.viable]
1567      First, to be a viable function, a candidate function shall have enough
1568      parameters to agree in number with the arguments in the list.
1569
1570      We need to check this first; otherwise, checking the ICSes might cause
1571      us to produce an ill-formed template instantiation.  */
1572
1573   parmnode = parmlist;
1574   for (i = 0; i < len; ++i)
1575     {
1576       if (parmnode == NULL_TREE || parmnode == void_list_node)
1577         break;
1578       parmnode = TREE_CHAIN (parmnode);
1579     }
1580
1581   if (i < len && parmnode)
1582     viable = 0;
1583
1584   /* Make sure there are default args for the rest of the parms.  */
1585   else if (!sufficient_parms_p (parmnode))
1586     viable = 0;
1587
1588   if (! viable)
1589     goto out;
1590
1591   /* Second, for F to be a viable function, there shall exist for each
1592      argument an implicit conversion sequence that converts that argument
1593      to the corresponding parameter of F.  */
1594
1595   parmnode = parmlist;
1596
1597   for (i = 0; i < len; ++i)
1598     {
1599       tree arg, argtype;
1600       conversion *t;
1601       int is_this;
1602
1603       if (parmnode == void_list_node)
1604         break;
1605
1606       if (i == 0 && first_arg != NULL_TREE)
1607         arg = first_arg;
1608       else
1609         arg = VEC_index (tree, args,
1610                          i + skip - (first_arg != NULL_TREE ? 1 : 0));
1611       argtype = lvalue_type (arg);
1612
1613       is_this = (i == 0 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1614                  && ! DECL_CONSTRUCTOR_P (fn));
1615
1616       if (parmnode)
1617         {
1618           tree parmtype = TREE_VALUE (parmnode);
1619           int lflags = flags;
1620
1621           /* The type of the implicit object parameter ('this') for
1622              overload resolution is not always the same as for the
1623              function itself; conversion functions are considered to
1624              be members of the class being converted, and functions
1625              introduced by a using-declaration are considered to be
1626              members of the class that uses them.
1627
1628              Since build_over_call ignores the ICS for the `this'
1629              parameter, we can just change the parm type.  */
1630           if (ctype && is_this)
1631             {
1632               parmtype = cp_build_qualified_type
1633                 (ctype, cp_type_quals (TREE_TYPE (parmtype)));
1634               parmtype = build_pointer_type (parmtype);
1635             }
1636
1637           if (ctype && i == 0 && DECL_COPY_CONSTRUCTOR_P (fn)
1638               && (len-skip == 1))
1639             {
1640               /* Hack: Direct-initialize copy parm (i.e. suppress
1641                  LOOKUP_ONLYCONVERTING) to make explicit conversion ops
1642                  work.  See also reference_binding.  */
1643               lflags |= LOOKUP_COPY_PARM;
1644               if (flags & LOOKUP_NO_COPY_CTOR_CONVERSION)
1645                 lflags |= LOOKUP_NO_CONVERSION;
1646             }
1647           else
1648             lflags |= LOOKUP_ONLYCONVERTING;
1649
1650           t = implicit_conversion (parmtype, argtype, arg,
1651                                    /*c_cast_p=*/false, lflags);
1652         }
1653       else
1654         {
1655           t = build_identity_conv (argtype, arg);
1656           t->ellipsis_p = true;
1657         }
1658
1659       if (t && is_this)
1660         t->this_p = true;
1661
1662       convs[i] = t;
1663       if (! t)
1664         {
1665           viable = 0;
1666           break;
1667         }
1668
1669       if (t->bad_p)
1670         viable = -1;
1671
1672       if (parmnode)
1673         parmnode = TREE_CHAIN (parmnode);
1674     }
1675
1676  out:
1677   return add_candidate (candidates, fn, orig_first_arg, args, len, convs,
1678                         access_path, conversion_path, viable);
1679 }
1680
1681 /* Create an overload candidate for the conversion function FN which will
1682    be invoked for expression OBJ, producing a pointer-to-function which
1683    will in turn be called with the argument list FIRST_ARG/ARGLIST,
1684    and add it to CANDIDATES.  This does not change ARGLIST.  FLAGS is
1685    passed on to implicit_conversion.
1686
1687    Actually, we don't really care about FN; we care about the type it
1688    converts to.  There may be multiple conversion functions that will
1689    convert to that type, and we rely on build_user_type_conversion_1 to
1690    choose the best one; so when we create our candidate, we record the type
1691    instead of the function.  */
1692
1693 static struct z_candidate *
1694 add_conv_candidate (struct z_candidate **candidates, tree fn, tree obj,
1695                     tree first_arg, const VEC(tree,gc) *arglist,
1696                     tree access_path, tree conversion_path)
1697 {
1698   tree totype = TREE_TYPE (TREE_TYPE (fn));
1699   int i, len, viable, flags;
1700   tree parmlist, parmnode;
1701   conversion **convs;
1702
1703   for (parmlist = totype; TREE_CODE (parmlist) != FUNCTION_TYPE; )
1704     parmlist = TREE_TYPE (parmlist);
1705   parmlist = TYPE_ARG_TYPES (parmlist);
1706
1707   len = VEC_length (tree, arglist) + (first_arg != NULL_TREE ? 1 : 0) + 1;
1708   convs = alloc_conversions (len);
1709   parmnode = parmlist;
1710   viable = 1;
1711   flags = LOOKUP_IMPLICIT;
1712
1713   /* Don't bother looking up the same type twice.  */
1714   if (*candidates && (*candidates)->fn == totype)
1715     return NULL;
1716
1717   for (i = 0; i < len; ++i)
1718     {
1719       tree arg, argtype;
1720       conversion *t;
1721
1722       if (i == 0)
1723         arg = obj;
1724       else if (i == 1 && first_arg != NULL_TREE)
1725         arg = first_arg;
1726       else
1727         arg = VEC_index (tree, arglist,
1728                          i - (first_arg != NULL_TREE ? 1 : 0) - 1);
1729       argtype = lvalue_type (arg);
1730
1731       if (i == 0)
1732         t = implicit_conversion (totype, argtype, arg, /*c_cast_p=*/false,
1733                                  flags);
1734       else if (parmnode == void_list_node)
1735         break;
1736       else if (parmnode)
1737         t = implicit_conversion (TREE_VALUE (parmnode), argtype, arg,
1738                                  /*c_cast_p=*/false, flags);
1739       else
1740         {
1741           t = build_identity_conv (argtype, arg);
1742           t->ellipsis_p = true;
1743         }
1744
1745       convs[i] = t;
1746       if (! t)
1747         break;
1748
1749       if (t->bad_p)
1750         viable = -1;
1751
1752       if (i == 0)
1753         continue;
1754
1755       if (parmnode)
1756         parmnode = TREE_CHAIN (parmnode);
1757     }
1758
1759   if (i < len)
1760     viable = 0;
1761
1762   if (!sufficient_parms_p (parmnode))
1763     viable = 0;
1764
1765   return add_candidate (candidates, totype, first_arg, arglist, len, convs,
1766                         access_path, conversion_path, viable);
1767 }
1768
1769 static void
1770 build_builtin_candidate (struct z_candidate **candidates, tree fnname,
1771                          tree type1, tree type2, tree *args, tree *argtypes,
1772                          int flags)
1773 {
1774   conversion *t;
1775   conversion **convs;
1776   size_t num_convs;
1777   int viable = 1, i;
1778   tree types[2];
1779
1780   types[0] = type1;
1781   types[1] = type2;
1782
1783   num_convs =  args[2] ? 3 : (args[1] ? 2 : 1);
1784   convs = alloc_conversions (num_convs);
1785
1786   /* TRUTH_*_EXPR do "contextual conversion to bool", which means explicit
1787      conversion ops are allowed.  We handle that here by just checking for
1788      boolean_type_node because other operators don't ask for it.  COND_EXPR
1789      also does contextual conversion to bool for the first operand, but we
1790      handle that in build_conditional_expr, and type1 here is operand 2.  */
1791   if (type1 != boolean_type_node)
1792     flags |= LOOKUP_ONLYCONVERTING;
1793
1794   for (i = 0; i < 2; ++i)
1795     {
1796       if (! args[i])
1797         break;
1798
1799       t = implicit_conversion (types[i], argtypes[i], args[i],
1800                                /*c_cast_p=*/false, flags);
1801       if (! t)
1802         {
1803           viable = 0;
1804           /* We need something for printing the candidate.  */
1805           t = build_identity_conv (types[i], NULL_TREE);
1806         }
1807       else if (t->bad_p)
1808         viable = 0;
1809       convs[i] = t;
1810     }
1811
1812   /* For COND_EXPR we rearranged the arguments; undo that now.  */
1813   if (args[2])
1814     {
1815       convs[2] = convs[1];
1816       convs[1] = convs[0];
1817       t = implicit_conversion (boolean_type_node, argtypes[2], args[2],
1818                                /*c_cast_p=*/false, flags);
1819       if (t)
1820         convs[0] = t;
1821       else
1822         viable = 0;
1823     }
1824
1825   add_candidate (candidates, fnname, /*first_arg=*/NULL_TREE, /*args=*/NULL,
1826                  num_convs, convs,
1827                  /*access_path=*/NULL_TREE,
1828                  /*conversion_path=*/NULL_TREE,
1829                  viable);
1830 }
1831
1832 static bool
1833 is_complete (tree t)
1834 {
1835   return COMPLETE_TYPE_P (complete_type (t));
1836 }
1837
1838 /* Returns nonzero if TYPE is a promoted arithmetic type.  */
1839
1840 static bool
1841 promoted_arithmetic_type_p (tree type)
1842 {
1843   /* [over.built]
1844
1845      In this section, the term promoted integral type is used to refer
1846      to those integral types which are preserved by integral promotion
1847      (including e.g.  int and long but excluding e.g.  char).
1848      Similarly, the term promoted arithmetic type refers to promoted
1849      integral types plus floating types.  */
1850   return ((CP_INTEGRAL_TYPE_P (type)
1851            && same_type_p (type_promotes_to (type), type))
1852           || TREE_CODE (type) == REAL_TYPE);
1853 }
1854
1855 /* Create any builtin operator overload candidates for the operator in
1856    question given the converted operand types TYPE1 and TYPE2.  The other
1857    args are passed through from add_builtin_candidates to
1858    build_builtin_candidate.
1859
1860    TYPE1 and TYPE2 may not be permissible, and we must filter them.
1861    If CODE is requires candidates operands of the same type of the kind
1862    of which TYPE1 and TYPE2 are, we add both candidates
1863    CODE (TYPE1, TYPE1) and CODE (TYPE2, TYPE2).  */
1864
1865 static void
1866 add_builtin_candidate (struct z_candidate **candidates, enum tree_code code,
1867                        enum tree_code code2, tree fnname, tree type1,
1868                        tree type2, tree *args, tree *argtypes, int flags)
1869 {
1870   switch (code)
1871     {
1872     case POSTINCREMENT_EXPR:
1873     case POSTDECREMENT_EXPR:
1874       args[1] = integer_zero_node;
1875       type2 = integer_type_node;
1876       break;
1877     default:
1878       break;
1879     }
1880
1881   switch (code)
1882     {
1883
1884 /* 4 For every pair T, VQ), where T is an arithmetic or  enumeration  type,
1885      and  VQ  is  either  volatile or empty, there exist candidate operator
1886      functions of the form
1887              VQ T&   operator++(VQ T&);
1888              T       operator++(VQ T&, int);
1889    5 For every pair T, VQ), where T is an enumeration type or an arithmetic
1890      type  other than bool, and VQ is either volatile or empty, there exist
1891      candidate operator functions of the form
1892              VQ T&   operator--(VQ T&);
1893              T       operator--(VQ T&, int);
1894    6 For every pair T, VQ), where T is  a  cv-qualified  or  cv-unqualified
1895      complete  object type, and VQ is either volatile or empty, there exist
1896      candidate operator functions of the form
1897              T*VQ&   operator++(T*VQ&);
1898              T*VQ&   operator--(T*VQ&);
1899              T*      operator++(T*VQ&, int);
1900              T*      operator--(T*VQ&, int);  */
1901
1902     case POSTDECREMENT_EXPR:
1903     case PREDECREMENT_EXPR:
1904       if (TREE_CODE (type1) == BOOLEAN_TYPE)
1905         return;
1906     case POSTINCREMENT_EXPR:
1907     case PREINCREMENT_EXPR:
1908       if (ARITHMETIC_TYPE_P (type1) || TYPE_PTROB_P (type1))
1909         {
1910           type1 = build_reference_type (type1);
1911           break;
1912         }
1913       return;
1914
1915 /* 7 For every cv-qualified or cv-unqualified complete object type T, there
1916      exist candidate operator functions of the form
1917
1918              T&      operator*(T*);
1919
1920    8 For every function type T, there exist candidate operator functions of
1921      the form
1922              T&      operator*(T*);  */
1923
1924     case INDIRECT_REF:
1925       if (TREE_CODE (type1) == POINTER_TYPE
1926           && (TYPE_PTROB_P (type1)
1927               || TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE))
1928         break;
1929       return;
1930
1931 /* 9 For every type T, there exist candidate operator functions of the form
1932              T*      operator+(T*);
1933
1934    10For  every  promoted arithmetic type T, there exist candidate operator
1935      functions of the form
1936              T       operator+(T);
1937              T       operator-(T);  */
1938
1939     case UNARY_PLUS_EXPR: /* unary + */
1940       if (TREE_CODE (type1) == POINTER_TYPE)
1941         break;
1942     case NEGATE_EXPR:
1943       if (ARITHMETIC_TYPE_P (type1))
1944         break;
1945       return;
1946
1947 /* 11For every promoted integral type T,  there  exist  candidate  operator
1948      functions of the form
1949              T       operator~(T);  */
1950
1951     case BIT_NOT_EXPR:
1952       if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1))
1953         break;
1954       return;
1955
1956 /* 12For every quintuple C1, C2, T, CV1, CV2), where C2 is a class type, C1
1957      is the same type as C2 or is a derived class of C2, T  is  a  complete
1958      object type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
1959      there exist candidate operator functions of the form
1960              CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
1961      where CV12 is the union of CV1 and CV2.  */
1962
1963     case MEMBER_REF:
1964       if (TREE_CODE (type1) == POINTER_TYPE
1965           && TYPE_PTR_TO_MEMBER_P (type2))
1966         {
1967           tree c1 = TREE_TYPE (type1);
1968           tree c2 = TYPE_PTRMEM_CLASS_TYPE (type2);
1969
1970           if (MAYBE_CLASS_TYPE_P (c1) && DERIVED_FROM_P (c2, c1)
1971               && (TYPE_PTRMEMFUNC_P (type2)
1972                   || is_complete (TYPE_PTRMEM_POINTED_TO_TYPE (type2))))
1973             break;
1974         }
1975       return;
1976
1977 /* 13For every pair of promoted arithmetic types L and R, there exist  can-
1978      didate operator functions of the form
1979              LR      operator*(L, R);
1980              LR      operator/(L, R);
1981              LR      operator+(L, R);
1982              LR      operator-(L, R);
1983              bool    operator<(L, R);
1984              bool    operator>(L, R);
1985              bool    operator<=(L, R);
1986              bool    operator>=(L, R);
1987              bool    operator==(L, R);
1988              bool    operator!=(L, R);
1989      where  LR  is  the  result of the usual arithmetic conversions between
1990      types L and R.
1991
1992    14For every pair of types T and I, where T  is  a  cv-qualified  or  cv-
1993      unqualified  complete  object  type and I is a promoted integral type,
1994      there exist candidate operator functions of the form
1995              T*      operator+(T*, I);
1996              T&      operator[](T*, I);
1997              T*      operator-(T*, I);
1998              T*      operator+(I, T*);
1999              T&      operator[](I, T*);
2000
2001    15For every T, where T is a pointer to complete object type, there exist
2002      candidate operator functions of the form112)
2003              ptrdiff_t operator-(T, T);
2004
2005    16For every pointer or enumeration type T, there exist candidate operator
2006      functions of the form
2007              bool    operator<(T, T);
2008              bool    operator>(T, T);
2009              bool    operator<=(T, T);
2010              bool    operator>=(T, T);
2011              bool    operator==(T, T);
2012              bool    operator!=(T, T);
2013
2014    17For every pointer to member type T,  there  exist  candidate  operator
2015      functions of the form
2016              bool    operator==(T, T);
2017              bool    operator!=(T, T);  */
2018
2019     case MINUS_EXPR:
2020       if (TYPE_PTROB_P (type1) && TYPE_PTROB_P (type2))
2021         break;
2022       if (TYPE_PTROB_P (type1)
2023           && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2024         {
2025           type2 = ptrdiff_type_node;
2026           break;
2027         }
2028     case MULT_EXPR:
2029     case TRUNC_DIV_EXPR:
2030       if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2031         break;
2032       return;
2033
2034     case EQ_EXPR:
2035     case NE_EXPR:
2036       if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
2037           || (TYPE_PTRMEM_P (type1) && TYPE_PTRMEM_P (type2)))
2038         break;
2039       if (TYPE_PTR_TO_MEMBER_P (type1) && null_ptr_cst_p (args[1]))
2040         {
2041           type2 = type1;
2042           break;
2043         }
2044       if (TYPE_PTR_TO_MEMBER_P (type2) && null_ptr_cst_p (args[0]))
2045         {
2046           type1 = type2;
2047           break;
2048         }
2049       /* Fall through.  */
2050     case LT_EXPR:
2051     case GT_EXPR:
2052     case LE_EXPR:
2053     case GE_EXPR:
2054     case MAX_EXPR:
2055     case MIN_EXPR:
2056       if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2057         break;
2058       if (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
2059         break;
2060       if (TREE_CODE (type1) == ENUMERAL_TYPE 
2061           && TREE_CODE (type2) == ENUMERAL_TYPE)
2062         break;
2063       if (TYPE_PTR_P (type1) 
2064           && null_ptr_cst_p (args[1])
2065           && !uses_template_parms (type1))
2066         {
2067           type2 = type1;
2068           break;
2069         }
2070       if (null_ptr_cst_p (args[0]) 
2071           && TYPE_PTR_P (type2)
2072           && !uses_template_parms (type2))
2073         {
2074           type1 = type2;
2075           break;
2076         }
2077       return;
2078
2079     case PLUS_EXPR:
2080       if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2081         break;
2082     case ARRAY_REF:
2083       if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && TYPE_PTROB_P (type2))
2084         {
2085           type1 = ptrdiff_type_node;
2086           break;
2087         }
2088       if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2089         {
2090           type2 = ptrdiff_type_node;
2091           break;
2092         }
2093       return;
2094
2095 /* 18For  every pair of promoted integral types L and R, there exist candi-
2096      date operator functions of the form
2097              LR      operator%(L, R);
2098              LR      operator&(L, R);
2099              LR      operator^(L, R);
2100              LR      operator|(L, R);
2101              L       operator<<(L, R);
2102              L       operator>>(L, R);
2103      where LR is the result of the  usual  arithmetic  conversions  between
2104      types L and R.  */
2105
2106     case TRUNC_MOD_EXPR:
2107     case BIT_AND_EXPR:
2108     case BIT_IOR_EXPR:
2109     case BIT_XOR_EXPR:
2110     case LSHIFT_EXPR:
2111     case RSHIFT_EXPR:
2112       if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2113         break;
2114       return;
2115
2116 /* 19For  every  triple  L, VQ, R), where L is an arithmetic or enumeration
2117      type, VQ is either volatile or empty, and R is a  promoted  arithmetic
2118      type, there exist candidate operator functions of the form
2119              VQ L&   operator=(VQ L&, R);
2120              VQ L&   operator*=(VQ L&, R);
2121              VQ L&   operator/=(VQ L&, R);
2122              VQ L&   operator+=(VQ L&, R);
2123              VQ L&   operator-=(VQ L&, R);
2124
2125    20For  every  pair T, VQ), where T is any type and VQ is either volatile
2126      or empty, there exist candidate operator functions of the form
2127              T*VQ&   operator=(T*VQ&, T*);
2128
2129    21For every pair T, VQ), where T is a pointer to member type and  VQ  is
2130      either  volatile or empty, there exist candidate operator functions of
2131      the form
2132              VQ T&   operator=(VQ T&, T);
2133
2134    22For every triple  T,  VQ,  I),  where  T  is  a  cv-qualified  or  cv-
2135      unqualified  complete object type, VQ is either volatile or empty, and
2136      I is a promoted integral type, there exist  candidate  operator  func-
2137      tions of the form
2138              T*VQ&   operator+=(T*VQ&, I);
2139              T*VQ&   operator-=(T*VQ&, I);
2140
2141    23For  every  triple  L,  VQ,  R), where L is an integral or enumeration
2142      type, VQ is either volatile or empty, and R  is  a  promoted  integral
2143      type, there exist candidate operator functions of the form
2144
2145              VQ L&   operator%=(VQ L&, R);
2146              VQ L&   operator<<=(VQ L&, R);
2147              VQ L&   operator>>=(VQ L&, R);
2148              VQ L&   operator&=(VQ L&, R);
2149              VQ L&   operator^=(VQ L&, R);
2150              VQ L&   operator|=(VQ L&, R);  */
2151
2152     case MODIFY_EXPR:
2153       switch (code2)
2154         {
2155         case PLUS_EXPR:
2156         case MINUS_EXPR:
2157           if (TYPE_PTROB_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2158             {
2159               type2 = ptrdiff_type_node;
2160               break;
2161             }
2162         case MULT_EXPR:
2163         case TRUNC_DIV_EXPR:
2164           if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2165             break;
2166           return;
2167
2168         case TRUNC_MOD_EXPR:
2169         case BIT_AND_EXPR:
2170         case BIT_IOR_EXPR:
2171         case BIT_XOR_EXPR:
2172         case LSHIFT_EXPR:
2173         case RSHIFT_EXPR:
2174           if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type1) && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type2))
2175             break;
2176           return;
2177
2178         case NOP_EXPR:
2179           if (ARITHMETIC_TYPE_P (type1) && ARITHMETIC_TYPE_P (type2))
2180             break;
2181           if ((TYPE_PTRMEMFUNC_P (type1) && TYPE_PTRMEMFUNC_P (type2))
2182               || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
2183               || (TYPE_PTRMEM_P (type1) && TYPE_PTRMEM_P (type2))
2184               || ((TYPE_PTRMEMFUNC_P (type1)
2185                    || TREE_CODE (type1) == POINTER_TYPE)
2186                   && null_ptr_cst_p (args[1])))
2187             {
2188               type2 = type1;
2189               break;
2190             }
2191           return;
2192
2193         default:
2194           gcc_unreachable ();
2195         }
2196       type1 = build_reference_type (type1);
2197       break;
2198
2199     case COND_EXPR:
2200       /* [over.built]
2201
2202          For every pair of promoted arithmetic types L and R, there
2203          exist candidate operator functions of the form
2204
2205          LR operator?(bool, L, R);
2206
2207          where LR is the result of the usual arithmetic conversions
2208          between types L and R.
2209
2210          For every type T, where T is a pointer or pointer-to-member
2211          type, there exist candidate operator functions of the form T
2212          operator?(bool, T, T);  */
2213
2214       if (promoted_arithmetic_type_p (type1)
2215           && promoted_arithmetic_type_p (type2))
2216         /* That's OK.  */
2217         break;
2218
2219       /* Otherwise, the types should be pointers.  */
2220       if (!(TYPE_PTR_P (type1) || TYPE_PTR_TO_MEMBER_P (type1))
2221           || !(TYPE_PTR_P (type2) || TYPE_PTR_TO_MEMBER_P (type2)))
2222         return;
2223
2224       /* We don't check that the two types are the same; the logic
2225          below will actually create two candidates; one in which both
2226          parameter types are TYPE1, and one in which both parameter
2227          types are TYPE2.  */
2228       break;
2229
2230     default:
2231       gcc_unreachable ();
2232     }
2233
2234   /* If we're dealing with two pointer types or two enumeral types,
2235      we need candidates for both of them.  */
2236   if (type2 && !same_type_p (type1, type2)
2237       && TREE_CODE (type1) == TREE_CODE (type2)
2238       && (TREE_CODE (type1) == REFERENCE_TYPE
2239           || (TYPE_PTR_P (type1) && TYPE_PTR_P (type2))
2240           || (TYPE_PTRMEM_P (type1) && TYPE_PTRMEM_P (type2))
2241           || TYPE_PTRMEMFUNC_P (type1)
2242           || MAYBE_CLASS_TYPE_P (type1)
2243           || TREE_CODE (type1) == ENUMERAL_TYPE))
2244     {
2245       build_builtin_candidate
2246         (candidates, fnname, type1, type1, args, argtypes, flags);
2247       build_builtin_candidate
2248         (candidates, fnname, type2, type2, args, argtypes, flags);
2249       return;
2250     }
2251
2252   build_builtin_candidate
2253     (candidates, fnname, type1, type2, args, argtypes, flags);
2254 }
2255
2256 tree
2257 type_decays_to (tree type)
2258 {
2259   if (TREE_CODE (type) == ARRAY_TYPE)
2260     return build_pointer_type (TREE_TYPE (type));
2261   if (TREE_CODE (type) == FUNCTION_TYPE)
2262     return build_pointer_type (type);
2263   if (!MAYBE_CLASS_TYPE_P (type))
2264     type = cv_unqualified (type);
2265   return type;
2266 }
2267
2268 /* There are three conditions of builtin candidates:
2269
2270    1) bool-taking candidates.  These are the same regardless of the input.
2271    2) pointer-pair taking candidates.  These are generated for each type
2272       one of the input types converts to.
2273    3) arithmetic candidates.  According to the standard, we should generate
2274       all of these, but I'm trying not to...
2275
2276    Here we generate a superset of the possible candidates for this particular
2277    case.  That is a subset of the full set the standard defines, plus some
2278    other cases which the standard disallows. add_builtin_candidate will
2279    filter out the invalid set.  */
2280
2281 static void
2282 add_builtin_candidates (struct z_candidate **candidates, enum tree_code code,
2283                         enum tree_code code2, tree fnname, tree *args,
2284                         int flags)
2285 {
2286   int ref1, i;
2287   int enum_p = 0;
2288   tree type, argtypes[3];
2289   /* TYPES[i] is the set of possible builtin-operator parameter types
2290      we will consider for the Ith argument.  These are represented as
2291      a TREE_LIST; the TREE_VALUE of each node is the potential
2292      parameter type.  */
2293   tree types[2];
2294
2295   for (i = 0; i < 3; ++i)
2296     {
2297       if (args[i])
2298         argtypes[i] = unlowered_expr_type (args[i]);
2299       else
2300         argtypes[i] = NULL_TREE;
2301     }
2302
2303   switch (code)
2304     {
2305 /* 4 For every pair T, VQ), where T is an arithmetic or  enumeration  type,
2306      and  VQ  is  either  volatile or empty, there exist candidate operator
2307      functions of the form
2308                  VQ T&   operator++(VQ T&);  */
2309
2310     case POSTINCREMENT_EXPR:
2311     case PREINCREMENT_EXPR:
2312     case POSTDECREMENT_EXPR:
2313     case PREDECREMENT_EXPR:
2314     case MODIFY_EXPR:
2315       ref1 = 1;
2316       break;
2317
2318 /* 24There also exist candidate operator functions of the form
2319              bool    operator!(bool);
2320              bool    operator&&(bool, bool);
2321              bool    operator||(bool, bool);  */
2322
2323     case TRUTH_NOT_EXPR:
2324       build_builtin_candidate
2325         (candidates, fnname, boolean_type_node,
2326          NULL_TREE, args, argtypes, flags);
2327       return;
2328
2329     case TRUTH_ORIF_EXPR:
2330     case TRUTH_ANDIF_EXPR:
2331       build_builtin_candidate
2332         (candidates, fnname, boolean_type_node,
2333          boolean_type_node, args, argtypes, flags);
2334       return;
2335
2336     case ADDR_EXPR:
2337     case COMPOUND_EXPR:
2338     case COMPONENT_REF:
2339       return;
2340
2341     case COND_EXPR:
2342     case EQ_EXPR:
2343     case NE_EXPR:
2344     case LT_EXPR:
2345     case LE_EXPR:
2346     case GT_EXPR:
2347     case GE_EXPR:
2348       enum_p = 1;
2349       /* Fall through.  */
2350
2351     default:
2352       ref1 = 0;
2353     }
2354
2355   types[0] = types[1] = NULL_TREE;
2356
2357   for (i = 0; i < 2; ++i)
2358     {
2359       if (! args[i])
2360         ;
2361       else if (MAYBE_CLASS_TYPE_P (argtypes[i]))
2362         {
2363           tree convs;
2364
2365           if (i == 0 && code == MODIFY_EXPR && code2 == NOP_EXPR)
2366             return;
2367
2368           convs = lookup_conversions (argtypes[i],
2369                                       /*lookup_template_convs_p=*/false);
2370
2371           if (code == COND_EXPR)
2372             {
2373               if (real_lvalue_p (args[i]))
2374                 types[i] = tree_cons
2375                   (NULL_TREE, build_reference_type (argtypes[i]), types[i]);
2376
2377               types[i] = tree_cons
2378                 (NULL_TREE, TYPE_MAIN_VARIANT (argtypes[i]), types[i]);
2379             }
2380
2381           else if (! convs)
2382             return;
2383
2384           for (; convs; convs = TREE_CHAIN (convs))
2385             {
2386               type = TREE_TYPE (convs);
2387
2388               if (i == 0 && ref1
2389                   && (TREE_CODE (type) != REFERENCE_TYPE
2390                       || CP_TYPE_CONST_P (TREE_TYPE (type))))
2391                 continue;
2392
2393               if (code == COND_EXPR && TREE_CODE (type) == REFERENCE_TYPE)
2394                 types[i] = tree_cons (NULL_TREE, type, types[i]);
2395
2396               type = non_reference (type);
2397               if (i != 0 || ! ref1)
2398                 {
2399                   type = TYPE_MAIN_VARIANT (type_decays_to (type));
2400                   if (enum_p && TREE_CODE (type) == ENUMERAL_TYPE)
2401                     types[i] = tree_cons (NULL_TREE, type, types[i]);
2402                   if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
2403                     type = type_promotes_to (type);
2404                 }
2405
2406               if (! value_member (type, types[i]))
2407                 types[i] = tree_cons (NULL_TREE, type, types[i]);
2408             }
2409         }
2410       else
2411         {
2412           if (code == COND_EXPR && real_lvalue_p (args[i]))
2413             types[i] = tree_cons
2414               (NULL_TREE, build_reference_type (argtypes[i]), types[i]);
2415           type = non_reference (argtypes[i]);
2416           if (i != 0 || ! ref1)
2417             {
2418               type = TYPE_MAIN_VARIANT (type_decays_to (type));
2419               if (enum_p && UNSCOPED_ENUM_P (type))
2420                 types[i] = tree_cons (NULL_TREE, type, types[i]);
2421               if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
2422                 type = type_promotes_to (type);
2423             }
2424           types[i] = tree_cons (NULL_TREE, type, types[i]);
2425         }
2426     }
2427
2428   /* Run through the possible parameter types of both arguments,
2429      creating candidates with those parameter types.  */
2430   for (; types[0]; types[0] = TREE_CHAIN (types[0]))
2431     {
2432       if (types[1])
2433         for (type = types[1]; type; type = TREE_CHAIN (type))
2434           add_builtin_candidate
2435             (candidates, code, code2, fnname, TREE_VALUE (types[0]),
2436              TREE_VALUE (type), args, argtypes, flags);
2437       else
2438         add_builtin_candidate
2439           (candidates, code, code2, fnname, TREE_VALUE (types[0]),
2440            NULL_TREE, args, argtypes, flags);
2441     }
2442 }
2443
2444
2445 /* If TMPL can be successfully instantiated as indicated by
2446    EXPLICIT_TARGS and ARGLIST, adds the instantiation to CANDIDATES.
2447
2448    TMPL is the template.  EXPLICIT_TARGS are any explicit template
2449    arguments.  ARGLIST is the arguments provided at the call-site.
2450    This does not change ARGLIST.  The RETURN_TYPE is the desired type
2451    for conversion operators.  If OBJ is NULL_TREE, FLAGS and CTYPE are
2452    as for add_function_candidate.  If an OBJ is supplied, FLAGS and
2453    CTYPE are ignored, and OBJ is as for add_conv_candidate.  */
2454
2455 static struct z_candidate*
2456 add_template_candidate_real (struct z_candidate **candidates, tree tmpl,
2457                              tree ctype, tree explicit_targs, tree first_arg,
2458                              const VEC(tree,gc) *arglist, tree return_type,
2459                              tree access_path, tree conversion_path,
2460                              int flags, tree obj, unification_kind_t strict)
2461 {
2462   int ntparms = DECL_NTPARMS (tmpl);
2463   tree targs = make_tree_vec (ntparms);
2464   unsigned int len = VEC_length (tree, arglist);
2465   unsigned int nargs = (first_arg == NULL_TREE ? 0 : 1) + len;
2466   unsigned int skip_without_in_chrg = 0;
2467   tree first_arg_without_in_chrg = first_arg;
2468   tree *args_without_in_chrg;
2469   unsigned int nargs_without_in_chrg;
2470   unsigned int ia, ix;
2471   tree arg;
2472   struct z_candidate *cand;
2473   int i;
2474   tree fn;
2475
2476   /* We don't do deduction on the in-charge parameter, the VTT
2477      parameter or 'this'.  */
2478   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tmpl))
2479     {
2480       if (first_arg_without_in_chrg != NULL_TREE)
2481         first_arg_without_in_chrg = NULL_TREE;
2482       else
2483         ++skip_without_in_chrg;
2484     }
2485
2486   if ((DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (tmpl)
2487        || DECL_BASE_CONSTRUCTOR_P (tmpl))
2488       && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (tmpl)))
2489     {
2490       if (first_arg_without_in_chrg != NULL_TREE)
2491         first_arg_without_in_chrg = NULL_TREE;
2492       else
2493         ++skip_without_in_chrg;
2494     }
2495
2496   if (len < skip_without_in_chrg)
2497     return NULL;
2498
2499   nargs_without_in_chrg = ((first_arg_without_in_chrg != NULL_TREE ? 1 : 0)
2500                            + (len - skip_without_in_chrg));
2501   args_without_in_chrg = XALLOCAVEC (tree, nargs_without_in_chrg);
2502   ia = 0;
2503   if (first_arg_without_in_chrg != NULL_TREE)
2504     {
2505       args_without_in_chrg[ia] = first_arg_without_in_chrg;
2506       ++ia;
2507     }
2508   for (ix = skip_without_in_chrg;
2509        VEC_iterate (tree, arglist, ix, arg);
2510        ++ix)
2511     {
2512       args_without_in_chrg[ia] = arg;
2513       ++ia;
2514     }
2515   gcc_assert (ia == nargs_without_in_chrg);
2516
2517   i = fn_type_unification (tmpl, explicit_targs, targs,
2518                            args_without_in_chrg,
2519                            nargs_without_in_chrg,
2520                            return_type, strict, flags);
2521
2522   if (i != 0)
2523     goto fail;
2524
2525   fn = instantiate_template (tmpl, targs, tf_none);
2526   if (fn == error_mark_node)
2527     goto fail;
2528
2529   /* In [class.copy]:
2530
2531        A member function template is never instantiated to perform the
2532        copy of a class object to an object of its class type.
2533
2534      It's a little unclear what this means; the standard explicitly
2535      does allow a template to be used to copy a class.  For example,
2536      in:
2537
2538        struct A {
2539          A(A&);
2540          template <class T> A(const T&);
2541        };
2542        const A f ();
2543        void g () { A a (f ()); }
2544
2545      the member template will be used to make the copy.  The section
2546      quoted above appears in the paragraph that forbids constructors
2547      whose only parameter is (a possibly cv-qualified variant of) the
2548      class type, and a logical interpretation is that the intent was
2549      to forbid the instantiation of member templates which would then
2550      have that form.  */
2551   if (DECL_CONSTRUCTOR_P (fn) && nargs == 2)
2552     {
2553       tree arg_types = FUNCTION_FIRST_USER_PARMTYPE (fn);
2554       if (arg_types && same_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (arg_types)),
2555                                     ctype))
2556         goto fail;
2557     }
2558
2559   if (obj != NULL_TREE)
2560     /* Aha, this is a conversion function.  */
2561     cand = add_conv_candidate (candidates, fn, obj, first_arg, arglist,
2562                                access_path, conversion_path);
2563   else
2564     cand = add_function_candidate (candidates, fn, ctype,
2565                                    first_arg, arglist, access_path,
2566                                    conversion_path, flags);
2567   if (DECL_TI_TEMPLATE (fn) != tmpl)
2568     /* This situation can occur if a member template of a template
2569        class is specialized.  Then, instantiate_template might return
2570        an instantiation of the specialization, in which case the
2571        DECL_TI_TEMPLATE field will point at the original
2572        specialization.  For example:
2573
2574          template <class T> struct S { template <class U> void f(U);
2575                                        template <> void f(int) {}; };
2576          S<double> sd;
2577          sd.f(3);
2578
2579        Here, TMPL will be template <class U> S<double>::f(U).
2580        And, instantiate template will give us the specialization
2581        template <> S<double>::f(int).  But, the DECL_TI_TEMPLATE field
2582        for this will point at template <class T> template <> S<T>::f(int),
2583        so that we can find the definition.  For the purposes of
2584        overload resolution, however, we want the original TMPL.  */
2585     cand->template_decl = build_template_info (tmpl, targs);
2586   else
2587     cand->template_decl = DECL_TEMPLATE_INFO (fn);
2588   cand->explicit_targs = explicit_targs;
2589
2590   return cand;
2591  fail:
2592   return add_candidate (candidates, tmpl, first_arg, arglist, nargs, NULL,
2593                         access_path, conversion_path, 0);
2594 }
2595
2596
2597 static struct z_candidate *
2598 add_template_candidate (struct z_candidate **candidates, tree tmpl, tree ctype,
2599                         tree explicit_targs, tree first_arg,
2600                         const VEC(tree,gc) *arglist, tree return_type,
2601                         tree access_path, tree conversion_path, int flags,
2602                         unification_kind_t strict)
2603 {
2604   return
2605     add_template_candidate_real (candidates, tmpl, ctype,
2606                                  explicit_targs, first_arg, arglist,
2607                                  return_type, access_path, conversion_path,
2608                                  flags, NULL_TREE, strict);
2609 }
2610
2611
2612 static struct z_candidate *
2613 add_template_conv_candidate (struct z_candidate **candidates, tree tmpl,
2614                              tree obj, tree first_arg,
2615                              const VEC(tree,gc) *arglist,
2616                              tree return_type, tree access_path,
2617                              tree conversion_path)
2618 {
2619   return
2620     add_template_candidate_real (candidates, tmpl, NULL_TREE, NULL_TREE,
2621                                  first_arg, arglist, return_type, access_path,
2622                                  conversion_path, 0, obj, DEDUCE_CONV);
2623 }
2624
2625 /* The CANDS are the set of candidates that were considered for
2626    overload resolution.  Return the set of viable candidates, or CANDS
2627    if none are viable.  If any of the candidates were viable, set
2628    *ANY_VIABLE_P to true.  STRICT_P is true if a candidate should be
2629    considered viable only if it is strictly viable.  */
2630
2631 static struct z_candidate*
2632 splice_viable (struct z_candidate *cands,
2633                bool strict_p,
2634                bool *any_viable_p)
2635 {
2636   struct z_candidate *viable;
2637   struct z_candidate **last_viable;
2638   struct z_candidate **cand;
2639
2640   viable = NULL;
2641   last_viable = &viable;
2642   *any_viable_p = false;
2643
2644   cand = &cands;
2645   while (*cand)
2646     {
2647       struct z_candidate *c = *cand;
2648       if (strict_p ? c->viable == 1 : c->viable)
2649         {
2650           *last_viable = c;
2651           *cand = c->next;
2652           c->next = NULL;
2653           last_viable = &c->next;
2654           *any_viable_p = true;
2655         }
2656       else
2657         cand = &c->next;
2658     }
2659
2660   return viable ? viable : cands;
2661 }
2662
2663 static bool
2664 any_strictly_viable (struct z_candidate *cands)
2665 {
2666   for (; cands; cands = cands->next)
2667     if (cands->viable == 1)
2668       return true;
2669   return false;
2670 }
2671
2672 /* OBJ is being used in an expression like "OBJ.f (...)".  In other
2673    words, it is about to become the "this" pointer for a member
2674    function call.  Take the address of the object.  */
2675
2676 static tree
2677 build_this (tree obj)
2678 {
2679   /* In a template, we are only concerned about the type of the
2680      expression, so we can take a shortcut.  */
2681   if (processing_template_decl)
2682     return build_address (obj);
2683
2684   return cp_build_unary_op (ADDR_EXPR, obj, 0, tf_warning_or_error);
2685 }
2686
2687 /* Returns true iff functions are equivalent. Equivalent functions are
2688    not '==' only if one is a function-local extern function or if
2689    both are extern "C".  */
2690
2691 static inline int
2692 equal_functions (tree fn1, tree fn2)
2693 {
2694   if (TREE_CODE (fn1) != TREE_CODE (fn2))
2695     return 0;
2696   if (TREE_CODE (fn1) == TEMPLATE_DECL)
2697     return fn1 == fn2;
2698   if (DECL_LOCAL_FUNCTION_P (fn1) || DECL_LOCAL_FUNCTION_P (fn2)
2699       || DECL_EXTERN_C_FUNCTION_P (fn1))
2700     return decls_match (fn1, fn2);
2701   return fn1 == fn2;
2702 }
2703
2704 /* Print information about one overload candidate CANDIDATE.  MSGSTR
2705    is the text to print before the candidate itself.
2706
2707    NOTE: Unlike most diagnostic functions in GCC, MSGSTR is expected
2708    to have been run through gettext by the caller.  This wart makes
2709    life simpler in print_z_candidates and for the translators.  */
2710
2711 static void
2712 print_z_candidate (const char *msgstr, struct z_candidate *candidate)
2713 {
2714   if (TREE_CODE (candidate->fn) == IDENTIFIER_NODE)
2715     {
2716       if (candidate->num_convs == 3)
2717         inform (input_location, "%s %D(%T, %T, %T) <built-in>", msgstr, candidate->fn,
2718                 candidate->convs[0]->type,
2719                 candidate->convs[1]->type,
2720                 candidate->convs[2]->type);
2721       else if (candidate->num_convs == 2)
2722         inform (input_location, "%s %D(%T, %T) <built-in>", msgstr, candidate->fn,
2723                 candidate->convs[0]->type,
2724                 candidate->convs[1]->type);
2725       else
2726         inform (input_location, "%s %D(%T) <built-in>", msgstr, candidate->fn,
2727                 candidate->convs[0]->type);
2728     }
2729   else if (TYPE_P (candidate->fn))
2730     inform (input_location, "%s %T <conversion>", msgstr, candidate->fn);
2731   else if (candidate->viable == -1)
2732     inform (input_location, "%s %+#D <near match>", msgstr, candidate->fn);
2733   else if (DECL_DELETED_FN (STRIP_TEMPLATE (candidate->fn)))
2734     inform (input_location, "%s %+#D <deleted>", msgstr, candidate->fn);
2735   else
2736     inform (input_location, "%s %+#D", msgstr, candidate->fn);
2737 }
2738
2739 static void
2740 print_z_candidates (struct z_candidate *candidates)
2741 {
2742   const char *str;
2743   struct z_candidate *cand1;
2744   struct z_candidate **cand2;
2745   char *spaces;
2746
2747   if (!candidates)
2748     return;
2749
2750   /* Remove non-viable deleted candidates.  */
2751   cand1 = candidates;
2752   for (cand2 = &cand1; *cand2; )
2753     {
2754       if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
2755           && !(*cand2)->viable
2756           && DECL_DELETED_FN ((*cand2)->fn))
2757         *cand2 = (*cand2)->next;
2758       else
2759         cand2 = &(*cand2)->next;
2760     }
2761   /* ...if there are any non-deleted ones.  */
2762   if (cand1)
2763     candidates = cand1;
2764
2765   /* There may be duplicates in the set of candidates.  We put off
2766      checking this condition as long as possible, since we have no way
2767      to eliminate duplicates from a set of functions in less than n^2
2768      time.  Now we are about to emit an error message, so it is more
2769      permissible to go slowly.  */
2770   for (cand1 = candidates; cand1; cand1 = cand1->next)
2771     {
2772       tree fn = cand1->fn;
2773       /* Skip builtin candidates and conversion functions.  */
2774       if (!DECL_P (fn))
2775         continue;
2776       cand2 = &cand1->next;
2777       while (*cand2)
2778         {
2779           if (DECL_P ((*cand2)->fn)
2780               && equal_functions (fn, (*cand2)->fn))
2781             *cand2 = (*cand2)->next;
2782           else
2783             cand2 = &(*cand2)->next;
2784         }
2785     }
2786
2787   str = candidates->next ? _("candidates are:") :  _("candidate is:");
2788   spaces = NULL;
2789   for (; candidates; candidates = candidates->next)
2790     {
2791       print_z_candidate (spaces ? spaces : str, candidates);
2792       spaces = spaces ? spaces : get_spaces (str);
2793     }
2794   free (spaces);
2795 }
2796
2797 /* USER_SEQ is a user-defined conversion sequence, beginning with a
2798    USER_CONV.  STD_SEQ is the standard conversion sequence applied to
2799    the result of the conversion function to convert it to the final
2800    desired type.  Merge the two sequences into a single sequence,
2801    and return the merged sequence.  */
2802
2803 static conversion *
2804 merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
2805 {
2806   conversion **t;
2807
2808   gcc_assert (user_seq->kind == ck_user);
2809
2810   /* Find the end of the second conversion sequence.  */
2811   t = &(std_seq);
2812   while ((*t)->kind != ck_identity)
2813     t = &((*t)->u.next);
2814
2815   /* Replace the identity conversion with the user conversion
2816      sequence.  */
2817   *t = user_seq;
2818
2819   /* The entire sequence is a user-conversion sequence.  */
2820   std_seq->user_conv_p = true;
2821
2822   return std_seq;
2823 }
2824
2825 /* Handle overload resolution for initializing an object of class type from
2826    an initializer list.  First we look for a suitable constructor that
2827    takes a std::initializer_list; if we don't find one, we then look for a
2828    non-list constructor.
2829
2830    Parameters are as for add_candidates, except that the arguments are in
2831    the form of a CONSTRUCTOR (the initializer list) rather than a VEC, and
2832    the RETURN_TYPE parameter is replaced by TOTYPE, the desired type.  */
2833
2834 static void
2835 add_list_candidates (tree fns, tree first_arg,
2836                      tree init_list, tree totype,
2837                      tree explicit_targs, bool template_only,
2838                      tree conversion_path, tree access_path,
2839                      int flags,
2840                      struct z_candidate **candidates)
2841 {
2842   VEC(tree,gc) *args;
2843
2844   gcc_assert (*candidates == NULL);
2845
2846   /* For list-initialization we consider explicit constructors, but
2847      give an error if one is selected.  */
2848   flags &= ~LOOKUP_ONLYCONVERTING;
2849   /* And we don't allow narrowing conversions.  We also use this flag to
2850      avoid the copy constructor call for copy-list-initialization.  */
2851   flags |= LOOKUP_NO_NARROWING;
2852
2853   /* Always use the default constructor if the list is empty (DR 990).  */
2854   if (CONSTRUCTOR_NELTS (init_list) == 0
2855       && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
2856     ;
2857   /* If the class has a list ctor, try passing the list as a single
2858      argument first, but only consider list ctors.  */
2859   else if (TYPE_HAS_LIST_CTOR (totype))
2860     {
2861       flags |= LOOKUP_LIST_ONLY;
2862       args = make_tree_vector_single (init_list);
2863       add_candidates (fns, first_arg, args, NULL_TREE,
2864                       explicit_targs, template_only, conversion_path,
2865                       access_path, flags, candidates);
2866       if (any_strictly_viable (*candidates))
2867         return;
2868     }
2869
2870   args = ctor_to_vec (init_list);
2871
2872   /* We aren't looking for list-ctors anymore.  */
2873   flags &= ~LOOKUP_LIST_ONLY;
2874   /* We allow more user-defined conversions within an init-list.  */
2875   flags &= ~LOOKUP_NO_CONVERSION;
2876   /* But not for the copy ctor.  */
2877   flags |= LOOKUP_NO_COPY_CTOR_CONVERSION;
2878
2879   add_candidates (fns, first_arg, args, NULL_TREE,
2880                   explicit_targs, template_only, conversion_path,
2881                   access_path, flags, candidates);
2882 }
2883
2884 /* Returns the best overload candidate to perform the requested
2885    conversion.  This function is used for three the overloading situations
2886    described in [over.match.copy], [over.match.conv], and [over.match.ref].
2887    If TOTYPE is a REFERENCE_TYPE, we're trying to find an lvalue binding as
2888    per [dcl.init.ref], so we ignore temporary bindings.  */
2889
2890 static struct z_candidate *
2891 build_user_type_conversion_1 (tree totype, tree expr, int flags)
2892 {
2893   struct z_candidate *candidates, *cand;
2894   tree fromtype = TREE_TYPE (expr);
2895   tree ctors = NULL_TREE;
2896   tree conv_fns = NULL_TREE;
2897   conversion *conv = NULL;
2898   tree first_arg = NULL_TREE;
2899   VEC(tree,gc) *args = NULL;
2900   bool any_viable_p;
2901   int convflags;
2902
2903   /* We represent conversion within a hierarchy using RVALUE_CONV and
2904      BASE_CONV, as specified by [over.best.ics]; these become plain
2905      constructor calls, as specified in [dcl.init].  */
2906   gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
2907               || !DERIVED_FROM_P (totype, fromtype));
2908
2909   if (MAYBE_CLASS_TYPE_P (totype))
2910     ctors = lookup_fnfields (totype, complete_ctor_identifier, 0);
2911
2912   if (MAYBE_CLASS_TYPE_P (fromtype))
2913     {
2914       tree to_nonref = non_reference (totype);
2915       if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
2916           (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
2917            && DERIVED_FROM_P (to_nonref, fromtype)))
2918         {
2919           /* [class.conv.fct] A conversion function is never used to
2920              convert a (possibly cv-qualified) object to the (possibly
2921              cv-qualified) same object type (or a reference to it), to a
2922              (possibly cv-qualified) base class of that type (or a
2923              reference to it)...  */
2924         }
2925       else
2926         conv_fns = lookup_conversions (fromtype,
2927                                        /*lookup_template_convs_p=*/true);
2928     }
2929
2930   candidates = 0;
2931   flags |= LOOKUP_NO_CONVERSION;
2932   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
2933     flags |= LOOKUP_NO_NARROWING;
2934
2935   /* It's OK to bind a temporary for converting constructor arguments, but
2936      not in converting the return value of a conversion operator.  */
2937   convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION);
2938   flags &= ~LOOKUP_NO_TEMP_BIND;
2939
2940   if (ctors)
2941     {
2942       int ctorflags = flags;
2943       ctors = BASELINK_FUNCTIONS (ctors);
2944
2945       first_arg = build_int_cst (build_pointer_type (totype), 0);
2946
2947       /* We should never try to call the abstract or base constructor
2948          from here.  */
2949       gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_CURRENT (ctors))
2950                   && !DECL_HAS_VTT_PARM_P (OVL_CURRENT (ctors)));
2951
2952       if (BRACE_ENCLOSED_INITIALIZER_P (expr))
2953         {
2954           /* List-initialization.  */
2955           add_list_candidates (ctors, first_arg, expr, totype, NULL_TREE,
2956                                false, TYPE_BINFO (totype), TYPE_BINFO (totype),
2957                                ctorflags, &candidates);
2958         }
2959       else
2960         {
2961           args = make_tree_vector_single (expr);
2962           add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
2963                           TYPE_BINFO (totype), TYPE_BINFO (totype),
2964                           ctorflags, &candidates);
2965         }
2966
2967       for (cand = candidates; cand; cand = cand->next)
2968         {
2969           cand->second_conv = build_identity_conv (totype, NULL_TREE);
2970
2971           /* If totype isn't a reference, and LOOKUP_NO_TEMP_BIND isn't
2972              set, then this is copy-initialization.  In that case, "The
2973              result of the call is then used to direct-initialize the
2974              object that is the destination of the copy-initialization."
2975              [dcl.init]
2976
2977              We represent this in the conversion sequence with an
2978              rvalue conversion, which means a constructor call.  */
2979           if (TREE_CODE (totype) != REFERENCE_TYPE
2980               && !(convflags & LOOKUP_NO_TEMP_BIND))
2981             cand->second_conv
2982               = build_conv (ck_rvalue, totype, cand->second_conv);
2983         }
2984     }
2985
2986   if (conv_fns)
2987     first_arg = build_this (expr);
2988
2989   for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
2990     {
2991       tree conversion_path = TREE_PURPOSE (conv_fns);
2992       struct z_candidate *old_candidates;
2993
2994       /* If we are called to convert to a reference type, we are trying to
2995          find an lvalue binding, so don't even consider temporaries.  If
2996          we don't find an lvalue binding, the caller will try again to
2997          look for a temporary binding.  */
2998       if (TREE_CODE (totype) == REFERENCE_TYPE)
2999         convflags |= LOOKUP_NO_TEMP_BIND;
3000
3001       old_candidates = candidates;
3002       add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
3003                       NULL_TREE, false,
3004                       conversion_path, TYPE_BINFO (fromtype),
3005                       flags, &candidates);
3006
3007       for (cand = candidates; cand != old_candidates; cand = cand->next)
3008         {
3009           conversion *ics
3010             = implicit_conversion (totype,
3011                                    TREE_TYPE (TREE_TYPE (cand->fn)),
3012                                    0,
3013                                    /*c_cast_p=*/false, convflags);
3014
3015           /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
3016              copy-initialization.  In that case, "The result of the
3017              call is then used to direct-initialize the object that is
3018              the destination of the copy-initialization."  [dcl.init]
3019
3020              We represent this in the conversion sequence with an
3021              rvalue conversion, which means a constructor call.  But
3022              don't add a second rvalue conversion if there's already
3023              one there.  Which there really shouldn't be, but it's
3024              harmless since we'd add it here anyway. */
3025           if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
3026               && !(convflags & LOOKUP_NO_TEMP_BIND))
3027             ics = build_conv (ck_rvalue, totype, ics);
3028
3029           cand->second_conv = ics;
3030
3031           if (!ics)
3032             cand->viable = 0;
3033           else if (cand->viable == 1 && ics->bad_p)
3034             cand->viable = -1;
3035         }
3036     }
3037
3038   candidates = splice_viable (candidates, pedantic, &any_viable_p);
3039   if (!any_viable_p)
3040     return NULL;
3041
3042   cand = tourney (candidates);
3043   if (cand == 0)
3044     {
3045       if (flags & LOOKUP_COMPLAIN)
3046         {
3047           error ("conversion from %qT to %qT is ambiguous",
3048                     fromtype, totype);
3049           print_z_candidates (candidates);
3050         }
3051
3052       cand = candidates;        /* any one will do */
3053       cand->second_conv = build_ambiguous_conv (totype, expr);
3054       cand->second_conv->user_conv_p = true;
3055       if (!any_strictly_viable (candidates))
3056         cand->second_conv->bad_p = true;
3057       /* If there are viable candidates, don't set ICS_BAD_FLAG; an
3058          ambiguous conversion is no worse than another user-defined
3059          conversion.  */
3060
3061       return cand;
3062     }
3063
3064   /* Build the user conversion sequence.  */
3065   conv = build_conv
3066     (ck_user,
3067      (DECL_CONSTRUCTOR_P (cand->fn)
3068       ? totype : non_reference (TREE_TYPE (TREE_TYPE (cand->fn)))),
3069      build_identity_conv (TREE_TYPE (expr), expr));
3070   conv->cand = cand;
3071
3072   /* Remember that this was a list-initialization.  */
3073   if (flags & LOOKUP_NO_NARROWING)
3074     conv->check_narrowing = true;
3075
3076   /* Combine it with the second conversion sequence.  */
3077   cand->second_conv = merge_conversion_sequences (conv,
3078                                                   cand->second_conv);
3079
3080   if (cand->viable == -1)
3081     cand->second_conv->bad_p = true;
3082
3083   return cand;
3084 }
3085
3086 tree
3087 build_user_type_conversion (tree totype, tree expr, int flags)
3088 {
3089   struct z_candidate *cand
3090     = build_user_type_conversion_1 (totype, expr, flags);
3091
3092   if (cand)
3093     {
3094       if (cand->second_conv->kind == ck_ambig)
3095         return error_mark_node;
3096       expr = convert_like (cand->second_conv, expr, tf_warning_or_error);
3097       return convert_from_reference (expr);
3098     }
3099   return NULL_TREE;
3100 }
3101
3102 /* Do any initial processing on the arguments to a function call.  */
3103
3104 static VEC(tree,gc) *
3105 resolve_args (VEC(tree,gc) *args)
3106 {
3107   unsigned int ix;
3108   tree arg;
3109
3110   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
3111     {
3112       if (error_operand_p (arg))
3113         return NULL;
3114       else if (VOID_TYPE_P (TREE_TYPE (arg)))
3115         {
3116           error ("invalid use of void expression");
3117           return NULL;
3118         }
3119       else if (invalid_nonstatic_memfn_p (arg, tf_warning_or_error))
3120         return NULL;
3121     }
3122   return args;
3123 }
3124
3125 /* Perform overload resolution on FN, which is called with the ARGS.
3126
3127    Return the candidate function selected by overload resolution, or
3128    NULL if the event that overload resolution failed.  In the case
3129    that overload resolution fails, *CANDIDATES will be the set of
3130    candidates considered, and ANY_VIABLE_P will be set to true or
3131    false to indicate whether or not any of the candidates were
3132    viable.
3133
3134    The ARGS should already have gone through RESOLVE_ARGS before this
3135    function is called.  */
3136
3137 static struct z_candidate *
3138 perform_overload_resolution (tree fn,
3139                              const VEC(tree,gc) *args,
3140                              struct z_candidate **candidates,
3141                              bool *any_viable_p)
3142 {
3143   struct z_candidate *cand;
3144   tree explicit_targs = NULL_TREE;
3145   int template_only = 0;
3146
3147   *candidates = NULL;
3148   *any_viable_p = true;
3149
3150   /* Check FN.  */
3151   gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
3152               || TREE_CODE (fn) == TEMPLATE_DECL
3153               || TREE_CODE (fn) == OVERLOAD
3154               || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
3155
3156   if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
3157     {
3158       explicit_targs = TREE_OPERAND (fn, 1);
3159       fn = TREE_OPERAND (fn, 0);
3160       template_only = 1;
3161     }
3162
3163   /* Add the various candidate functions.  */
3164   add_candidates (fn, NULL_TREE, args, NULL_TREE,
3165                   explicit_targs, template_only,
3166                   /*conversion_path=*/NULL_TREE,
3167                   /*access_path=*/NULL_TREE,
3168                   LOOKUP_NORMAL,
3169                   candidates);
3170
3171   *candidates = splice_viable (*candidates, pedantic, any_viable_p);
3172   if (!*any_viable_p)
3173     return NULL;
3174
3175   cand = tourney (*candidates);
3176   return cand;
3177 }
3178
3179 /* Return an expression for a call to FN (a namespace-scope function,
3180    or a static member function) with the ARGS.  This may change
3181    ARGS.  */
3182
3183 tree
3184 build_new_function_call (tree fn, VEC(tree,gc) **args, bool koenig_p, 
3185                          tsubst_flags_t complain)
3186 {
3187   struct z_candidate *candidates, *cand;
3188   bool any_viable_p;
3189   void *p;
3190   tree result;
3191
3192   if (args != NULL && *args != NULL)
3193     {
3194       *args = resolve_args (*args);
3195       if (*args == NULL)
3196         return error_mark_node;
3197     }
3198
3199   /* If this function was found without using argument dependent
3200      lookup, then we want to ignore any undeclared friend
3201      functions.  */
3202   if (!koenig_p)
3203     {
3204       tree orig_fn = fn;
3205
3206       fn = remove_hidden_names (fn);
3207       if (!fn)
3208         {
3209           if (complain & tf_error)
3210             error ("no matching function for call to %<%D(%A)%>",
3211                    DECL_NAME (OVL_CURRENT (orig_fn)),
3212                    build_tree_list_vec (*args));
3213           return error_mark_node;
3214         }
3215     }
3216
3217   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
3218   p = conversion_obstack_alloc (0);
3219
3220   cand = perform_overload_resolution (fn, *args, &candidates, &any_viable_p);
3221
3222   if (!cand)
3223     {
3224       if (complain & tf_error)
3225         {
3226           if (!any_viable_p && candidates && ! candidates->next
3227               && (TREE_CODE (candidates->fn) == FUNCTION_DECL))
3228             return cp_build_function_call_vec (candidates->fn, args, complain);
3229           if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
3230             fn = TREE_OPERAND (fn, 0);
3231           if (!any_viable_p)
3232             error ("no matching function for call to %<%D(%A)%>",
3233                    DECL_NAME (OVL_CURRENT (fn)), build_tree_list_vec (*args));
3234           else
3235             error ("call of overloaded %<%D(%A)%> is ambiguous",
3236                    DECL_NAME (OVL_CURRENT (fn)), build_tree_list_vec (*args));
3237           if (candidates)
3238             print_z_candidates (candidates);
3239         }
3240       result = error_mark_node;
3241     }
3242   else
3243     result = build_over_call (cand, LOOKUP_NORMAL, complain);
3244
3245   /* Free all the conversions we allocated.  */
3246   obstack_free (&conversion_obstack, p);
3247
3248   return result;
3249 }
3250
3251 /* Build a call to a global operator new.  FNNAME is the name of the
3252    operator (either "operator new" or "operator new[]") and ARGS are
3253    the arguments provided.  This may change ARGS.  *SIZE points to the
3254    total number of bytes required by the allocation, and is updated if
3255    that is changed here.  *COOKIE_SIZE is non-NULL if a cookie should
3256    be used.  If this function determines that no cookie should be
3257    used, after all, *COOKIE_SIZE is set to NULL_TREE.  If FN is
3258    non-NULL, it will be set, upon return, to the allocation function
3259    called.  */
3260
3261 tree
3262 build_operator_new_call (tree fnname, VEC(tree,gc) **args,
3263                          tree *size, tree *cookie_size,
3264                          tree *fn)
3265 {
3266   tree fns;
3267   struct z_candidate *candidates;
3268   struct z_candidate *cand;
3269   bool any_viable_p;
3270
3271   if (fn)
3272     *fn = NULL_TREE;
3273   VEC_safe_insert (tree, gc, *args, 0, *size);
3274   *args = resolve_args (*args);
3275   if (*args == NULL)
3276     return error_mark_node;
3277
3278   /* Based on:
3279
3280        [expr.new]
3281
3282        If this lookup fails to find the name, or if the allocated type
3283        is not a class type, the allocation function's name is looked
3284        up in the global scope.
3285
3286      we disregard block-scope declarations of "operator new".  */
3287   fns = lookup_function_nonclass (fnname, *args, /*block_p=*/false);
3288
3289   /* Figure out what function is being called.  */
3290   cand = perform_overload_resolution (fns, *args, &candidates, &any_viable_p);
3291
3292   /* If no suitable function could be found, issue an error message
3293      and give up.  */
3294   if (!cand)
3295     {
3296       if (!any_viable_p)
3297         error ("no matching function for call to %<%D(%A)%>",
3298                DECL_NAME (OVL_CURRENT (fns)), build_tree_list_vec (*args));
3299       else
3300         error ("call of overloaded %<%D(%A)%> is ambiguous",
3301                DECL_NAME (OVL_CURRENT (fns)), build_tree_list_vec (*args));
3302       if (candidates)
3303         print_z_candidates (candidates);
3304       return error_mark_node;
3305     }
3306
3307    /* If a cookie is required, add some extra space.  Whether
3308       or not a cookie is required cannot be determined until
3309       after we know which function was called.  */
3310    if (*cookie_size)
3311      {
3312        bool use_cookie = true;
3313        if (!abi_version_at_least (2))
3314          {
3315            /* In G++ 3.2, the check was implemented incorrectly; it
3316               looked at the placement expression, rather than the
3317               type of the function.  */
3318            if (VEC_length (tree, *args) == 2
3319                && same_type_p (TREE_TYPE (VEC_index (tree, *args, 1)),
3320                                ptr_type_node))
3321              use_cookie = false;
3322          }
3323        else
3324          {
3325            tree arg_types;
3326
3327            arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
3328            /* Skip the size_t parameter.  */
3329            arg_types = TREE_CHAIN (arg_types);
3330            /* Check the remaining parameters (if any).  */
3331            if (arg_types
3332                && TREE_CHAIN (arg_types) == void_list_node
3333                && same_type_p (TREE_VALUE (arg_types),
3334                                ptr_type_node))
3335              use_cookie = false;
3336          }
3337        /* If we need a cookie, adjust the number of bytes allocated.  */
3338        if (use_cookie)
3339          {
3340            /* Update the total size.  */
3341            *size = size_binop (PLUS_EXPR, *size, *cookie_size);
3342            /* Update the argument list to reflect the adjusted size.  */
3343            VEC_replace (tree, *args, 0, *size);
3344          }
3345        else
3346          *cookie_size = NULL_TREE;
3347      }
3348
3349    /* Tell our caller which function we decided to call.  */
3350    if (fn)
3351      *fn = cand->fn;
3352
3353    /* Build the CALL_EXPR.  */
3354    return build_over_call (cand, LOOKUP_NORMAL, tf_warning_or_error);
3355 }
3356
3357 /* Build a new call to operator().  This may change ARGS.  */
3358
3359 tree
3360 build_op_call (tree obj, VEC(tree,gc) **args, tsubst_flags_t complain)
3361 {
3362   struct z_candidate *candidates = 0, *cand;
3363   tree fns, convs, first_mem_arg = NULL_TREE;
3364   tree type = TREE_TYPE (obj);
3365   bool any_viable_p;
3366   tree result = NULL_TREE;
3367   void *p;
3368
3369   if (error_operand_p (obj))
3370     return error_mark_node;
3371
3372   obj = prep_operand (obj);
3373
3374   if (TYPE_PTRMEMFUNC_P (type))
3375     {
3376       if (complain & tf_error)
3377         /* It's no good looking for an overloaded operator() on a
3378            pointer-to-member-function.  */
3379         error ("pointer-to-member function %E cannot be called without an object; consider using .* or ->*", obj);
3380       return error_mark_node;
3381     }
3382
3383   if (TYPE_BINFO (type))
3384     {
3385       fns = lookup_fnfields (TYPE_BINFO (type), ansi_opname (CALL_EXPR), 1);
3386       if (fns == error_mark_node)
3387         return error_mark_node;
3388     }
3389   else
3390     fns = NULL_TREE;
3391
3392   if (args != NULL && *args != NULL)
3393     {
3394       *args = resolve_args (*args);
3395       if (*args == NULL)
3396         return error_mark_node;
3397     }
3398
3399   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
3400   p = conversion_obstack_alloc (0);
3401
3402   if (fns)
3403     {
3404       first_mem_arg = build_this (obj);
3405
3406       add_candidates (BASELINK_FUNCTIONS (fns),
3407                       first_mem_arg, *args, NULL_TREE,
3408                       NULL_TREE, false,
3409                       BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
3410                       LOOKUP_NORMAL, &candidates);
3411     }
3412
3413   convs = lookup_conversions (type, /*lookup_template_convs_p=*/true);
3414
3415   for (; convs; convs = TREE_CHAIN (convs))
3416     {
3417       tree fns = TREE_VALUE (convs);
3418       tree totype = TREE_TYPE (convs);
3419
3420       if ((TREE_CODE (totype) == POINTER_TYPE
3421            && TREE_CODE (TREE_TYPE (totype)) == FUNCTION_TYPE)
3422           || (TREE_CODE (totype) == REFERENCE_TYPE
3423               && TREE_CODE (TREE_TYPE (totype)) == FUNCTION_TYPE)
3424           || (TREE_CODE (totype) == REFERENCE_TYPE
3425               && TREE_CODE (TREE_TYPE (totype)) == POINTER_TYPE
3426               && TREE_CODE (TREE_TYPE (TREE_TYPE (totype))) == FUNCTION_TYPE))
3427         for (; fns; fns = OVL_NEXT (fns))
3428           {
3429             tree fn = OVL_CURRENT (fns);
3430
3431             if (DECL_NONCONVERTING_P (fn))
3432               continue;
3433
3434             if (TREE_CODE (fn) == TEMPLATE_DECL)
3435               add_template_conv_candidate
3436                 (&candidates, fn, obj, NULL_TREE, *args, totype,
3437                  /*access_path=*/NULL_TREE,
3438                  /*conversion_path=*/NULL_TREE);
3439             else
3440               add_conv_candidate (&candidates, fn, obj, NULL_TREE,
3441                                   *args, /*conversion_path=*/NULL_TREE,
3442                                   /*access_path=*/NULL_TREE);
3443           }
3444     }
3445
3446   candidates = splice_viable (candidates, pedantic, &any_viable_p);
3447   if (!any_viable_p)
3448     {
3449       if (complain & tf_error)
3450         {
3451           error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
3452                  build_tree_list_vec (*args));
3453           print_z_candidates (candidates);
3454         }
3455       result = error_mark_node;
3456     }
3457   else
3458     {
3459       cand = tourney (candidates);
3460       if (cand == 0)
3461         {
3462           if (complain & tf_error)
3463             {
3464               error ("call of %<(%T) (%A)%> is ambiguous", 
3465                      TREE_TYPE (obj), build_tree_list_vec (*args));
3466               print_z_candidates (candidates);
3467             }
3468           result = error_mark_node;
3469         }
3470       /* Since cand->fn will be a type, not a function, for a conversion
3471          function, we must be careful not to unconditionally look at
3472          DECL_NAME here.  */
3473       else if (TREE_CODE (cand->fn) == FUNCTION_DECL
3474                && DECL_OVERLOADED_OPERATOR_P (cand->fn) == CALL_EXPR)
3475         result = build_over_call (cand, LOOKUP_NORMAL, complain);
3476       else
3477         {
3478           obj = convert_like_with_context (cand->convs[0], obj, cand->fn, -1,
3479                                            complain);
3480           obj = convert_from_reference (obj);
3481           result = cp_build_function_call_vec (obj, args, complain);
3482         }
3483     }
3484
3485   /* Free all the conversions we allocated.  */
3486   obstack_free (&conversion_obstack, p);
3487
3488   return result;
3489 }
3490
3491 static void
3492 op_error (enum tree_code code, enum tree_code code2,
3493           tree arg1, tree arg2, tree arg3, bool match)
3494 {
3495   const char *opname;
3496
3497   if (code == MODIFY_EXPR)
3498     opname = assignment_operator_name_info[code2].name;
3499   else
3500     opname = operator_name_info[code].name;
3501
3502   switch (code)
3503     {
3504     case COND_EXPR:
3505       if (match)
3506         error ("ambiguous overload for ternary %<operator?:%> "
3507                "in %<%E ? %E : %E%>", arg1, arg2, arg3);
3508       else
3509         error ("no match for ternary %<operator?:%> "
3510                "in %<%E ? %E : %E%>", arg1, arg2, arg3);
3511       break;
3512
3513     case POSTINCREMENT_EXPR:
3514     case POSTDECREMENT_EXPR:
3515       if (match)
3516         error ("ambiguous overload for %<operator%s%> in %<%E%s%>",
3517                opname, arg1, opname);
3518       else
3519         error ("no match for %<operator%s%> in %<%E%s%>", 
3520                opname, arg1, opname);
3521       break;
3522
3523     case ARRAY_REF:
3524       if (match)
3525         error ("ambiguous overload for %<operator[]%> in %<%E[%E]%>", 
3526                arg1, arg2);
3527       else
3528         error ("no match for %<operator[]%> in %<%E[%E]%>", 
3529                arg1, arg2);
3530       break;
3531
3532     case REALPART_EXPR:
3533     case IMAGPART_EXPR:
3534       if (match)
3535         error ("ambiguous overload for %qs in %<%s %E%>", 
3536                opname, opname, arg1);
3537       else
3538         error ("no match for %qs in %<%s %E%>",
3539                opname, opname, arg1);
3540       break;
3541
3542     default:
3543       if (arg2)
3544         if (match)
3545           error ("ambiguous overload for %<operator%s%> in %<%E %s %E%>",
3546                   opname, arg1, opname, arg2);
3547         else
3548           error ("no match for %<operator%s%> in %<%E %s %E%>",
3549                  opname, arg1, opname, arg2);
3550       else
3551         if (match)
3552           error ("ambiguous overload for %<operator%s%> in %<%s%E%>",
3553                  opname, opname, arg1);
3554         else
3555           error ("no match for %<operator%s%> in %<%s%E%>",
3556                  opname, opname, arg1);
3557       break;
3558     }
3559 }
3560
3561 /* Return the implicit conversion sequence that could be used to
3562    convert E1 to E2 in [expr.cond].  */
3563
3564 static conversion *
3565 conditional_conversion (tree e1, tree e2)
3566 {
3567   tree t1 = non_reference (TREE_TYPE (e1));
3568   tree t2 = non_reference (TREE_TYPE (e2));
3569   conversion *conv;
3570   bool good_base;
3571
3572   /* [expr.cond]
3573
3574      If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
3575      implicitly converted (clause _conv_) to the type "reference to
3576      T2", subject to the constraint that in the conversion the
3577      reference must bind directly (_dcl.init.ref_) to E1.  */
3578   if (real_lvalue_p (e2))
3579     {
3580       conv = implicit_conversion (build_reference_type (t2),
3581                                   t1,
3582                                   e1,
3583                                   /*c_cast_p=*/false,
3584                                   LOOKUP_NO_TEMP_BIND|LOOKUP_ONLYCONVERTING);
3585       if (conv)
3586         return conv;
3587     }
3588
3589   /* [expr.cond]
3590
3591      If E1 and E2 have class type, and the underlying class types are
3592      the same or one is a base class of the other: E1 can be converted
3593      to match E2 if the class of T2 is the same type as, or a base
3594      class of, the class of T1, and the cv-qualification of T2 is the
3595      same cv-qualification as, or a greater cv-qualification than, the
3596      cv-qualification of T1.  If the conversion is applied, E1 is
3597      changed to an rvalue of type T2 that still refers to the original
3598      source class object (or the appropriate subobject thereof).  */
3599   if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
3600       && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
3601     {
3602       if (good_base && at_least_as_qualified_p (t2, t1))
3603         {
3604           conv = build_identity_conv (t1, e1);
3605           if (!same_type_p (TYPE_MAIN_VARIANT (t1),
3606                             TYPE_MAIN_VARIANT (t2)))
3607             conv = build_conv (ck_base, t2, conv);
3608           else
3609             conv = build_conv (ck_rvalue, t2, conv);
3610           return conv;
3611         }
3612       else
3613         return NULL;
3614     }
3615   else
3616     /* [expr.cond]
3617
3618        Otherwise: E1 can be converted to match E2 if E1 can be implicitly
3619        converted to the type that expression E2 would have if E2 were
3620        converted to an rvalue (or the type it has, if E2 is an rvalue).  */
3621     return implicit_conversion (t2, t1, e1, /*c_cast_p=*/false,
3622                                 LOOKUP_IMPLICIT);
3623 }
3624
3625 /* Implement [expr.cond].  ARG1, ARG2, and ARG3 are the three
3626    arguments to the conditional expression.  */
3627
3628 tree
3629 build_conditional_expr (tree arg1, tree arg2, tree arg3,
3630                         tsubst_flags_t complain)
3631 {
3632   tree arg2_type;
3633   tree arg3_type;
3634   tree result = NULL_TREE;
3635   tree result_type = NULL_TREE;
3636   bool lvalue_p = true;
3637   struct z_candidate *candidates = 0;
3638   struct z_candidate *cand;
3639   void *p;
3640
3641   /* As a G++ extension, the second argument to the conditional can be
3642      omitted.  (So that `a ? : c' is roughly equivalent to `a ? a :
3643      c'.)  If the second operand is omitted, make sure it is
3644      calculated only once.  */
3645   if (!arg2)
3646     {
3647       if (complain & tf_error)
3648         pedwarn (input_location, OPT_pedantic, 
3649                  "ISO C++ forbids omitting the middle term of a ?: expression");
3650
3651       /* Make sure that lvalues remain lvalues.  See g++.oliva/ext1.C.  */
3652       if (real_lvalue_p (arg1))
3653         arg2 = arg1 = stabilize_reference (arg1);
3654       else
3655         arg2 = arg1 = save_expr (arg1);
3656     }
3657
3658   /* [expr.cond]
3659
3660      The first expression is implicitly converted to bool (clause
3661      _conv_).  */
3662   arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
3663                                             LOOKUP_NORMAL);
3664
3665   /* If something has already gone wrong, just pass that fact up the
3666      tree.  */
3667   if (error_operand_p (arg1)
3668       || error_operand_p (arg2)
3669       || error_operand_p (arg3))
3670     return error_mark_node;
3671
3672   /* [expr.cond]
3673
3674      If either the second or the third operand has type (possibly
3675      cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
3676      array-to-pointer (_conv.array_), and function-to-pointer
3677      (_conv.func_) standard conversions are performed on the second
3678      and third operands.  */
3679   arg2_type = unlowered_expr_type (arg2);
3680   arg3_type = unlowered_expr_type (arg3);
3681   if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
3682     {
3683       /* Do the conversions.  We don't these for `void' type arguments
3684          since it can't have any effect and since decay_conversion
3685          does not handle that case gracefully.  */
3686       if (!VOID_TYPE_P (arg2_type))
3687         arg2 = decay_conversion (arg2);
3688       if (!VOID_TYPE_P (arg3_type))
3689         arg3 = decay_conversion (arg3);
3690       arg2_type = TREE_TYPE (arg2);
3691       arg3_type = TREE_TYPE (arg3);
3692
3693       /* [expr.cond]
3694
3695          One of the following shall hold:
3696
3697          --The second or the third operand (but not both) is a
3698            throw-expression (_except.throw_); the result is of the
3699            type of the other and is an rvalue.
3700
3701          --Both the second and the third operands have type void; the
3702            result is of type void and is an rvalue.
3703
3704          We must avoid calling force_rvalue for expressions of type
3705          "void" because it will complain that their value is being
3706          used.  */
3707       if (TREE_CODE (arg2) == THROW_EXPR
3708           && TREE_CODE (arg3) != THROW_EXPR)
3709         {
3710           if (!VOID_TYPE_P (arg3_type))
3711             arg3 = force_rvalue (arg3);
3712           arg3_type = TREE_TYPE (arg3);
3713           result_type = arg3_type;
3714         }
3715       else if (TREE_CODE (arg2) != THROW_EXPR
3716                && TREE_CODE (arg3) == THROW_EXPR)
3717         {
3718           if (!VOID_TYPE_P (arg2_type))
3719             arg2 = force_rvalue (arg2);
3720           arg2_type = TREE_TYPE (arg2);
3721           result_type = arg2_type;
3722         }
3723       else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
3724         result_type = void_type_node;
3725       else
3726         {
3727           if (complain & tf_error)
3728             {
3729               if (VOID_TYPE_P (arg2_type))
3730                 error ("second operand to the conditional operator "
3731                        "is of type %<void%>, "
3732                        "but the third operand is neither a throw-expression "
3733                        "nor of type %<void%>");
3734               else
3735                 error ("third operand to the conditional operator "
3736                        "is of type %<void%>, "
3737                        "but the second operand is neither a throw-expression "
3738                        "nor of type %<void%>");
3739             }
3740           return error_mark_node;
3741         }
3742
3743       lvalue_p = false;
3744       goto valid_operands;
3745     }
3746   /* [expr.cond]
3747
3748      Otherwise, if the second and third operand have different types,
3749      and either has (possibly cv-qualified) class type, an attempt is
3750      made to convert each of those operands to the type of the other.  */
3751   else if (!same_type_p (arg2_type, arg3_type)
3752            && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
3753     {
3754       conversion *conv2;
3755       conversion *conv3;
3756
3757       /* Get the high-water mark for the CONVERSION_OBSTACK.  */
3758       p = conversion_obstack_alloc (0);
3759
3760       conv2 = conditional_conversion (arg2, arg3);
3761       conv3 = conditional_conversion (arg3, arg2);
3762
3763       /* [expr.cond]
3764
3765          If both can be converted, or one can be converted but the
3766          conversion is ambiguous, the program is ill-formed.  If
3767          neither can be converted, the operands are left unchanged and
3768          further checking is performed as described below.  If exactly
3769          one conversion is possible, that conversion is applied to the
3770          chosen operand and the converted operand is used in place of
3771          the original operand for the remainder of this section.  */
3772       if ((conv2 && !conv2->bad_p
3773            && conv3 && !conv3->bad_p)
3774           || (conv2 && conv2->kind == ck_ambig)
3775           || (conv3 && conv3->kind == ck_ambig))
3776         {
3777           error ("operands to ?: have different types %qT and %qT",
3778                  arg2_type, arg3_type);
3779           result = error_mark_node;
3780         }
3781       else if (conv2 && (!conv2->bad_p || !conv3))
3782         {
3783           arg2 = convert_like (conv2, arg2, complain);
3784           arg2 = convert_from_reference (arg2);
3785           arg2_type = TREE_TYPE (arg2);
3786           /* Even if CONV2 is a valid conversion, the result of the
3787              conversion may be invalid.  For example, if ARG3 has type
3788              "volatile X", and X does not have a copy constructor
3789              accepting a "volatile X&", then even if ARG2 can be
3790              converted to X, the conversion will fail.  */
3791           if (error_operand_p (arg2))
3792             result = error_mark_node;
3793         }
3794       else if (conv3 && (!conv3->bad_p || !conv2))
3795         {
3796           arg3 = convert_like (conv3, arg3, complain);
3797           arg3 = convert_from_reference (arg3);
3798           arg3_type = TREE_TYPE (arg3);
3799           if (error_operand_p (arg3))
3800             result = error_mark_node;
3801         }
3802
3803       /* Free all the conversions we allocated.  */
3804       obstack_free (&conversion_obstack, p);
3805
3806       if (result)
3807         return result;
3808
3809       /* If, after the conversion, both operands have class type,
3810          treat the cv-qualification of both operands as if it were the
3811          union of the cv-qualification of the operands.
3812
3813          The standard is not clear about what to do in this
3814          circumstance.  For example, if the first operand has type
3815          "const X" and the second operand has a user-defined
3816          conversion to "volatile X", what is the type of the second
3817          operand after this step?  Making it be "const X" (matching
3818          the first operand) seems wrong, as that discards the
3819          qualification without actually performing a copy.  Leaving it
3820          as "volatile X" seems wrong as that will result in the
3821          conditional expression failing altogether, even though,
3822          according to this step, the one operand could be converted to
3823          the type of the other.  */
3824       if ((conv2 || conv3)
3825           && CLASS_TYPE_P (arg2_type)
3826           && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
3827         arg2_type = arg3_type =
3828           cp_build_qualified_type (arg2_type,
3829                                    cp_type_quals (arg2_type)
3830                                    | cp_type_quals (arg3_type));
3831     }
3832
3833   /* [expr.cond]
3834
3835      If the second and third operands are lvalues and have the same
3836      type, the result is of that type and is an lvalue.  */
3837   if (real_lvalue_p (arg2)
3838       && real_lvalue_p (arg3)
3839       && same_type_p (arg2_type, arg3_type))
3840     {
3841       result_type = arg2_type;
3842       mark_lvalue_use (arg2);
3843       mark_lvalue_use (arg3);
3844       goto valid_operands;
3845     }
3846
3847   /* [expr.cond]
3848
3849      Otherwise, the result is an rvalue.  If the second and third
3850      operand do not have the same type, and either has (possibly
3851      cv-qualified) class type, overload resolution is used to
3852      determine the conversions (if any) to be applied to the operands
3853      (_over.match.oper_, _over.built_).  */
3854   lvalue_p = false;
3855   if (!same_type_p (arg2_type, arg3_type)
3856       && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
3857     {
3858       tree args[3];
3859       conversion *conv;
3860       bool any_viable_p;
3861
3862       /* Rearrange the arguments so that add_builtin_candidate only has
3863          to know about two args.  In build_builtin_candidate, the
3864          arguments are unscrambled.  */
3865       args[0] = arg2;
3866       args[1] = arg3;
3867       args[2] = arg1;
3868       add_builtin_candidates (&candidates,
3869                               COND_EXPR,
3870                               NOP_EXPR,
3871                               ansi_opname (COND_EXPR),
3872                               args,
3873                               LOOKUP_NORMAL);
3874
3875       /* [expr.cond]
3876
3877          If the overload resolution fails, the program is
3878          ill-formed.  */
3879       candidates = splice_viable (candidates, pedantic, &any_viable_p);
3880       if (!any_viable_p)
3881         {
3882           if (complain & tf_error)
3883             {
3884               op_error (COND_EXPR, NOP_EXPR, arg1, arg2, arg3, FALSE);
3885               print_z_candidates (candidates);
3886             }
3887           return error_mark_node;
3888         }
3889       cand = tourney (candidates);
3890       if (!cand)
3891         {
3892           if (complain & tf_error)
3893             {
3894               op_error (COND_EXPR, NOP_EXPR, arg1, arg2, arg3, FALSE);
3895               print_z_candidates (candidates);
3896             }
3897           return error_mark_node;
3898         }
3899
3900       /* [expr.cond]
3901
3902          Otherwise, the conversions thus determined are applied, and
3903          the converted operands are used in place of the original
3904          operands for the remainder of this section.  */
3905       conv = cand->convs[0];
3906       arg1 = convert_like (conv, arg1, complain);
3907       conv = cand->convs[1];
3908       arg2 = convert_like (conv, arg2, complain);
3909       arg2_type = TREE_TYPE (arg2);
3910       conv = cand->convs[2];
3911       arg3 = convert_like (conv, arg3, complain);
3912       arg3_type = TREE_TYPE (arg3);
3913     }
3914
3915   /* [expr.cond]
3916
3917      Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
3918      and function-to-pointer (_conv.func_) standard conversions are
3919      performed on the second and third operands.
3920
3921      We need to force the lvalue-to-rvalue conversion here for class types,
3922      so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
3923      that isn't wrapped with a TARGET_EXPR plays havoc with exception
3924      regions.  */
3925
3926   arg2 = force_rvalue (arg2);
3927   if (!CLASS_TYPE_P (arg2_type))
3928     arg2_type = TREE_TYPE (arg2);
3929
3930   arg3 = force_rvalue (arg3);
3931   if (!CLASS_TYPE_P (arg3_type))
3932     arg3_type = TREE_TYPE (arg3);
3933
3934   if (arg2 == error_mark_node || arg3 == error_mark_node)
3935     return error_mark_node;
3936
3937   /* [expr.cond]
3938
3939      After those conversions, one of the following shall hold:
3940
3941      --The second and third operands have the same type; the result  is  of
3942        that type.  */
3943   if (same_type_p (arg2_type, arg3_type))
3944     result_type = arg2_type;
3945   /* [expr.cond]
3946
3947      --The second and third operands have arithmetic or enumeration
3948        type; the usual arithmetic conversions are performed to bring
3949        them to a common type, and the result is of that type.  */
3950   else if ((ARITHMETIC_TYPE_P (arg2_type)
3951             || UNSCOPED_ENUM_P (arg2_type))
3952            && (ARITHMETIC_TYPE_P (arg3_type)
3953                || UNSCOPED_ENUM_P (arg3_type)))
3954     {
3955       /* In this case, there is always a common type.  */
3956       result_type = type_after_usual_arithmetic_conversions (arg2_type,
3957                                                              arg3_type);
3958
3959       if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
3960           && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
3961         {
3962           if (complain & tf_warning)
3963             warning (0, 
3964                      "enumeral mismatch in conditional expression: %qT vs %qT",
3965                      arg2_type, arg3_type);
3966         }
3967       else if (extra_warnings
3968                && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
3969                     && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
3970                    || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
3971                        && !same_type_p (arg2_type, type_promotes_to (arg3_type)))))
3972         {
3973           if (complain & tf_warning)
3974             warning (0, 
3975                      "enumeral and non-enumeral type in conditional expression");
3976         }
3977
3978       arg2 = perform_implicit_conversion (result_type, arg2, complain);
3979       arg3 = perform_implicit_conversion (result_type, arg3, complain);
3980     }
3981   /* [expr.cond]
3982
3983      --The second and third operands have pointer type, or one has
3984        pointer type and the other is a null pointer constant; pointer
3985        conversions (_conv.ptr_) and qualification conversions
3986        (_conv.qual_) are performed to bring them to their composite
3987        pointer type (_expr.rel_).  The result is of the composite
3988        pointer type.
3989
3990      --The second and third operands have pointer to member type, or
3991        one has pointer to member type and the other is a null pointer
3992        constant; pointer to member conversions (_conv.mem_) and
3993        qualification conversions (_conv.qual_) are performed to bring
3994        them to a common type, whose cv-qualification shall match the
3995        cv-qualification of either the second or the third operand.
3996        The result is of the common type.  */
3997   else if ((null_ptr_cst_p (arg2)
3998             && (TYPE_PTR_P (arg3_type) || TYPE_PTR_TO_MEMBER_P (arg3_type)))
3999            || (null_ptr_cst_p (arg3)
4000                && (TYPE_PTR_P (arg2_type) || TYPE_PTR_TO_MEMBER_P (arg2_type)))
4001            || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
4002            || (TYPE_PTRMEM_P (arg2_type) && TYPE_PTRMEM_P (arg3_type))
4003            || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
4004     {
4005       result_type = composite_pointer_type (arg2_type, arg3_type, arg2,
4006                                             arg3, CPO_CONDITIONAL_EXPR,
4007                                             complain);
4008       if (result_type == error_mark_node)
4009         return error_mark_node;
4010       arg2 = perform_implicit_conversion (result_type, arg2, complain);
4011       arg3 = perform_implicit_conversion (result_type, arg3, complain);
4012     }
4013
4014   if (!result_type)
4015     {
4016       if (complain & tf_error)
4017         error ("operands to ?: have different types %qT and %qT",
4018                arg2_type, arg3_type);
4019       return error_mark_node;
4020     }
4021
4022  valid_operands:
4023   result = build3 (COND_EXPR, result_type, arg1, arg2, arg3);
4024   if (!cp_unevaluated_operand)
4025     /* Avoid folding within decltype (c++/42013) and noexcept.  */
4026     result = fold_if_not_in_template (result);
4027
4028   /* We can't use result_type below, as fold might have returned a
4029      throw_expr.  */
4030
4031   if (!lvalue_p)
4032     {
4033       /* Expand both sides into the same slot, hopefully the target of
4034          the ?: expression.  We used to check for TARGET_EXPRs here,
4035          but now we sometimes wrap them in NOP_EXPRs so the test would
4036          fail.  */
4037       if (CLASS_TYPE_P (TREE_TYPE (result)))
4038         result = get_target_expr (result);
4039       /* If this expression is an rvalue, but might be mistaken for an
4040          lvalue, we must add a NON_LVALUE_EXPR.  */
4041       result = rvalue (result);
4042     }
4043
4044   return result;
4045 }
4046
4047 /* OPERAND is an operand to an expression.  Perform necessary steps
4048    required before using it.  If OPERAND is NULL_TREE, NULL_TREE is
4049    returned.  */
4050
4051 static tree
4052 prep_operand (tree operand)
4053 {
4054   if (operand)
4055     {
4056       if (CLASS_TYPE_P (TREE_TYPE (operand))
4057           && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
4058         /* Make sure the template type is instantiated now.  */
4059         instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
4060     }
4061
4062   return operand;
4063 }
4064
4065 /* Add each of the viable functions in FNS (a FUNCTION_DECL or
4066    OVERLOAD) to the CANDIDATES, returning an updated list of
4067    CANDIDATES.  The ARGS are the arguments provided to the call;
4068    if FIRST_ARG is non-null it is the implicit object argument,
4069    otherwise the first element of ARGS is used if needed.  The
4070    EXPLICIT_TARGS are explicit template arguments provided.
4071    TEMPLATE_ONLY is true if only template functions should be
4072    considered.  CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
4073    add_function_candidate.  */
4074
4075 static void
4076 add_candidates (tree fns, tree first_arg, const VEC(tree,gc) *args,
4077                 tree return_type,
4078                 tree explicit_targs, bool template_only,
4079                 tree conversion_path, tree access_path,
4080                 int flags,
4081                 struct z_candidate **candidates)
4082 {
4083   tree ctype;
4084   const VEC(tree,gc) *non_static_args;
4085   bool check_list_ctor;
4086   bool check_converting;
4087   unification_kind_t strict;
4088   tree fn;
4089
4090   if (!fns)
4091     return;
4092
4093   /* Precalculate special handling of constructors and conversion ops.  */
4094   fn = OVL_CURRENT (fns);
4095   if (DECL_CONV_FN_P (fn))
4096     {
4097       check_list_ctor = false;
4098       check_converting = !!(flags & LOOKUP_ONLYCONVERTING);
4099       if (flags & LOOKUP_NO_CONVERSION)
4100         /* We're doing return_type(x).  */
4101         strict = DEDUCE_CONV;
4102       else
4103         /* We're doing x.operator return_type().  */
4104         strict = DEDUCE_EXACT;
4105       /* [over.match.funcs] For conversion functions, the function
4106          is considered to be a member of the class of the implicit
4107          object argument for the purpose of defining the type of
4108          the implicit object parameter.  */
4109       ctype = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (first_arg)));
4110     }
4111   else
4112     {
4113       if (DECL_CONSTRUCTOR_P (fn))
4114         {
4115           check_list_ctor = !!(flags & LOOKUP_LIST_ONLY);
4116           check_converting = !!(flags & LOOKUP_ONLYCONVERTING);
4117         }
4118       else
4119         {
4120           check_list_ctor = false;
4121           check_converting = false;
4122         }
4123       strict = DEDUCE_CALL;
4124       ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
4125     }
4126
4127   if (first_arg)
4128     non_static_args = args;
4129   else
4130     /* Delay creating the implicit this parameter until it is needed.  */
4131     non_static_args = NULL;
4132
4133   for (; fns; fns = OVL_NEXT (fns))
4134     {
4135       tree fn_first_arg;
4136       const VEC(tree,gc) *fn_args;
4137
4138       fn = OVL_CURRENT (fns);
4139
4140       if (check_converting && DECL_NONCONVERTING_P (fn))
4141         continue;
4142       if (check_list_ctor && !is_list_ctor (fn))
4143         continue;
4144
4145       /* Figure out which set of arguments to use.  */
4146       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
4147         {
4148           /* If this function is a non-static member and we didn't get an
4149              implicit object argument, move it out of args.  */
4150           if (first_arg == NULL_TREE)
4151             {
4152               unsigned int ix;
4153               tree arg;
4154               VEC(tree,gc) *tempvec
4155                 = VEC_alloc (tree, gc, VEC_length (tree, args) - 1);
4156               for (ix = 1; VEC_iterate (tree, args, ix, arg); ++ix)
4157                 VEC_quick_push (tree, tempvec, arg);
4158               non_static_args = tempvec;
4159               first_arg = build_this (VEC_index (tree, args, 0));
4160             }
4161
4162           fn_first_arg = first_arg;
4163           fn_args = non_static_args;
4164         }
4165       else
4166         {
4167           /* Otherwise, just use the list of arguments provided.  */
4168           fn_first_arg = NULL_TREE;
4169           fn_args = args;
4170         }
4171
4172       if (TREE_CODE (fn) == TEMPLATE_DECL)
4173         add_template_candidate (candidates,
4174                                 fn,
4175                                 ctype,
4176                                 explicit_targs,
4177                                 fn_first_arg, 
4178                                 fn_args,
4179                                 return_type,
4180                                 access_path,
4181                                 conversion_path,
4182                                 flags,
4183                                 strict);
4184       else if (!template_only)
4185         add_function_candidate (candidates,
4186                                 fn,
4187                                 ctype,
4188                                 fn_first_arg,
4189                                 fn_args,
4190                                 access_path,
4191                                 conversion_path,
4192                                 flags);
4193     }
4194 }
4195
4196 /* Even unsigned enum types promote to signed int.  We don't want to
4197    issue -Wsign-compare warnings for this case.  Here ORIG_ARG is the
4198    original argument and ARG is the argument after any conversions
4199    have been applied.  We set TREE_NO_WARNING if we have added a cast
4200    from an unsigned enum type to a signed integer type.  */
4201
4202 static void
4203 avoid_sign_compare_warnings (tree orig_arg, tree arg)
4204 {
4205   if (orig_arg != NULL_TREE
4206       && arg != NULL_TREE
4207       && orig_arg != arg
4208       && TREE_CODE (TREE_TYPE (orig_arg)) == ENUMERAL_TYPE
4209       && TYPE_UNSIGNED (TREE_TYPE (orig_arg))
4210       && INTEGRAL_TYPE_P (TREE_TYPE (arg))
4211       && !TYPE_UNSIGNED (TREE_TYPE (arg)))
4212     TREE_NO_WARNING (arg) = 1;
4213 }
4214
4215 tree
4216 build_new_op (enum tree_code code, int flags, tree arg1, tree arg2, tree arg3,
4217               bool *overloaded_p, tsubst_flags_t complain)
4218 {
4219   tree orig_arg1 = arg1;
4220   tree orig_arg2 = arg2;
4221   tree orig_arg3 = arg3;
4222   struct z_candidate *candidates = 0, *cand;
4223   VEC(tree,gc) *arglist;
4224   tree fnname;
4225   tree args[3];
4226   tree result = NULL_TREE;
4227   bool result_valid_p = false;
4228   enum tree_code code2 = NOP_EXPR;
4229   enum tree_code code_orig_arg1 = ERROR_MARK;
4230   enum tree_code code_orig_arg2 = ERROR_MARK;
4231   conversion *conv;
4232   void *p;
4233   bool strict_p;
4234   bool any_viable_p;
4235
4236   if (error_operand_p (arg1)
4237       || error_operand_p (arg2)
4238       || error_operand_p (arg3))
4239     return error_mark_node;
4240
4241   if (code == MODIFY_EXPR)
4242     {
4243       code2 = TREE_CODE (arg3);
4244       arg3 = NULL_TREE;
4245       fnname = ansi_assopname (code2);
4246     }
4247   else
4248     fnname = ansi_opname (code);
4249
4250   arg1 = prep_operand (arg1);
4251
4252   switch (code)
4253     {
4254     case NEW_EXPR:
4255     case VEC_NEW_EXPR:
4256     case VEC_DELETE_EXPR:
4257     case DELETE_EXPR:
4258       /* Use build_op_new_call and build_op_delete_call instead.  */
4259       gcc_unreachable ();
4260
4261     case CALL_EXPR:
4262       /* Use build_op_call instead.  */
4263       gcc_unreachable ();
4264
4265     case TRUTH_ORIF_EXPR:
4266     case TRUTH_ANDIF_EXPR:
4267     case TRUTH_AND_EXPR:
4268     case TRUTH_OR_EXPR:
4269       /* These are saved for the sake of warn_logical_operator.  */
4270       code_orig_arg1 = TREE_CODE (arg1);
4271       code_orig_arg2 = TREE_CODE (arg2);
4272
4273     default:
4274       break;
4275     }
4276
4277   arg2 = prep_operand (arg2);
4278   arg3 = prep_operand (arg3);
4279
4280   if (code == COND_EXPR)
4281     /* Use build_conditional_expr instead.  */
4282     gcc_unreachable ();
4283   else if (! IS_OVERLOAD_TYPE (TREE_TYPE (arg1))
4284            && (! arg2 || ! IS_OVERLOAD_TYPE (TREE_TYPE (arg2))))
4285     goto builtin;
4286
4287   if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
4288     arg2 = integer_zero_node;
4289
4290   arglist = VEC_alloc (tree, gc, 3);
4291   VEC_quick_push (tree, arglist, arg1);
4292   if (arg2 != NULL_TREE)
4293     VEC_quick_push (tree, arglist, arg2);
4294   if (arg3 != NULL_TREE)
4295     VEC_quick_push (tree, arglist, arg3);
4296
4297   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
4298   p = conversion_obstack_alloc (0);
4299
4300   /* Add namespace-scope operators to the list of functions to
4301      consider.  */
4302   add_candidates (lookup_function_nonclass (fnname, arglist, /*block_p=*/true),
4303                   NULL_TREE, arglist, NULL_TREE,
4304                   NULL_TREE, false, NULL_TREE, NULL_TREE,
4305                   flags, &candidates);
4306   /* Add class-member operators to the candidate set.  */
4307   if (CLASS_TYPE_P (TREE_TYPE (arg1)))
4308     {
4309       tree fns;
4310
4311       fns = lookup_fnfields (TREE_TYPE (arg1), fnname, 1);
4312       if (fns == error_mark_node)
4313         {
4314           result = error_mark_node;
4315           goto user_defined_result_ready;
4316         }
4317       if (fns)
4318         add_candidates (BASELINK_FUNCTIONS (fns),
4319                         NULL_TREE, arglist, NULL_TREE,
4320                         NULL_TREE, false,
4321                         BASELINK_BINFO (fns),
4322                         BASELINK_ACCESS_BINFO (fns),
4323                         flags, &candidates);
4324     }
4325
4326   args[0] = arg1;
4327   args[1] = arg2;
4328   args[2] = NULL_TREE;
4329
4330   add_builtin_candidates (&candidates, code, code2, fnname, args, flags);
4331
4332   switch (code)
4333     {
4334     case COMPOUND_EXPR:
4335     case ADDR_EXPR:
4336       /* For these, the built-in candidates set is empty
4337          [over.match.oper]/3.  We don't want non-strict matches
4338          because exact matches are always possible with built-in
4339          operators.  The built-in candidate set for COMPONENT_REF
4340          would be empty too, but since there are no such built-in
4341          operators, we accept non-strict matches for them.  */
4342       strict_p = true;
4343       break;
4344
4345     default:
4346       strict_p = pedantic;
4347       break;
4348     }
4349
4350   candidates = splice_viable (candidates, strict_p, &any_viable_p);
4351   if (!any_viable_p)
4352     {
4353       switch (code)
4354         {
4355         case POSTINCREMENT_EXPR:
4356         case POSTDECREMENT_EXPR:
4357           /* Don't try anything fancy if we're not allowed to produce
4358              errors.  */
4359           if (!(complain & tf_error))
4360             return error_mark_node;
4361
4362           /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
4363              distinguish between prefix and postfix ++ and
4364              operator++() was used for both, so we allow this with
4365              -fpermissive.  */
4366           if (flags & LOOKUP_COMPLAIN)
4367             {
4368               const char *msg = (flag_permissive) 
4369                 ? G_("no %<%D(int)%> declared for postfix %qs,"
4370                      " trying prefix operator instead")
4371                 : G_("no %<%D(int)%> declared for postfix %qs");
4372               permerror (input_location, msg, fnname,
4373                          operator_name_info[code].name);
4374             }
4375
4376           if (!flag_permissive)
4377             return error_mark_node;
4378
4379           if (code == POSTINCREMENT_EXPR)
4380             code = PREINCREMENT_EXPR;
4381           else
4382             code = PREDECREMENT_EXPR;
4383           result = build_new_op (code, flags, arg1, NULL_TREE, NULL_TREE,
4384                                  overloaded_p, complain);
4385           break;
4386
4387           /* The caller will deal with these.  */
4388         case ADDR_EXPR:
4389         case COMPOUND_EXPR:
4390         case COMPONENT_REF:
4391           result = NULL_TREE;
4392           result_valid_p = true;
4393           break;
4394
4395         default:
4396           if ((flags & LOOKUP_COMPLAIN) && (complain & tf_error))
4397             {
4398                 /* If one of the arguments of the operator represents
4399                    an invalid use of member function pointer, try to report
4400                    a meaningful error ...  */
4401                 if (invalid_nonstatic_memfn_p (arg1, tf_error)
4402                     || invalid_nonstatic_memfn_p (arg2, tf_error)
4403                     || invalid_nonstatic_memfn_p (arg3, tf_error))
4404                   /* We displayed the error message.  */;
4405                 else
4406                   {
4407                     /* ... Otherwise, report the more generic
4408                        "no matching operator found" error */
4409                     op_error (code, code2, arg1, arg2, arg3, FALSE);
4410                     print_z_candidates (candidates);
4411                   }
4412             }
4413           result = error_mark_node;
4414           break;
4415         }
4416     }
4417   else
4418     {
4419       cand = tourney (candidates);
4420       if (cand == 0)
4421         {
4422           if ((flags & LOOKUP_COMPLAIN) && (complain & tf_error))
4423             {
4424               op_error (code, code2, arg1, arg2, arg3, TRUE);
4425               print_z_candidates (candidates);
4426             }
4427           result = error_mark_node;
4428         }
4429       else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
4430         {
4431           if (overloaded_p)
4432             *overloaded_p = true;
4433
4434           if (resolve_args (arglist) == NULL)
4435             result = error_mark_node;
4436           else
4437             result = build_over_call (cand, LOOKUP_NORMAL, complain);
4438         }
4439       else
4440         {
4441           /* Give any warnings we noticed during overload resolution.  */
4442           if (cand->warnings && (complain & tf_warning))
4443             {
4444               struct candidate_warning *w;
4445               for (w = cand->warnings; w; w = w->next)
4446                 joust (cand, w->loser, 1);
4447             }
4448
4449           /* Check for comparison of different enum types.  */
4450           switch (code)
4451             {
4452             case GT_EXPR:
4453             case LT_EXPR:
4454             case GE_EXPR:
4455             case LE_EXPR:
4456             case EQ_EXPR:
4457             case NE_EXPR:
4458               if (TREE_CODE (TREE_TYPE (arg1)) == ENUMERAL_TYPE
4459                   && TREE_CODE (TREE_TYPE (arg2)) == ENUMERAL_TYPE
4460                   && (TYPE_MAIN_VARIANT (TREE_TYPE (arg1))
4461                       != TYPE_MAIN_VARIANT (TREE_TYPE (arg2)))
4462                   && (complain & tf_warning))
4463                 {
4464                   warning (OPT_Wenum_compare,
4465                            "comparison between %q#T and %q#T",
4466                            TREE_TYPE (arg1), TREE_TYPE (arg2));
4467                 }
4468               break;
4469             default:
4470               break;
4471             }
4472
4473           /* We need to strip any leading REF_BIND so that bitfields
4474              don't cause errors.  This should not remove any important
4475              conversions, because builtins don't apply to class
4476              objects directly.  */
4477           conv = cand->convs[0];
4478           if (conv->kind == ck_ref_bind)
4479             conv = conv->u.next;
4480           arg1 = convert_like (conv, arg1, complain);
4481
4482           if (arg2)
4483             {
4484               /* We need to call warn_logical_operator before
4485                  converting arg2 to a boolean_type.  */
4486               if (complain & tf_warning)
4487                 warn_logical_operator (input_location, code, boolean_type_node,
4488                                        code_orig_arg1, arg1,
4489                                        code_orig_arg2, arg2);
4490
4491               conv = cand->convs[1];
4492               if (conv->kind == ck_ref_bind)
4493                 conv = conv->u.next;
4494               arg2 = convert_like (conv, arg2, complain);
4495             }
4496           if (arg3)
4497             {
4498               conv = cand->convs[2];
4499               if (conv->kind == ck_ref_bind)
4500                 conv = conv->u.next;
4501               arg3 = convert_like (conv, arg3, complain);
4502             }
4503
4504         }
4505     }
4506
4507  user_defined_result_ready:
4508
4509   /* Free all the conversions we allocated.  */
4510   obstack_free (&conversion_obstack, p);
4511
4512   if (result || result_valid_p)
4513     return result;
4514
4515  builtin:
4516   avoid_sign_compare_warnings (orig_arg1, arg1);
4517   avoid_sign_compare_warnings (orig_arg2, arg2);
4518   avoid_sign_compare_warnings (orig_arg3, arg3);
4519
4520   switch (code)
4521     {
4522     case MODIFY_EXPR:
4523       return cp_build_modify_expr (arg1, code2, arg2, complain);
4524
4525     case INDIRECT_REF:
4526       return cp_build_indirect_ref (arg1, RO_UNARY_STAR, complain);
4527
4528     case TRUTH_ANDIF_EXPR:
4529     case TRUTH_ORIF_EXPR:
4530     case TRUTH_AND_EXPR:
4531     case TRUTH_OR_EXPR:
4532       warn_logical_operator (input_location, code, boolean_type_node,
4533                              code_orig_arg1, arg1, code_orig_arg2, arg2);
4534       /* Fall through.  */
4535     case PLUS_EXPR:
4536     case MINUS_EXPR:
4537     case MULT_EXPR:
4538     case TRUNC_DIV_EXPR:
4539     case GT_EXPR:
4540     case LT_EXPR:
4541     case GE_EXPR:
4542     case LE_EXPR:
4543     case EQ_EXPR:
4544     case NE_EXPR:
4545     case MAX_EXPR:
4546     case MIN_EXPR:
4547     case LSHIFT_EXPR:
4548     case RSHIFT_EXPR:
4549     case TRUNC_MOD_EXPR:
4550     case BIT_AND_EXPR:
4551     case BIT_IOR_EXPR:
4552     case BIT_XOR_EXPR:
4553       return cp_build_binary_op (input_location, code, arg1, arg2, complain);
4554
4555     case UNARY_PLUS_EXPR:
4556     case NEGATE_EXPR:
4557     case BIT_NOT_EXPR:
4558     case TRUTH_NOT_EXPR:
4559     case PREINCREMENT_EXPR:
4560     case POSTINCREMENT_EXPR:
4561     case PREDECREMENT_EXPR:
4562     case POSTDECREMENT_EXPR:
4563     case REALPART_EXPR:
4564     case IMAGPART_EXPR:
4565       return cp_build_unary_op (code, arg1, candidates != 0, complain);
4566
4567     case ARRAY_REF:
4568       return cp_build_array_ref (input_location, arg1, arg2, complain);
4569
4570     case MEMBER_REF:
4571       return build_m_component_ref (cp_build_indirect_ref (arg1, RO_NULL, 
4572                                                            complain), 
4573                                     arg2);
4574
4575       /* The caller will deal with these.  */
4576     case ADDR_EXPR:
4577     case COMPONENT_REF:
4578     case COMPOUND_EXPR:
4579       return NULL_TREE;
4580
4581     default:
4582       gcc_unreachable ();
4583     }
4584   return NULL_TREE;
4585 }
4586
4587 /* Returns true iff T, an element of an OVERLOAD chain, is a usual
4588    deallocation function (3.7.4.2 [basic.stc.dynamic.deallocation]).  */
4589
4590 static bool
4591 non_placement_deallocation_fn_p (tree t)
4592 {
4593   /* A template instance is never a usual deallocation function,
4594      regardless of its signature.  */
4595   if (TREE_CODE (t) == TEMPLATE_DECL
4596       || primary_template_instantiation_p (t))
4597     return false;
4598
4599   /* If a class T has a member deallocation function named operator delete
4600      with exactly one parameter, then that function is a usual
4601      (non-placement) deallocation function. If class T does not declare
4602      such an operator delete but does declare a member deallocation
4603      function named operator delete with exactly two parameters, the second
4604      of which has type std::size_t (18.2), then this function is a usual
4605      deallocation function.  */
4606   t = FUNCTION_ARG_CHAIN (t);
4607   if (t == void_list_node
4608       || (t && same_type_p (TREE_VALUE (t), size_type_node)
4609           && TREE_CHAIN (t) == void_list_node))
4610     return true;
4611   return false;
4612 }
4613
4614 /* Build a call to operator delete.  This has to be handled very specially,
4615    because the restrictions on what signatures match are different from all
4616    other call instances.  For a normal delete, only a delete taking (void *)
4617    or (void *, size_t) is accepted.  For a placement delete, only an exact
4618    match with the placement new is accepted.
4619
4620    CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
4621    ADDR is the pointer to be deleted.
4622    SIZE is the size of the memory block to be deleted.
4623    GLOBAL_P is true if the delete-expression should not consider
4624    class-specific delete operators.
4625    PLACEMENT is the corresponding placement new call, or NULL_TREE.
4626
4627    If this call to "operator delete" is being generated as part to
4628    deallocate memory allocated via a new-expression (as per [expr.new]
4629    which requires that if the initialization throws an exception then
4630    we call a deallocation function), then ALLOC_FN is the allocation
4631    function.  */
4632
4633 tree
4634 build_op_delete_call (enum tree_code code, tree addr, tree size,
4635                       bool global_p, tree placement,
4636                       tree alloc_fn)
4637 {
4638   tree fn = NULL_TREE;
4639   tree fns, fnname, type, t;
4640
4641   if (addr == error_mark_node)
4642     return error_mark_node;
4643
4644   type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
4645
4646   fnname = ansi_opname (code);
4647
4648   if (CLASS_TYPE_P (type)
4649       && COMPLETE_TYPE_P (complete_type (type))
4650       && !global_p)
4651     /* In [class.free]
4652
4653        If the result of the lookup is ambiguous or inaccessible, or if
4654        the lookup selects a placement deallocation function, the
4655        program is ill-formed.
4656
4657        Therefore, we ask lookup_fnfields to complain about ambiguity.  */
4658     {
4659       fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1);
4660       if (fns == error_mark_node)
4661         return error_mark_node;
4662     }
4663   else
4664     fns = NULL_TREE;
4665
4666   if (fns == NULL_TREE)
4667     fns = lookup_name_nonclass (fnname);
4668
4669   /* Strip const and volatile from addr.  */
4670   addr = cp_convert (ptr_type_node, addr);
4671
4672   if (placement)
4673     {
4674       /* "A declaration of a placement deallocation function matches the
4675          declaration of a placement allocation function if it has the same
4676          number of parameters and, after parameter transformations (8.3.5),
4677          all parameter types except the first are identical."
4678
4679          So we build up the function type we want and ask instantiate_type
4680          to get it for us.  */
4681       t = FUNCTION_ARG_CHAIN (alloc_fn);
4682       t = tree_cons (NULL_TREE, ptr_type_node, t);
4683       t = build_function_type (void_type_node, t);
4684
4685       fn = instantiate_type (t, fns, tf_none);
4686       if (fn == error_mark_node)
4687         return NULL_TREE;
4688
4689       if (BASELINK_P (fn))
4690         fn = BASELINK_FUNCTIONS (fn);
4691
4692       /* "If the lookup finds the two-parameter form of a usual deallocation
4693          function (3.7.4.2) and that function, considered as a placement
4694          deallocation function, would have been selected as a match for the
4695          allocation function, the program is ill-formed."  */
4696       if (non_placement_deallocation_fn_p (fn))
4697         {
4698           /* But if the class has an operator delete (void *), then that is
4699              the usual deallocation function, so we shouldn't complain
4700              about using the operator delete (void *, size_t).  */
4701           for (t = BASELINK_P (fns) ? BASELINK_FUNCTIONS (fns) : fns;
4702                t; t = OVL_NEXT (t))
4703             {
4704               tree elt = OVL_CURRENT (t);
4705               if (non_placement_deallocation_fn_p (elt)
4706                   && FUNCTION_ARG_CHAIN (elt) == void_list_node)
4707                 goto ok;
4708             }
4709           permerror (0, "non-placement deallocation function %q+D", fn);
4710           permerror (input_location, "selected for placement delete");
4711         ok:;
4712         }
4713     }
4714   else
4715     /* "Any non-placement deallocation function matches a non-placement
4716        allocation function. If the lookup finds a single matching
4717        deallocation function, that function will be called; otherwise, no
4718        deallocation function will be called."  */
4719     for (t = BASELINK_P (fns) ? BASELINK_FUNCTIONS (fns) : fns;
4720          t; t = OVL_NEXT (t))
4721       {
4722         tree elt = OVL_CURRENT (t);
4723         if (non_placement_deallocation_fn_p (elt))
4724           {
4725             fn = elt;
4726             /* "If a class T has a member deallocation function named
4727                operator delete with exactly one parameter, then that
4728                function is a usual (non-placement) deallocation
4729                function. If class T does not declare such an operator
4730                delete but does declare a member deallocation function named
4731                operator delete with exactly two parameters, the second of
4732                which has type std::size_t (18.2), then this function is a
4733                usual deallocation function."
4734
4735                So (void*) beats (void*, size_t).  */
4736             if (FUNCTION_ARG_CHAIN (fn) == void_list_node)
4737               break;
4738           }
4739       }
4740
4741   /* If we have a matching function, call it.  */
4742   if (fn)
4743     {
4744       gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
4745
4746       /* If the FN is a member function, make sure that it is
4747          accessible.  */
4748       if (BASELINK_P (fns))
4749         perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn);
4750
4751       /* Core issue 901: It's ok to new a type with deleted delete.  */
4752       if (DECL_DELETED_FN (fn) && alloc_fn)
4753         return NULL_TREE;
4754
4755       if (placement)
4756         {
4757           /* The placement args might not be suitable for overload
4758              resolution at this point, so build the call directly.  */
4759           int nargs = call_expr_nargs (placement);
4760           tree *argarray = XALLOCAVEC (tree, nargs);
4761           int i;
4762           argarray[0] = addr;
4763           for (i = 1; i < nargs; i++)
4764             argarray[i] = CALL_EXPR_ARG (placement, i);
4765           mark_used (fn);
4766           return build_cxx_call (fn, nargs, argarray);
4767         }
4768       else
4769         {
4770           tree ret;
4771           VEC(tree,gc) *args = VEC_alloc (tree, gc, 2);
4772           VEC_quick_push (tree, args, addr);
4773           if (FUNCTION_ARG_CHAIN (fn) != void_list_node)
4774             VEC_quick_push (tree, args, size);
4775           ret = cp_build_function_call_vec (fn, &args, tf_warning_or_error);
4776           VEC_free (tree, gc, args);
4777           return ret;
4778         }
4779     }
4780
4781   /* [expr.new]
4782
4783      If no unambiguous matching deallocation function can be found,
4784      propagating the exception does not cause the object's memory to
4785      be freed.  */
4786   if (alloc_fn)
4787     {
4788       if (!placement)
4789         warning (0, "no corresponding deallocation function for %qD",
4790                  alloc_fn);
4791       return NULL_TREE;
4792     }
4793
4794   error ("no suitable %<operator %s%> for %qT",
4795          operator_name_info[(int)code].name, type);
4796   return error_mark_node;
4797 }
4798
4799 /* If the current scope isn't allowed to access DECL along
4800    BASETYPE_PATH, give an error.  The most derived class in
4801    BASETYPE_PATH is the one used to qualify DECL. DIAG_DECL is
4802    the declaration to use in the error diagnostic.  */
4803
4804 bool
4805 enforce_access (tree basetype_path, tree decl, tree diag_decl)
4806 {
4807   gcc_assert (TREE_CODE (basetype_path) == TREE_BINFO);
4808
4809   if (!accessible_p (basetype_path, decl, true))
4810     {
4811       if (TREE_PRIVATE (decl))
4812         error ("%q+#D is private", diag_decl);
4813       else if (TREE_PROTECTED (decl))
4814         error ("%q+#D is protected", diag_decl);
4815       else
4816         error ("%q+#D is inaccessible", diag_decl);
4817       error ("within this context");
4818       return false;
4819     }
4820
4821   return true;
4822 }
4823
4824 /* Initialize a temporary of type TYPE with EXPR.  The FLAGS are a
4825    bitwise or of LOOKUP_* values.  If any errors are warnings are
4826    generated, set *DIAGNOSTIC_FN to "error" or "warning",
4827    respectively.  If no diagnostics are generated, set *DIAGNOSTIC_FN
4828    to NULL.  */
4829
4830 static tree
4831 build_temp (tree expr, tree type, int flags,
4832             diagnostic_t *diagnostic_kind)
4833 {
4834   int savew, savee;
4835   VEC(tree,gc) *args;
4836
4837   savew = warningcount, savee = errorcount;
4838   args = make_tree_vector_single (expr);
4839   expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
4840                                     &args, type, flags, tf_warning_or_error);
4841   release_tree_vector (args);
4842   if (warningcount > savew)
4843     *diagnostic_kind = DK_WARNING;
4844   else if (errorcount > savee)
4845     *diagnostic_kind = DK_ERROR;
4846   else
4847     *diagnostic_kind = DK_UNSPECIFIED;
4848   return expr;
4849 }
4850
4851 /* Perform warnings about peculiar, but valid, conversions from/to NULL.
4852    EXPR is implicitly converted to type TOTYPE.
4853    FN and ARGNUM are used for diagnostics.  */
4854
4855 static void
4856 conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
4857 {
4858   tree t = non_reference (totype);
4859
4860   /* Issue warnings about peculiar, but valid, uses of NULL.  */
4861   if (expr == null_node && TREE_CODE (t) != BOOLEAN_TYPE && ARITHMETIC_TYPE_P (t))
4862     {
4863       if (fn)
4864         warning_at (input_location, OPT_Wconversion_null,
4865                     "passing NULL to non-pointer argument %P of %qD",
4866                     argnum, fn);
4867       else
4868         warning_at (input_location, OPT_Wconversion_null,
4869                     "converting to non-pointer type %qT from NULL", t);
4870     }
4871
4872   /* Issue warnings if "false" is converted to a NULL pointer */
4873   else if (expr == boolean_false_node && fn && POINTER_TYPE_P (t))
4874     warning_at (input_location, OPT_Wconversion_null,
4875                 "converting %<false%> to pointer type for argument %P of %qD",
4876                 argnum, fn);
4877 }
4878
4879 /* Perform the conversions in CONVS on the expression EXPR.  FN and
4880    ARGNUM are used for diagnostics.  ARGNUM is zero based, -1
4881    indicates the `this' argument of a method.  INNER is nonzero when
4882    being called to continue a conversion chain. It is negative when a
4883    reference binding will be applied, positive otherwise.  If
4884    ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
4885    conversions will be emitted if appropriate.  If C_CAST_P is true,
4886    this conversion is coming from a C-style cast; in that case,
4887    conversions to inaccessible bases are permitted.  */
4888
4889 static tree
4890 convert_like_real (conversion *convs, tree expr, tree fn, int argnum,
4891                    int inner, bool issue_conversion_warnings,
4892                    bool c_cast_p, tsubst_flags_t complain)
4893 {
4894   tree totype = convs->type;
4895   diagnostic_t diag_kind;
4896   int flags;
4897
4898   if (convs->bad_p
4899       && convs->kind != ck_user
4900       && convs->kind != ck_list
4901       && convs->kind != ck_ambig
4902       && convs->kind != ck_ref_bind
4903       && convs->kind != ck_rvalue
4904       && convs->kind != ck_base)
4905     {
4906       conversion *t = convs;
4907
4908       /* Give a helpful error if this is bad because of excess braces.  */
4909       if (BRACE_ENCLOSED_INITIALIZER_P (expr)
4910           && SCALAR_TYPE_P (totype)
4911           && CONSTRUCTOR_NELTS (expr) > 0
4912           && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
4913         permerror (input_location, "too many braces around initializer for %qT", totype);
4914
4915       for (; t; t = convs->u.next)
4916         {
4917           if (t->kind == ck_user || !t->bad_p)
4918             {
4919               expr = convert_like_real (t, expr, fn, argnum, 1,
4920                                         /*issue_conversion_warnings=*/false,
4921                                         /*c_cast_p=*/false,
4922                                         complain);
4923               break;
4924             }
4925           else if (t->kind == ck_ambig)
4926             return convert_like_real (t, expr, fn, argnum, 1,
4927                                       /*issue_conversion_warnings=*/false,
4928                                       /*c_cast_p=*/false,
4929                                       complain);
4930           else if (t->kind == ck_identity)
4931             break;
4932         }
4933       if (complain & tf_error)
4934         {
4935           permerror (input_location, "invalid conversion from %qT to %qT", TREE_TYPE (expr), totype);
4936           if (fn)
4937             permerror (DECL_SOURCE_LOCATION (fn),
4938                        "  initializing argument %P of %qD", argnum, fn);
4939         }
4940       else
4941         return error_mark_node;
4942
4943       return cp_convert (totype, expr);
4944     }
4945
4946   if (issue_conversion_warnings && (complain & tf_warning))
4947     conversion_null_warnings (totype, expr, fn, argnum);
4948
4949   switch (convs->kind)
4950     {
4951     case ck_user:
4952       {
4953         struct z_candidate *cand = convs->cand;
4954         tree convfn = cand->fn;
4955         unsigned i;
4956
4957         expr = mark_rvalue_use (expr);
4958
4959         /* When converting from an init list we consider explicit
4960            constructors, but actually trying to call one is an error.  */
4961         if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn)
4962             /* Unless we're calling it for value-initialization from an
4963                empty list, since that is handled separately in 8.5.4.  */
4964             && cand->num_convs > 0)
4965           {
4966             if (complain & tf_error)
4967               error ("converting to %qT from initializer list would use "
4968                      "explicit constructor %qD", totype, convfn);
4969             else
4970               return error_mark_node;
4971           }
4972
4973         /* Set user_conv_p on the argument conversions, so rvalue/base
4974            handling knows not to allow any more UDCs.  */
4975         for (i = 0; i < cand->num_convs; ++i)
4976           cand->convs[i]->user_conv_p = true;
4977
4978         expr = build_over_call (cand, LOOKUP_NORMAL, complain);
4979
4980         /* If this is a constructor or a function returning an aggr type,
4981            we need to build up a TARGET_EXPR.  */
4982         if (DECL_CONSTRUCTOR_P (convfn))
4983           {
4984             expr = build_cplus_new (totype, expr);
4985
4986             /* Remember that this was list-initialization.  */
4987             if (convs->check_narrowing)
4988               TARGET_EXPR_LIST_INIT_P (expr) = true;
4989           }
4990
4991         return expr;
4992       }
4993     case ck_identity:
4994       expr = mark_rvalue_use (expr);
4995       if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4996         {
4997           int nelts = CONSTRUCTOR_NELTS (expr);
4998           if (nelts == 0)
4999             expr = integer_zero_node;
5000           else if (nelts == 1)
5001             expr = CONSTRUCTOR_ELT (expr, 0)->value;
5002           else
5003             gcc_unreachable ();
5004         }
5005
5006       if (type_unknown_p (expr))
5007         expr = instantiate_type (totype, expr, complain);
5008       /* Convert a constant to its underlying value, unless we are
5009          about to bind it to a reference, in which case we need to
5010          leave it as an lvalue.  */
5011       if (inner >= 0)
5012         {   
5013           expr = decl_constant_value (expr);
5014           if (expr == null_node && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
5015             /* If __null has been converted to an integer type, we do not
5016                want to warn about uses of EXPR as an integer, rather than
5017                as a pointer.  */
5018             expr = build_int_cst (totype, 0);
5019         }
5020       return expr;
5021     case ck_ambig:
5022       if (complain & tf_error)
5023         {
5024           /* Call build_user_type_conversion again for the error.  */
5025           build_user_type_conversion (totype, convs->u.expr, LOOKUP_NORMAL);
5026           if (fn)
5027             error ("  initializing argument %P of %q+D", argnum, fn);
5028         }
5029       return error_mark_node;
5030
5031     case ck_list:
5032       {
5033         /* Conversion to std::initializer_list<T>.  */
5034         tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
5035         tree new_ctor = build_constructor (init_list_type_node, NULL);
5036         unsigned len = CONSTRUCTOR_NELTS (expr);
5037         tree array, val;
5038         VEC(tree,gc) *parms;
5039         unsigned ix;
5040
5041         /* Convert all the elements.  */
5042         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
5043           {
5044             tree sub = convert_like_real (convs->u.list[ix], val, fn, argnum,
5045                                           1, false, false, complain);
5046             if (sub == error_mark_node)
5047               return sub;
5048             check_narrowing (TREE_TYPE (sub), val);
5049             CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor), NULL_TREE, sub);
5050           }
5051         /* Build up the array.  */
5052         elttype = cp_build_qualified_type
5053           (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
5054         array = build_array_of_n_type (elttype, len);
5055         array = finish_compound_literal (array, new_ctor);
5056
5057         parms = make_tree_vector ();
5058         VEC_safe_push (tree, gc, parms, decay_conversion (array));
5059         VEC_safe_push (tree, gc, parms, size_int (len));
5060         /* Call the private constructor.  */
5061         push_deferring_access_checks (dk_no_check);
5062         new_ctor = build_special_member_call
5063           (NULL_TREE, complete_ctor_identifier, &parms, totype, 0, complain);
5064         release_tree_vector (parms);
5065         pop_deferring_access_checks ();
5066         return build_cplus_new (totype, new_ctor);
5067       }
5068
5069     case ck_aggr:
5070       return get_target_expr (digest_init (totype, expr));
5071
5072     default:
5073       break;
5074     };
5075
5076   expr = convert_like_real (convs->u.next, expr, fn, argnum,
5077                             convs->kind == ck_ref_bind ? -1 : 1,
5078                             convs->kind == ck_ref_bind ? issue_conversion_warnings : false, 
5079                             c_cast_p,
5080                             complain);
5081   if (expr == error_mark_node)
5082     return error_mark_node;
5083
5084   switch (convs->kind)
5085     {
5086     case ck_rvalue:
5087       expr = decay_conversion (expr);
5088       if (! MAYBE_CLASS_TYPE_P (totype))
5089         return expr;
5090       /* Else fall through.  */
5091     case ck_base:
5092       if (convs->kind == ck_base && !convs->need_temporary_p)
5093         {
5094           /* We are going to bind a reference directly to a base-class
5095              subobject of EXPR.  */
5096           /* Build an expression for `*((base*) &expr)'.  */
5097           expr = cp_build_unary_op (ADDR_EXPR, expr, 0, complain);
5098           expr = convert_to_base (expr, build_pointer_type (totype),
5099                                   !c_cast_p, /*nonnull=*/true, complain);
5100           expr = cp_build_indirect_ref (expr, RO_IMPLICIT_CONVERSION, complain);
5101           return expr;
5102         }
5103
5104       /* Copy-initialization where the cv-unqualified version of the source
5105          type is the same class as, or a derived class of, the class of the
5106          destination [is treated as direct-initialization].  [dcl.init] */
5107       flags = LOOKUP_NORMAL|LOOKUP_ONLYCONVERTING;
5108       if (convs->user_conv_p)
5109         /* This conversion is being done in the context of a user-defined
5110            conversion (i.e. the second step of copy-initialization), so
5111            don't allow any more.  */
5112         flags |= LOOKUP_NO_CONVERSION;
5113       expr = build_temp (expr, totype, flags, &diag_kind);
5114       if (diag_kind && fn)
5115         {
5116           if ((complain & tf_error))
5117             emit_diagnostic (diag_kind, DECL_SOURCE_LOCATION (fn), 0,
5118                              "  initializing argument %P of %qD", argnum, fn);
5119           else if (diag_kind == DK_ERROR)
5120             return error_mark_node;
5121         }
5122       return build_cplus_new (totype, expr);
5123
5124     case ck_ref_bind:
5125       {
5126         tree ref_type = totype;
5127
5128         if (convs->bad_p && TYPE_REF_IS_RVALUE (ref_type)
5129             && real_lvalue_p (expr))
5130           {
5131             if (complain & tf_error)
5132               {
5133                 error ("cannot bind %qT lvalue to %qT",
5134                        TREE_TYPE (expr), totype);
5135                 if (fn)
5136                   error ("  initializing argument %P of %q+D", argnum, fn);
5137               }
5138             return error_mark_node;
5139           }
5140
5141         /* If necessary, create a temporary. 
5142
5143            VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
5144            that need temporaries, even when their types are reference
5145            compatible with the type of reference being bound, so the
5146            upcoming call to cp_build_unary_op (ADDR_EXPR, expr, ...)
5147            doesn't fail.  */
5148         if (convs->need_temporary_p
5149             || TREE_CODE (expr) == CONSTRUCTOR
5150             || TREE_CODE (expr) == VA_ARG_EXPR)
5151           {
5152             tree type = convs->u.next->type;
5153             cp_lvalue_kind lvalue = real_lvalue_p (expr);
5154
5155             if (!CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (ref_type))
5156                 && !TYPE_REF_IS_RVALUE (ref_type))
5157               {
5158                 if (complain & tf_error)
5159                   {
5160                     /* If the reference is volatile or non-const, we
5161                        cannot create a temporary.  */
5162                     if (lvalue & clk_bitfield)
5163                       error ("cannot bind bitfield %qE to %qT",
5164                              expr, ref_type);
5165                     else if (lvalue & clk_packed)
5166                       error ("cannot bind packed field %qE to %qT",
5167                              expr, ref_type);
5168                     else
5169                       error ("cannot bind rvalue %qE to %qT", expr, ref_type);
5170                   }
5171                 return error_mark_node;
5172               }
5173             /* If the source is a packed field, and we must use a copy
5174                constructor, then building the target expr will require
5175                binding the field to the reference parameter to the
5176                copy constructor, and we'll end up with an infinite
5177                loop.  If we can use a bitwise copy, then we'll be
5178                OK.  */
5179             if ((lvalue & clk_packed)
5180                 && CLASS_TYPE_P (type)
5181                 && !TYPE_HAS_TRIVIAL_INIT_REF (type))
5182               {
5183                 if (complain & tf_error)
5184                   error ("cannot bind packed field %qE to %qT",
5185                          expr, ref_type);
5186                 return error_mark_node;
5187               }
5188             if (lvalue & clk_bitfield)
5189               {
5190                 expr = convert_bitfield_to_declared_type (expr);
5191                 expr = fold_convert (type, expr);
5192               }
5193             expr = build_target_expr_with_type (expr, type);
5194           }
5195
5196         /* Take the address of the thing to which we will bind the
5197            reference.  */
5198         expr = cp_build_unary_op (ADDR_EXPR, expr, 1, complain);
5199         if (expr == error_mark_node)
5200           return error_mark_node;
5201
5202         /* Convert it to a pointer to the type referred to by the
5203            reference.  This will adjust the pointer if a derived to
5204            base conversion is being performed.  */
5205         expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
5206                            expr);
5207         /* Convert the pointer to the desired reference type.  */
5208         return build_nop (ref_type, expr);
5209       }
5210
5211     case ck_lvalue:
5212       return decay_conversion (expr);
5213
5214     case ck_qual:
5215       /* Warn about deprecated conversion if appropriate.  */
5216       string_conv_p (totype, expr, 1);
5217       break;
5218
5219     case ck_ptr:
5220       if (convs->base_p)
5221         expr = convert_to_base (expr, totype, !c_cast_p,
5222                                 /*nonnull=*/false, complain);
5223       return build_nop (totype, expr);
5224
5225     case ck_pmem:
5226       return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
5227                              c_cast_p);
5228
5229     default:
5230       break;
5231     }
5232
5233   if (convs->check_narrowing)
5234     check_narrowing (totype, expr);
5235
5236   if (issue_conversion_warnings && (complain & tf_warning))
5237     expr = convert_and_check (totype, expr);
5238   else
5239     expr = convert (totype, expr);
5240
5241   return expr;
5242 }
5243
5244 /* ARG is being passed to a varargs function.  Perform any conversions
5245    required.  Return the converted value.  */
5246
5247 tree
5248 convert_arg_to_ellipsis (tree arg)
5249 {
5250   /* [expr.call]
5251
5252      The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
5253      standard conversions are performed.  */
5254   arg = decay_conversion (arg);
5255   /* [expr.call]
5256
5257      If the argument has integral or enumeration type that is subject
5258      to the integral promotions (_conv.prom_), or a floating point
5259      type that is subject to the floating point promotion
5260      (_conv.fpprom_), the value of the argument is converted to the
5261      promoted type before the call.  */
5262   if (TREE_CODE (TREE_TYPE (arg)) == REAL_TYPE
5263       && (TYPE_PRECISION (TREE_TYPE (arg))
5264           < TYPE_PRECISION (double_type_node))
5265       && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (arg))))
5266     arg = convert_to_real (double_type_node, arg);
5267   else if (NULLPTR_TYPE_P (TREE_TYPE (arg)))
5268     arg = null_pointer_node;
5269   else if (INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (arg)))
5270     arg = perform_integral_promotions (arg);
5271
5272   arg = require_complete_type (arg);
5273
5274   if (arg != error_mark_node
5275       && (type_has_nontrivial_copy_init (TREE_TYPE (arg))
5276           || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (arg))))
5277     {
5278       /* [expr.call] 5.2.2/7:
5279          Passing a potentially-evaluated argument of class type (Clause 9)
5280          with a non-trivial copy constructor or a non-trivial destructor
5281          with no corresponding parameter is conditionally-supported, with
5282          implementation-defined semantics.
5283
5284          We used to just warn here and do a bitwise copy, but now
5285          cp_expr_size will abort if we try to do that.
5286
5287          If the call appears in the context of a sizeof expression,
5288          it is not potentially-evaluated.  */
5289       if (cp_unevaluated_operand == 0)
5290         error ("cannot pass objects of non-trivially-copyable "
5291                "type %q#T through %<...%>", TREE_TYPE (arg));
5292     }
5293
5294   return arg;
5295 }
5296
5297 /* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused.  */
5298
5299 tree
5300 build_x_va_arg (tree expr, tree type)
5301 {
5302   if (processing_template_decl)
5303     return build_min (VA_ARG_EXPR, type, expr);
5304
5305   type = complete_type_or_else (type, NULL_TREE);
5306
5307   if (expr == error_mark_node || !type)
5308     return error_mark_node;
5309
5310   expr = mark_lvalue_use (expr);
5311
5312   if (type_has_nontrivial_copy_init (type)
5313       || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
5314       || TREE_CODE (type) == REFERENCE_TYPE)
5315     {
5316       /* Remove reference types so we don't ICE later on.  */
5317       tree type1 = non_reference (type);
5318       /* conditionally-supported behavior [expr.call] 5.2.2/7.  */
5319       error ("cannot receive objects of non-trivially-copyable type %q#T "
5320              "through %<...%>; ", type);
5321       expr = convert (build_pointer_type (type1), null_node);
5322       expr = cp_build_indirect_ref (expr, RO_NULL, tf_warning_or_error);
5323       return expr;
5324     }
5325
5326   return build_va_arg (input_location, expr, type);
5327 }
5328
5329 /* TYPE has been given to va_arg.  Apply the default conversions which
5330    would have happened when passed via ellipsis.  Return the promoted
5331    type, or the passed type if there is no change.  */
5332
5333 tree
5334 cxx_type_promotes_to (tree type)
5335 {
5336   tree promote;
5337
5338   /* Perform the array-to-pointer and function-to-pointer
5339      conversions.  */
5340   type = type_decays_to (type);
5341
5342   promote = type_promotes_to (type);
5343   if (same_type_p (type, promote))
5344     promote = type;
5345
5346   return promote;
5347 }
5348
5349 /* ARG is a default argument expression being passed to a parameter of
5350    the indicated TYPE, which is a parameter to FN.  Do any required
5351    conversions.  Return the converted value.  */
5352
5353 static GTY(()) VEC(tree,gc) *default_arg_context;
5354
5355 tree
5356 convert_default_arg (tree type, tree arg, tree fn, int parmnum)
5357 {
5358   int i;
5359   tree t;
5360
5361   /* If the ARG is an unparsed default argument expression, the
5362      conversion cannot be performed.  */
5363   if (TREE_CODE (arg) == DEFAULT_ARG)
5364     {
5365       error ("the default argument for parameter %d of %qD has "
5366              "not yet been parsed",
5367              parmnum, fn);
5368       return error_mark_node;
5369     }
5370
5371   /* Detect recursion.  */
5372   for (i = 0; VEC_iterate (tree, default_arg_context, i, t); ++i)
5373     if (t == fn)
5374       {
5375         error ("recursive evaluation of default argument for %q#D", fn);
5376         return error_mark_node;
5377       }
5378   VEC_safe_push (tree, gc, default_arg_context, fn);
5379
5380   if (fn && DECL_TEMPLATE_INFO (fn))
5381     arg = tsubst_default_argument (fn, type, arg);
5382
5383   /* Due to:
5384
5385        [dcl.fct.default]
5386
5387        The names in the expression are bound, and the semantic
5388        constraints are checked, at the point where the default
5389        expressions appears.
5390
5391      we must not perform access checks here.  */
5392   push_deferring_access_checks (dk_no_check);
5393   arg = break_out_target_exprs (arg);
5394   if (TREE_CODE (arg) == CONSTRUCTOR)
5395     {
5396       arg = digest_init (type, arg);
5397       arg = convert_for_initialization (0, type, arg, LOOKUP_NORMAL,
5398                                         ICR_DEFAULT_ARGUMENT, fn, parmnum,
5399                                         tf_warning_or_error);
5400     }
5401   else
5402     {
5403       /* We must make a copy of ARG, in case subsequent processing
5404          alters any part of it.  For example, during gimplification a
5405          cast of the form (T) &X::f (where "f" is a member function)
5406          will lead to replacing the PTRMEM_CST for &X::f with a
5407          VAR_DECL.  We can avoid the copy for constants, since they
5408          are never modified in place.  */
5409       if (!CONSTANT_CLASS_P (arg))
5410         arg = unshare_expr (arg);
5411       arg = convert_for_initialization (0, type, arg, LOOKUP_NORMAL,
5412                                         ICR_DEFAULT_ARGUMENT, fn, parmnum,
5413                                         tf_warning_or_error);
5414       arg = convert_for_arg_passing (type, arg);
5415     }
5416   pop_deferring_access_checks();
5417
5418   VEC_pop (tree, default_arg_context);
5419
5420   return arg;
5421 }
5422
5423 /* Returns the type which will really be used for passing an argument of
5424    type TYPE.  */
5425
5426 tree
5427 type_passed_as (tree type)
5428 {
5429   /* Pass classes with copy ctors by invisible reference.  */
5430   if (TREE_ADDRESSABLE (type))
5431     {
5432       type = build_reference_type (type);
5433       /* There are no other pointers to this temporary.  */
5434       type = cp_build_qualified_type (type, TYPE_QUAL_RESTRICT);
5435     }
5436   else if (targetm.calls.promote_prototypes (type)
5437            && INTEGRAL_TYPE_P (type)
5438            && COMPLETE_TYPE_P (type)
5439            && INT_CST_LT_UNSIGNED (TYPE_SIZE (type),
5440                                    TYPE_SIZE (integer_type_node)))
5441     type = integer_type_node;
5442
5443   return type;
5444 }
5445
5446 /* Actually perform the appropriate conversion.  */
5447
5448 tree
5449 convert_for_arg_passing (tree type, tree val)
5450 {
5451   tree bitfield_type;
5452
5453   /* If VAL is a bitfield, then -- since it has already been converted
5454      to TYPE -- it cannot have a precision greater than TYPE.  
5455
5456      If it has a smaller precision, we must widen it here.  For
5457      example, passing "int f:3;" to a function expecting an "int" will
5458      not result in any conversion before this point.
5459
5460      If the precision is the same we must not risk widening.  For
5461      example, the COMPONENT_REF for a 32-bit "long long" bitfield will
5462      often have type "int", even though the C++ type for the field is
5463      "long long".  If the value is being passed to a function
5464      expecting an "int", then no conversions will be required.  But,
5465      if we call convert_bitfield_to_declared_type, the bitfield will
5466      be converted to "long long".  */
5467   bitfield_type = is_bitfield_expr_with_lowered_type (val);
5468   if (bitfield_type 
5469       && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
5470     val = convert_to_integer (TYPE_MAIN_VARIANT (bitfield_type), val);
5471
5472   if (val == error_mark_node)
5473     ;
5474   /* Pass classes with copy ctors by invisible reference.  */
5475   else if (TREE_ADDRESSABLE (type))
5476     val = build1 (ADDR_EXPR, build_reference_type (type), val);
5477   else if (targetm.calls.promote_prototypes (type)
5478            && INTEGRAL_TYPE_P (type)
5479            && COMPLETE_TYPE_P (type)
5480            && INT_CST_LT_UNSIGNED (TYPE_SIZE (type),
5481                                    TYPE_SIZE (integer_type_node)))
5482     val = perform_integral_promotions (val);
5483   if (warn_missing_format_attribute)
5484     {
5485       tree rhstype = TREE_TYPE (val);
5486       const enum tree_code coder = TREE_CODE (rhstype);
5487       const enum tree_code codel = TREE_CODE (type);
5488       if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
5489           && coder == codel
5490           && check_missing_format_attribute (type, rhstype))
5491         warning (OPT_Wmissing_format_attribute,
5492                  "argument of function call might be a candidate for a format attribute");
5493     }
5494   return val;
5495 }
5496
5497 /* Returns true iff FN is a function with magic varargs, i.e. ones for
5498    which no conversions at all should be done.  This is true for some
5499    builtins which don't act like normal functions.  */
5500
5501 static bool
5502 magic_varargs_p (tree fn)
5503 {
5504   if (DECL_BUILT_IN (fn))
5505     switch (DECL_FUNCTION_CODE (fn))
5506       {
5507       case BUILT_IN_CLASSIFY_TYPE:
5508       case BUILT_IN_CONSTANT_P:
5509       case BUILT_IN_NEXT_ARG:
5510       case BUILT_IN_VA_START:
5511         return true;
5512
5513       default:;
5514         return lookup_attribute ("type generic",
5515                                  TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
5516       }
5517
5518   return false;
5519 }
5520
5521 /* Subroutine of the various build_*_call functions.  Overload resolution
5522    has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
5523    ARGS is a TREE_LIST of the unconverted arguments to the call.  FLAGS is a
5524    bitmask of various LOOKUP_* flags which apply to the call itself.  */
5525
5526 static tree
5527 build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
5528 {
5529   tree fn = cand->fn;
5530   const VEC(tree,gc) *args = cand->args;
5531   tree first_arg = cand->first_arg;
5532   conversion **convs = cand->convs;
5533   conversion *conv;
5534   tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
5535   int parmlen;
5536   tree val;
5537   int i = 0;
5538   int j = 0;
5539   unsigned int arg_index = 0;
5540   int is_method = 0;
5541   int nargs;
5542   tree *argarray;
5543   bool already_used = false;
5544
5545   /* In a template, there is no need to perform all of the work that
5546      is normally done.  We are only interested in the type of the call
5547      expression, i.e., the return type of the function.  Any semantic
5548      errors will be deferred until the template is instantiated.  */
5549   if (processing_template_decl)
5550     {
5551       tree expr;
5552       tree return_type;
5553       const tree *argarray;
5554       unsigned int nargs;
5555
5556       return_type = TREE_TYPE (TREE_TYPE (fn));
5557       nargs = VEC_length (tree, args);
5558       if (first_arg == NULL_TREE)
5559         argarray = VEC_address (tree, CONST_CAST (VEC(tree,gc) *, args));
5560       else
5561         {
5562           tree *alcarray;
5563           unsigned int ix;
5564           tree arg;
5565
5566           ++nargs;
5567           alcarray = XALLOCAVEC (tree, nargs);
5568           alcarray[0] = first_arg;
5569           for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
5570             alcarray[ix + 1] = arg;
5571           argarray = alcarray;
5572         }
5573       expr = build_call_array_loc (input_location,
5574                                    return_type, build_addr_func (fn), nargs,
5575                                    argarray);
5576       if (TREE_THIS_VOLATILE (fn) && cfun)
5577         current_function_returns_abnormally = 1;
5578       if (!VOID_TYPE_P (return_type))
5579         require_complete_type (return_type);
5580       return convert_from_reference (expr);
5581     }
5582
5583   /* Give any warnings we noticed during overload resolution.  */
5584   if (cand->warnings)
5585     {
5586       struct candidate_warning *w;
5587       for (w = cand->warnings; w; w = w->next)
5588         joust (cand, w->loser, 1);
5589     }
5590
5591   /* Make =delete work with SFINAE.  */
5592   if (DECL_DELETED_FN (fn) && !(complain & tf_error))
5593     return error_mark_node;
5594
5595   if (DECL_FUNCTION_MEMBER_P (fn))
5596     {
5597       /* If FN is a template function, two cases must be considered.
5598          For example:
5599
5600            struct A {
5601              protected:
5602                template <class T> void f();
5603            };
5604            template <class T> struct B {
5605              protected:
5606                void g();
5607            };
5608            struct C : A, B<int> {
5609              using A::f;        // #1
5610              using B<int>::g;   // #2
5611            };
5612
5613          In case #1 where `A::f' is a member template, DECL_ACCESS is
5614          recorded in the primary template but not in its specialization.
5615          We check access of FN using its primary template.
5616
5617          In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
5618          because it is a member of class template B, DECL_ACCESS is
5619          recorded in the specialization `B<int>::g'.  We cannot use its
5620          primary template because `B<T>::g' and `B<int>::g' may have
5621          different access.  */
5622       if (DECL_TEMPLATE_INFO (fn)
5623           && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
5624         perform_or_defer_access_check (cand->access_path,
5625                                        DECL_TI_TEMPLATE (fn), fn);
5626       else
5627         perform_or_defer_access_check (cand->access_path, fn, fn);
5628     }
5629
5630   /* Find maximum size of vector to hold converted arguments.  */
5631   parmlen = list_length (parm);
5632   nargs = VEC_length (tree, args) + (first_arg != NULL_TREE ? 1 : 0);
5633   if (parmlen > nargs)
5634     nargs = parmlen;
5635   argarray = XALLOCAVEC (tree, nargs);
5636
5637   /* The implicit parameters to a constructor are not considered by overload
5638      resolution, and must be of the proper type.  */
5639   if (DECL_CONSTRUCTOR_P (fn))
5640     {
5641       if (first_arg != NULL_TREE)
5642         {
5643           argarray[j++] = first_arg;
5644           first_arg = NULL_TREE;
5645         }
5646       else
5647         {
5648           argarray[j++] = VEC_index (tree, args, arg_index);
5649           ++arg_index;
5650         }
5651       parm = TREE_CHAIN (parm);
5652       /* We should never try to call the abstract constructor.  */
5653       gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
5654
5655       if (DECL_HAS_VTT_PARM_P (fn))
5656         {
5657           argarray[j++] = VEC_index (tree, args, arg_index);
5658           ++arg_index;
5659           parm = TREE_CHAIN (parm);
5660         }
5661     }
5662   /* Bypass access control for 'this' parameter.  */
5663   else if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
5664     {
5665       tree parmtype = TREE_VALUE (parm);
5666       tree arg = (first_arg != NULL_TREE
5667                   ? first_arg
5668                   : VEC_index (tree, args, arg_index));
5669       tree argtype = TREE_TYPE (arg);
5670       tree converted_arg;
5671       tree base_binfo;
5672
5673       if (convs[i]->bad_p)
5674         {
5675           if (complain & tf_error)
5676             permerror (input_location, "passing %qT as %<this%> argument of %q#D discards qualifiers",
5677                        TREE_TYPE (argtype), fn);
5678           else
5679             return error_mark_node;
5680         }
5681
5682       /* [class.mfct.nonstatic]: If a nonstatic member function of a class
5683          X is called for an object that is not of type X, or of a type
5684          derived from X, the behavior is undefined.
5685
5686          So we can assume that anything passed as 'this' is non-null, and
5687          optimize accordingly.  */
5688       gcc_assert (TREE_CODE (parmtype) == POINTER_TYPE);
5689       /* Convert to the base in which the function was declared.  */
5690       gcc_assert (cand->conversion_path != NULL_TREE);
5691       converted_arg = build_base_path (PLUS_EXPR,
5692                                        arg,
5693                                        cand->conversion_path,
5694                                        1);
5695       /* Check that the base class is accessible.  */
5696       if (!accessible_base_p (TREE_TYPE (argtype),
5697                               BINFO_TYPE (cand->conversion_path), true))
5698         error ("%qT is not an accessible base of %qT",
5699                BINFO_TYPE (cand->conversion_path),
5700                TREE_TYPE (argtype));
5701       /* If fn was found by a using declaration, the conversion path
5702          will be to the derived class, not the base declaring fn. We
5703          must convert from derived to base.  */
5704       base_binfo = lookup_base (TREE_TYPE (TREE_TYPE (converted_arg)),
5705                                 TREE_TYPE (parmtype), ba_unique, NULL);
5706       converted_arg = build_base_path (PLUS_EXPR, converted_arg,
5707                                        base_binfo, 1);
5708
5709       argarray[j++] = converted_arg;
5710       parm = TREE_CHAIN (parm);
5711       if (first_arg != NULL_TREE)
5712         first_arg = NULL_TREE;
5713       else
5714         ++arg_index;
5715       ++i;
5716       is_method = 1;
5717     }
5718
5719   gcc_assert (first_arg == NULL_TREE);
5720   for (; arg_index < VEC_length (tree, args) && parm;
5721        parm = TREE_CHAIN (parm), ++arg_index, ++i)
5722     {
5723       tree type = TREE_VALUE (parm);
5724       tree arg = VEC_index (tree, args, arg_index);
5725
5726       conv = convs[i];
5727
5728       /* Don't make a copy here if build_call is going to.  */
5729       if (conv->kind == ck_rvalue
5730           && COMPLETE_TYPE_P (complete_type (type))
5731           && !TREE_ADDRESSABLE (type))
5732         conv = conv->u.next;
5733
5734       /* Warn about initializer_list deduction that isn't currently in the
5735          working draft.  */
5736       if (cxx_dialect > cxx98
5737           && flag_deduce_init_list
5738           && cand->template_decl
5739           && is_std_init_list (non_reference (type))
5740           && BRACE_ENCLOSED_INITIALIZER_P (arg))
5741         {
5742           tree tmpl = TI_TEMPLATE (cand->template_decl);
5743           tree realparm = chain_index (j, DECL_ARGUMENTS (cand->fn));
5744           tree patparm = get_pattern_parm (realparm, tmpl);
5745           tree pattype = TREE_TYPE (patparm);
5746           if (PACK_EXPANSION_P (pattype))
5747             pattype = PACK_EXPANSION_PATTERN (pattype);
5748           pattype = non_reference (pattype);
5749
5750           if (TREE_CODE (pattype) == TEMPLATE_TYPE_PARM
5751               && (cand->explicit_targs == NULL_TREE
5752                   || (TREE_VEC_LENGTH (cand->explicit_targs)
5753                       <= TEMPLATE_TYPE_IDX (pattype))))
5754             {
5755               pedwarn (input_location, 0, "deducing %qT as %qT",
5756                        non_reference (TREE_TYPE (patparm)),
5757                        non_reference (type));
5758               pedwarn (input_location, 0, "  in call to %q+D", cand->fn);
5759               pedwarn (input_location, 0,
5760                        "  (you can disable this with -fno-deduce-init-list)");
5761             }
5762         }
5763
5764       val = convert_like_with_context (conv, arg, fn, i-is_method, complain);
5765
5766       val = convert_for_arg_passing (type, val);
5767       if (val == error_mark_node)
5768         return error_mark_node;
5769       else
5770         argarray[j++] = val;
5771     }
5772
5773   /* Default arguments */
5774   for (; parm && parm != void_list_node; parm = TREE_CHAIN (parm), i++)
5775     argarray[j++] = convert_default_arg (TREE_VALUE (parm),
5776                                          TREE_PURPOSE (parm),
5777                                          fn, i - is_method);
5778   /* Ellipsis */
5779   for (; arg_index < VEC_length (tree, args); ++arg_index)
5780     {
5781       tree a = VEC_index (tree, args, arg_index);
5782       if (magic_varargs_p (fn))
5783         /* Do no conversions for magic varargs.  */
5784         a = mark_type_use (a);
5785       else
5786         a = convert_arg_to_ellipsis (a);
5787       argarray[j++] = a;
5788     }
5789
5790   gcc_assert (j <= nargs);
5791   nargs = j;
5792
5793   check_function_arguments (TYPE_ATTRIBUTES (TREE_TYPE (fn)),
5794                             nargs, argarray, TYPE_ARG_TYPES (TREE_TYPE (fn)));
5795
5796   /* Avoid actually calling copy constructors and copy assignment operators,
5797      if possible.  */
5798
5799   if (! flag_elide_constructors)
5800     /* Do things the hard way.  */;
5801   else if (cand->num_convs == 1 
5802            && (DECL_COPY_CONSTRUCTOR_P (fn) 
5803                || DECL_MOVE_CONSTRUCTOR_P (fn)))
5804     {
5805       tree targ;
5806       tree arg = argarray[num_artificial_parms_for (fn)];
5807       tree fa;
5808
5809       /* Pull out the real argument, disregarding const-correctness.  */
5810       targ = arg;
5811       while (CONVERT_EXPR_P (targ)
5812              || TREE_CODE (targ) == NON_LVALUE_EXPR)
5813         targ = TREE_OPERAND (targ, 0);
5814       if (TREE_CODE (targ) == ADDR_EXPR)
5815         {
5816           targ = TREE_OPERAND (targ, 0);
5817           if (!same_type_ignoring_top_level_qualifiers_p
5818               (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
5819             targ = NULL_TREE;
5820         }
5821       else
5822         targ = NULL_TREE;
5823
5824       if (targ)
5825         arg = targ;
5826       else
5827         arg = cp_build_indirect_ref (arg, RO_NULL, complain);
5828
5829       if (TREE_CODE (arg) == TARGET_EXPR
5830           && TARGET_EXPR_LIST_INIT_P (arg))
5831         {
5832           /* Copy-list-initialization doesn't require the copy constructor
5833              to be defined.  */
5834         }
5835       /* [class.copy]: the copy constructor is implicitly defined even if
5836          the implementation elided its use.  */
5837       else if (TYPE_HAS_COMPLEX_INIT_REF (DECL_CONTEXT (fn))
5838                || move_fn_p (fn))
5839         {
5840           mark_used (fn);
5841           already_used = true;
5842         }
5843
5844       /* If we're creating a temp and we already have one, don't create a
5845          new one.  If we're not creating a temp but we get one, use
5846          INIT_EXPR to collapse the temp into our target.  Otherwise, if the
5847          ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
5848          temp or an INIT_EXPR otherwise.  */
5849       fa = (cand->first_arg != NULL_TREE
5850             ? cand->first_arg
5851             : VEC_index (tree, args, 0));
5852       if (integer_zerop (fa))
5853         {
5854           if (TREE_CODE (arg) == TARGET_EXPR)
5855             return arg;
5856           else if (TYPE_HAS_TRIVIAL_INIT_REF (DECL_CONTEXT (fn))
5857                    && !move_fn_p (fn))
5858             return build_target_expr_with_type (arg, DECL_CONTEXT (fn));
5859         }
5860       else if (TREE_CODE (arg) == TARGET_EXPR
5861                || (TYPE_HAS_TRIVIAL_INIT_REF (DECL_CONTEXT (fn))
5862                    && !move_fn_p (fn)))
5863         {
5864           tree to = stabilize_reference (cp_build_indirect_ref (fa, RO_NULL,
5865                                                                 complain));
5866
5867           val = build2 (INIT_EXPR, DECL_CONTEXT (fn), to, arg);
5868           return val;
5869         }
5870     }
5871   else if (DECL_OVERLOADED_OPERATOR_P (fn) == NOP_EXPR
5872            && copy_fn_p (fn)
5873            && TYPE_HAS_TRIVIAL_ASSIGN_REF (DECL_CONTEXT (fn)))
5874     {
5875       tree to = stabilize_reference
5876         (cp_build_indirect_ref (argarray[0], RO_NULL, complain));
5877       tree type = TREE_TYPE (to);
5878       tree as_base = CLASSTYPE_AS_BASE (type);
5879       tree arg = argarray[1];
5880
5881       if (is_really_empty_class (type))
5882         {
5883           /* Avoid copying empty classes.  */
5884           val = build2 (COMPOUND_EXPR, void_type_node, to, arg);
5885           TREE_NO_WARNING (val) = 1;
5886           val = build2 (COMPOUND_EXPR, type, val, to);
5887           TREE_NO_WARNING (val) = 1;
5888         }
5889       else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
5890         {
5891           arg = cp_build_indirect_ref (arg, RO_NULL, complain);
5892           val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
5893         }
5894       else
5895         {
5896           /* We must only copy the non-tail padding parts.
5897              Use __builtin_memcpy for the bitwise copy.
5898              FIXME fix 22488 so we can go back to using MODIFY_EXPR
5899              instead of an explicit call to memcpy.  */
5900         
5901           tree arg0, arg1, arg2, t;
5902           tree test = NULL_TREE;
5903
5904           arg2 = TYPE_SIZE_UNIT (as_base);
5905           arg1 = arg;
5906           arg0 = cp_build_unary_op (ADDR_EXPR, to, 0, complain);
5907
5908           if (!can_trust_pointer_alignment ())
5909             {
5910               /* If we can't be sure about pointer alignment, a call
5911                  to __builtin_memcpy is expanded as a call to memcpy, which
5912                  is invalid with identical args.  Otherwise it is
5913                  expanded as a block move, which should be safe.  */
5914               arg0 = save_expr (arg0);
5915               arg1 = save_expr (arg1);
5916               test = build2 (EQ_EXPR, boolean_type_node, arg0, arg1);
5917             }
5918           t = implicit_built_in_decls[BUILT_IN_MEMCPY];
5919           t = build_call_n (t, 3, arg0, arg1, arg2);
5920
5921           t = convert (TREE_TYPE (arg0), t);
5922           if (test)
5923             t = build3 (COND_EXPR, TREE_TYPE (t), test, arg0, t);
5924           val = cp_build_indirect_ref (t, RO_NULL, complain);
5925           TREE_NO_WARNING (val) = 1;
5926         }
5927
5928       return val;
5929     }
5930
5931   if (!already_used)
5932     mark_used (fn);
5933
5934   if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
5935     {
5936       tree t;
5937       tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
5938                                 DECL_CONTEXT (fn),
5939                                 ba_any, NULL);
5940       gcc_assert (binfo && binfo != error_mark_node);
5941
5942       /* Warn about deprecated virtual functions now, since we're about
5943          to throw away the decl.  */
5944       if (TREE_DEPRECATED (fn))
5945         warn_deprecated_use (fn, NULL_TREE);
5946
5947       argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1);
5948       if (TREE_SIDE_EFFECTS (argarray[0]))
5949         argarray[0] = save_expr (argarray[0]);
5950       t = build_pointer_type (TREE_TYPE (fn));
5951       if (DECL_CONTEXT (fn) && TYPE_JAVA_INTERFACE (DECL_CONTEXT (fn)))
5952         fn = build_java_interface_fn_ref (fn, argarray[0]);
5953       else
5954         fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
5955       TREE_TYPE (fn) = t;
5956     }
5957   else
5958     fn = build_addr_func (fn);
5959
5960   return build_cxx_call (fn, nargs, argarray);
5961 }
5962
5963 /* Build and return a call to FN, using NARGS arguments in ARGARRAY.
5964    This function performs no overload resolution, conversion, or other
5965    high-level operations.  */
5966
5967 tree
5968 build_cxx_call (tree fn, int nargs, tree *argarray)
5969 {
5970   tree fndecl;
5971
5972   fn = build_call_a (fn, nargs, argarray);
5973
5974   /* If this call might throw an exception, note that fact.  */
5975   fndecl = get_callee_fndecl (fn);
5976   if ((!fndecl || !TREE_NOTHROW (fndecl))
5977       && at_function_scope_p ()
5978       && cfun)
5979     cp_function_chain->can_throw = 1;
5980
5981   /* Check that arguments to builtin functions match the expectations.  */
5982   if (fndecl
5983       && DECL_BUILT_IN (fndecl)
5984       && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
5985       && !check_builtin_function_arguments (fndecl, nargs, argarray))
5986     return error_mark_node;
5987
5988   /* Some built-in function calls will be evaluated at compile-time in
5989      fold ().  */
5990   fn = fold_if_not_in_template (fn);
5991
5992   if (VOID_TYPE_P (TREE_TYPE (fn)))
5993     return fn;
5994
5995   fn = require_complete_type (fn);
5996   if (fn == error_mark_node)
5997     return error_mark_node;
5998
5999   if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
6000     fn = build_cplus_new (TREE_TYPE (fn), fn);
6001   return convert_from_reference (fn);
6002 }
6003
6004 static GTY(()) tree java_iface_lookup_fn;
6005
6006 /* Make an expression which yields the address of the Java interface
6007    method FN.  This is achieved by generating a call to libjava's
6008    _Jv_LookupInterfaceMethodIdx().  */
6009
6010 static tree
6011 build_java_interface_fn_ref (tree fn, tree instance)
6012 {
6013   tree lookup_fn, method, idx;
6014   tree klass_ref, iface, iface_ref;
6015   int i;
6016
6017   if (!java_iface_lookup_fn)
6018     {
6019       tree ftype = build_function_type_list (ptr_type_node,
6020                                              ptr_type_node, ptr_type_node,
6021                                              java_int_type_node, NULL_TREE);
6022       java_iface_lookup_fn
6023         = add_builtin_function ("_Jv_LookupInterfaceMethodIdx", ftype,
6024                                 0, NOT_BUILT_IN, NULL, NULL_TREE);
6025     }
6026
6027   /* Look up the pointer to the runtime java.lang.Class object for `instance'.
6028      This is the first entry in the vtable.  */
6029   klass_ref = build_vtbl_ref (cp_build_indirect_ref (instance, RO_NULL, 
6030                                                      tf_warning_or_error),
6031                               integer_zero_node);
6032
6033   /* Get the java.lang.Class pointer for the interface being called.  */
6034   iface = DECL_CONTEXT (fn);
6035   iface_ref = lookup_field (iface, get_identifier ("class$"), 0, false);
6036   if (!iface_ref || TREE_CODE (iface_ref) != VAR_DECL
6037       || DECL_CONTEXT (iface_ref) != iface)
6038     {
6039       error ("could not find class$ field in java interface type %qT",
6040                 iface);
6041       return error_mark_node;
6042     }
6043   iface_ref = build_address (iface_ref);
6044   iface_ref = convert (build_pointer_type (iface), iface_ref);
6045
6046   /* Determine the itable index of FN.  */
6047   i = 1;
6048   for (method = TYPE_METHODS (iface); method; method = TREE_CHAIN (method))
6049     {
6050       if (!DECL_VIRTUAL_P (method))
6051         continue;
6052       if (fn == method)
6053         break;
6054       i++;
6055     }
6056   idx = build_int_cst (NULL_TREE, i);
6057
6058   lookup_fn = build1 (ADDR_EXPR,
6059                       build_pointer_type (TREE_TYPE (java_iface_lookup_fn)),
6060                       java_iface_lookup_fn);
6061   return build_call_nary (ptr_type_node, lookup_fn,
6062                           3, klass_ref, iface_ref, idx);
6063 }
6064
6065 /* Returns the value to use for the in-charge parameter when making a
6066    call to a function with the indicated NAME.
6067
6068    FIXME:Can't we find a neater way to do this mapping?  */
6069
6070 tree
6071 in_charge_arg_for_name (tree name)
6072 {
6073  if (name == base_ctor_identifier
6074       || name == base_dtor_identifier)
6075     return integer_zero_node;
6076   else if (name == complete_ctor_identifier)
6077     return integer_one_node;
6078   else if (name == complete_dtor_identifier)
6079     return integer_two_node;
6080   else if (name == deleting_dtor_identifier)
6081     return integer_three_node;
6082
6083   /* This function should only be called with one of the names listed
6084      above.  */
6085   gcc_unreachable ();
6086   return NULL_TREE;
6087 }
6088
6089 /* Build a call to a constructor, destructor, or an assignment
6090    operator for INSTANCE, an expression with class type.  NAME
6091    indicates the special member function to call; *ARGS are the
6092    arguments.  ARGS may be NULL.  This may change ARGS.  BINFO
6093    indicates the base of INSTANCE that is to be passed as the `this'
6094    parameter to the member function called.
6095
6096    FLAGS are the LOOKUP_* flags to use when processing the call.
6097
6098    If NAME indicates a complete object constructor, INSTANCE may be
6099    NULL_TREE.  In this case, the caller will call build_cplus_new to
6100    store the newly constructed object into a VAR_DECL.  */
6101
6102 tree
6103 build_special_member_call (tree instance, tree name, VEC(tree,gc) **args,
6104                            tree binfo, int flags, tsubst_flags_t complain)
6105 {
6106   tree fns;
6107   /* The type of the subobject to be constructed or destroyed.  */
6108   tree class_type;
6109   VEC(tree,gc) *allocated = NULL;
6110   tree ret;
6111
6112   gcc_assert (name == complete_ctor_identifier
6113               || name == base_ctor_identifier
6114               || name == complete_dtor_identifier
6115               || name == base_dtor_identifier
6116               || name == deleting_dtor_identifier
6117               || name == ansi_assopname (NOP_EXPR));
6118   if (TYPE_P (binfo))
6119     {
6120       /* Resolve the name.  */
6121       if (!complete_type_or_else (binfo, NULL_TREE))
6122         return error_mark_node;
6123
6124       binfo = TYPE_BINFO (binfo);
6125     }
6126
6127   gcc_assert (binfo != NULL_TREE);
6128
6129   class_type = BINFO_TYPE (binfo);
6130
6131   /* Handle the special case where INSTANCE is NULL_TREE.  */
6132   if (name == complete_ctor_identifier && !instance)
6133     {
6134       instance = build_int_cst (build_pointer_type (class_type), 0);
6135       instance = build1 (INDIRECT_REF, class_type, instance);
6136     }
6137   else
6138     {
6139       if (name == complete_dtor_identifier
6140           || name == base_dtor_identifier
6141           || name == deleting_dtor_identifier)
6142         gcc_assert (args == NULL || VEC_empty (tree, *args));
6143
6144       /* Convert to the base class, if necessary.  */
6145       if (!same_type_ignoring_top_level_qualifiers_p
6146           (TREE_TYPE (instance), BINFO_TYPE (binfo)))
6147         {
6148           if (name != ansi_assopname (NOP_EXPR))
6149             /* For constructors and destructors, either the base is
6150                non-virtual, or it is virtual but we are doing the
6151                conversion from a constructor or destructor for the
6152                complete object.  In either case, we can convert
6153                statically.  */
6154             instance = convert_to_base_statically (instance, binfo);
6155           else
6156             /* However, for assignment operators, we must convert
6157                dynamically if the base is virtual.  */
6158             instance = build_base_path (PLUS_EXPR, instance,
6159                                         binfo, /*nonnull=*/1);
6160         }
6161     }
6162
6163   gcc_assert (instance != NULL_TREE);
6164
6165   fns = lookup_fnfields (binfo, name, 1);
6166
6167   /* When making a call to a constructor or destructor for a subobject
6168      that uses virtual base classes, pass down a pointer to a VTT for
6169      the subobject.  */
6170   if ((name == base_ctor_identifier
6171        || name == base_dtor_identifier)
6172       && CLASSTYPE_VBASECLASSES (class_type))
6173     {
6174       tree vtt;
6175       tree sub_vtt;
6176
6177       /* If the current function is a complete object constructor
6178          or destructor, then we fetch the VTT directly.
6179          Otherwise, we look it up using the VTT we were given.  */
6180       vtt = TREE_CHAIN (CLASSTYPE_VTABLES (current_class_type));
6181       vtt = decay_conversion (vtt);
6182       vtt = build3 (COND_EXPR, TREE_TYPE (vtt),
6183                     build2 (EQ_EXPR, boolean_type_node,
6184                             current_in_charge_parm, integer_zero_node),
6185                     current_vtt_parm,
6186                     vtt);
6187       gcc_assert (BINFO_SUBVTT_INDEX (binfo));
6188       sub_vtt = build2 (POINTER_PLUS_EXPR, TREE_TYPE (vtt), vtt,
6189                         BINFO_SUBVTT_INDEX (binfo));
6190
6191       if (args == NULL)
6192         {
6193           allocated = make_tree_vector ();
6194           args = &allocated;
6195         }
6196
6197       VEC_safe_insert (tree, gc, *args, 0, sub_vtt);
6198     }
6199
6200   ret = build_new_method_call (instance, fns, args,
6201                                TYPE_BINFO (BINFO_TYPE (binfo)),
6202                                flags, /*fn=*/NULL,
6203                                complain);
6204
6205   if (allocated != NULL)
6206     release_tree_vector (allocated);
6207
6208   return ret;
6209 }
6210
6211 /* Return the NAME, as a C string.  The NAME indicates a function that
6212    is a member of TYPE.  *FREE_P is set to true if the caller must
6213    free the memory returned.
6214
6215    Rather than go through all of this, we should simply set the names
6216    of constructors and destructors appropriately, and dispense with
6217    ctor_identifier, dtor_identifier, etc.  */
6218
6219 static char *
6220 name_as_c_string (tree name, tree type, bool *free_p)
6221 {
6222   char *pretty_name;
6223
6224   /* Assume that we will not allocate memory.  */
6225   *free_p = false;
6226   /* Constructors and destructors are special.  */
6227   if (IDENTIFIER_CTOR_OR_DTOR_P (name))
6228     {
6229       pretty_name
6230         = CONST_CAST (char *, identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type))));
6231       /* For a destructor, add the '~'.  */
6232       if (name == complete_dtor_identifier
6233           || name == base_dtor_identifier
6234           || name == deleting_dtor_identifier)
6235         {
6236           pretty_name = concat ("~", pretty_name, NULL);
6237           /* Remember that we need to free the memory allocated.  */
6238           *free_p = true;
6239         }
6240     }
6241   else if (IDENTIFIER_TYPENAME_P (name))
6242     {
6243       pretty_name = concat ("operator ",
6244                             type_as_string_translate (TREE_TYPE (name),
6245                                                       TFF_PLAIN_IDENTIFIER),
6246                             NULL);
6247       /* Remember that we need to free the memory allocated.  */
6248       *free_p = true;
6249     }
6250   else
6251     pretty_name = CONST_CAST (char *, identifier_to_locale (IDENTIFIER_POINTER (name)));
6252
6253   return pretty_name;
6254 }
6255
6256 /* Build a call to "INSTANCE.FN (ARGS)".  If FN_P is non-NULL, it will
6257    be set, upon return, to the function called.  ARGS may be NULL.
6258    This may change ARGS.  */
6259
6260 tree
6261 build_new_method_call (tree instance, tree fns, VEC(tree,gc) **args,
6262                        tree conversion_path, int flags,
6263                        tree *fn_p, tsubst_flags_t complain)
6264 {
6265   struct z_candidate *candidates = 0, *cand;
6266   tree explicit_targs = NULL_TREE;
6267   tree basetype = NULL_TREE;
6268   tree access_binfo;
6269   tree optype;
6270   tree first_mem_arg = NULL_TREE;
6271   tree instance_ptr;
6272   tree name;
6273   bool skip_first_for_error;
6274   VEC(tree,gc) *user_args;
6275   tree call;
6276   tree fn;
6277   int template_only = 0;
6278   bool any_viable_p;
6279   tree orig_instance;
6280   tree orig_fns;
6281   VEC(tree,gc) *orig_args = NULL;
6282   void *p;
6283
6284   gcc_assert (instance != NULL_TREE);
6285
6286   /* We don't know what function we're going to call, yet.  */
6287   if (fn_p)
6288     *fn_p = NULL_TREE;
6289
6290   if (error_operand_p (instance)
6291       || !fns || error_operand_p (fns))
6292     return error_mark_node;
6293
6294   if (!BASELINK_P (fns))
6295     {
6296       if (complain & tf_error)
6297         error ("call to non-function %qD", fns);
6298       return error_mark_node;
6299     }
6300
6301   orig_instance = instance;
6302   orig_fns = fns;
6303
6304   /* Dismantle the baselink to collect all the information we need.  */
6305   if (!conversion_path)
6306     conversion_path = BASELINK_BINFO (fns);
6307   access_binfo = BASELINK_ACCESS_BINFO (fns);
6308   optype = BASELINK_OPTYPE (fns);
6309   fns = BASELINK_FUNCTIONS (fns);
6310   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
6311     {
6312       explicit_targs = TREE_OPERAND (fns, 1);
6313       fns = TREE_OPERAND (fns, 0);
6314       template_only = 1;
6315     }
6316   gcc_assert (TREE_CODE (fns) == FUNCTION_DECL
6317               || TREE_CODE (fns) == TEMPLATE_DECL
6318               || TREE_CODE (fns) == OVERLOAD);
6319   fn = get_first_fn (fns);
6320   name = DECL_NAME (fn);
6321
6322   basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
6323   gcc_assert (CLASS_TYPE_P (basetype));
6324
6325   if (processing_template_decl)
6326     {
6327       orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
6328       instance = build_non_dependent_expr (instance);
6329       if (args != NULL)
6330         make_args_non_dependent (*args);
6331     }
6332
6333   user_args = args == NULL ? NULL : *args;
6334   /* Under DR 147 A::A() is an invalid constructor call,
6335      not a functional cast.  */
6336   if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
6337     {
6338       if (! (complain & tf_error))
6339         return error_mark_node;
6340
6341       permerror (input_location,
6342                  "cannot call constructor %<%T::%D%> directly",
6343                  basetype, name);
6344       permerror (input_location, "  for a function-style cast, remove the "
6345                  "redundant %<::%D%>", name);
6346       call = build_functional_cast (basetype, build_tree_list_vec (user_args),
6347                                     complain);
6348       return call;
6349     }
6350
6351   /* Figure out whether to skip the first argument for the error
6352      message we will display to users if an error occurs.  We don't
6353      want to display any compiler-generated arguments.  The "this"
6354      pointer hasn't been added yet.  However, we must remove the VTT
6355      pointer if this is a call to a base-class constructor or
6356      destructor.  */
6357   skip_first_for_error = false;
6358   if (IDENTIFIER_CTOR_OR_DTOR_P (name))
6359     {
6360       /* Callers should explicitly indicate whether they want to construct
6361          the complete object or just the part without virtual bases.  */
6362       gcc_assert (name != ctor_identifier);
6363       /* Similarly for destructors.  */
6364       gcc_assert (name != dtor_identifier);
6365       /* Remove the VTT pointer, if present.  */
6366       if ((name == base_ctor_identifier || name == base_dtor_identifier)
6367           && CLASSTYPE_VBASECLASSES (basetype))
6368         skip_first_for_error = true;
6369     }
6370
6371   /* Process the argument list.  */
6372   if (args != NULL && *args != NULL)
6373     {
6374       *args = resolve_args (*args);
6375       if (*args == NULL)
6376         return error_mark_node;
6377     }
6378
6379   instance_ptr = build_this (instance);
6380
6381   /* It's OK to call destructors and constructors on cv-qualified objects.
6382      Therefore, convert the INSTANCE_PTR to the unqualified type, if
6383      necessary.  */
6384   if (DECL_DESTRUCTOR_P (fn)
6385       || DECL_CONSTRUCTOR_P (fn))
6386     {
6387       tree type = build_pointer_type (basetype);
6388       if (!same_type_p (type, TREE_TYPE (instance_ptr)))
6389         instance_ptr = build_nop (type, instance_ptr);
6390     }
6391   if (DECL_DESTRUCTOR_P (fn))
6392     name = complete_dtor_identifier;
6393
6394   first_mem_arg = instance_ptr;
6395
6396   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
6397   p = conversion_obstack_alloc (0);
6398
6399   /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
6400      initializer, not T({ }).  */
6401   if (DECL_CONSTRUCTOR_P (fn) && args != NULL && !VEC_empty (tree, *args)
6402       && BRACE_ENCLOSED_INITIALIZER_P (VEC_index (tree, *args, 0))
6403       && CONSTRUCTOR_IS_DIRECT_INIT (VEC_index (tree, *args, 0)))
6404     {
6405       gcc_assert (VEC_length (tree, *args) == 1
6406                   && !(flags & LOOKUP_ONLYCONVERTING));
6407
6408       add_list_candidates (fns, first_mem_arg, VEC_index (tree, *args, 0),
6409                            basetype, explicit_targs, template_only,
6410                            conversion_path, access_binfo, flags, &candidates);
6411     }
6412   else
6413     {
6414       add_candidates (fns, first_mem_arg, user_args, optype,
6415                       explicit_targs, template_only, conversion_path,
6416                       access_binfo, flags, &candidates);
6417     }
6418   any_viable_p = false;
6419   candidates = splice_viable (candidates, pedantic, &any_viable_p);
6420
6421   if (!any_viable_p)
6422     {
6423       if (complain & tf_error)
6424         {
6425           if (!COMPLETE_TYPE_P (basetype))
6426             cxx_incomplete_type_error (instance_ptr, basetype);
6427           else if (optype)
6428             error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
6429                    basetype, optype, build_tree_list_vec (user_args),
6430                    TREE_TYPE (TREE_TYPE (instance_ptr)));
6431           else
6432             {
6433               char *pretty_name;
6434               bool free_p;
6435               tree arglist;
6436
6437               pretty_name = name_as_c_string (name, basetype, &free_p);
6438               arglist = build_tree_list_vec (user_args);
6439               if (skip_first_for_error)
6440                 arglist = TREE_CHAIN (arglist);
6441               error ("no matching function for call to %<%T::%s(%A)%#V%>",
6442                      basetype, pretty_name, arglist,
6443                      TREE_TYPE (TREE_TYPE (instance_ptr)));
6444               if (free_p)
6445                 free (pretty_name);
6446             }
6447           print_z_candidates (candidates);
6448         }
6449       call = error_mark_node;
6450     }
6451   else
6452     {
6453       cand = tourney (candidates);
6454       if (cand == 0)
6455         {
6456           char *pretty_name;
6457           bool free_p;
6458           tree arglist;
6459
6460           if (complain & tf_error)
6461             {
6462               pretty_name = name_as_c_string (name, basetype, &free_p);
6463               arglist = build_tree_list_vec (user_args);
6464               if (skip_first_for_error)
6465                 arglist = TREE_CHAIN (arglist);
6466               error ("call of overloaded %<%s(%A)%> is ambiguous", pretty_name,
6467                      arglist);
6468               print_z_candidates (candidates);
6469               if (free_p)
6470                 free (pretty_name);
6471             }
6472           call = error_mark_node;
6473         }
6474       else
6475         {
6476           fn = cand->fn;
6477
6478           if (!(flags & LOOKUP_NONVIRTUAL)
6479               && DECL_PURE_VIRTUAL_P (fn)
6480               && instance == current_class_ref
6481               && (DECL_CONSTRUCTOR_P (current_function_decl)
6482                   || DECL_DESTRUCTOR_P (current_function_decl))
6483               && (complain & tf_warning))
6484             /* This is not an error, it is runtime undefined
6485                behavior.  */
6486             warning (0, (DECL_CONSTRUCTOR_P (current_function_decl) ?
6487                       "pure virtual %q#D called from constructor"
6488                       : "pure virtual %q#D called from destructor"),
6489                      fn);
6490
6491           if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
6492               && is_dummy_object (instance_ptr))
6493             {
6494               if (complain & tf_error)
6495                 error ("cannot call member function %qD without object",
6496                        fn);
6497               call = error_mark_node;
6498             }
6499           else
6500             {
6501               if (DECL_VINDEX (fn) && ! (flags & LOOKUP_NONVIRTUAL)
6502                   && resolves_to_fixed_type_p (instance, 0))
6503                 flags |= LOOKUP_NONVIRTUAL;
6504               /* Now we know what function is being called.  */
6505               if (fn_p)
6506                 *fn_p = fn;
6507               /* Build the actual CALL_EXPR.  */
6508               call = build_over_call (cand, flags, complain);
6509               /* In an expression of the form `a->f()' where `f' turns
6510                  out to be a static member function, `a' is
6511                  none-the-less evaluated.  */
6512               if (TREE_CODE (TREE_TYPE (fn)) != METHOD_TYPE
6513                   && !is_dummy_object (instance_ptr)
6514                   && TREE_SIDE_EFFECTS (instance_ptr))
6515                 call = build2 (COMPOUND_EXPR, TREE_TYPE (call),
6516                                instance_ptr, call);
6517               else if (call != error_mark_node
6518                        && DECL_DESTRUCTOR_P (cand->fn)
6519                        && !VOID_TYPE_P (TREE_TYPE (call)))
6520                 /* An explicit call of the form "x->~X()" has type
6521                    "void".  However, on platforms where destructors
6522                    return "this" (i.e., those where
6523                    targetm.cxx.cdtor_returns_this is true), such calls
6524                    will appear to have a return value of pointer type
6525                    to the low-level call machinery.  We do not want to
6526                    change the low-level machinery, since we want to be
6527                    able to optimize "delete f()" on such platforms as
6528                    "operator delete(~X(f()))" (rather than generating
6529                    "t = f(), ~X(t), operator delete (t)").  */
6530                 call = build_nop (void_type_node, call);
6531             }
6532         }
6533     }
6534
6535   if (processing_template_decl && call != error_mark_node)
6536     {
6537       bool cast_to_void = false;
6538
6539       if (TREE_CODE (call) == COMPOUND_EXPR)
6540         call = TREE_OPERAND (call, 1);
6541       else if (TREE_CODE (call) == NOP_EXPR)
6542         {
6543           cast_to_void = true;
6544           call = TREE_OPERAND (call, 0);
6545         }
6546       if (TREE_CODE (call) == INDIRECT_REF)
6547         call = TREE_OPERAND (call, 0);
6548       call = (build_min_non_dep_call_vec
6549               (call,
6550                build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
6551                           orig_instance, orig_fns, NULL_TREE),
6552                orig_args));
6553       call = convert_from_reference (call);
6554       if (cast_to_void)
6555         call = build_nop (void_type_node, call);
6556     }
6557
6558  /* Free all the conversions we allocated.  */
6559   obstack_free (&conversion_obstack, p);
6560
6561   if (orig_args != NULL)
6562     release_tree_vector (orig_args);
6563
6564   return call;
6565 }
6566
6567 /* Returns true iff standard conversion sequence ICS1 is a proper
6568    subsequence of ICS2.  */
6569
6570 static bool
6571 is_subseq (conversion *ics1, conversion *ics2)
6572 {
6573   /* We can assume that a conversion of the same code
6574      between the same types indicates a subsequence since we only get
6575      here if the types we are converting from are the same.  */
6576
6577   while (ics1->kind == ck_rvalue
6578          || ics1->kind == ck_lvalue)
6579     ics1 = ics1->u.next;
6580
6581   while (1)
6582     {
6583       while (ics2->kind == ck_rvalue
6584              || ics2->kind == ck_lvalue)
6585         ics2 = ics2->u.next;
6586
6587       if (ics2->kind == ck_user
6588           || ics2->kind == ck_ambig
6589           || ics2->kind == ck_aggr
6590           || ics2->kind == ck_list
6591           || ics2->kind == ck_identity)
6592         /* At this point, ICS1 cannot be a proper subsequence of
6593            ICS2.  We can get a USER_CONV when we are comparing the
6594            second standard conversion sequence of two user conversion
6595            sequences.  */
6596         return false;
6597
6598       ics2 = ics2->u.next;
6599
6600       if (ics2->kind == ics1->kind
6601           && same_type_p (ics2->type, ics1->type)
6602           && same_type_p (ics2->u.next->type,
6603                           ics1->u.next->type))
6604         return true;
6605     }
6606 }
6607
6608 /* Returns nonzero iff DERIVED is derived from BASE.  The inputs may
6609    be any _TYPE nodes.  */
6610
6611 bool
6612 is_properly_derived_from (tree derived, tree base)
6613 {
6614   if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
6615     return false;
6616
6617   /* We only allow proper derivation here.  The DERIVED_FROM_P macro
6618      considers every class derived from itself.  */
6619   return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
6620           && DERIVED_FROM_P (base, derived));
6621 }
6622
6623 /* We build the ICS for an implicit object parameter as a pointer
6624    conversion sequence.  However, such a sequence should be compared
6625    as if it were a reference conversion sequence.  If ICS is the
6626    implicit conversion sequence for an implicit object parameter,
6627    modify it accordingly.  */
6628
6629 static void
6630 maybe_handle_implicit_object (conversion **ics)
6631 {
6632   if ((*ics)->this_p)
6633     {
6634       /* [over.match.funcs]
6635
6636          For non-static member functions, the type of the
6637          implicit object parameter is "reference to cv X"
6638          where X is the class of which the function is a
6639          member and cv is the cv-qualification on the member
6640          function declaration.  */
6641       conversion *t = *ics;
6642       tree reference_type;
6643
6644       /* The `this' parameter is a pointer to a class type.  Make the
6645          implicit conversion talk about a reference to that same class
6646          type.  */
6647       reference_type = TREE_TYPE (t->type);
6648       reference_type = build_reference_type (reference_type);
6649
6650       if (t->kind == ck_qual)
6651         t = t->u.next;
6652       if (t->kind == ck_ptr)
6653         t = t->u.next;
6654       t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
6655       t = direct_reference_binding (reference_type, t);
6656       t->this_p = 1;
6657       t->rvaluedness_matches_p = 0;
6658       *ics = t;
6659     }
6660 }
6661
6662 /* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
6663    and return the initial reference binding conversion. Otherwise,
6664    leave *ICS unchanged and return NULL.  */
6665
6666 static conversion *
6667 maybe_handle_ref_bind (conversion **ics)
6668 {
6669   if ((*ics)->kind == ck_ref_bind)
6670     {
6671       conversion *old_ics = *ics;
6672       *ics = old_ics->u.next;
6673       (*ics)->user_conv_p = old_ics->user_conv_p;
6674       return old_ics;
6675     }
6676
6677   return NULL;
6678 }
6679
6680 /* Compare two implicit conversion sequences according to the rules set out in
6681    [over.ics.rank].  Return values:
6682
6683       1: ics1 is better than ics2
6684      -1: ics2 is better than ics1
6685       0: ics1 and ics2 are indistinguishable */
6686
6687 static int
6688 compare_ics (conversion *ics1, conversion *ics2)
6689 {
6690   tree from_type1;
6691   tree from_type2;
6692   tree to_type1;
6693   tree to_type2;
6694   tree deref_from_type1 = NULL_TREE;
6695   tree deref_from_type2 = NULL_TREE;
6696   tree deref_to_type1 = NULL_TREE;
6697   tree deref_to_type2 = NULL_TREE;
6698   conversion_rank rank1, rank2;
6699
6700   /* REF_BINDING is nonzero if the result of the conversion sequence
6701      is a reference type.   In that case REF_CONV is the reference
6702      binding conversion. */
6703   conversion *ref_conv1;
6704   conversion *ref_conv2;
6705
6706   /* Handle implicit object parameters.  */
6707   maybe_handle_implicit_object (&ics1);
6708   maybe_handle_implicit_object (&ics2);
6709
6710   /* Handle reference parameters.  */
6711   ref_conv1 = maybe_handle_ref_bind (&ics1);
6712   ref_conv2 = maybe_handle_ref_bind (&ics2);
6713
6714   /* List-initialization sequence L1 is a better conversion sequence than
6715      list-initialization sequence L2 if L1 converts to
6716      std::initializer_list<X> for some X and L2 does not.  */
6717   if (ics1->kind == ck_list && ics2->kind != ck_list)
6718     return 1;
6719   if (ics2->kind == ck_list && ics1->kind != ck_list)
6720     return -1;
6721
6722   /* [over.ics.rank]
6723
6724      When  comparing  the  basic forms of implicit conversion sequences (as
6725      defined in _over.best.ics_)
6726
6727      --a standard conversion sequence (_over.ics.scs_) is a better
6728        conversion sequence than a user-defined conversion sequence
6729        or an ellipsis conversion sequence, and
6730
6731      --a user-defined conversion sequence (_over.ics.user_) is a
6732        better conversion sequence than an ellipsis conversion sequence
6733        (_over.ics.ellipsis_).  */
6734   rank1 = CONVERSION_RANK (ics1);
6735   rank2 = CONVERSION_RANK (ics2);
6736
6737   if (rank1 > rank2)
6738     return -1;
6739   else if (rank1 < rank2)
6740     return 1;
6741
6742   if (rank1 == cr_bad)
6743     {
6744       /* XXX Isn't this an extension? */
6745       /* Both ICS are bad.  We try to make a decision based on what
6746          would have happened if they'd been good.  */
6747       if (ics1->user_conv_p > ics2->user_conv_p
6748           || ics1->rank  > ics2->rank)
6749         return -1;
6750       else if (ics1->user_conv_p < ics2->user_conv_p
6751                || ics1->rank < ics2->rank)
6752         return 1;
6753
6754       /* We couldn't make up our minds; try to figure it out below.  */
6755     }
6756
6757   if (ics1->ellipsis_p || ics1->kind == ck_list)
6758     /* Both conversions are ellipsis conversions or both are building a
6759        std::initializer_list.  */
6760     return 0;
6761
6762   /* User-defined  conversion sequence U1 is a better conversion sequence
6763      than another user-defined conversion sequence U2 if they contain the
6764      same user-defined conversion operator or constructor and if the sec-
6765      ond standard conversion sequence of U1 is  better  than  the  second
6766      standard conversion sequence of U2.  */
6767
6768   if (ics1->user_conv_p)
6769     {
6770       conversion *t1;
6771       conversion *t2;
6772
6773       for (t1 = ics1; t1->kind != ck_user; t1 = t1->u.next)
6774         if (t1->kind == ck_ambig || t1->kind == ck_aggr)
6775           break;
6776       for (t2 = ics2; t2->kind != ck_user; t2 = t2->u.next)
6777         if (t2->kind == ck_ambig || t2->kind == ck_aggr)
6778           break;
6779
6780       if (t1->kind != t2->kind)
6781         return 0;
6782       else if (t1->kind == ck_user)
6783         {
6784           if (t1->cand->fn != t2->cand->fn)
6785             return 0;
6786         }
6787       else
6788         {
6789           /* For ambiguous or aggregate conversions, use the target type as
6790              a proxy for the conversion function.  */
6791           if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
6792             return 0;
6793         }
6794
6795       /* We can just fall through here, after setting up
6796          FROM_TYPE1 and FROM_TYPE2.  */
6797       from_type1 = t1->type;
6798       from_type2 = t2->type;
6799     }
6800   else
6801     {
6802       conversion *t1;
6803       conversion *t2;
6804
6805       /* We're dealing with two standard conversion sequences.
6806
6807          [over.ics.rank]
6808
6809          Standard conversion sequence S1 is a better conversion
6810          sequence than standard conversion sequence S2 if
6811
6812          --S1 is a proper subsequence of S2 (comparing the conversion
6813            sequences in the canonical form defined by _over.ics.scs_,
6814            excluding any Lvalue Transformation; the identity
6815            conversion sequence is considered to be a subsequence of
6816            any non-identity conversion sequence */
6817
6818       t1 = ics1;
6819       while (t1->kind != ck_identity)
6820         t1 = t1->u.next;
6821       from_type1 = t1->type;
6822
6823       t2 = ics2;
6824       while (t2->kind != ck_identity)
6825         t2 = t2->u.next;
6826       from_type2 = t2->type;
6827     }
6828
6829   /* One sequence can only be a subsequence of the other if they start with
6830      the same type.  They can start with different types when comparing the
6831      second standard conversion sequence in two user-defined conversion
6832      sequences.  */
6833   if (same_type_p (from_type1, from_type2))
6834     {
6835       if (is_subseq (ics1, ics2))
6836         return 1;
6837       if (is_subseq (ics2, ics1))
6838         return -1;
6839     }
6840
6841   /* [over.ics.rank]
6842
6843      Or, if not that,
6844
6845      --the rank of S1 is better than the rank of S2 (by the rules
6846        defined below):
6847
6848     Standard conversion sequences are ordered by their ranks: an Exact
6849     Match is a better conversion than a Promotion, which is a better
6850     conversion than a Conversion.
6851
6852     Two conversion sequences with the same rank are indistinguishable
6853     unless one of the following rules applies:
6854
6855     --A conversion that does not a convert a pointer, pointer to member,
6856       or std::nullptr_t to bool is better than one that does.
6857
6858     The ICS_STD_RANK automatically handles the pointer-to-bool rule,
6859     so that we do not have to check it explicitly.  */
6860   if (ics1->rank < ics2->rank)
6861     return 1;
6862   else if (ics2->rank < ics1->rank)
6863     return -1;
6864
6865   to_type1 = ics1->type;
6866   to_type2 = ics2->type;
6867
6868   /* A conversion from scalar arithmetic type to complex is worse than a
6869      conversion between scalar arithmetic types.  */
6870   if (same_type_p (from_type1, from_type2)
6871       && ARITHMETIC_TYPE_P (from_type1)
6872       && ARITHMETIC_TYPE_P (to_type1)
6873       && ARITHMETIC_TYPE_P (to_type2)
6874       && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
6875           != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
6876     {
6877       if (TREE_CODE (to_type1) == COMPLEX_TYPE)
6878         return -1;
6879       else
6880         return 1;
6881     }
6882
6883   if (TYPE_PTR_P (from_type1)
6884       && TYPE_PTR_P (from_type2)
6885       && TYPE_PTR_P (to_type1)
6886       && TYPE_PTR_P (to_type2))
6887     {
6888       deref_from_type1 = TREE_TYPE (from_type1);
6889       deref_from_type2 = TREE_TYPE (from_type2);
6890       deref_to_type1 = TREE_TYPE (to_type1);
6891       deref_to_type2 = TREE_TYPE (to_type2);
6892     }
6893   /* The rules for pointers to members A::* are just like the rules
6894      for pointers A*, except opposite: if B is derived from A then
6895      A::* converts to B::*, not vice versa.  For that reason, we
6896      switch the from_ and to_ variables here.  */
6897   else if ((TYPE_PTRMEM_P (from_type1) && TYPE_PTRMEM_P (from_type2)
6898             && TYPE_PTRMEM_P (to_type1) && TYPE_PTRMEM_P (to_type2))
6899            || (TYPE_PTRMEMFUNC_P (from_type1)
6900                && TYPE_PTRMEMFUNC_P (from_type2)
6901                && TYPE_PTRMEMFUNC_P (to_type1)
6902                && TYPE_PTRMEMFUNC_P (to_type2)))
6903     {
6904       deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
6905       deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
6906       deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
6907       deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
6908     }
6909
6910   if (deref_from_type1 != NULL_TREE
6911       && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
6912       && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
6913     {
6914       /* This was one of the pointer or pointer-like conversions.
6915
6916          [over.ics.rank]
6917
6918          --If class B is derived directly or indirectly from class A,
6919            conversion of B* to A* is better than conversion of B* to
6920            void*, and conversion of A* to void* is better than
6921            conversion of B* to void*.  */
6922       if (TREE_CODE (deref_to_type1) == VOID_TYPE
6923           && TREE_CODE (deref_to_type2) == VOID_TYPE)
6924         {
6925           if (is_properly_derived_from (deref_from_type1,
6926                                         deref_from_type2))
6927             return -1;
6928           else if (is_properly_derived_from (deref_from_type2,
6929                                              deref_from_type1))
6930             return 1;
6931         }
6932       else if (TREE_CODE (deref_to_type1) == VOID_TYPE
6933                || TREE_CODE (deref_to_type2) == VOID_TYPE)
6934         {
6935           if (same_type_p (deref_from_type1, deref_from_type2))
6936             {
6937               if (TREE_CODE (deref_to_type2) == VOID_TYPE)
6938                 {
6939                   if (is_properly_derived_from (deref_from_type1,
6940                                                 deref_to_type1))
6941                     return 1;
6942                 }
6943               /* We know that DEREF_TO_TYPE1 is `void' here.  */
6944               else if (is_properly_derived_from (deref_from_type1,
6945                                                  deref_to_type2))
6946                 return -1;
6947             }
6948         }
6949       else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
6950                && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
6951         {
6952           /* [over.ics.rank]
6953
6954              --If class B is derived directly or indirectly from class A
6955                and class C is derived directly or indirectly from B,
6956
6957              --conversion of C* to B* is better than conversion of C* to
6958                A*,
6959
6960              --conversion of B* to A* is better than conversion of C* to
6961                A*  */
6962           if (same_type_p (deref_from_type1, deref_from_type2))
6963             {
6964               if (is_properly_derived_from (deref_to_type1,
6965                                             deref_to_type2))
6966                 return 1;
6967               else if (is_properly_derived_from (deref_to_type2,
6968                                                  deref_to_type1))
6969                 return -1;
6970             }
6971           else if (same_type_p (deref_to_type1, deref_to_type2))
6972             {
6973               if (is_properly_derived_from (deref_from_type2,
6974                                             deref_from_type1))
6975                 return 1;
6976               else if (is_properly_derived_from (deref_from_type1,
6977                                                  deref_from_type2))
6978                 return -1;
6979             }
6980         }
6981     }
6982   else if (CLASS_TYPE_P (non_reference (from_type1))
6983            && same_type_p (from_type1, from_type2))
6984     {
6985       tree from = non_reference (from_type1);
6986
6987       /* [over.ics.rank]
6988
6989          --binding of an expression of type C to a reference of type
6990            B& is better than binding an expression of type C to a
6991            reference of type A&
6992
6993          --conversion of C to B is better than conversion of C to A,  */
6994       if (is_properly_derived_from (from, to_type1)
6995           && is_properly_derived_from (from, to_type2))
6996         {
6997           if (is_properly_derived_from (to_type1, to_type2))
6998             return 1;
6999           else if (is_properly_derived_from (to_type2, to_type1))
7000             return -1;
7001         }
7002     }
7003   else if (CLASS_TYPE_P (non_reference (to_type1))
7004            && same_type_p (to_type1, to_type2))
7005     {
7006       tree to = non_reference (to_type1);
7007
7008       /* [over.ics.rank]
7009
7010          --binding of an expression of type B to a reference of type
7011            A& is better than binding an expression of type C to a
7012            reference of type A&,
7013
7014          --conversion of B to A is better than conversion of C to A  */
7015       if (is_properly_derived_from (from_type1, to)
7016           && is_properly_derived_from (from_type2, to))
7017         {
7018           if (is_properly_derived_from (from_type2, from_type1))
7019             return 1;
7020           else if (is_properly_derived_from (from_type1, from_type2))
7021             return -1;
7022         }
7023     }
7024
7025   /* [over.ics.rank]
7026
7027      --S1 and S2 differ only in their qualification conversion and  yield
7028        similar  types  T1 and T2 (_conv.qual_), respectively, and the cv-
7029        qualification signature of type T1 is a proper subset of  the  cv-
7030        qualification signature of type T2  */
7031   if (ics1->kind == ck_qual
7032       && ics2->kind == ck_qual
7033       && same_type_p (from_type1, from_type2))
7034     {
7035       int result = comp_cv_qual_signature (to_type1, to_type2);
7036       if (result != 0)
7037         return result;
7038     }
7039
7040   /* [over.ics.rank]
7041
7042      --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
7043      to an implicit object parameter, and either S1 binds an lvalue reference
7044      to an lvalue and S2 binds an rvalue reference or S1 binds an rvalue
7045      reference to an rvalue and S2 binds an lvalue reference
7046      (C++0x draft standard, 13.3.3.2)
7047
7048      --S1 and S2 are reference bindings (_dcl.init.ref_), and the
7049      types to which the references refer are the same type except for
7050      top-level cv-qualifiers, and the type to which the reference
7051      initialized by S2 refers is more cv-qualified than the type to
7052      which the reference initialized by S1 refers */
7053
7054   if (ref_conv1 && ref_conv2)
7055     {
7056       if (!ref_conv1->this_p && !ref_conv2->this_p
7057           && (TYPE_REF_IS_RVALUE (ref_conv1->type)
7058               != TYPE_REF_IS_RVALUE (ref_conv2->type)))
7059         {
7060           if (ref_conv1->rvaluedness_matches_p)
7061             return 1;
7062           if (ref_conv2->rvaluedness_matches_p)
7063             return -1;
7064         }
7065
7066       if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
7067         return comp_cv_qualification (TREE_TYPE (ref_conv2->type),
7068                                       TREE_TYPE (ref_conv1->type));
7069     }
7070
7071   /* Neither conversion sequence is better than the other.  */
7072   return 0;
7073 }
7074
7075 /* The source type for this standard conversion sequence.  */
7076
7077 static tree
7078 source_type (conversion *t)
7079 {
7080   for (;; t = t->u.next)
7081     {
7082       if (t->kind == ck_user
7083           || t->kind == ck_ambig
7084           || t->kind == ck_identity)
7085         return t->type;
7086     }
7087   gcc_unreachable ();
7088 }
7089
7090 /* Note a warning about preferring WINNER to LOSER.  We do this by storing
7091    a pointer to LOSER and re-running joust to produce the warning if WINNER
7092    is actually used.  */
7093
7094 static void
7095 add_warning (struct z_candidate *winner, struct z_candidate *loser)
7096 {
7097   candidate_warning *cw = (candidate_warning *)
7098     conversion_obstack_alloc (sizeof (candidate_warning));
7099   cw->loser = loser;
7100   cw->next = winner->warnings;
7101   winner->warnings = cw;
7102 }
7103
7104 /* Compare two candidates for overloading as described in
7105    [over.match.best].  Return values:
7106
7107       1: cand1 is better than cand2
7108      -1: cand2 is better than cand1
7109       0: cand1 and cand2 are indistinguishable */
7110
7111 static int
7112 joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn)
7113 {
7114   int winner = 0;
7115   int off1 = 0, off2 = 0;
7116   size_t i;
7117   size_t len;
7118
7119   /* Candidates that involve bad conversions are always worse than those
7120      that don't.  */
7121   if (cand1->viable > cand2->viable)
7122     return 1;
7123   if (cand1->viable < cand2->viable)
7124     return -1;
7125
7126   /* If we have two pseudo-candidates for conversions to the same type,
7127      or two candidates for the same function, arbitrarily pick one.  */
7128   if (cand1->fn == cand2->fn
7129       && (IS_TYPE_OR_DECL_P (cand1->fn)))
7130     return 1;
7131
7132   /* a viable function F1
7133      is defined to be a better function than another viable function F2  if
7134      for  all arguments i, ICSi(F1) is not a worse conversion sequence than
7135      ICSi(F2), and then */
7136
7137   /* for some argument j, ICSj(F1) is a better conversion  sequence  than
7138      ICSj(F2) */
7139
7140   /* For comparing static and non-static member functions, we ignore
7141      the implicit object parameter of the non-static function.  The
7142      standard says to pretend that the static function has an object
7143      parm, but that won't work with operator overloading.  */
7144   len = cand1->num_convs;
7145   if (len != cand2->num_convs)
7146     {
7147       int static_1 = DECL_STATIC_FUNCTION_P (cand1->fn);
7148       int static_2 = DECL_STATIC_FUNCTION_P (cand2->fn);
7149
7150       gcc_assert (static_1 != static_2);
7151
7152       if (static_1)
7153         off2 = 1;
7154       else
7155         {
7156           off1 = 1;
7157           --len;
7158         }
7159     }
7160
7161   for (i = 0; i < len; ++i)
7162     {
7163       conversion *t1 = cand1->convs[i + off1];
7164       conversion *t2 = cand2->convs[i + off2];
7165       int comp = compare_ics (t1, t2);
7166
7167       if (comp != 0)
7168         {
7169           if (warn_sign_promo
7170               && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
7171                   == cr_std + cr_promotion)
7172               && t1->kind == ck_std
7173               && t2->kind == ck_std
7174               && TREE_CODE (t1->type) == INTEGER_TYPE
7175               && TREE_CODE (t2->type) == INTEGER_TYPE
7176               && (TYPE_PRECISION (t1->type)
7177                   == TYPE_PRECISION (t2->type))
7178               && (TYPE_UNSIGNED (t1->u.next->type)
7179                   || (TREE_CODE (t1->u.next->type)
7180                       == ENUMERAL_TYPE)))
7181             {
7182               tree type = t1->u.next->type;
7183               tree type1, type2;
7184               struct z_candidate *w, *l;
7185               if (comp > 0)
7186                 type1 = t1->type, type2 = t2->type,
7187                   w = cand1, l = cand2;
7188               else
7189                 type1 = t2->type, type2 = t1->type,
7190                   w = cand2, l = cand1;
7191
7192               if (warn)
7193                 {
7194                   warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
7195                            type, type1, type2);
7196                   warning (OPT_Wsign_promo, "  in call to %qD", w->fn);
7197                 }
7198               else
7199                 add_warning (w, l);
7200             }
7201
7202           if (winner && comp != winner)
7203             {
7204               winner = 0;
7205               goto tweak;
7206             }
7207           winner = comp;
7208         }
7209     }
7210
7211   /* warn about confusing overload resolution for user-defined conversions,
7212      either between a constructor and a conversion op, or between two
7213      conversion ops.  */
7214   if (winner && warn_conversion && cand1->second_conv
7215       && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
7216       && winner != compare_ics (cand1->second_conv, cand2->second_conv))
7217     {
7218       struct z_candidate *w, *l;
7219       bool give_warning = false;
7220
7221       if (winner == 1)
7222         w = cand1, l = cand2;
7223       else
7224         w = cand2, l = cand1;
7225
7226       /* We don't want to complain about `X::operator T1 ()'
7227          beating `X::operator T2 () const', when T2 is a no less
7228          cv-qualified version of T1.  */
7229       if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
7230           && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
7231         {
7232           tree t = TREE_TYPE (TREE_TYPE (l->fn));
7233           tree f = TREE_TYPE (TREE_TYPE (w->fn));
7234
7235           if (TREE_CODE (t) == TREE_CODE (f) && POINTER_TYPE_P (t))
7236             {
7237               t = TREE_TYPE (t);
7238               f = TREE_TYPE (f);
7239             }
7240           if (!comp_ptr_ttypes (t, f))
7241             give_warning = true;
7242         }
7243       else
7244         give_warning = true;
7245
7246       if (!give_warning)
7247         /*NOP*/;
7248       else if (warn)
7249         {
7250           tree source = source_type (w->convs[0]);
7251           if (! DECL_CONSTRUCTOR_P (w->fn))
7252             source = TREE_TYPE (source);
7253           if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
7254               && warning (OPT_Wconversion, "  for conversion from %qT to %qT",
7255                           source, w->second_conv->type)) 
7256             {
7257               inform (input_location, "  because conversion sequence for the argument is better");
7258             }
7259         }
7260       else
7261         add_warning (w, l);
7262     }
7263
7264   if (winner)
7265     return winner;
7266
7267   /* or, if not that,
7268      F1 is a non-template function and F2 is a template function
7269      specialization.  */
7270
7271   if (!cand1->template_decl && cand2->template_decl)
7272     return 1;
7273   else if (cand1->template_decl && !cand2->template_decl)
7274     return -1;
7275
7276   /* or, if not that,
7277      F1 and F2 are template functions and the function template for F1 is
7278      more specialized than the template for F2 according to the partial
7279      ordering rules.  */
7280
7281   if (cand1->template_decl && cand2->template_decl)
7282     {
7283       winner = more_specialized_fn
7284         (TI_TEMPLATE (cand1->template_decl),
7285          TI_TEMPLATE (cand2->template_decl),
7286          /* [temp.func.order]: The presence of unused ellipsis and default
7287             arguments has no effect on the partial ordering of function
7288             templates.   add_function_candidate() will not have
7289             counted the "this" argument for constructors.  */
7290          cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
7291       if (winner)
7292         return winner;
7293     }
7294
7295   /* or, if not that,
7296      the  context  is  an  initialization by user-defined conversion (see
7297      _dcl.init_  and  _over.match.user_)  and  the  standard   conversion
7298      sequence  from  the return type of F1 to the destination type (i.e.,
7299      the type of the entity being initialized)  is  a  better  conversion
7300      sequence  than the standard conversion sequence from the return type
7301      of F2 to the destination type.  */
7302
7303   if (cand1->second_conv)
7304     {
7305       winner = compare_ics (cand1->second_conv, cand2->second_conv);
7306       if (winner)
7307         return winner;
7308     }
7309
7310   /* Check whether we can discard a builtin candidate, either because we
7311      have two identical ones or matching builtin and non-builtin candidates.
7312
7313      (Pedantically in the latter case the builtin which matched the user
7314      function should not be added to the overload set, but we spot it here.
7315
7316      [over.match.oper]
7317      ... the builtin candidates include ...
7318      - do not have the same parameter type list as any non-template
7319        non-member candidate.  */
7320
7321   if (TREE_CODE (cand1->fn) == IDENTIFIER_NODE
7322       || TREE_CODE (cand2->fn) == IDENTIFIER_NODE)
7323     {
7324       for (i = 0; i < len; ++i)
7325         if (!same_type_p (cand1->convs[i]->type,
7326                           cand2->convs[i]->type))
7327           break;
7328       if (i == cand1->num_convs)
7329         {
7330           if (cand1->fn == cand2->fn)
7331             /* Two built-in candidates; arbitrarily pick one.  */
7332             return 1;
7333           else if (TREE_CODE (cand1->fn) == IDENTIFIER_NODE)
7334             /* cand1 is built-in; prefer cand2.  */
7335             return -1;
7336           else
7337             /* cand2 is built-in; prefer cand1.  */
7338             return 1;
7339         }
7340     }
7341
7342   /* If the two function declarations represent the same function (this can
7343      happen with declarations in multiple scopes and arg-dependent lookup),
7344      arbitrarily choose one.  But first make sure the default args we're
7345      using match.  */
7346   if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
7347       && equal_functions (cand1->fn, cand2->fn))
7348     {
7349       tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
7350       tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
7351
7352       gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
7353
7354       for (i = 0; i < len; ++i)
7355         {
7356           /* Don't crash if the fn is variadic.  */
7357           if (!parms1)
7358             break;
7359           parms1 = TREE_CHAIN (parms1);
7360           parms2 = TREE_CHAIN (parms2);
7361         }
7362
7363       if (off1)
7364         parms1 = TREE_CHAIN (parms1);
7365       else if (off2)
7366         parms2 = TREE_CHAIN (parms2);
7367
7368       for (; parms1; ++i)
7369         {
7370           if (!cp_tree_equal (TREE_PURPOSE (parms1),
7371                               TREE_PURPOSE (parms2)))
7372             {
7373               if (warn)
7374                 {
7375                   permerror (input_location, "default argument mismatch in "
7376                              "overload resolution");
7377                   inform (input_location,
7378                           " candidate 1: %q+#F", cand1->fn);
7379                   inform (input_location,
7380                           " candidate 2: %q+#F", cand2->fn);
7381                 }
7382               else
7383                 add_warning (cand1, cand2);
7384               break;
7385             }
7386           parms1 = TREE_CHAIN (parms1);
7387           parms2 = TREE_CHAIN (parms2);
7388         }
7389
7390       return 1;
7391     }
7392
7393 tweak:
7394
7395   /* Extension: If the worst conversion for one candidate is worse than the
7396      worst conversion for the other, take the first.  */
7397   if (!pedantic)
7398     {
7399       conversion_rank rank1 = cr_identity, rank2 = cr_identity;
7400       struct z_candidate *w = 0, *l = 0;
7401
7402       for (i = 0; i < len; ++i)
7403         {
7404           if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
7405             rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
7406           if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
7407             rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
7408         }
7409       if (rank1 < rank2)
7410         winner = 1, w = cand1, l = cand2;
7411       if (rank1 > rank2)
7412         winner = -1, w = cand2, l = cand1;
7413       if (winner)
7414         {
7415           /* Don't choose a deleted function over ambiguity.  */
7416           if (DECL_P (w->fn) && DECL_DELETED_FN (w->fn))
7417             return 0;
7418           if (warn)
7419             {
7420               pedwarn (input_location, 0,
7421               "ISO C++ says that these are ambiguous, even "
7422               "though the worst conversion for the first is better than "
7423               "the worst conversion for the second:");
7424               print_z_candidate (_("candidate 1:"), w);
7425               print_z_candidate (_("candidate 2:"), l);
7426             }
7427           else
7428             add_warning (w, l);
7429           return winner;
7430         }
7431     }
7432
7433   gcc_assert (!winner);
7434   return 0;
7435 }
7436
7437 /* Given a list of candidates for overloading, find the best one, if any.
7438    This algorithm has a worst case of O(2n) (winner is last), and a best
7439    case of O(n/2) (totally ambiguous); much better than a sorting
7440    algorithm.  */
7441
7442 static struct z_candidate *
7443 tourney (struct z_candidate *candidates)
7444 {
7445   struct z_candidate *champ = candidates, *challenger;
7446   int fate;
7447   int champ_compared_to_predecessor = 0;
7448
7449   /* Walk through the list once, comparing each current champ to the next
7450      candidate, knocking out a candidate or two with each comparison.  */
7451
7452   for (challenger = champ->next; challenger; )
7453     {
7454       fate = joust (champ, challenger, 0);
7455       if (fate == 1)
7456         challenger = challenger->next;
7457       else
7458         {
7459           if (fate == 0)
7460             {
7461               champ = challenger->next;
7462               if (champ == 0)
7463                 return NULL;
7464               champ_compared_to_predecessor = 0;
7465             }
7466           else
7467             {
7468               champ = challenger;
7469               champ_compared_to_predecessor = 1;
7470             }
7471
7472           challenger = champ->next;
7473         }
7474     }
7475
7476   /* Make sure the champ is better than all the candidates it hasn't yet
7477      been compared to.  */
7478
7479   for (challenger = candidates;
7480        challenger != champ
7481          && !(champ_compared_to_predecessor && challenger->next == champ);
7482        challenger = challenger->next)
7483     {
7484       fate = joust (champ, challenger, 0);
7485       if (fate != 1)
7486         return NULL;
7487     }
7488
7489   return champ;
7490 }
7491
7492 /* Returns nonzero if things of type FROM can be converted to TO.  */
7493
7494 bool
7495 can_convert (tree to, tree from)
7496 {
7497   return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT);
7498 }
7499
7500 /* Returns nonzero if ARG (of type FROM) can be converted to TO.  */
7501
7502 bool
7503 can_convert_arg (tree to, tree from, tree arg, int flags)
7504 {
7505   conversion *t;
7506   void *p;
7507   bool ok_p;
7508
7509   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
7510   p = conversion_obstack_alloc (0);
7511
7512   t  = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
7513                             flags);
7514   ok_p = (t && !t->bad_p);
7515
7516   /* Free all the conversions we allocated.  */
7517   obstack_free (&conversion_obstack, p);
7518
7519   return ok_p;
7520 }
7521
7522 /* Like can_convert_arg, but allows dubious conversions as well.  */
7523
7524 bool
7525 can_convert_arg_bad (tree to, tree from, tree arg, int flags)
7526 {
7527   conversion *t;
7528   void *p;
7529
7530   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
7531   p = conversion_obstack_alloc (0);
7532   /* Try to perform the conversion.  */
7533   t  = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
7534                             flags);
7535   /* Free all the conversions we allocated.  */
7536   obstack_free (&conversion_obstack, p);
7537
7538   return t != NULL;
7539 }
7540
7541 /* Convert EXPR to TYPE.  Return the converted expression.
7542
7543    Note that we allow bad conversions here because by the time we get to
7544    this point we are committed to doing the conversion.  If we end up
7545    doing a bad conversion, convert_like will complain.  */
7546
7547 tree
7548 perform_implicit_conversion_flags (tree type, tree expr, tsubst_flags_t complain, int flags)
7549 {
7550   conversion *conv;
7551   void *p;
7552
7553   if (error_operand_p (expr))
7554     return error_mark_node;
7555
7556   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
7557   p = conversion_obstack_alloc (0);
7558
7559   conv = implicit_conversion (type, TREE_TYPE (expr), expr,
7560                               /*c_cast_p=*/false,
7561                               flags);
7562
7563   if (!conv)
7564     {
7565       if (complain & tf_error)
7566         {
7567           /* If expr has unknown type, then it is an overloaded function.
7568              Call instantiate_type to get good error messages.  */
7569           if (TREE_TYPE (expr) == unknown_type_node)
7570             instantiate_type (type, expr, complain);
7571           else if (invalid_nonstatic_memfn_p (expr, complain))
7572             /* We gave an error.  */;
7573           else
7574             error ("could not convert %qE to %qT", expr, type);
7575         }
7576       expr = error_mark_node;
7577     }
7578   else if (processing_template_decl)
7579     {
7580       /* In a template, we are only concerned about determining the
7581          type of non-dependent expressions, so we do not have to
7582          perform the actual conversion.  */
7583       if (TREE_TYPE (expr) != type)
7584         expr = build_nop (type, expr);
7585     }
7586   else
7587     expr = convert_like (conv, expr, complain);
7588
7589   /* Free all the conversions we allocated.  */
7590   obstack_free (&conversion_obstack, p);
7591
7592   return expr;
7593 }
7594
7595 tree
7596 perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
7597 {
7598   return perform_implicit_conversion_flags (type, expr, complain, LOOKUP_IMPLICIT);
7599 }
7600
7601 /* Convert EXPR to TYPE (as a direct-initialization) if that is
7602    permitted.  If the conversion is valid, the converted expression is
7603    returned.  Otherwise, NULL_TREE is returned, except in the case
7604    that TYPE is a class type; in that case, an error is issued.  If
7605    C_CAST_P is true, then this direction initialization is taking
7606    place as part of a static_cast being attempted as part of a C-style
7607    cast.  */
7608
7609 tree
7610 perform_direct_initialization_if_possible (tree type,
7611                                            tree expr,
7612                                            bool c_cast_p,
7613                                            tsubst_flags_t complain)
7614 {
7615   conversion *conv;
7616   void *p;
7617
7618   if (type == error_mark_node || error_operand_p (expr))
7619     return error_mark_node;
7620   /* [dcl.init]
7621
7622      If the destination type is a (possibly cv-qualified) class type:
7623
7624      -- If the initialization is direct-initialization ...,
7625      constructors are considered. ... If no constructor applies, or
7626      the overload resolution is ambiguous, the initialization is
7627      ill-formed.  */
7628   if (CLASS_TYPE_P (type))
7629     {
7630       VEC(tree,gc) *args = make_tree_vector_single (expr);
7631       expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
7632                                         &args, type, LOOKUP_NORMAL, complain);
7633       release_tree_vector (args);
7634       return build_cplus_new (type, expr);
7635     }
7636
7637   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
7638   p = conversion_obstack_alloc (0);
7639
7640   conv = implicit_conversion (type, TREE_TYPE (expr), expr,
7641                               c_cast_p,
7642                               LOOKUP_NORMAL);
7643   if (!conv || conv->bad_p)
7644     expr = NULL_TREE;
7645   else
7646     expr = convert_like_real (conv, expr, NULL_TREE, 0, 0,
7647                               /*issue_conversion_warnings=*/false,
7648                               c_cast_p,
7649                               complain);
7650
7651   /* Free all the conversions we allocated.  */
7652   obstack_free (&conversion_obstack, p);
7653
7654   return expr;
7655 }
7656
7657 /* DECL is a VAR_DECL whose type is a REFERENCE_TYPE.  The reference
7658    is being bound to a temporary.  Create and return a new VAR_DECL
7659    with the indicated TYPE; this variable will store the value to
7660    which the reference is bound.  */
7661
7662 tree
7663 make_temporary_var_for_ref_to_temp (tree decl, tree type)
7664 {
7665   tree var;
7666
7667   /* Create the variable.  */
7668   var = create_temporary_var (type);
7669
7670   /* Register the variable.  */
7671   if (TREE_STATIC (decl))
7672     {
7673       /* Namespace-scope or local static; give it a mangled name.  */
7674       tree name;
7675
7676       TREE_STATIC (var) = 1;
7677       name = mangle_ref_init_variable (decl);
7678       DECL_NAME (var) = name;
7679       SET_DECL_ASSEMBLER_NAME (var, name);
7680       var = pushdecl_top_level (var);
7681     }
7682   else
7683     /* Create a new cleanup level if necessary.  */
7684     maybe_push_cleanup_level (type);
7685
7686   return var;
7687 }
7688
7689 /* EXPR is the initializer for a variable DECL of reference or
7690    std::initializer_list type.  Create, push and return a new VAR_DECL
7691    for the initializer so that it will live as long as DECL.  Any
7692    cleanup for the new variable is returned through CLEANUP, and the
7693    code to initialize the new variable is returned through INITP.  */
7694
7695 tree
7696 set_up_extended_ref_temp (tree decl, tree expr, tree *cleanup, tree *initp)
7697 {
7698   tree init;
7699   tree type;
7700   tree var;
7701
7702   /* Create the temporary variable.  */
7703   type = TREE_TYPE (expr);
7704   var = make_temporary_var_for_ref_to_temp (decl, type);
7705   layout_decl (var, 0);
7706   /* If the rvalue is the result of a function call it will be
7707      a TARGET_EXPR.  If it is some other construct (such as a
7708      member access expression where the underlying object is
7709      itself the result of a function call), turn it into a
7710      TARGET_EXPR here.  It is important that EXPR be a
7711      TARGET_EXPR below since otherwise the INIT_EXPR will
7712      attempt to make a bitwise copy of EXPR to initialize
7713      VAR.  */
7714   if (TREE_CODE (expr) != TARGET_EXPR)
7715     expr = get_target_expr (expr);
7716   /* Create the INIT_EXPR that will initialize the temporary
7717      variable.  */
7718   init = build2 (INIT_EXPR, type, var, expr);
7719   if (at_function_scope_p ())
7720     {
7721       add_decl_expr (var);
7722
7723       if (TREE_STATIC (var))
7724         init = add_stmt_to_compound (init, register_dtor_fn (var));
7725       else
7726         *cleanup = cxx_maybe_build_cleanup (var);
7727
7728       /* We must be careful to destroy the temporary only
7729          after its initialization has taken place.  If the
7730          initialization throws an exception, then the
7731          destructor should not be run.  We cannot simply
7732          transform INIT into something like:
7733
7734          (INIT, ({ CLEANUP_STMT; }))
7735
7736          because emit_local_var always treats the
7737          initializer as a full-expression.  Thus, the
7738          destructor would run too early; it would run at the
7739          end of initializing the reference variable, rather
7740          than at the end of the block enclosing the
7741          reference variable.
7742
7743          The solution is to pass back a cleanup expression
7744          which the caller is responsible for attaching to
7745          the statement tree.  */
7746     }
7747   else
7748     {
7749       rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
7750       if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
7751         static_aggregates = tree_cons (NULL_TREE, var,
7752                                        static_aggregates);
7753     }
7754
7755   *initp = init;
7756   return var;
7757 }
7758
7759 /* Convert EXPR to the indicated reference TYPE, in a way suitable for
7760    initializing a variable of that TYPE.  If DECL is non-NULL, it is
7761    the VAR_DECL being initialized with the EXPR.  (In that case, the
7762    type of DECL will be TYPE.)  If DECL is non-NULL, then CLEANUP must
7763    also be non-NULL, and with *CLEANUP initialized to NULL.  Upon
7764    return, if *CLEANUP is no longer NULL, it will be an expression
7765    that should be pushed as a cleanup after the returned expression
7766    is used to initialize DECL.
7767
7768    Return the converted expression.  */
7769
7770 tree
7771 initialize_reference (tree type, tree expr, tree decl, tree *cleanup,
7772                       tsubst_flags_t complain)
7773 {
7774   conversion *conv;
7775   void *p;
7776
7777   if (type == error_mark_node || error_operand_p (expr))
7778     return error_mark_node;
7779
7780   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
7781   p = conversion_obstack_alloc (0);
7782
7783   conv = reference_binding (type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
7784                             LOOKUP_NORMAL);
7785   if (!conv || conv->bad_p)
7786     {
7787       if (complain & tf_error)
7788         {
7789           if (!CP_TYPE_CONST_P (TREE_TYPE (type))
7790               && !TYPE_REF_IS_RVALUE (type)
7791               && !real_lvalue_p (expr))
7792             error ("invalid initialization of non-const reference of "
7793                    "type %qT from an rvalue of type %qT",
7794                    type, TREE_TYPE (expr));
7795           else
7796             error ("invalid initialization of reference of type "
7797                    "%qT from expression of type %qT", type,
7798                    TREE_TYPE (expr));
7799         }
7800       return error_mark_node;
7801     }
7802
7803   /* If DECL is non-NULL, then this special rule applies:
7804
7805        [class.temporary]
7806
7807        The temporary to which the reference is bound or the temporary
7808        that is the complete object to which the reference is bound
7809        persists for the lifetime of the reference.
7810
7811        The temporaries created during the evaluation of the expression
7812        initializing the reference, except the temporary to which the
7813        reference is bound, are destroyed at the end of the
7814        full-expression in which they are created.
7815
7816      In that case, we store the converted expression into a new
7817      VAR_DECL in a new scope.
7818
7819      However, we want to be careful not to create temporaries when
7820      they are not required.  For example, given:
7821
7822        struct B {};
7823        struct D : public B {};
7824        D f();
7825        const B& b = f();
7826
7827      there is no need to copy the return value from "f"; we can just
7828      extend its lifetime.  Similarly, given:
7829
7830        struct S {};
7831        struct T { operator S(); };
7832        T t;
7833        const S& s = t;
7834
7835     we can extend the lifetime of the return value of the conversion
7836     operator.  */
7837   gcc_assert (conv->kind == ck_ref_bind);
7838   if (decl)
7839     {
7840       tree var;
7841       tree base_conv_type;
7842
7843       /* Skip over the REF_BIND.  */
7844       conv = conv->u.next;
7845       /* If the next conversion is a BASE_CONV, skip that too -- but
7846          remember that the conversion was required.  */
7847       if (conv->kind == ck_base)
7848         {
7849           base_conv_type = conv->type;
7850           conv = conv->u.next;
7851         }
7852       else
7853         base_conv_type = NULL_TREE;
7854       /* Perform the remainder of the conversion.  */
7855       expr = convert_like_real (conv, expr,
7856                                 /*fn=*/NULL_TREE, /*argnum=*/0,
7857                                 /*inner=*/-1,
7858                                 /*issue_conversion_warnings=*/true,
7859                                 /*c_cast_p=*/false,
7860                                 tf_warning_or_error);
7861       if (error_operand_p (expr))
7862         expr = error_mark_node;
7863       else
7864         {
7865           if (!lvalue_or_rvalue_with_address_p (expr))
7866             {
7867               tree init;
7868               var = set_up_extended_ref_temp (decl, expr, cleanup, &init);
7869               /* Use its address to initialize the reference variable.  */
7870               expr = build_address (var);
7871               if (base_conv_type)
7872                 expr = convert_to_base (expr,
7873                                         build_pointer_type (base_conv_type),
7874                                         /*check_access=*/true,
7875                                         /*nonnull=*/true, complain);
7876               expr = build2 (COMPOUND_EXPR, TREE_TYPE (expr), init, expr);
7877             }
7878           else
7879             /* Take the address of EXPR.  */
7880             expr = cp_build_unary_op (ADDR_EXPR, expr, 0, tf_warning_or_error);
7881           /* If a BASE_CONV was required, perform it now.  */
7882           if (base_conv_type)
7883             expr = (perform_implicit_conversion
7884                     (build_pointer_type (base_conv_type), expr,
7885                      tf_warning_or_error));
7886           expr = build_nop (type, expr);
7887         }
7888     }
7889   else
7890     /* Perform the conversion.  */
7891     expr = convert_like (conv, expr, tf_warning_or_error);
7892
7893   /* Free all the conversions we allocated.  */
7894   obstack_free (&conversion_obstack, p);
7895
7896   return expr;
7897 }
7898
7899 /* Returns true iff TYPE is some variant of std::initializer_list.  */
7900
7901 bool
7902 is_std_init_list (tree type)
7903 {
7904   return (CLASS_TYPE_P (type)
7905           && CP_TYPE_CONTEXT (type) == std_node
7906           && strcmp (TYPE_NAME_STRING (type), "initializer_list") == 0);
7907 }
7908
7909 /* Returns true iff DECL is a list constructor: i.e. a constructor which
7910    will accept an argument list of a single std::initializer_list<T>.  */
7911
7912 bool
7913 is_list_ctor (tree decl)
7914 {
7915   tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
7916   tree arg;
7917
7918   if (!args || args == void_list_node)
7919     return false;
7920
7921   arg = non_reference (TREE_VALUE (args));
7922   if (!is_std_init_list (arg))
7923     return false;
7924
7925   args = TREE_CHAIN (args);
7926
7927   if (args && args != void_list_node && !TREE_PURPOSE (args))
7928     /* There are more non-defaulted parms.  */
7929     return false;
7930
7931   return true;
7932 }
7933
7934 #include "gt-cp-call.h"