OSDN Git Service

* call.c (is_subseq): Handle ck_aggr, ck_list.
[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 deleted candidates.  */
2751   cand1 = candidates;
2752   for (cand2 = &cand1; *cand2; )
2753     {
2754       if (TREE_CODE ((*cand2)->fn) == FUNCTION_DECL
2755           && DECL_DELETED_FN ((*cand2)->fn))
2756         *cand2 = (*cand2)->next;
2757       else
2758         cand2 = &(*cand2)->next;
2759     }
2760   /* ...if there are any non-deleted ones.  */
2761   if (cand1)
2762     candidates = cand1;
2763
2764   /* There may be duplicates in the set of candidates.  We put off
2765      checking this condition as long as possible, since we have no way
2766      to eliminate duplicates from a set of functions in less than n^2
2767      time.  Now we are about to emit an error message, so it is more
2768      permissible to go slowly.  */
2769   for (cand1 = candidates; cand1; cand1 = cand1->next)
2770     {
2771       tree fn = cand1->fn;
2772       /* Skip builtin candidates and conversion functions.  */
2773       if (!DECL_P (fn))
2774         continue;
2775       cand2 = &cand1->next;
2776       while (*cand2)
2777         {
2778           if (DECL_P ((*cand2)->fn)
2779               && equal_functions (fn, (*cand2)->fn))
2780             *cand2 = (*cand2)->next;
2781           else
2782             cand2 = &(*cand2)->next;
2783         }
2784     }
2785
2786   str = candidates->next ? _("candidates are:") :  _("candidate is:");
2787   spaces = NULL;
2788   for (; candidates; candidates = candidates->next)
2789     {
2790       print_z_candidate (spaces ? spaces : str, candidates);
2791       spaces = spaces ? spaces : get_spaces (str);
2792     }
2793   free (spaces);
2794 }
2795
2796 /* USER_SEQ is a user-defined conversion sequence, beginning with a
2797    USER_CONV.  STD_SEQ is the standard conversion sequence applied to
2798    the result of the conversion function to convert it to the final
2799    desired type.  Merge the two sequences into a single sequence,
2800    and return the merged sequence.  */
2801
2802 static conversion *
2803 merge_conversion_sequences (conversion *user_seq, conversion *std_seq)
2804 {
2805   conversion **t;
2806
2807   gcc_assert (user_seq->kind == ck_user);
2808
2809   /* Find the end of the second conversion sequence.  */
2810   t = &(std_seq);
2811   while ((*t)->kind != ck_identity)
2812     t = &((*t)->u.next);
2813
2814   /* Replace the identity conversion with the user conversion
2815      sequence.  */
2816   *t = user_seq;
2817
2818   /* The entire sequence is a user-conversion sequence.  */
2819   std_seq->user_conv_p = true;
2820
2821   return std_seq;
2822 }
2823
2824 /* Handle overload resolution for initializing an object of class type from
2825    an initializer list.  First we look for a suitable constructor that
2826    takes a std::initializer_list; if we don't find one, we then look for a
2827    non-list constructor.
2828
2829    Parameters are as for add_candidates, except that the arguments are in
2830    the form of a CONSTRUCTOR (the initializer list) rather than a VEC, and
2831    the RETURN_TYPE parameter is replaced by TOTYPE, the desired type.  */
2832
2833 static void
2834 add_list_candidates (tree fns, tree first_arg,
2835                      tree init_list, tree totype,
2836                      tree explicit_targs, bool template_only,
2837                      tree conversion_path, tree access_path,
2838                      int flags,
2839                      struct z_candidate **candidates)
2840 {
2841   VEC(tree,gc) *args;
2842
2843   gcc_assert (*candidates == NULL);
2844
2845   /* For list-initialization we consider explicit constructors, but
2846      give an error if one is selected.  */
2847   flags &= ~LOOKUP_ONLYCONVERTING;
2848   /* And we don't allow narrowing conversions.  We also use this flag to
2849      avoid the copy constructor call for copy-list-initialization.  */
2850   flags |= LOOKUP_NO_NARROWING;
2851
2852   /* Always use the default constructor if the list is empty (DR 990).  */
2853   if (CONSTRUCTOR_NELTS (init_list) == 0
2854       && TYPE_HAS_DEFAULT_CONSTRUCTOR (totype))
2855     ;
2856   /* If the class has a list ctor, try passing the list as a single
2857      argument first, but only consider list ctors.  */
2858   else if (TYPE_HAS_LIST_CTOR (totype))
2859     {
2860       flags |= LOOKUP_LIST_ONLY;
2861       args = make_tree_vector_single (init_list);
2862       add_candidates (fns, first_arg, args, NULL_TREE,
2863                       explicit_targs, template_only, conversion_path,
2864                       access_path, flags, candidates);
2865       if (any_strictly_viable (*candidates))
2866         return;
2867     }
2868
2869   args = ctor_to_vec (init_list);
2870
2871   /* We aren't looking for list-ctors anymore.  */
2872   flags &= ~LOOKUP_LIST_ONLY;
2873   /* We allow more user-defined conversions within an init-list.  */
2874   flags &= ~LOOKUP_NO_CONVERSION;
2875   /* But not for the copy ctor.  */
2876   flags |= LOOKUP_NO_COPY_CTOR_CONVERSION;
2877
2878   add_candidates (fns, first_arg, args, NULL_TREE,
2879                   explicit_targs, template_only, conversion_path,
2880                   access_path, flags, candidates);
2881 }
2882
2883 /* Returns the best overload candidate to perform the requested
2884    conversion.  This function is used for three the overloading situations
2885    described in [over.match.copy], [over.match.conv], and [over.match.ref].
2886    If TOTYPE is a REFERENCE_TYPE, we're trying to find an lvalue binding as
2887    per [dcl.init.ref], so we ignore temporary bindings.  */
2888
2889 static struct z_candidate *
2890 build_user_type_conversion_1 (tree totype, tree expr, int flags)
2891 {
2892   struct z_candidate *candidates, *cand;
2893   tree fromtype = TREE_TYPE (expr);
2894   tree ctors = NULL_TREE;
2895   tree conv_fns = NULL_TREE;
2896   conversion *conv = NULL;
2897   tree first_arg = NULL_TREE;
2898   VEC(tree,gc) *args = NULL;
2899   bool any_viable_p;
2900   int convflags;
2901
2902   /* We represent conversion within a hierarchy using RVALUE_CONV and
2903      BASE_CONV, as specified by [over.best.ics]; these become plain
2904      constructor calls, as specified in [dcl.init].  */
2905   gcc_assert (!MAYBE_CLASS_TYPE_P (fromtype) || !MAYBE_CLASS_TYPE_P (totype)
2906               || !DERIVED_FROM_P (totype, fromtype));
2907
2908   if (MAYBE_CLASS_TYPE_P (totype))
2909     ctors = lookup_fnfields (totype, complete_ctor_identifier, 0);
2910
2911   if (MAYBE_CLASS_TYPE_P (fromtype))
2912     {
2913       tree to_nonref = non_reference (totype);
2914       if (same_type_ignoring_top_level_qualifiers_p (to_nonref, fromtype) ||
2915           (CLASS_TYPE_P (to_nonref) && CLASS_TYPE_P (fromtype)
2916            && DERIVED_FROM_P (to_nonref, fromtype)))
2917         {
2918           /* [class.conv.fct] A conversion function is never used to
2919              convert a (possibly cv-qualified) object to the (possibly
2920              cv-qualified) same object type (or a reference to it), to a
2921              (possibly cv-qualified) base class of that type (or a
2922              reference to it)...  */
2923         }
2924       else
2925         conv_fns = lookup_conversions (fromtype,
2926                                        /*lookup_template_convs_p=*/true);
2927     }
2928
2929   candidates = 0;
2930   flags |= LOOKUP_NO_CONVERSION;
2931   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
2932     flags |= LOOKUP_NO_NARROWING;
2933
2934   /* It's OK to bind a temporary for converting constructor arguments, but
2935      not in converting the return value of a conversion operator.  */
2936   convflags = ((flags & LOOKUP_NO_TEMP_BIND) | LOOKUP_NO_CONVERSION);
2937   flags &= ~LOOKUP_NO_TEMP_BIND;
2938
2939   if (ctors)
2940     {
2941       int ctorflags = flags;
2942       ctors = BASELINK_FUNCTIONS (ctors);
2943
2944       first_arg = build_int_cst (build_pointer_type (totype), 0);
2945
2946       /* We should never try to call the abstract or base constructor
2947          from here.  */
2948       gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (OVL_CURRENT (ctors))
2949                   && !DECL_HAS_VTT_PARM_P (OVL_CURRENT (ctors)));
2950
2951       if (BRACE_ENCLOSED_INITIALIZER_P (expr))
2952         {
2953           /* List-initialization.  */
2954           add_list_candidates (ctors, first_arg, expr, totype, NULL_TREE,
2955                                false, TYPE_BINFO (totype), TYPE_BINFO (totype),
2956                                ctorflags, &candidates);
2957         }
2958       else
2959         {
2960           args = make_tree_vector_single (expr);
2961           add_candidates (ctors, first_arg, args, NULL_TREE, NULL_TREE, false,
2962                           TYPE_BINFO (totype), TYPE_BINFO (totype),
2963                           ctorflags, &candidates);
2964         }
2965
2966       for (cand = candidates; cand; cand = cand->next)
2967         {
2968           cand->second_conv = build_identity_conv (totype, NULL_TREE);
2969
2970           /* If totype isn't a reference, and LOOKUP_NO_TEMP_BIND isn't
2971              set, then this is copy-initialization.  In that case, "The
2972              result of the call is then used to direct-initialize the
2973              object that is the destination of the copy-initialization."
2974              [dcl.init]
2975
2976              We represent this in the conversion sequence with an
2977              rvalue conversion, which means a constructor call.  */
2978           if (TREE_CODE (totype) != REFERENCE_TYPE
2979               && !(convflags & LOOKUP_NO_TEMP_BIND))
2980             cand->second_conv
2981               = build_conv (ck_rvalue, totype, cand->second_conv);
2982         }
2983     }
2984
2985   if (conv_fns)
2986     first_arg = build_this (expr);
2987
2988   for (; conv_fns; conv_fns = TREE_CHAIN (conv_fns))
2989     {
2990       tree conversion_path = TREE_PURPOSE (conv_fns);
2991       struct z_candidate *old_candidates;
2992
2993       /* If we are called to convert to a reference type, we are trying to
2994          find an lvalue binding, so don't even consider temporaries.  If
2995          we don't find an lvalue binding, the caller will try again to
2996          look for a temporary binding.  */
2997       if (TREE_CODE (totype) == REFERENCE_TYPE)
2998         convflags |= LOOKUP_NO_TEMP_BIND;
2999
3000       old_candidates = candidates;
3001       add_candidates (TREE_VALUE (conv_fns), first_arg, NULL, totype,
3002                       NULL_TREE, false,
3003                       conversion_path, TYPE_BINFO (fromtype),
3004                       flags, &candidates);
3005
3006       for (cand = candidates; cand != old_candidates; cand = cand->next)
3007         {
3008           conversion *ics
3009             = implicit_conversion (totype,
3010                                    TREE_TYPE (TREE_TYPE (cand->fn)),
3011                                    0,
3012                                    /*c_cast_p=*/false, convflags);
3013
3014           /* If LOOKUP_NO_TEMP_BIND isn't set, then this is
3015              copy-initialization.  In that case, "The result of the
3016              call is then used to direct-initialize the object that is
3017              the destination of the copy-initialization."  [dcl.init]
3018
3019              We represent this in the conversion sequence with an
3020              rvalue conversion, which means a constructor call.  But
3021              don't add a second rvalue conversion if there's already
3022              one there.  Which there really shouldn't be, but it's
3023              harmless since we'd add it here anyway. */
3024           if (ics && MAYBE_CLASS_TYPE_P (totype) && ics->kind != ck_rvalue
3025               && !(convflags & LOOKUP_NO_TEMP_BIND))
3026             ics = build_conv (ck_rvalue, totype, ics);
3027
3028           cand->second_conv = ics;
3029
3030           if (!ics)
3031             cand->viable = 0;
3032           else if (cand->viable == 1 && ics->bad_p)
3033             cand->viable = -1;
3034         }
3035     }
3036
3037   candidates = splice_viable (candidates, pedantic, &any_viable_p);
3038   if (!any_viable_p)
3039     return NULL;
3040
3041   cand = tourney (candidates);
3042   if (cand == 0)
3043     {
3044       if (flags & LOOKUP_COMPLAIN)
3045         {
3046           error ("conversion from %qT to %qT is ambiguous",
3047                     fromtype, totype);
3048           print_z_candidates (candidates);
3049         }
3050
3051       cand = candidates;        /* any one will do */
3052       cand->second_conv = build_ambiguous_conv (totype, expr);
3053       cand->second_conv->user_conv_p = true;
3054       if (!any_strictly_viable (candidates))
3055         cand->second_conv->bad_p = true;
3056       /* If there are viable candidates, don't set ICS_BAD_FLAG; an
3057          ambiguous conversion is no worse than another user-defined
3058          conversion.  */
3059
3060       return cand;
3061     }
3062
3063   /* Build the user conversion sequence.  */
3064   conv = build_conv
3065     (ck_user,
3066      (DECL_CONSTRUCTOR_P (cand->fn)
3067       ? totype : non_reference (TREE_TYPE (TREE_TYPE (cand->fn)))),
3068      build_identity_conv (TREE_TYPE (expr), expr));
3069   conv->cand = cand;
3070
3071   /* Remember that this was a list-initialization.  */
3072   if (flags & LOOKUP_NO_NARROWING)
3073     conv->check_narrowing = true;
3074
3075   /* Combine it with the second conversion sequence.  */
3076   cand->second_conv = merge_conversion_sequences (conv,
3077                                                   cand->second_conv);
3078
3079   if (cand->viable == -1)
3080     cand->second_conv->bad_p = true;
3081
3082   return cand;
3083 }
3084
3085 tree
3086 build_user_type_conversion (tree totype, tree expr, int flags)
3087 {
3088   struct z_candidate *cand
3089     = build_user_type_conversion_1 (totype, expr, flags);
3090
3091   if (cand)
3092     {
3093       if (cand->second_conv->kind == ck_ambig)
3094         return error_mark_node;
3095       expr = convert_like (cand->second_conv, expr, tf_warning_or_error);
3096       return convert_from_reference (expr);
3097     }
3098   return NULL_TREE;
3099 }
3100
3101 /* Do any initial processing on the arguments to a function call.  */
3102
3103 static VEC(tree,gc) *
3104 resolve_args (VEC(tree,gc) *args)
3105 {
3106   unsigned int ix;
3107   tree arg;
3108
3109   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
3110     {
3111       if (error_operand_p (arg))
3112         return NULL;
3113       else if (VOID_TYPE_P (TREE_TYPE (arg)))
3114         {
3115           error ("invalid use of void expression");
3116           return NULL;
3117         }
3118       else if (invalid_nonstatic_memfn_p (arg, tf_warning_or_error))
3119         return NULL;
3120     }
3121   return args;
3122 }
3123
3124 /* Perform overload resolution on FN, which is called with the ARGS.
3125
3126    Return the candidate function selected by overload resolution, or
3127    NULL if the event that overload resolution failed.  In the case
3128    that overload resolution fails, *CANDIDATES will be the set of
3129    candidates considered, and ANY_VIABLE_P will be set to true or
3130    false to indicate whether or not any of the candidates were
3131    viable.
3132
3133    The ARGS should already have gone through RESOLVE_ARGS before this
3134    function is called.  */
3135
3136 static struct z_candidate *
3137 perform_overload_resolution (tree fn,
3138                              const VEC(tree,gc) *args,
3139                              struct z_candidate **candidates,
3140                              bool *any_viable_p)
3141 {
3142   struct z_candidate *cand;
3143   tree explicit_targs = NULL_TREE;
3144   int template_only = 0;
3145
3146   *candidates = NULL;
3147   *any_viable_p = true;
3148
3149   /* Check FN.  */
3150   gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
3151               || TREE_CODE (fn) == TEMPLATE_DECL
3152               || TREE_CODE (fn) == OVERLOAD
3153               || TREE_CODE (fn) == TEMPLATE_ID_EXPR);
3154
3155   if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
3156     {
3157       explicit_targs = TREE_OPERAND (fn, 1);
3158       fn = TREE_OPERAND (fn, 0);
3159       template_only = 1;
3160     }
3161
3162   /* Add the various candidate functions.  */
3163   add_candidates (fn, NULL_TREE, args, NULL_TREE,
3164                   explicit_targs, template_only,
3165                   /*conversion_path=*/NULL_TREE,
3166                   /*access_path=*/NULL_TREE,
3167                   LOOKUP_NORMAL,
3168                   candidates);
3169
3170   *candidates = splice_viable (*candidates, pedantic, any_viable_p);
3171   if (!*any_viable_p)
3172     return NULL;
3173
3174   cand = tourney (*candidates);
3175   return cand;
3176 }
3177
3178 /* Return an expression for a call to FN (a namespace-scope function,
3179    or a static member function) with the ARGS.  This may change
3180    ARGS.  */
3181
3182 tree
3183 build_new_function_call (tree fn, VEC(tree,gc) **args, bool koenig_p, 
3184                          tsubst_flags_t complain)
3185 {
3186   struct z_candidate *candidates, *cand;
3187   bool any_viable_p;
3188   void *p;
3189   tree result;
3190
3191   if (args != NULL && *args != NULL)
3192     {
3193       *args = resolve_args (*args);
3194       if (*args == NULL)
3195         return error_mark_node;
3196     }
3197
3198   /* If this function was found without using argument dependent
3199      lookup, then we want to ignore any undeclared friend
3200      functions.  */
3201   if (!koenig_p)
3202     {
3203       tree orig_fn = fn;
3204
3205       fn = remove_hidden_names (fn);
3206       if (!fn)
3207         {
3208           if (complain & tf_error)
3209             error ("no matching function for call to %<%D(%A)%>",
3210                    DECL_NAME (OVL_CURRENT (orig_fn)),
3211                    build_tree_list_vec (*args));
3212           return error_mark_node;
3213         }
3214     }
3215
3216   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
3217   p = conversion_obstack_alloc (0);
3218
3219   cand = perform_overload_resolution (fn, *args, &candidates, &any_viable_p);
3220
3221   if (!cand)
3222     {
3223       if (complain & tf_error)
3224         {
3225           if (!any_viable_p && candidates && ! candidates->next
3226               && (TREE_CODE (candidates->fn) == FUNCTION_DECL))
3227             return cp_build_function_call_vec (candidates->fn, args, complain);
3228           if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
3229             fn = TREE_OPERAND (fn, 0);
3230           if (!any_viable_p)
3231             error ("no matching function for call to %<%D(%A)%>",
3232                    DECL_NAME (OVL_CURRENT (fn)), build_tree_list_vec (*args));
3233           else
3234             error ("call of overloaded %<%D(%A)%> is ambiguous",
3235                    DECL_NAME (OVL_CURRENT (fn)), build_tree_list_vec (*args));
3236           if (candidates)
3237             print_z_candidates (candidates);
3238         }
3239       result = error_mark_node;
3240     }
3241   else
3242     result = build_over_call (cand, LOOKUP_NORMAL, complain);
3243
3244   /* Free all the conversions we allocated.  */
3245   obstack_free (&conversion_obstack, p);
3246
3247   return result;
3248 }
3249
3250 /* Build a call to a global operator new.  FNNAME is the name of the
3251    operator (either "operator new" or "operator new[]") and ARGS are
3252    the arguments provided.  This may change ARGS.  *SIZE points to the
3253    total number of bytes required by the allocation, and is updated if
3254    that is changed here.  *COOKIE_SIZE is non-NULL if a cookie should
3255    be used.  If this function determines that no cookie should be
3256    used, after all, *COOKIE_SIZE is set to NULL_TREE.  If FN is
3257    non-NULL, it will be set, upon return, to the allocation function
3258    called.  */
3259
3260 tree
3261 build_operator_new_call (tree fnname, VEC(tree,gc) **args,
3262                          tree *size, tree *cookie_size,
3263                          tree *fn)
3264 {
3265   tree fns;
3266   struct z_candidate *candidates;
3267   struct z_candidate *cand;
3268   bool any_viable_p;
3269
3270   if (fn)
3271     *fn = NULL_TREE;
3272   VEC_safe_insert (tree, gc, *args, 0, *size);
3273   *args = resolve_args (*args);
3274   if (*args == NULL)
3275     return error_mark_node;
3276
3277   /* Based on:
3278
3279        [expr.new]
3280
3281        If this lookup fails to find the name, or if the allocated type
3282        is not a class type, the allocation function's name is looked
3283        up in the global scope.
3284
3285      we disregard block-scope declarations of "operator new".  */
3286   fns = lookup_function_nonclass (fnname, *args, /*block_p=*/false);
3287
3288   /* Figure out what function is being called.  */
3289   cand = perform_overload_resolution (fns, *args, &candidates, &any_viable_p);
3290
3291   /* If no suitable function could be found, issue an error message
3292      and give up.  */
3293   if (!cand)
3294     {
3295       if (!any_viable_p)
3296         error ("no matching function for call to %<%D(%A)%>",
3297                DECL_NAME (OVL_CURRENT (fns)), build_tree_list_vec (*args));
3298       else
3299         error ("call of overloaded %<%D(%A)%> is ambiguous",
3300                DECL_NAME (OVL_CURRENT (fns)), build_tree_list_vec (*args));
3301       if (candidates)
3302         print_z_candidates (candidates);
3303       return error_mark_node;
3304     }
3305
3306    /* If a cookie is required, add some extra space.  Whether
3307       or not a cookie is required cannot be determined until
3308       after we know which function was called.  */
3309    if (*cookie_size)
3310      {
3311        bool use_cookie = true;
3312        if (!abi_version_at_least (2))
3313          {
3314            /* In G++ 3.2, the check was implemented incorrectly; it
3315               looked at the placement expression, rather than the
3316               type of the function.  */
3317            if (VEC_length (tree, *args) == 2
3318                && same_type_p (TREE_TYPE (VEC_index (tree, *args, 1)),
3319                                ptr_type_node))
3320              use_cookie = false;
3321          }
3322        else
3323          {
3324            tree arg_types;
3325
3326            arg_types = TYPE_ARG_TYPES (TREE_TYPE (cand->fn));
3327            /* Skip the size_t parameter.  */
3328            arg_types = TREE_CHAIN (arg_types);
3329            /* Check the remaining parameters (if any).  */
3330            if (arg_types
3331                && TREE_CHAIN (arg_types) == void_list_node
3332                && same_type_p (TREE_VALUE (arg_types),
3333                                ptr_type_node))
3334              use_cookie = false;
3335          }
3336        /* If we need a cookie, adjust the number of bytes allocated.  */
3337        if (use_cookie)
3338          {
3339            /* Update the total size.  */
3340            *size = size_binop (PLUS_EXPR, *size, *cookie_size);
3341            /* Update the argument list to reflect the adjusted size.  */
3342            VEC_replace (tree, *args, 0, *size);
3343          }
3344        else
3345          *cookie_size = NULL_TREE;
3346      }
3347
3348    /* Tell our caller which function we decided to call.  */
3349    if (fn)
3350      *fn = cand->fn;
3351
3352    /* Build the CALL_EXPR.  */
3353    return build_over_call (cand, LOOKUP_NORMAL, tf_warning_or_error);
3354 }
3355
3356 /* Build a new call to operator().  This may change ARGS.  */
3357
3358 tree
3359 build_op_call (tree obj, VEC(tree,gc) **args, tsubst_flags_t complain)
3360 {
3361   struct z_candidate *candidates = 0, *cand;
3362   tree fns, convs, first_mem_arg = NULL_TREE;
3363   tree type = TREE_TYPE (obj);
3364   bool any_viable_p;
3365   tree result = NULL_TREE;
3366   void *p;
3367
3368   if (error_operand_p (obj))
3369     return error_mark_node;
3370
3371   obj = prep_operand (obj);
3372
3373   if (TYPE_PTRMEMFUNC_P (type))
3374     {
3375       if (complain & tf_error)
3376         /* It's no good looking for an overloaded operator() on a
3377            pointer-to-member-function.  */
3378         error ("pointer-to-member function %E cannot be called without an object; consider using .* or ->*", obj);
3379       return error_mark_node;
3380     }
3381
3382   if (TYPE_BINFO (type))
3383     {
3384       fns = lookup_fnfields (TYPE_BINFO (type), ansi_opname (CALL_EXPR), 1);
3385       if (fns == error_mark_node)
3386         return error_mark_node;
3387     }
3388   else
3389     fns = NULL_TREE;
3390
3391   if (args != NULL && *args != NULL)
3392     {
3393       *args = resolve_args (*args);
3394       if (*args == NULL)
3395         return error_mark_node;
3396     }
3397
3398   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
3399   p = conversion_obstack_alloc (0);
3400
3401   if (fns)
3402     {
3403       first_mem_arg = build_this (obj);
3404
3405       add_candidates (BASELINK_FUNCTIONS (fns),
3406                       first_mem_arg, *args, NULL_TREE,
3407                       NULL_TREE, false,
3408                       BASELINK_BINFO (fns), BASELINK_ACCESS_BINFO (fns),
3409                       LOOKUP_NORMAL, &candidates);
3410     }
3411
3412   convs = lookup_conversions (type, /*lookup_template_convs_p=*/true);
3413
3414   for (; convs; convs = TREE_CHAIN (convs))
3415     {
3416       tree fns = TREE_VALUE (convs);
3417       tree totype = TREE_TYPE (convs);
3418
3419       if ((TREE_CODE (totype) == POINTER_TYPE
3420            && TREE_CODE (TREE_TYPE (totype)) == FUNCTION_TYPE)
3421           || (TREE_CODE (totype) == REFERENCE_TYPE
3422               && TREE_CODE (TREE_TYPE (totype)) == FUNCTION_TYPE)
3423           || (TREE_CODE (totype) == REFERENCE_TYPE
3424               && TREE_CODE (TREE_TYPE (totype)) == POINTER_TYPE
3425               && TREE_CODE (TREE_TYPE (TREE_TYPE (totype))) == FUNCTION_TYPE))
3426         for (; fns; fns = OVL_NEXT (fns))
3427           {
3428             tree fn = OVL_CURRENT (fns);
3429
3430             if (DECL_NONCONVERTING_P (fn))
3431               continue;
3432
3433             if (TREE_CODE (fn) == TEMPLATE_DECL)
3434               add_template_conv_candidate
3435                 (&candidates, fn, obj, NULL_TREE, *args, totype,
3436                  /*access_path=*/NULL_TREE,
3437                  /*conversion_path=*/NULL_TREE);
3438             else
3439               add_conv_candidate (&candidates, fn, obj, NULL_TREE,
3440                                   *args, /*conversion_path=*/NULL_TREE,
3441                                   /*access_path=*/NULL_TREE);
3442           }
3443     }
3444
3445   candidates = splice_viable (candidates, pedantic, &any_viable_p);
3446   if (!any_viable_p)
3447     {
3448       if (complain & tf_error)
3449         {
3450           error ("no match for call to %<(%T) (%A)%>", TREE_TYPE (obj),
3451                  build_tree_list_vec (*args));
3452           print_z_candidates (candidates);
3453         }
3454       result = error_mark_node;
3455     }
3456   else
3457     {
3458       cand = tourney (candidates);
3459       if (cand == 0)
3460         {
3461           if (complain & tf_error)
3462             {
3463               error ("call of %<(%T) (%A)%> is ambiguous", 
3464                      TREE_TYPE (obj), build_tree_list_vec (*args));
3465               print_z_candidates (candidates);
3466             }
3467           result = error_mark_node;
3468         }
3469       /* Since cand->fn will be a type, not a function, for a conversion
3470          function, we must be careful not to unconditionally look at
3471          DECL_NAME here.  */
3472       else if (TREE_CODE (cand->fn) == FUNCTION_DECL
3473                && DECL_OVERLOADED_OPERATOR_P (cand->fn) == CALL_EXPR)
3474         result = build_over_call (cand, LOOKUP_NORMAL, complain);
3475       else
3476         {
3477           obj = convert_like_with_context (cand->convs[0], obj, cand->fn, -1,
3478                                            complain);
3479           obj = convert_from_reference (obj);
3480           result = cp_build_function_call_vec (obj, args, complain);
3481         }
3482     }
3483
3484   /* Free all the conversions we allocated.  */
3485   obstack_free (&conversion_obstack, p);
3486
3487   return result;
3488 }
3489
3490 static void
3491 op_error (enum tree_code code, enum tree_code code2,
3492           tree arg1, tree arg2, tree arg3, bool match)
3493 {
3494   const char *opname;
3495
3496   if (code == MODIFY_EXPR)
3497     opname = assignment_operator_name_info[code2].name;
3498   else
3499     opname = operator_name_info[code].name;
3500
3501   switch (code)
3502     {
3503     case COND_EXPR:
3504       if (match)
3505         error ("ambiguous overload for ternary %<operator?:%> "
3506                "in %<%E ? %E : %E%>", arg1, arg2, arg3);
3507       else
3508         error ("no match for ternary %<operator?:%> "
3509                "in %<%E ? %E : %E%>", arg1, arg2, arg3);
3510       break;
3511
3512     case POSTINCREMENT_EXPR:
3513     case POSTDECREMENT_EXPR:
3514       if (match)
3515         error ("ambiguous overload for %<operator%s%> in %<%E%s%>",
3516                opname, arg1, opname);
3517       else
3518         error ("no match for %<operator%s%> in %<%E%s%>", 
3519                opname, arg1, opname);
3520       break;
3521
3522     case ARRAY_REF:
3523       if (match)
3524         error ("ambiguous overload for %<operator[]%> in %<%E[%E]%>", 
3525                arg1, arg2);
3526       else
3527         error ("no match for %<operator[]%> in %<%E[%E]%>", 
3528                arg1, arg2);
3529       break;
3530
3531     case REALPART_EXPR:
3532     case IMAGPART_EXPR:
3533       if (match)
3534         error ("ambiguous overload for %qs in %<%s %E%>", 
3535                opname, opname, arg1);
3536       else
3537         error ("no match for %qs in %<%s %E%>",
3538                opname, opname, arg1);
3539       break;
3540
3541     default:
3542       if (arg2)
3543         if (match)
3544           error ("ambiguous overload for %<operator%s%> in %<%E %s %E%>",
3545                   opname, arg1, opname, arg2);
3546         else
3547           error ("no match for %<operator%s%> in %<%E %s %E%>",
3548                  opname, arg1, opname, arg2);
3549       else
3550         if (match)
3551           error ("ambiguous overload for %<operator%s%> in %<%s%E%>",
3552                  opname, opname, arg1);
3553         else
3554           error ("no match for %<operator%s%> in %<%s%E%>",
3555                  opname, opname, arg1);
3556       break;
3557     }
3558 }
3559
3560 /* Return the implicit conversion sequence that could be used to
3561    convert E1 to E2 in [expr.cond].  */
3562
3563 static conversion *
3564 conditional_conversion (tree e1, tree e2)
3565 {
3566   tree t1 = non_reference (TREE_TYPE (e1));
3567   tree t2 = non_reference (TREE_TYPE (e2));
3568   conversion *conv;
3569   bool good_base;
3570
3571   /* [expr.cond]
3572
3573      If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
3574      implicitly converted (clause _conv_) to the type "reference to
3575      T2", subject to the constraint that in the conversion the
3576      reference must bind directly (_dcl.init.ref_) to E1.  */
3577   if (real_lvalue_p (e2))
3578     {
3579       conv = implicit_conversion (build_reference_type (t2),
3580                                   t1,
3581                                   e1,
3582                                   /*c_cast_p=*/false,
3583                                   LOOKUP_NO_TEMP_BIND|LOOKUP_ONLYCONVERTING);
3584       if (conv)
3585         return conv;
3586     }
3587
3588   /* [expr.cond]
3589
3590      If E1 and E2 have class type, and the underlying class types are
3591      the same or one is a base class of the other: E1 can be converted
3592      to match E2 if the class of T2 is the same type as, or a base
3593      class of, the class of T1, and the cv-qualification of T2 is the
3594      same cv-qualification as, or a greater cv-qualification than, the
3595      cv-qualification of T1.  If the conversion is applied, E1 is
3596      changed to an rvalue of type T2 that still refers to the original
3597      source class object (or the appropriate subobject thereof).  */
3598   if (CLASS_TYPE_P (t1) && CLASS_TYPE_P (t2)
3599       && ((good_base = DERIVED_FROM_P (t2, t1)) || DERIVED_FROM_P (t1, t2)))
3600     {
3601       if (good_base && at_least_as_qualified_p (t2, t1))
3602         {
3603           conv = build_identity_conv (t1, e1);
3604           if (!same_type_p (TYPE_MAIN_VARIANT (t1),
3605                             TYPE_MAIN_VARIANT (t2)))
3606             conv = build_conv (ck_base, t2, conv);
3607           else
3608             conv = build_conv (ck_rvalue, t2, conv);
3609           return conv;
3610         }
3611       else
3612         return NULL;
3613     }
3614   else
3615     /* [expr.cond]
3616
3617        Otherwise: E1 can be converted to match E2 if E1 can be implicitly
3618        converted to the type that expression E2 would have if E2 were
3619        converted to an rvalue (or the type it has, if E2 is an rvalue).  */
3620     return implicit_conversion (t2, t1, e1, /*c_cast_p=*/false,
3621                                 LOOKUP_IMPLICIT);
3622 }
3623
3624 /* Implement [expr.cond].  ARG1, ARG2, and ARG3 are the three
3625    arguments to the conditional expression.  */
3626
3627 tree
3628 build_conditional_expr (tree arg1, tree arg2, tree arg3,
3629                         tsubst_flags_t complain)
3630 {
3631   tree arg2_type;
3632   tree arg3_type;
3633   tree result = NULL_TREE;
3634   tree result_type = NULL_TREE;
3635   bool lvalue_p = true;
3636   struct z_candidate *candidates = 0;
3637   struct z_candidate *cand;
3638   void *p;
3639
3640   /* As a G++ extension, the second argument to the conditional can be
3641      omitted.  (So that `a ? : c' is roughly equivalent to `a ? a :
3642      c'.)  If the second operand is omitted, make sure it is
3643      calculated only once.  */
3644   if (!arg2)
3645     {
3646       if (complain & tf_error)
3647         pedwarn (input_location, OPT_pedantic, 
3648                  "ISO C++ forbids omitting the middle term of a ?: expression");
3649
3650       /* Make sure that lvalues remain lvalues.  See g++.oliva/ext1.C.  */
3651       if (real_lvalue_p (arg1))
3652         arg2 = arg1 = stabilize_reference (arg1);
3653       else
3654         arg2 = arg1 = save_expr (arg1);
3655     }
3656
3657   /* [expr.cond]
3658
3659      The first expression is implicitly converted to bool (clause
3660      _conv_).  */
3661   arg1 = perform_implicit_conversion_flags (boolean_type_node, arg1, complain,
3662                                             LOOKUP_NORMAL);
3663
3664   /* If something has already gone wrong, just pass that fact up the
3665      tree.  */
3666   if (error_operand_p (arg1)
3667       || error_operand_p (arg2)
3668       || error_operand_p (arg3))
3669     return error_mark_node;
3670
3671   /* [expr.cond]
3672
3673      If either the second or the third operand has type (possibly
3674      cv-qualified) void, then the lvalue-to-rvalue (_conv.lval_),
3675      array-to-pointer (_conv.array_), and function-to-pointer
3676      (_conv.func_) standard conversions are performed on the second
3677      and third operands.  */
3678   arg2_type = unlowered_expr_type (arg2);
3679   arg3_type = unlowered_expr_type (arg3);
3680   if (VOID_TYPE_P (arg2_type) || VOID_TYPE_P (arg3_type))
3681     {
3682       /* Do the conversions.  We don't these for `void' type arguments
3683          since it can't have any effect and since decay_conversion
3684          does not handle that case gracefully.  */
3685       if (!VOID_TYPE_P (arg2_type))
3686         arg2 = decay_conversion (arg2);
3687       if (!VOID_TYPE_P (arg3_type))
3688         arg3 = decay_conversion (arg3);
3689       arg2_type = TREE_TYPE (arg2);
3690       arg3_type = TREE_TYPE (arg3);
3691
3692       /* [expr.cond]
3693
3694          One of the following shall hold:
3695
3696          --The second or the third operand (but not both) is a
3697            throw-expression (_except.throw_); the result is of the
3698            type of the other and is an rvalue.
3699
3700          --Both the second and the third operands have type void; the
3701            result is of type void and is an rvalue.
3702
3703          We must avoid calling force_rvalue for expressions of type
3704          "void" because it will complain that their value is being
3705          used.  */
3706       if (TREE_CODE (arg2) == THROW_EXPR
3707           && TREE_CODE (arg3) != THROW_EXPR)
3708         {
3709           if (!VOID_TYPE_P (arg3_type))
3710             arg3 = force_rvalue (arg3);
3711           arg3_type = TREE_TYPE (arg3);
3712           result_type = arg3_type;
3713         }
3714       else if (TREE_CODE (arg2) != THROW_EXPR
3715                && TREE_CODE (arg3) == THROW_EXPR)
3716         {
3717           if (!VOID_TYPE_P (arg2_type))
3718             arg2 = force_rvalue (arg2);
3719           arg2_type = TREE_TYPE (arg2);
3720           result_type = arg2_type;
3721         }
3722       else if (VOID_TYPE_P (arg2_type) && VOID_TYPE_P (arg3_type))
3723         result_type = void_type_node;
3724       else
3725         {
3726           if (complain & tf_error)
3727             {
3728               if (VOID_TYPE_P (arg2_type))
3729                 error ("second operand to the conditional operator "
3730                        "is of type %<void%>, "
3731                        "but the third operand is neither a throw-expression "
3732                        "nor of type %<void%>");
3733               else
3734                 error ("third operand to the conditional operator "
3735                        "is of type %<void%>, "
3736                        "but the second operand is neither a throw-expression "
3737                        "nor of type %<void%>");
3738             }
3739           return error_mark_node;
3740         }
3741
3742       lvalue_p = false;
3743       goto valid_operands;
3744     }
3745   /* [expr.cond]
3746
3747      Otherwise, if the second and third operand have different types,
3748      and either has (possibly cv-qualified) class type, an attempt is
3749      made to convert each of those operands to the type of the other.  */
3750   else if (!same_type_p (arg2_type, arg3_type)
3751            && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
3752     {
3753       conversion *conv2;
3754       conversion *conv3;
3755
3756       /* Get the high-water mark for the CONVERSION_OBSTACK.  */
3757       p = conversion_obstack_alloc (0);
3758
3759       conv2 = conditional_conversion (arg2, arg3);
3760       conv3 = conditional_conversion (arg3, arg2);
3761
3762       /* [expr.cond]
3763
3764          If both can be converted, or one can be converted but the
3765          conversion is ambiguous, the program is ill-formed.  If
3766          neither can be converted, the operands are left unchanged and
3767          further checking is performed as described below.  If exactly
3768          one conversion is possible, that conversion is applied to the
3769          chosen operand and the converted operand is used in place of
3770          the original operand for the remainder of this section.  */
3771       if ((conv2 && !conv2->bad_p
3772            && conv3 && !conv3->bad_p)
3773           || (conv2 && conv2->kind == ck_ambig)
3774           || (conv3 && conv3->kind == ck_ambig))
3775         {
3776           error ("operands to ?: have different types %qT and %qT",
3777                  arg2_type, arg3_type);
3778           result = error_mark_node;
3779         }
3780       else if (conv2 && (!conv2->bad_p || !conv3))
3781         {
3782           arg2 = convert_like (conv2, arg2, complain);
3783           arg2 = convert_from_reference (arg2);
3784           arg2_type = TREE_TYPE (arg2);
3785           /* Even if CONV2 is a valid conversion, the result of the
3786              conversion may be invalid.  For example, if ARG3 has type
3787              "volatile X", and X does not have a copy constructor
3788              accepting a "volatile X&", then even if ARG2 can be
3789              converted to X, the conversion will fail.  */
3790           if (error_operand_p (arg2))
3791             result = error_mark_node;
3792         }
3793       else if (conv3 && (!conv3->bad_p || !conv2))
3794         {
3795           arg3 = convert_like (conv3, arg3, complain);
3796           arg3 = convert_from_reference (arg3);
3797           arg3_type = TREE_TYPE (arg3);
3798           if (error_operand_p (arg3))
3799             result = error_mark_node;
3800         }
3801
3802       /* Free all the conversions we allocated.  */
3803       obstack_free (&conversion_obstack, p);
3804
3805       if (result)
3806         return result;
3807
3808       /* If, after the conversion, both operands have class type,
3809          treat the cv-qualification of both operands as if it were the
3810          union of the cv-qualification of the operands.
3811
3812          The standard is not clear about what to do in this
3813          circumstance.  For example, if the first operand has type
3814          "const X" and the second operand has a user-defined
3815          conversion to "volatile X", what is the type of the second
3816          operand after this step?  Making it be "const X" (matching
3817          the first operand) seems wrong, as that discards the
3818          qualification without actually performing a copy.  Leaving it
3819          as "volatile X" seems wrong as that will result in the
3820          conditional expression failing altogether, even though,
3821          according to this step, the one operand could be converted to
3822          the type of the other.  */
3823       if ((conv2 || conv3)
3824           && CLASS_TYPE_P (arg2_type)
3825           && cp_type_quals (arg2_type) != cp_type_quals (arg3_type))
3826         arg2_type = arg3_type =
3827           cp_build_qualified_type (arg2_type,
3828                                    cp_type_quals (arg2_type)
3829                                    | cp_type_quals (arg3_type));
3830     }
3831
3832   /* [expr.cond]
3833
3834      If the second and third operands are lvalues and have the same
3835      type, the result is of that type and is an lvalue.  */
3836   if (real_lvalue_p (arg2)
3837       && real_lvalue_p (arg3)
3838       && same_type_p (arg2_type, arg3_type))
3839     {
3840       result_type = arg2_type;
3841       mark_lvalue_use (arg2);
3842       mark_lvalue_use (arg3);
3843       goto valid_operands;
3844     }
3845
3846   /* [expr.cond]
3847
3848      Otherwise, the result is an rvalue.  If the second and third
3849      operand do not have the same type, and either has (possibly
3850      cv-qualified) class type, overload resolution is used to
3851      determine the conversions (if any) to be applied to the operands
3852      (_over.match.oper_, _over.built_).  */
3853   lvalue_p = false;
3854   if (!same_type_p (arg2_type, arg3_type)
3855       && (CLASS_TYPE_P (arg2_type) || CLASS_TYPE_P (arg3_type)))
3856     {
3857       tree args[3];
3858       conversion *conv;
3859       bool any_viable_p;
3860
3861       /* Rearrange the arguments so that add_builtin_candidate only has
3862          to know about two args.  In build_builtin_candidate, the
3863          arguments are unscrambled.  */
3864       args[0] = arg2;
3865       args[1] = arg3;
3866       args[2] = arg1;
3867       add_builtin_candidates (&candidates,
3868                               COND_EXPR,
3869                               NOP_EXPR,
3870                               ansi_opname (COND_EXPR),
3871                               args,
3872                               LOOKUP_NORMAL);
3873
3874       /* [expr.cond]
3875
3876          If the overload resolution fails, the program is
3877          ill-formed.  */
3878       candidates = splice_viable (candidates, pedantic, &any_viable_p);
3879       if (!any_viable_p)
3880         {
3881           if (complain & tf_error)
3882             {
3883               op_error (COND_EXPR, NOP_EXPR, arg1, arg2, arg3, FALSE);
3884               print_z_candidates (candidates);
3885             }
3886           return error_mark_node;
3887         }
3888       cand = tourney (candidates);
3889       if (!cand)
3890         {
3891           if (complain & tf_error)
3892             {
3893               op_error (COND_EXPR, NOP_EXPR, arg1, arg2, arg3, FALSE);
3894               print_z_candidates (candidates);
3895             }
3896           return error_mark_node;
3897         }
3898
3899       /* [expr.cond]
3900
3901          Otherwise, the conversions thus determined are applied, and
3902          the converted operands are used in place of the original
3903          operands for the remainder of this section.  */
3904       conv = cand->convs[0];
3905       arg1 = convert_like (conv, arg1, complain);
3906       conv = cand->convs[1];
3907       arg2 = convert_like (conv, arg2, complain);
3908       arg2_type = TREE_TYPE (arg2);
3909       conv = cand->convs[2];
3910       arg3 = convert_like (conv, arg3, complain);
3911       arg3_type = TREE_TYPE (arg3);
3912     }
3913
3914   /* [expr.cond]
3915
3916      Lvalue-to-rvalue (_conv.lval_), array-to-pointer (_conv.array_),
3917      and function-to-pointer (_conv.func_) standard conversions are
3918      performed on the second and third operands.
3919
3920      We need to force the lvalue-to-rvalue conversion here for class types,
3921      so we get TARGET_EXPRs; trying to deal with a COND_EXPR of class rvalues
3922      that isn't wrapped with a TARGET_EXPR plays havoc with exception
3923      regions.  */
3924
3925   arg2 = force_rvalue (arg2);
3926   if (!CLASS_TYPE_P (arg2_type))
3927     arg2_type = TREE_TYPE (arg2);
3928
3929   arg3 = force_rvalue (arg3);
3930   if (!CLASS_TYPE_P (arg3_type))
3931     arg3_type = TREE_TYPE (arg3);
3932
3933   if (arg2 == error_mark_node || arg3 == error_mark_node)
3934     return error_mark_node;
3935
3936   /* [expr.cond]
3937
3938      After those conversions, one of the following shall hold:
3939
3940      --The second and third operands have the same type; the result  is  of
3941        that type.  */
3942   if (same_type_p (arg2_type, arg3_type))
3943     result_type = arg2_type;
3944   /* [expr.cond]
3945
3946      --The second and third operands have arithmetic or enumeration
3947        type; the usual arithmetic conversions are performed to bring
3948        them to a common type, and the result is of that type.  */
3949   else if ((ARITHMETIC_TYPE_P (arg2_type)
3950             || UNSCOPED_ENUM_P (arg2_type))
3951            && (ARITHMETIC_TYPE_P (arg3_type)
3952                || UNSCOPED_ENUM_P (arg3_type)))
3953     {
3954       /* In this case, there is always a common type.  */
3955       result_type = type_after_usual_arithmetic_conversions (arg2_type,
3956                                                              arg3_type);
3957
3958       if (TREE_CODE (arg2_type) == ENUMERAL_TYPE
3959           && TREE_CODE (arg3_type) == ENUMERAL_TYPE)
3960         {
3961           if (complain & tf_warning)
3962             warning (0, 
3963                      "enumeral mismatch in conditional expression: %qT vs %qT",
3964                      arg2_type, arg3_type);
3965         }
3966       else if (extra_warnings
3967                && ((TREE_CODE (arg2_type) == ENUMERAL_TYPE
3968                     && !same_type_p (arg3_type, type_promotes_to (arg2_type)))
3969                    || (TREE_CODE (arg3_type) == ENUMERAL_TYPE
3970                        && !same_type_p (arg2_type, type_promotes_to (arg3_type)))))
3971         {
3972           if (complain & tf_warning)
3973             warning (0, 
3974                      "enumeral and non-enumeral type in conditional expression");
3975         }
3976
3977       arg2 = perform_implicit_conversion (result_type, arg2, complain);
3978       arg3 = perform_implicit_conversion (result_type, arg3, complain);
3979     }
3980   /* [expr.cond]
3981
3982      --The second and third operands have pointer type, or one has
3983        pointer type and the other is a null pointer constant; pointer
3984        conversions (_conv.ptr_) and qualification conversions
3985        (_conv.qual_) are performed to bring them to their composite
3986        pointer type (_expr.rel_).  The result is of the composite
3987        pointer type.
3988
3989      --The second and third operands have pointer to member type, or
3990        one has pointer to member type and the other is a null pointer
3991        constant; pointer to member conversions (_conv.mem_) and
3992        qualification conversions (_conv.qual_) are performed to bring
3993        them to a common type, whose cv-qualification shall match the
3994        cv-qualification of either the second or the third operand.
3995        The result is of the common type.  */
3996   else if ((null_ptr_cst_p (arg2)
3997             && (TYPE_PTR_P (arg3_type) || TYPE_PTR_TO_MEMBER_P (arg3_type)))
3998            || (null_ptr_cst_p (arg3)
3999                && (TYPE_PTR_P (arg2_type) || TYPE_PTR_TO_MEMBER_P (arg2_type)))
4000            || (TYPE_PTR_P (arg2_type) && TYPE_PTR_P (arg3_type))
4001            || (TYPE_PTRMEM_P (arg2_type) && TYPE_PTRMEM_P (arg3_type))
4002            || (TYPE_PTRMEMFUNC_P (arg2_type) && TYPE_PTRMEMFUNC_P (arg3_type)))
4003     {
4004       result_type = composite_pointer_type (arg2_type, arg3_type, arg2,
4005                                             arg3, CPO_CONDITIONAL_EXPR,
4006                                             complain);
4007       if (result_type == error_mark_node)
4008         return error_mark_node;
4009       arg2 = perform_implicit_conversion (result_type, arg2, complain);
4010       arg3 = perform_implicit_conversion (result_type, arg3, complain);
4011     }
4012
4013   if (!result_type)
4014     {
4015       if (complain & tf_error)
4016         error ("operands to ?: have different types %qT and %qT",
4017                arg2_type, arg3_type);
4018       return error_mark_node;
4019     }
4020
4021  valid_operands:
4022   result = build3 (COND_EXPR, result_type, arg1, arg2, arg3);
4023   if (!cp_unevaluated_operand)
4024     /* Avoid folding within decltype (c++/42013) and noexcept.  */
4025     result = fold_if_not_in_template (result);
4026
4027   /* We can't use result_type below, as fold might have returned a
4028      throw_expr.  */
4029
4030   if (!lvalue_p)
4031     {
4032       /* Expand both sides into the same slot, hopefully the target of
4033          the ?: expression.  We used to check for TARGET_EXPRs here,
4034          but now we sometimes wrap them in NOP_EXPRs so the test would
4035          fail.  */
4036       if (CLASS_TYPE_P (TREE_TYPE (result)))
4037         result = get_target_expr (result);
4038       /* If this expression is an rvalue, but might be mistaken for an
4039          lvalue, we must add a NON_LVALUE_EXPR.  */
4040       result = rvalue (result);
4041     }
4042
4043   return result;
4044 }
4045
4046 /* OPERAND is an operand to an expression.  Perform necessary steps
4047    required before using it.  If OPERAND is NULL_TREE, NULL_TREE is
4048    returned.  */
4049
4050 static tree
4051 prep_operand (tree operand)
4052 {
4053   if (operand)
4054     {
4055       if (CLASS_TYPE_P (TREE_TYPE (operand))
4056           && CLASSTYPE_TEMPLATE_INSTANTIATION (TREE_TYPE (operand)))
4057         /* Make sure the template type is instantiated now.  */
4058         instantiate_class_template (TYPE_MAIN_VARIANT (TREE_TYPE (operand)));
4059     }
4060
4061   return operand;
4062 }
4063
4064 /* Add each of the viable functions in FNS (a FUNCTION_DECL or
4065    OVERLOAD) to the CANDIDATES, returning an updated list of
4066    CANDIDATES.  The ARGS are the arguments provided to the call;
4067    if FIRST_ARG is non-null it is the implicit object argument,
4068    otherwise the first element of ARGS is used if needed.  The
4069    EXPLICIT_TARGS are explicit template arguments provided.
4070    TEMPLATE_ONLY is true if only template functions should be
4071    considered.  CONVERSION_PATH, ACCESS_PATH, and FLAGS are as for
4072    add_function_candidate.  */
4073
4074 static void
4075 add_candidates (tree fns, tree first_arg, const VEC(tree,gc) *args,
4076                 tree return_type,
4077                 tree explicit_targs, bool template_only,
4078                 tree conversion_path, tree access_path,
4079                 int flags,
4080                 struct z_candidate **candidates)
4081 {
4082   tree ctype;
4083   const VEC(tree,gc) *non_static_args;
4084   bool check_list_ctor;
4085   bool check_converting;
4086   unification_kind_t strict;
4087   tree fn;
4088
4089   if (!fns)
4090     return;
4091
4092   /* Precalculate special handling of constructors and conversion ops.  */
4093   fn = OVL_CURRENT (fns);
4094   if (DECL_CONV_FN_P (fn))
4095     {
4096       check_list_ctor = false;
4097       check_converting = !!(flags & LOOKUP_ONLYCONVERTING);
4098       if (flags & LOOKUP_NO_CONVERSION)
4099         /* We're doing return_type(x).  */
4100         strict = DEDUCE_CONV;
4101       else
4102         /* We're doing x.operator return_type().  */
4103         strict = DEDUCE_EXACT;
4104       /* [over.match.funcs] For conversion functions, the function
4105          is considered to be a member of the class of the implicit
4106          object argument for the purpose of defining the type of
4107          the implicit object parameter.  */
4108       ctype = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (first_arg)));
4109     }
4110   else
4111     {
4112       if (DECL_CONSTRUCTOR_P (fn))
4113         {
4114           check_list_ctor = !!(flags & LOOKUP_LIST_ONLY);
4115           check_converting = !!(flags & LOOKUP_ONLYCONVERTING);
4116         }
4117       else
4118         {
4119           check_list_ctor = false;
4120           check_converting = false;
4121         }
4122       strict = DEDUCE_CALL;
4123       ctype = conversion_path ? BINFO_TYPE (conversion_path) : NULL_TREE;
4124     }
4125
4126   if (first_arg)
4127     non_static_args = args;
4128   else
4129     /* Delay creating the implicit this parameter until it is needed.  */
4130     non_static_args = NULL;
4131
4132   for (; fns; fns = OVL_NEXT (fns))
4133     {
4134       tree fn_first_arg;
4135       const VEC(tree,gc) *fn_args;
4136
4137       fn = OVL_CURRENT (fns);
4138
4139       if (check_converting && DECL_NONCONVERTING_P (fn))
4140         continue;
4141       if (check_list_ctor && !is_list_ctor (fn))
4142         continue;
4143
4144       /* Figure out which set of arguments to use.  */
4145       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
4146         {
4147           /* If this function is a non-static member and we didn't get an
4148              implicit object argument, move it out of args.  */
4149           if (first_arg == NULL_TREE)
4150             {
4151               unsigned int ix;
4152               tree arg;
4153               VEC(tree,gc) *tempvec
4154                 = VEC_alloc (tree, gc, VEC_length (tree, args) - 1);
4155               for (ix = 1; VEC_iterate (tree, args, ix, arg); ++ix)
4156                 VEC_quick_push (tree, tempvec, arg);
4157               non_static_args = tempvec;
4158               first_arg = build_this (VEC_index (tree, args, 0));
4159             }
4160
4161           fn_first_arg = first_arg;
4162           fn_args = non_static_args;
4163         }
4164       else
4165         {
4166           /* Otherwise, just use the list of arguments provided.  */
4167           fn_first_arg = NULL_TREE;
4168           fn_args = args;
4169         }
4170
4171       if (TREE_CODE (fn) == TEMPLATE_DECL)
4172         add_template_candidate (candidates,
4173                                 fn,
4174                                 ctype,
4175                                 explicit_targs,
4176                                 fn_first_arg, 
4177                                 fn_args,
4178                                 return_type,
4179                                 access_path,
4180                                 conversion_path,
4181                                 flags,
4182                                 strict);
4183       else if (!template_only)
4184         add_function_candidate (candidates,
4185                                 fn,
4186                                 ctype,
4187                                 fn_first_arg,
4188                                 fn_args,
4189                                 access_path,
4190                                 conversion_path,
4191                                 flags);
4192     }
4193 }
4194
4195 /* Even unsigned enum types promote to signed int.  We don't want to
4196    issue -Wsign-compare warnings for this case.  Here ORIG_ARG is the
4197    original argument and ARG is the argument after any conversions
4198    have been applied.  We set TREE_NO_WARNING if we have added a cast
4199    from an unsigned enum type to a signed integer type.  */
4200
4201 static void
4202 avoid_sign_compare_warnings (tree orig_arg, tree arg)
4203 {
4204   if (orig_arg != NULL_TREE
4205       && arg != NULL_TREE
4206       && orig_arg != arg
4207       && TREE_CODE (TREE_TYPE (orig_arg)) == ENUMERAL_TYPE
4208       && TYPE_UNSIGNED (TREE_TYPE (orig_arg))
4209       && INTEGRAL_TYPE_P (TREE_TYPE (arg))
4210       && !TYPE_UNSIGNED (TREE_TYPE (arg)))
4211     TREE_NO_WARNING (arg) = 1;
4212 }
4213
4214 tree
4215 build_new_op (enum tree_code code, int flags, tree arg1, tree arg2, tree arg3,
4216               bool *overloaded_p, tsubst_flags_t complain)
4217 {
4218   tree orig_arg1 = arg1;
4219   tree orig_arg2 = arg2;
4220   tree orig_arg3 = arg3;
4221   struct z_candidate *candidates = 0, *cand;
4222   VEC(tree,gc) *arglist;
4223   tree fnname;
4224   tree args[3];
4225   tree result = NULL_TREE;
4226   bool result_valid_p = false;
4227   enum tree_code code2 = NOP_EXPR;
4228   enum tree_code code_orig_arg1 = ERROR_MARK;
4229   enum tree_code code_orig_arg2 = ERROR_MARK;
4230   conversion *conv;
4231   void *p;
4232   bool strict_p;
4233   bool any_viable_p;
4234
4235   if (error_operand_p (arg1)
4236       || error_operand_p (arg2)
4237       || error_operand_p (arg3))
4238     return error_mark_node;
4239
4240   if (code == MODIFY_EXPR)
4241     {
4242       code2 = TREE_CODE (arg3);
4243       arg3 = NULL_TREE;
4244       fnname = ansi_assopname (code2);
4245     }
4246   else
4247     fnname = ansi_opname (code);
4248
4249   arg1 = prep_operand (arg1);
4250
4251   switch (code)
4252     {
4253     case NEW_EXPR:
4254     case VEC_NEW_EXPR:
4255     case VEC_DELETE_EXPR:
4256     case DELETE_EXPR:
4257       /* Use build_op_new_call and build_op_delete_call instead.  */
4258       gcc_unreachable ();
4259
4260     case CALL_EXPR:
4261       /* Use build_op_call instead.  */
4262       gcc_unreachable ();
4263
4264     case TRUTH_ORIF_EXPR:
4265     case TRUTH_ANDIF_EXPR:
4266     case TRUTH_AND_EXPR:
4267     case TRUTH_OR_EXPR:
4268       /* These are saved for the sake of warn_logical_operator.  */
4269       code_orig_arg1 = TREE_CODE (arg1);
4270       code_orig_arg2 = TREE_CODE (arg2);
4271
4272     default:
4273       break;
4274     }
4275
4276   arg2 = prep_operand (arg2);
4277   arg3 = prep_operand (arg3);
4278
4279   if (code == COND_EXPR)
4280     /* Use build_conditional_expr instead.  */
4281     gcc_unreachable ();
4282   else if (! IS_OVERLOAD_TYPE (TREE_TYPE (arg1))
4283            && (! arg2 || ! IS_OVERLOAD_TYPE (TREE_TYPE (arg2))))
4284     goto builtin;
4285
4286   if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
4287     arg2 = integer_zero_node;
4288
4289   arglist = VEC_alloc (tree, gc, 3);
4290   VEC_quick_push (tree, arglist, arg1);
4291   if (arg2 != NULL_TREE)
4292     VEC_quick_push (tree, arglist, arg2);
4293   if (arg3 != NULL_TREE)
4294     VEC_quick_push (tree, arglist, arg3);
4295
4296   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
4297   p = conversion_obstack_alloc (0);
4298
4299   /* Add namespace-scope operators to the list of functions to
4300      consider.  */
4301   add_candidates (lookup_function_nonclass (fnname, arglist, /*block_p=*/true),
4302                   NULL_TREE, arglist, NULL_TREE,
4303                   NULL_TREE, false, NULL_TREE, NULL_TREE,
4304                   flags, &candidates);
4305   /* Add class-member operators to the candidate set.  */
4306   if (CLASS_TYPE_P (TREE_TYPE (arg1)))
4307     {
4308       tree fns;
4309
4310       fns = lookup_fnfields (TREE_TYPE (arg1), fnname, 1);
4311       if (fns == error_mark_node)
4312         {
4313           result = error_mark_node;
4314           goto user_defined_result_ready;
4315         }
4316       if (fns)
4317         add_candidates (BASELINK_FUNCTIONS (fns),
4318                         NULL_TREE, arglist, NULL_TREE,
4319                         NULL_TREE, false,
4320                         BASELINK_BINFO (fns),
4321                         BASELINK_ACCESS_BINFO (fns),
4322                         flags, &candidates);
4323     }
4324
4325   args[0] = arg1;
4326   args[1] = arg2;
4327   args[2] = NULL_TREE;
4328
4329   add_builtin_candidates (&candidates, code, code2, fnname, args, flags);
4330
4331   switch (code)
4332     {
4333     case COMPOUND_EXPR:
4334     case ADDR_EXPR:
4335       /* For these, the built-in candidates set is empty
4336          [over.match.oper]/3.  We don't want non-strict matches
4337          because exact matches are always possible with built-in
4338          operators.  The built-in candidate set for COMPONENT_REF
4339          would be empty too, but since there are no such built-in
4340          operators, we accept non-strict matches for them.  */
4341       strict_p = true;
4342       break;
4343
4344     default:
4345       strict_p = pedantic;
4346       break;
4347     }
4348
4349   candidates = splice_viable (candidates, strict_p, &any_viable_p);
4350   if (!any_viable_p)
4351     {
4352       switch (code)
4353         {
4354         case POSTINCREMENT_EXPR:
4355         case POSTDECREMENT_EXPR:
4356           /* Don't try anything fancy if we're not allowed to produce
4357              errors.  */
4358           if (!(complain & tf_error))
4359             return error_mark_node;
4360
4361           /* Look for an `operator++ (int)'. Pre-1985 C++ didn't
4362              distinguish between prefix and postfix ++ and
4363              operator++() was used for both, so we allow this with
4364              -fpermissive.  */
4365           if (flags & LOOKUP_COMPLAIN)
4366             {
4367               const char *msg = (flag_permissive) 
4368                 ? G_("no %<%D(int)%> declared for postfix %qs,"
4369                      " trying prefix operator instead")
4370                 : G_("no %<%D(int)%> declared for postfix %qs");
4371               permerror (input_location, msg, fnname,
4372                          operator_name_info[code].name);
4373             }
4374
4375           if (!flag_permissive)
4376             return error_mark_node;
4377
4378           if (code == POSTINCREMENT_EXPR)
4379             code = PREINCREMENT_EXPR;
4380           else
4381             code = PREDECREMENT_EXPR;
4382           result = build_new_op (code, flags, arg1, NULL_TREE, NULL_TREE,
4383                                  overloaded_p, complain);
4384           break;
4385
4386           /* The caller will deal with these.  */
4387         case ADDR_EXPR:
4388         case COMPOUND_EXPR:
4389         case COMPONENT_REF:
4390           result = NULL_TREE;
4391           result_valid_p = true;
4392           break;
4393
4394         default:
4395           if ((flags & LOOKUP_COMPLAIN) && (complain & tf_error))
4396             {
4397                 /* If one of the arguments of the operator represents
4398                    an invalid use of member function pointer, try to report
4399                    a meaningful error ...  */
4400                 if (invalid_nonstatic_memfn_p (arg1, tf_error)
4401                     || invalid_nonstatic_memfn_p (arg2, tf_error)
4402                     || invalid_nonstatic_memfn_p (arg3, tf_error))
4403                   /* We displayed the error message.  */;
4404                 else
4405                   {
4406                     /* ... Otherwise, report the more generic
4407                        "no matching operator found" error */
4408                     op_error (code, code2, arg1, arg2, arg3, FALSE);
4409                     print_z_candidates (candidates);
4410                   }
4411             }
4412           result = error_mark_node;
4413           break;
4414         }
4415     }
4416   else
4417     {
4418       cand = tourney (candidates);
4419       if (cand == 0)
4420         {
4421           if ((flags & LOOKUP_COMPLAIN) && (complain & tf_error))
4422             {
4423               op_error (code, code2, arg1, arg2, arg3, TRUE);
4424               print_z_candidates (candidates);
4425             }
4426           result = error_mark_node;
4427         }
4428       else if (TREE_CODE (cand->fn) == FUNCTION_DECL)
4429         {
4430           if (overloaded_p)
4431             *overloaded_p = true;
4432
4433           if (resolve_args (arglist) == NULL)
4434             result = error_mark_node;
4435           else
4436             result = build_over_call (cand, LOOKUP_NORMAL, complain);
4437         }
4438       else
4439         {
4440           /* Give any warnings we noticed during overload resolution.  */
4441           if (cand->warnings && (complain & tf_warning))
4442             {
4443               struct candidate_warning *w;
4444               for (w = cand->warnings; w; w = w->next)
4445                 joust (cand, w->loser, 1);
4446             }
4447
4448           /* Check for comparison of different enum types.  */
4449           switch (code)
4450             {
4451             case GT_EXPR:
4452             case LT_EXPR:
4453             case GE_EXPR:
4454             case LE_EXPR:
4455             case EQ_EXPR:
4456             case NE_EXPR:
4457               if (TREE_CODE (TREE_TYPE (arg1)) == ENUMERAL_TYPE
4458                   && TREE_CODE (TREE_TYPE (arg2)) == ENUMERAL_TYPE
4459                   && (TYPE_MAIN_VARIANT (TREE_TYPE (arg1))
4460                       != TYPE_MAIN_VARIANT (TREE_TYPE (arg2)))
4461                   && (complain & tf_warning))
4462                 {
4463                   warning (OPT_Wenum_compare,
4464                            "comparison between %q#T and %q#T",
4465                            TREE_TYPE (arg1), TREE_TYPE (arg2));
4466                 }
4467               break;
4468             default:
4469               break;
4470             }
4471
4472           /* We need to strip any leading REF_BIND so that bitfields
4473              don't cause errors.  This should not remove any important
4474              conversions, because builtins don't apply to class
4475              objects directly.  */
4476           conv = cand->convs[0];
4477           if (conv->kind == ck_ref_bind)
4478             conv = conv->u.next;
4479           arg1 = convert_like (conv, arg1, complain);
4480
4481           if (arg2)
4482             {
4483               /* We need to call warn_logical_operator before
4484                  converting arg2 to a boolean_type.  */
4485               if (complain & tf_warning)
4486                 warn_logical_operator (input_location, code, boolean_type_node,
4487                                        code_orig_arg1, arg1,
4488                                        code_orig_arg2, arg2);
4489
4490               conv = cand->convs[1];
4491               if (conv->kind == ck_ref_bind)
4492                 conv = conv->u.next;
4493               arg2 = convert_like (conv, arg2, complain);
4494             }
4495           if (arg3)
4496             {
4497               conv = cand->convs[2];
4498               if (conv->kind == ck_ref_bind)
4499                 conv = conv->u.next;
4500               arg3 = convert_like (conv, arg3, complain);
4501             }
4502
4503         }
4504     }
4505
4506  user_defined_result_ready:
4507
4508   /* Free all the conversions we allocated.  */
4509   obstack_free (&conversion_obstack, p);
4510
4511   if (result || result_valid_p)
4512     return result;
4513
4514  builtin:
4515   avoid_sign_compare_warnings (orig_arg1, arg1);
4516   avoid_sign_compare_warnings (orig_arg2, arg2);
4517   avoid_sign_compare_warnings (orig_arg3, arg3);
4518
4519   switch (code)
4520     {
4521     case MODIFY_EXPR:
4522       return cp_build_modify_expr (arg1, code2, arg2, complain);
4523
4524     case INDIRECT_REF:
4525       return cp_build_indirect_ref (arg1, RO_UNARY_STAR, complain);
4526
4527     case TRUTH_ANDIF_EXPR:
4528     case TRUTH_ORIF_EXPR:
4529     case TRUTH_AND_EXPR:
4530     case TRUTH_OR_EXPR:
4531       warn_logical_operator (input_location, code, boolean_type_node,
4532                              code_orig_arg1, arg1, code_orig_arg2, arg2);
4533       /* Fall through.  */
4534     case PLUS_EXPR:
4535     case MINUS_EXPR:
4536     case MULT_EXPR:
4537     case TRUNC_DIV_EXPR:
4538     case GT_EXPR:
4539     case LT_EXPR:
4540     case GE_EXPR:
4541     case LE_EXPR:
4542     case EQ_EXPR:
4543     case NE_EXPR:
4544     case MAX_EXPR:
4545     case MIN_EXPR:
4546     case LSHIFT_EXPR:
4547     case RSHIFT_EXPR:
4548     case TRUNC_MOD_EXPR:
4549     case BIT_AND_EXPR:
4550     case BIT_IOR_EXPR:
4551     case BIT_XOR_EXPR:
4552       return cp_build_binary_op (input_location, code, arg1, arg2, complain);
4553
4554     case UNARY_PLUS_EXPR:
4555     case NEGATE_EXPR:
4556     case BIT_NOT_EXPR:
4557     case TRUTH_NOT_EXPR:
4558     case PREINCREMENT_EXPR:
4559     case POSTINCREMENT_EXPR:
4560     case PREDECREMENT_EXPR:
4561     case POSTDECREMENT_EXPR:
4562     case REALPART_EXPR:
4563     case IMAGPART_EXPR:
4564       return cp_build_unary_op (code, arg1, candidates != 0, complain);
4565
4566     case ARRAY_REF:
4567       return cp_build_array_ref (input_location, arg1, arg2, complain);
4568
4569     case MEMBER_REF:
4570       return build_m_component_ref (cp_build_indirect_ref (arg1, RO_NULL, 
4571                                                            complain), 
4572                                     arg2);
4573
4574       /* The caller will deal with these.  */
4575     case ADDR_EXPR:
4576     case COMPONENT_REF:
4577     case COMPOUND_EXPR:
4578       return NULL_TREE;
4579
4580     default:
4581       gcc_unreachable ();
4582     }
4583   return NULL_TREE;
4584 }
4585
4586 /* Returns true iff T, an element of an OVERLOAD chain, is a usual
4587    deallocation function (3.7.4.2 [basic.stc.dynamic.deallocation]).  */
4588
4589 static bool
4590 non_placement_deallocation_fn_p (tree t)
4591 {
4592   /* A template instance is never a usual deallocation function,
4593      regardless of its signature.  */
4594   if (TREE_CODE (t) == TEMPLATE_DECL
4595       || primary_template_instantiation_p (t))
4596     return false;
4597
4598   /* If a class T has a member deallocation function named operator delete
4599      with exactly one parameter, then that function is a usual
4600      (non-placement) deallocation function. If class T does not declare
4601      such an operator delete but does declare a member deallocation
4602      function named operator delete with exactly two parameters, the second
4603      of which has type std::size_t (18.2), then this function is a usual
4604      deallocation function.  */
4605   t = FUNCTION_ARG_CHAIN (t);
4606   if (t == void_list_node
4607       || (t && same_type_p (TREE_VALUE (t), size_type_node)
4608           && TREE_CHAIN (t) == void_list_node))
4609     return true;
4610   return false;
4611 }
4612
4613 /* Build a call to operator delete.  This has to be handled very specially,
4614    because the restrictions on what signatures match are different from all
4615    other call instances.  For a normal delete, only a delete taking (void *)
4616    or (void *, size_t) is accepted.  For a placement delete, only an exact
4617    match with the placement new is accepted.
4618
4619    CODE is either DELETE_EXPR or VEC_DELETE_EXPR.
4620    ADDR is the pointer to be deleted.
4621    SIZE is the size of the memory block to be deleted.
4622    GLOBAL_P is true if the delete-expression should not consider
4623    class-specific delete operators.
4624    PLACEMENT is the corresponding placement new call, or NULL_TREE.
4625
4626    If this call to "operator delete" is being generated as part to
4627    deallocate memory allocated via a new-expression (as per [expr.new]
4628    which requires that if the initialization throws an exception then
4629    we call a deallocation function), then ALLOC_FN is the allocation
4630    function.  */
4631
4632 tree
4633 build_op_delete_call (enum tree_code code, tree addr, tree size,
4634                       bool global_p, tree placement,
4635                       tree alloc_fn)
4636 {
4637   tree fn = NULL_TREE;
4638   tree fns, fnname, type, t;
4639
4640   if (addr == error_mark_node)
4641     return error_mark_node;
4642
4643   type = strip_array_types (TREE_TYPE (TREE_TYPE (addr)));
4644
4645   fnname = ansi_opname (code);
4646
4647   if (CLASS_TYPE_P (type)
4648       && COMPLETE_TYPE_P (complete_type (type))
4649       && !global_p)
4650     /* In [class.free]
4651
4652        If the result of the lookup is ambiguous or inaccessible, or if
4653        the lookup selects a placement deallocation function, the
4654        program is ill-formed.
4655
4656        Therefore, we ask lookup_fnfields to complain about ambiguity.  */
4657     {
4658       fns = lookup_fnfields (TYPE_BINFO (type), fnname, 1);
4659       if (fns == error_mark_node)
4660         return error_mark_node;
4661     }
4662   else
4663     fns = NULL_TREE;
4664
4665   if (fns == NULL_TREE)
4666     fns = lookup_name_nonclass (fnname);
4667
4668   /* Strip const and volatile from addr.  */
4669   addr = cp_convert (ptr_type_node, addr);
4670
4671   if (placement)
4672     {
4673       /* "A declaration of a placement deallocation function matches the
4674          declaration of a placement allocation function if it has the same
4675          number of parameters and, after parameter transformations (8.3.5),
4676          all parameter types except the first are identical."
4677
4678          So we build up the function type we want and ask instantiate_type
4679          to get it for us.  */
4680       t = FUNCTION_ARG_CHAIN (alloc_fn);
4681       t = tree_cons (NULL_TREE, ptr_type_node, t);
4682       t = build_function_type (void_type_node, t);
4683
4684       fn = instantiate_type (t, fns, tf_none);
4685       if (fn == error_mark_node)
4686         return NULL_TREE;
4687
4688       if (BASELINK_P (fn))
4689         fn = BASELINK_FUNCTIONS (fn);
4690
4691       /* "If the lookup finds the two-parameter form of a usual deallocation
4692          function (3.7.4.2) and that function, considered as a placement
4693          deallocation function, would have been selected as a match for the
4694          allocation function, the program is ill-formed."  */
4695       if (non_placement_deallocation_fn_p (fn))
4696         {
4697           /* But if the class has an operator delete (void *), then that is
4698              the usual deallocation function, so we shouldn't complain
4699              about using the operator delete (void *, size_t).  */
4700           for (t = BASELINK_P (fns) ? BASELINK_FUNCTIONS (fns) : fns;
4701                t; t = OVL_NEXT (t))
4702             {
4703               tree elt = OVL_CURRENT (t);
4704               if (non_placement_deallocation_fn_p (elt)
4705                   && FUNCTION_ARG_CHAIN (elt) == void_list_node)
4706                 goto ok;
4707             }
4708           permerror (0, "non-placement deallocation function %q+D", fn);
4709           permerror (input_location, "selected for placement delete");
4710         ok:;
4711         }
4712     }
4713   else
4714     /* "Any non-placement deallocation function matches a non-placement
4715        allocation function. If the lookup finds a single matching
4716        deallocation function, that function will be called; otherwise, no
4717        deallocation function will be called."  */
4718     for (t = BASELINK_P (fns) ? BASELINK_FUNCTIONS (fns) : fns;
4719          t; t = OVL_NEXT (t))
4720       {
4721         tree elt = OVL_CURRENT (t);
4722         if (non_placement_deallocation_fn_p (elt))
4723           {
4724             fn = elt;
4725             /* "If a class T has a member deallocation function named
4726                operator delete with exactly one parameter, then that
4727                function is a usual (non-placement) deallocation
4728                function. If class T does not declare such an operator
4729                delete but does declare a member deallocation function named
4730                operator delete with exactly two parameters, the second of
4731                which has type std::size_t (18.2), then this function is a
4732                usual deallocation function."
4733
4734                So (void*) beats (void*, size_t).  */
4735             if (FUNCTION_ARG_CHAIN (fn) == void_list_node)
4736               break;
4737           }
4738       }
4739
4740   /* If we have a matching function, call it.  */
4741   if (fn)
4742     {
4743       gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
4744
4745       /* If the FN is a member function, make sure that it is
4746          accessible.  */
4747       if (BASELINK_P (fns))
4748         perform_or_defer_access_check (BASELINK_BINFO (fns), fn, fn);
4749
4750       /* Core issue 901: It's ok to new a type with deleted delete.  */
4751       if (DECL_DELETED_FN (fn) && alloc_fn)
4752         return NULL_TREE;
4753
4754       if (placement)
4755         {
4756           /* The placement args might not be suitable for overload
4757              resolution at this point, so build the call directly.  */
4758           int nargs = call_expr_nargs (placement);
4759           tree *argarray = XALLOCAVEC (tree, nargs);
4760           int i;
4761           argarray[0] = addr;
4762           for (i = 1; i < nargs; i++)
4763             argarray[i] = CALL_EXPR_ARG (placement, i);
4764           mark_used (fn);
4765           return build_cxx_call (fn, nargs, argarray);
4766         }
4767       else
4768         {
4769           tree ret;
4770           VEC(tree,gc) *args = VEC_alloc (tree, gc, 2);
4771           VEC_quick_push (tree, args, addr);
4772           if (FUNCTION_ARG_CHAIN (fn) != void_list_node)
4773             VEC_quick_push (tree, args, size);
4774           ret = cp_build_function_call_vec (fn, &args, tf_warning_or_error);
4775           VEC_free (tree, gc, args);
4776           return ret;
4777         }
4778     }
4779
4780   /* [expr.new]
4781
4782      If no unambiguous matching deallocation function can be found,
4783      propagating the exception does not cause the object's memory to
4784      be freed.  */
4785   if (alloc_fn)
4786     {
4787       if (!placement)
4788         warning (0, "no corresponding deallocation function for %qD",
4789                  alloc_fn);
4790       return NULL_TREE;
4791     }
4792
4793   error ("no suitable %<operator %s%> for %qT",
4794          operator_name_info[(int)code].name, type);
4795   return error_mark_node;
4796 }
4797
4798 /* If the current scope isn't allowed to access DECL along
4799    BASETYPE_PATH, give an error.  The most derived class in
4800    BASETYPE_PATH is the one used to qualify DECL. DIAG_DECL is
4801    the declaration to use in the error diagnostic.  */
4802
4803 bool
4804 enforce_access (tree basetype_path, tree decl, tree diag_decl)
4805 {
4806   gcc_assert (TREE_CODE (basetype_path) == TREE_BINFO);
4807
4808   if (!accessible_p (basetype_path, decl, true))
4809     {
4810       if (TREE_PRIVATE (decl))
4811         error ("%q+#D is private", diag_decl);
4812       else if (TREE_PROTECTED (decl))
4813         error ("%q+#D is protected", diag_decl);
4814       else
4815         error ("%q+#D is inaccessible", diag_decl);
4816       error ("within this context");
4817       return false;
4818     }
4819
4820   return true;
4821 }
4822
4823 /* Initialize a temporary of type TYPE with EXPR.  The FLAGS are a
4824    bitwise or of LOOKUP_* values.  If any errors are warnings are
4825    generated, set *DIAGNOSTIC_FN to "error" or "warning",
4826    respectively.  If no diagnostics are generated, set *DIAGNOSTIC_FN
4827    to NULL.  */
4828
4829 static tree
4830 build_temp (tree expr, tree type, int flags,
4831             diagnostic_t *diagnostic_kind)
4832 {
4833   int savew, savee;
4834   VEC(tree,gc) *args;
4835
4836   savew = warningcount, savee = errorcount;
4837   args = make_tree_vector_single (expr);
4838   expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
4839                                     &args, type, flags, tf_warning_or_error);
4840   release_tree_vector (args);
4841   if (warningcount > savew)
4842     *diagnostic_kind = DK_WARNING;
4843   else if (errorcount > savee)
4844     *diagnostic_kind = DK_ERROR;
4845   else
4846     *diagnostic_kind = DK_UNSPECIFIED;
4847   return expr;
4848 }
4849
4850 /* Perform warnings about peculiar, but valid, conversions from/to NULL.
4851    EXPR is implicitly converted to type TOTYPE.
4852    FN and ARGNUM are used for diagnostics.  */
4853
4854 static void
4855 conversion_null_warnings (tree totype, tree expr, tree fn, int argnum)
4856 {
4857   tree t = non_reference (totype);
4858
4859   /* Issue warnings about peculiar, but valid, uses of NULL.  */
4860   if (expr == null_node && TREE_CODE (t) != BOOLEAN_TYPE && ARITHMETIC_TYPE_P (t))
4861     {
4862       if (fn)
4863         warning_at (input_location, OPT_Wconversion_null,
4864                     "passing NULL to non-pointer argument %P of %qD",
4865                     argnum, fn);
4866       else
4867         warning_at (input_location, OPT_Wconversion_null,
4868                     "converting to non-pointer type %qT from NULL", t);
4869     }
4870
4871   /* Issue warnings if "false" is converted to a NULL pointer */
4872   else if (expr == boolean_false_node && fn && POINTER_TYPE_P (t))
4873     warning_at (input_location, OPT_Wconversion_null,
4874                 "converting %<false%> to pointer type for argument %P of %qD",
4875                 argnum, fn);
4876 }
4877
4878 /* Perform the conversions in CONVS on the expression EXPR.  FN and
4879    ARGNUM are used for diagnostics.  ARGNUM is zero based, -1
4880    indicates the `this' argument of a method.  INNER is nonzero when
4881    being called to continue a conversion chain. It is negative when a
4882    reference binding will be applied, positive otherwise.  If
4883    ISSUE_CONVERSION_WARNINGS is true, warnings about suspicious
4884    conversions will be emitted if appropriate.  If C_CAST_P is true,
4885    this conversion is coming from a C-style cast; in that case,
4886    conversions to inaccessible bases are permitted.  */
4887
4888 static tree
4889 convert_like_real (conversion *convs, tree expr, tree fn, int argnum,
4890                    int inner, bool issue_conversion_warnings,
4891                    bool c_cast_p, tsubst_flags_t complain)
4892 {
4893   tree totype = convs->type;
4894   diagnostic_t diag_kind;
4895   int flags;
4896
4897   if (convs->bad_p
4898       && convs->kind != ck_user
4899       && convs->kind != ck_list
4900       && convs->kind != ck_ambig
4901       && convs->kind != ck_ref_bind
4902       && convs->kind != ck_rvalue
4903       && convs->kind != ck_base)
4904     {
4905       conversion *t = convs;
4906
4907       /* Give a helpful error if this is bad because of excess braces.  */
4908       if (BRACE_ENCLOSED_INITIALIZER_P (expr)
4909           && SCALAR_TYPE_P (totype)
4910           && CONSTRUCTOR_NELTS (expr) > 0
4911           && BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (expr, 0)->value))
4912         permerror (input_location, "too many braces around initializer for %qT", totype);
4913
4914       for (; t; t = convs->u.next)
4915         {
4916           if (t->kind == ck_user || !t->bad_p)
4917             {
4918               expr = convert_like_real (t, expr, fn, argnum, 1,
4919                                         /*issue_conversion_warnings=*/false,
4920                                         /*c_cast_p=*/false,
4921                                         complain);
4922               break;
4923             }
4924           else if (t->kind == ck_ambig)
4925             return convert_like_real (t, expr, fn, argnum, 1,
4926                                       /*issue_conversion_warnings=*/false,
4927                                       /*c_cast_p=*/false,
4928                                       complain);
4929           else if (t->kind == ck_identity)
4930             break;
4931         }
4932       if (complain & tf_error)
4933         {
4934           permerror (input_location, "invalid conversion from %qT to %qT", TREE_TYPE (expr), totype);
4935           if (fn)
4936             permerror (input_location, "  initializing argument %P of %qD", argnum, fn);
4937         }
4938       else
4939         return error_mark_node;
4940
4941       return cp_convert (totype, expr);
4942     }
4943
4944   if (issue_conversion_warnings && (complain & tf_warning))
4945     conversion_null_warnings (totype, expr, fn, argnum);
4946
4947   switch (convs->kind)
4948     {
4949     case ck_user:
4950       {
4951         struct z_candidate *cand = convs->cand;
4952         tree convfn = cand->fn;
4953         unsigned i;
4954
4955         expr = mark_rvalue_use (expr);
4956
4957         /* When converting from an init list we consider explicit
4958            constructors, but actually trying to call one is an error.  */
4959         if (DECL_NONCONVERTING_P (convfn) && DECL_CONSTRUCTOR_P (convfn))
4960           {
4961             if (complain & tf_error)
4962               error ("converting to %qT from initializer list would use "
4963                      "explicit constructor %qD", totype, convfn);
4964             else
4965               return error_mark_node;
4966           }
4967
4968         /* Set user_conv_p on the argument conversions, so rvalue/base
4969            handling knows not to allow any more UDCs.  */
4970         for (i = 0; i < cand->num_convs; ++i)
4971           cand->convs[i]->user_conv_p = true;
4972
4973         expr = build_over_call (cand, LOOKUP_NORMAL, complain);
4974
4975         /* If this is a constructor or a function returning an aggr type,
4976            we need to build up a TARGET_EXPR.  */
4977         if (DECL_CONSTRUCTOR_P (convfn))
4978           {
4979             expr = build_cplus_new (totype, expr);
4980
4981             /* Remember that this was list-initialization.  */
4982             if (convs->check_narrowing)
4983               TARGET_EXPR_LIST_INIT_P (expr) = true;
4984           }
4985
4986         return expr;
4987       }
4988     case ck_identity:
4989       expr = mark_rvalue_use (expr);
4990       if (BRACE_ENCLOSED_INITIALIZER_P (expr))
4991         {
4992           int nelts = CONSTRUCTOR_NELTS (expr);
4993           if (nelts == 0)
4994             expr = integer_zero_node;
4995           else if (nelts == 1)
4996             expr = CONSTRUCTOR_ELT (expr, 0)->value;
4997           else
4998             gcc_unreachable ();
4999         }
5000
5001       if (type_unknown_p (expr))
5002         expr = instantiate_type (totype, expr, complain);
5003       /* Convert a constant to its underlying value, unless we are
5004          about to bind it to a reference, in which case we need to
5005          leave it as an lvalue.  */
5006       if (inner >= 0)
5007         {   
5008           expr = decl_constant_value (expr);
5009           if (expr == null_node && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (totype))
5010             /* If __null has been converted to an integer type, we do not
5011                want to warn about uses of EXPR as an integer, rather than
5012                as a pointer.  */
5013             expr = build_int_cst (totype, 0);
5014         }
5015       return expr;
5016     case ck_ambig:
5017       if (!(complain & tf_error))
5018         return error_mark_node;
5019       /* Call build_user_type_conversion again for the error.  */
5020       return build_user_type_conversion
5021         (totype, convs->u.expr, LOOKUP_NORMAL);
5022
5023     case ck_list:
5024       {
5025         /* Conversion to std::initializer_list<T>.  */
5026         tree elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (totype), 0);
5027         tree new_ctor = build_constructor (init_list_type_node, NULL);
5028         unsigned len = CONSTRUCTOR_NELTS (expr);
5029         tree array, val;
5030         VEC(tree,gc) *parms;
5031         unsigned ix;
5032
5033         /* Convert all the elements.  */
5034         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), ix, val)
5035           {
5036             tree sub = convert_like_real (convs->u.list[ix], val, fn, argnum,
5037                                           1, false, false, complain);
5038             if (sub == error_mark_node)
5039               return sub;
5040             check_narrowing (TREE_TYPE (sub), val);
5041             CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_ctor), NULL_TREE, sub);
5042           }
5043         /* Build up the array.  */
5044         elttype = cp_build_qualified_type
5045           (elttype, cp_type_quals (elttype) | TYPE_QUAL_CONST);
5046         array = build_array_of_n_type (elttype, len);
5047         array = finish_compound_literal (array, new_ctor);
5048
5049         parms = make_tree_vector ();
5050         VEC_safe_push (tree, gc, parms, decay_conversion (array));
5051         VEC_safe_push (tree, gc, parms, size_int (len));
5052         /* Call the private constructor.  */
5053         push_deferring_access_checks (dk_no_check);
5054         new_ctor = build_special_member_call
5055           (NULL_TREE, complete_ctor_identifier, &parms, totype, 0, complain);
5056         release_tree_vector (parms);
5057         pop_deferring_access_checks ();
5058         return build_cplus_new (totype, new_ctor);
5059       }
5060
5061     case ck_aggr:
5062       return get_target_expr (digest_init (totype, expr));
5063
5064     default:
5065       break;
5066     };
5067
5068   expr = convert_like_real (convs->u.next, expr, fn, argnum,
5069                             convs->kind == ck_ref_bind ? -1 : 1,
5070                             convs->kind == ck_ref_bind ? issue_conversion_warnings : false, 
5071                             c_cast_p,
5072                             complain);
5073   if (expr == error_mark_node)
5074     return error_mark_node;
5075
5076   switch (convs->kind)
5077     {
5078     case ck_rvalue:
5079       expr = decay_conversion (expr);
5080       if (! MAYBE_CLASS_TYPE_P (totype))
5081         return expr;
5082       /* Else fall through.  */
5083     case ck_base:
5084       if (convs->kind == ck_base && !convs->need_temporary_p)
5085         {
5086           /* We are going to bind a reference directly to a base-class
5087              subobject of EXPR.  */
5088           /* Build an expression for `*((base*) &expr)'.  */
5089           expr = cp_build_unary_op (ADDR_EXPR, expr, 0, complain);
5090           expr = convert_to_base (expr, build_pointer_type (totype),
5091                                   !c_cast_p, /*nonnull=*/true, complain);
5092           expr = cp_build_indirect_ref (expr, RO_IMPLICIT_CONVERSION, complain);
5093           return expr;
5094         }
5095
5096       /* Copy-initialization where the cv-unqualified version of the source
5097          type is the same class as, or a derived class of, the class of the
5098          destination [is treated as direct-initialization].  [dcl.init] */
5099       flags = LOOKUP_NORMAL|LOOKUP_ONLYCONVERTING;
5100       if (convs->user_conv_p)
5101         /* This conversion is being done in the context of a user-defined
5102            conversion (i.e. the second step of copy-initialization), so
5103            don't allow any more.  */
5104         flags |= LOOKUP_NO_CONVERSION;
5105       expr = build_temp (expr, totype, flags, &diag_kind);
5106       if (diag_kind && fn)
5107         {
5108           if ((complain & tf_error))
5109             emit_diagnostic (diag_kind, input_location, 0, 
5110                              "  initializing argument %P of %qD", argnum, fn);
5111           else if (diag_kind == DK_ERROR)
5112             return error_mark_node;
5113         }
5114       return build_cplus_new (totype, expr);
5115
5116     case ck_ref_bind:
5117       {
5118         tree ref_type = totype;
5119
5120         if (convs->bad_p && TYPE_REF_IS_RVALUE (ref_type)
5121             && real_lvalue_p (expr))
5122           {
5123             if (complain & tf_error)
5124               {
5125                 error ("cannot bind %qT lvalue to %qT",
5126                        TREE_TYPE (expr), totype);
5127                 if (fn)
5128                   error ("  initializing argument %P of %q+D", argnum, fn);
5129               }
5130             return error_mark_node;
5131           }
5132
5133         /* If necessary, create a temporary. 
5134
5135            VA_ARG_EXPR and CONSTRUCTOR expressions are special cases
5136            that need temporaries, even when their types are reference
5137            compatible with the type of reference being bound, so the
5138            upcoming call to cp_build_unary_op (ADDR_EXPR, expr, ...)
5139            doesn't fail.  */
5140         if (convs->need_temporary_p
5141             || TREE_CODE (expr) == CONSTRUCTOR
5142             || TREE_CODE (expr) == VA_ARG_EXPR)
5143           {
5144             tree type = convs->u.next->type;
5145             cp_lvalue_kind lvalue = real_lvalue_p (expr);
5146
5147             if (!CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (ref_type))
5148                 && !TYPE_REF_IS_RVALUE (ref_type))
5149               {
5150                 if (complain & tf_error)
5151                   {
5152                     /* If the reference is volatile or non-const, we
5153                        cannot create a temporary.  */
5154                     if (lvalue & clk_bitfield)
5155                       error ("cannot bind bitfield %qE to %qT",
5156                              expr, ref_type);
5157                     else if (lvalue & clk_packed)
5158                       error ("cannot bind packed field %qE to %qT",
5159                              expr, ref_type);
5160                     else
5161                       error ("cannot bind rvalue %qE to %qT", expr, ref_type);
5162                   }
5163                 return error_mark_node;
5164               }
5165             /* If the source is a packed field, and we must use a copy
5166                constructor, then building the target expr will require
5167                binding the field to the reference parameter to the
5168                copy constructor, and we'll end up with an infinite
5169                loop.  If we can use a bitwise copy, then we'll be
5170                OK.  */
5171             if ((lvalue & clk_packed)
5172                 && CLASS_TYPE_P (type)
5173                 && !TYPE_HAS_TRIVIAL_INIT_REF (type))
5174               {
5175                 if (complain & tf_error)
5176                   error ("cannot bind packed field %qE to %qT",
5177                          expr, ref_type);
5178                 return error_mark_node;
5179               }
5180             if (lvalue & clk_bitfield)
5181               {
5182                 expr = convert_bitfield_to_declared_type (expr);
5183                 expr = fold_convert (type, expr);
5184               }
5185             expr = build_target_expr_with_type (expr, type);
5186           }
5187
5188         /* Take the address of the thing to which we will bind the
5189            reference.  */
5190         expr = cp_build_unary_op (ADDR_EXPR, expr, 1, complain);
5191         if (expr == error_mark_node)
5192           return error_mark_node;
5193
5194         /* Convert it to a pointer to the type referred to by the
5195            reference.  This will adjust the pointer if a derived to
5196            base conversion is being performed.  */
5197         expr = cp_convert (build_pointer_type (TREE_TYPE (ref_type)),
5198                            expr);
5199         /* Convert the pointer to the desired reference type.  */
5200         return build_nop (ref_type, expr);
5201       }
5202
5203     case ck_lvalue:
5204       return decay_conversion (expr);
5205
5206     case ck_qual:
5207       /* Warn about deprecated conversion if appropriate.  */
5208       string_conv_p (totype, expr, 1);
5209       break;
5210
5211     case ck_ptr:
5212       if (convs->base_p)
5213         expr = convert_to_base (expr, totype, !c_cast_p,
5214                                 /*nonnull=*/false, complain);
5215       return build_nop (totype, expr);
5216
5217     case ck_pmem:
5218       return convert_ptrmem (totype, expr, /*allow_inverse_p=*/false,
5219                              c_cast_p);
5220
5221     default:
5222       break;
5223     }
5224
5225   if (convs->check_narrowing)
5226     check_narrowing (totype, expr);
5227
5228   if (issue_conversion_warnings && (complain & tf_warning))
5229     expr = convert_and_check (totype, expr);
5230   else
5231     expr = convert (totype, expr);
5232
5233   return expr;
5234 }
5235
5236 /* ARG is being passed to a varargs function.  Perform any conversions
5237    required.  Return the converted value.  */
5238
5239 tree
5240 convert_arg_to_ellipsis (tree arg)
5241 {
5242   /* [expr.call]
5243
5244      The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
5245      standard conversions are performed.  */
5246   arg = decay_conversion (arg);
5247   /* [expr.call]
5248
5249      If the argument has integral or enumeration type that is subject
5250      to the integral promotions (_conv.prom_), or a floating point
5251      type that is subject to the floating point promotion
5252      (_conv.fpprom_), the value of the argument is converted to the
5253      promoted type before the call.  */
5254   if (TREE_CODE (TREE_TYPE (arg)) == REAL_TYPE
5255       && (TYPE_PRECISION (TREE_TYPE (arg))
5256           < TYPE_PRECISION (double_type_node))
5257       && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (arg))))
5258     arg = convert_to_real (double_type_node, arg);
5259   else if (NULLPTR_TYPE_P (TREE_TYPE (arg)))
5260     arg = null_pointer_node;
5261   else if (INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (arg)))
5262     arg = perform_integral_promotions (arg);
5263
5264   arg = require_complete_type (arg);
5265
5266   if (arg != error_mark_node
5267       && (type_has_nontrivial_copy_init (TREE_TYPE (arg))
5268           || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (arg))))
5269     {
5270       /* [expr.call] 5.2.2/7:
5271          Passing a potentially-evaluated argument of class type (Clause 9)
5272          with a non-trivial copy constructor or a non-trivial destructor
5273          with no corresponding parameter is conditionally-supported, with
5274          implementation-defined semantics.
5275
5276          We used to just warn here and do a bitwise copy, but now
5277          cp_expr_size will abort if we try to do that.
5278
5279          If the call appears in the context of a sizeof expression,
5280          it is not potentially-evaluated.  */
5281       if (cp_unevaluated_operand == 0)
5282         error ("cannot pass objects of non-trivially-copyable "
5283                "type %q#T through %<...%>", TREE_TYPE (arg));
5284     }
5285
5286   return arg;
5287 }
5288
5289 /* va_arg (EXPR, TYPE) is a builtin. Make sure it is not abused.  */
5290
5291 tree
5292 build_x_va_arg (tree expr, tree type)
5293 {
5294   if (processing_template_decl)
5295     return build_min (VA_ARG_EXPR, type, expr);
5296
5297   type = complete_type_or_else (type, NULL_TREE);
5298
5299   if (expr == error_mark_node || !type)
5300     return error_mark_node;
5301
5302   expr = mark_lvalue_use (expr);
5303
5304   if (type_has_nontrivial_copy_init (type)
5305       || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
5306       || TREE_CODE (type) == REFERENCE_TYPE)
5307     {
5308       /* Remove reference types so we don't ICE later on.  */
5309       tree type1 = non_reference (type);
5310       /* conditionally-supported behavior [expr.call] 5.2.2/7.  */
5311       error ("cannot receive objects of non-trivially-copyable type %q#T "
5312              "through %<...%>; ", type);
5313       expr = convert (build_pointer_type (type1), null_node);
5314       expr = cp_build_indirect_ref (expr, RO_NULL, tf_warning_or_error);
5315       return expr;
5316     }
5317
5318   return build_va_arg (input_location, expr, type);
5319 }
5320
5321 /* TYPE has been given to va_arg.  Apply the default conversions which
5322    would have happened when passed via ellipsis.  Return the promoted
5323    type, or the passed type if there is no change.  */
5324
5325 tree
5326 cxx_type_promotes_to (tree type)
5327 {
5328   tree promote;
5329
5330   /* Perform the array-to-pointer and function-to-pointer
5331      conversions.  */
5332   type = type_decays_to (type);
5333
5334   promote = type_promotes_to (type);
5335   if (same_type_p (type, promote))
5336     promote = type;
5337
5338   return promote;
5339 }
5340
5341 /* ARG is a default argument expression being passed to a parameter of
5342    the indicated TYPE, which is a parameter to FN.  Do any required
5343    conversions.  Return the converted value.  */
5344
5345 static GTY(()) VEC(tree,gc) *default_arg_context;
5346
5347 tree
5348 convert_default_arg (tree type, tree arg, tree fn, int parmnum)
5349 {
5350   int i;
5351   tree t;
5352
5353   /* If the ARG is an unparsed default argument expression, the
5354      conversion cannot be performed.  */
5355   if (TREE_CODE (arg) == DEFAULT_ARG)
5356     {
5357       error ("the default argument for parameter %d of %qD has "
5358              "not yet been parsed",
5359              parmnum, fn);
5360       return error_mark_node;
5361     }
5362
5363   /* Detect recursion.  */
5364   for (i = 0; VEC_iterate (tree, default_arg_context, i, t); ++i)
5365     if (t == fn)
5366       {
5367         error ("recursive evaluation of default argument for %q#D", fn);
5368         return error_mark_node;
5369       }
5370   VEC_safe_push (tree, gc, default_arg_context, fn);
5371
5372   if (fn && DECL_TEMPLATE_INFO (fn))
5373     arg = tsubst_default_argument (fn, type, arg);
5374
5375   /* Due to:
5376
5377        [dcl.fct.default]
5378
5379        The names in the expression are bound, and the semantic
5380        constraints are checked, at the point where the default
5381        expressions appears.
5382
5383      we must not perform access checks here.  */
5384   push_deferring_access_checks (dk_no_check);
5385   arg = break_out_target_exprs (arg);
5386   if (TREE_CODE (arg) == CONSTRUCTOR)
5387     {
5388       arg = digest_init (type, arg);
5389       arg = convert_for_initialization (0, type, arg, LOOKUP_NORMAL,
5390                                         ICR_DEFAULT_ARGUMENT, fn, parmnum,
5391                                         tf_warning_or_error);
5392     }
5393   else
5394     {
5395       /* We must make a copy of ARG, in case subsequent processing
5396          alters any part of it.  For example, during gimplification a
5397          cast of the form (T) &X::f (where "f" is a member function)
5398          will lead to replacing the PTRMEM_CST for &X::f with a
5399          VAR_DECL.  We can avoid the copy for constants, since they
5400          are never modified in place.  */
5401       if (!CONSTANT_CLASS_P (arg))
5402         arg = unshare_expr (arg);
5403       arg = convert_for_initialization (0, type, arg, LOOKUP_NORMAL,
5404                                         ICR_DEFAULT_ARGUMENT, fn, parmnum,
5405                                         tf_warning_or_error);
5406       arg = convert_for_arg_passing (type, arg);
5407     }
5408   pop_deferring_access_checks();
5409
5410   VEC_pop (tree, default_arg_context);
5411
5412   return arg;
5413 }
5414
5415 /* Returns the type which will really be used for passing an argument of
5416    type TYPE.  */
5417
5418 tree
5419 type_passed_as (tree type)
5420 {
5421   /* Pass classes with copy ctors by invisible reference.  */
5422   if (TREE_ADDRESSABLE (type))
5423     {
5424       type = build_reference_type (type);
5425       /* There are no other pointers to this temporary.  */
5426       type = cp_build_qualified_type (type, TYPE_QUAL_RESTRICT);
5427     }
5428   else if (targetm.calls.promote_prototypes (type)
5429            && INTEGRAL_TYPE_P (type)
5430            && COMPLETE_TYPE_P (type)
5431            && INT_CST_LT_UNSIGNED (TYPE_SIZE (type),
5432                                    TYPE_SIZE (integer_type_node)))
5433     type = integer_type_node;
5434
5435   return type;
5436 }
5437
5438 /* Actually perform the appropriate conversion.  */
5439
5440 tree
5441 convert_for_arg_passing (tree type, tree val)
5442 {
5443   tree bitfield_type;
5444
5445   /* If VAL is a bitfield, then -- since it has already been converted
5446      to TYPE -- it cannot have a precision greater than TYPE.  
5447
5448      If it has a smaller precision, we must widen it here.  For
5449      example, passing "int f:3;" to a function expecting an "int" will
5450      not result in any conversion before this point.
5451
5452      If the precision is the same we must not risk widening.  For
5453      example, the COMPONENT_REF for a 32-bit "long long" bitfield will
5454      often have type "int", even though the C++ type for the field is
5455      "long long".  If the value is being passed to a function
5456      expecting an "int", then no conversions will be required.  But,
5457      if we call convert_bitfield_to_declared_type, the bitfield will
5458      be converted to "long long".  */
5459   bitfield_type = is_bitfield_expr_with_lowered_type (val);
5460   if (bitfield_type 
5461       && TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type))
5462     val = convert_to_integer (TYPE_MAIN_VARIANT (bitfield_type), val);
5463
5464   if (val == error_mark_node)
5465     ;
5466   /* Pass classes with copy ctors by invisible reference.  */
5467   else if (TREE_ADDRESSABLE (type))
5468     val = build1 (ADDR_EXPR, build_reference_type (type), val);
5469   else if (targetm.calls.promote_prototypes (type)
5470            && INTEGRAL_TYPE_P (type)
5471            && COMPLETE_TYPE_P (type)
5472            && INT_CST_LT_UNSIGNED (TYPE_SIZE (type),
5473                                    TYPE_SIZE (integer_type_node)))
5474     val = perform_integral_promotions (val);
5475   if (warn_missing_format_attribute)
5476     {
5477       tree rhstype = TREE_TYPE (val);
5478       const enum tree_code coder = TREE_CODE (rhstype);
5479       const enum tree_code codel = TREE_CODE (type);
5480       if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
5481           && coder == codel
5482           && check_missing_format_attribute (type, rhstype))
5483         warning (OPT_Wmissing_format_attribute,
5484                  "argument of function call might be a candidate for a format attribute");
5485     }
5486   return val;
5487 }
5488
5489 /* Returns true iff FN is a function with magic varargs, i.e. ones for
5490    which no conversions at all should be done.  This is true for some
5491    builtins which don't act like normal functions.  */
5492
5493 static bool
5494 magic_varargs_p (tree fn)
5495 {
5496   if (DECL_BUILT_IN (fn))
5497     switch (DECL_FUNCTION_CODE (fn))
5498       {
5499       case BUILT_IN_CLASSIFY_TYPE:
5500       case BUILT_IN_CONSTANT_P:
5501       case BUILT_IN_NEXT_ARG:
5502       case BUILT_IN_VA_START:
5503         return true;
5504
5505       default:;
5506         return lookup_attribute ("type generic",
5507                                  TYPE_ATTRIBUTES (TREE_TYPE (fn))) != 0;
5508       }
5509
5510   return false;
5511 }
5512
5513 /* Subroutine of the various build_*_call functions.  Overload resolution
5514    has chosen a winning candidate CAND; build up a CALL_EXPR accordingly.
5515    ARGS is a TREE_LIST of the unconverted arguments to the call.  FLAGS is a
5516    bitmask of various LOOKUP_* flags which apply to the call itself.  */
5517
5518 static tree
5519 build_over_call (struct z_candidate *cand, int flags, tsubst_flags_t complain)
5520 {
5521   tree fn = cand->fn;
5522   const VEC(tree,gc) *args = cand->args;
5523   tree first_arg = cand->first_arg;
5524   conversion **convs = cand->convs;
5525   conversion *conv;
5526   tree parm = TYPE_ARG_TYPES (TREE_TYPE (fn));
5527   int parmlen;
5528   tree val;
5529   int i = 0;
5530   int j = 0;
5531   unsigned int arg_index = 0;
5532   int is_method = 0;
5533   int nargs;
5534   tree *argarray;
5535   bool already_used = false;
5536
5537   /* In a template, there is no need to perform all of the work that
5538      is normally done.  We are only interested in the type of the call
5539      expression, i.e., the return type of the function.  Any semantic
5540      errors will be deferred until the template is instantiated.  */
5541   if (processing_template_decl)
5542     {
5543       tree expr;
5544       tree return_type;
5545       const tree *argarray;
5546       unsigned int nargs;
5547
5548       return_type = TREE_TYPE (TREE_TYPE (fn));
5549       nargs = VEC_length (tree, args);
5550       if (first_arg == NULL_TREE)
5551         argarray = VEC_address (tree, CONST_CAST (VEC(tree,gc) *, args));
5552       else
5553         {
5554           tree *alcarray;
5555           unsigned int ix;
5556           tree arg;
5557
5558           ++nargs;
5559           alcarray = XALLOCAVEC (tree, nargs);
5560           alcarray[0] = first_arg;
5561           for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
5562             alcarray[ix + 1] = arg;
5563           argarray = alcarray;
5564         }
5565       expr = build_call_array_loc (input_location,
5566                                    return_type, build_addr_func (fn), nargs,
5567                                    argarray);
5568       if (TREE_THIS_VOLATILE (fn) && cfun)
5569         current_function_returns_abnormally = 1;
5570       if (!VOID_TYPE_P (return_type))
5571         require_complete_type (return_type);
5572       return convert_from_reference (expr);
5573     }
5574
5575   /* Give any warnings we noticed during overload resolution.  */
5576   if (cand->warnings)
5577     {
5578       struct candidate_warning *w;
5579       for (w = cand->warnings; w; w = w->next)
5580         joust (cand, w->loser, 1);
5581     }
5582
5583   /* Make =delete work with SFINAE.  */
5584   if (DECL_DELETED_FN (fn) && !(complain & tf_error))
5585     return error_mark_node;
5586
5587   if (DECL_FUNCTION_MEMBER_P (fn))
5588     {
5589       /* If FN is a template function, two cases must be considered.
5590          For example:
5591
5592            struct A {
5593              protected:
5594                template <class T> void f();
5595            };
5596            template <class T> struct B {
5597              protected:
5598                void g();
5599            };
5600            struct C : A, B<int> {
5601              using A::f;        // #1
5602              using B<int>::g;   // #2
5603            };
5604
5605          In case #1 where `A::f' is a member template, DECL_ACCESS is
5606          recorded in the primary template but not in its specialization.
5607          We check access of FN using its primary template.
5608
5609          In case #2, where `B<int>::g' has a DECL_TEMPLATE_INFO simply
5610          because it is a member of class template B, DECL_ACCESS is
5611          recorded in the specialization `B<int>::g'.  We cannot use its
5612          primary template because `B<T>::g' and `B<int>::g' may have
5613          different access.  */
5614       if (DECL_TEMPLATE_INFO (fn)
5615           && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
5616         perform_or_defer_access_check (cand->access_path,
5617                                        DECL_TI_TEMPLATE (fn), fn);
5618       else
5619         perform_or_defer_access_check (cand->access_path, fn, fn);
5620     }
5621
5622   /* Find maximum size of vector to hold converted arguments.  */
5623   parmlen = list_length (parm);
5624   nargs = VEC_length (tree, args) + (first_arg != NULL_TREE ? 1 : 0);
5625   if (parmlen > nargs)
5626     nargs = parmlen;
5627   argarray = XALLOCAVEC (tree, nargs);
5628
5629   /* The implicit parameters to a constructor are not considered by overload
5630      resolution, and must be of the proper type.  */
5631   if (DECL_CONSTRUCTOR_P (fn))
5632     {
5633       if (first_arg != NULL_TREE)
5634         {
5635           argarray[j++] = first_arg;
5636           first_arg = NULL_TREE;
5637         }
5638       else
5639         {
5640           argarray[j++] = VEC_index (tree, args, arg_index);
5641           ++arg_index;
5642         }
5643       parm = TREE_CHAIN (parm);
5644       /* We should never try to call the abstract constructor.  */
5645       gcc_assert (!DECL_HAS_IN_CHARGE_PARM_P (fn));
5646
5647       if (DECL_HAS_VTT_PARM_P (fn))
5648         {
5649           argarray[j++] = VEC_index (tree, args, arg_index);
5650           ++arg_index;
5651           parm = TREE_CHAIN (parm);
5652         }
5653     }
5654   /* Bypass access control for 'this' parameter.  */
5655   else if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
5656     {
5657       tree parmtype = TREE_VALUE (parm);
5658       tree arg = (first_arg != NULL_TREE
5659                   ? first_arg
5660                   : VEC_index (tree, args, arg_index));
5661       tree argtype = TREE_TYPE (arg);
5662       tree converted_arg;
5663       tree base_binfo;
5664
5665       if (convs[i]->bad_p)
5666         {
5667           if (complain & tf_error)
5668             permerror (input_location, "passing %qT as %<this%> argument of %q#D discards qualifiers",
5669                        TREE_TYPE (argtype), fn);
5670           else
5671             return error_mark_node;
5672         }
5673
5674       /* [class.mfct.nonstatic]: If a nonstatic member function of a class
5675          X is called for an object that is not of type X, or of a type
5676          derived from X, the behavior is undefined.
5677
5678          So we can assume that anything passed as 'this' is non-null, and
5679          optimize accordingly.  */
5680       gcc_assert (TREE_CODE (parmtype) == POINTER_TYPE);
5681       /* Convert to the base in which the function was declared.  */
5682       gcc_assert (cand->conversion_path != NULL_TREE);
5683       converted_arg = build_base_path (PLUS_EXPR,
5684                                        arg,
5685                                        cand->conversion_path,
5686                                        1);
5687       /* Check that the base class is accessible.  */
5688       if (!accessible_base_p (TREE_TYPE (argtype),
5689                               BINFO_TYPE (cand->conversion_path), true))
5690         error ("%qT is not an accessible base of %qT",
5691                BINFO_TYPE (cand->conversion_path),
5692                TREE_TYPE (argtype));
5693       /* If fn was found by a using declaration, the conversion path
5694          will be to the derived class, not the base declaring fn. We
5695          must convert from derived to base.  */
5696       base_binfo = lookup_base (TREE_TYPE (TREE_TYPE (converted_arg)),
5697                                 TREE_TYPE (parmtype), ba_unique, NULL);
5698       converted_arg = build_base_path (PLUS_EXPR, converted_arg,
5699                                        base_binfo, 1);
5700
5701       argarray[j++] = converted_arg;
5702       parm = TREE_CHAIN (parm);
5703       if (first_arg != NULL_TREE)
5704         first_arg = NULL_TREE;
5705       else
5706         ++arg_index;
5707       ++i;
5708       is_method = 1;
5709     }
5710
5711   gcc_assert (first_arg == NULL_TREE);
5712   for (; arg_index < VEC_length (tree, args) && parm;
5713        parm = TREE_CHAIN (parm), ++arg_index, ++i)
5714     {
5715       tree type = TREE_VALUE (parm);
5716       tree arg = VEC_index (tree, args, arg_index);
5717
5718       conv = convs[i];
5719
5720       /* Don't make a copy here if build_call is going to.  */
5721       if (conv->kind == ck_rvalue
5722           && COMPLETE_TYPE_P (complete_type (type))
5723           && !TREE_ADDRESSABLE (type))
5724         conv = conv->u.next;
5725
5726       /* Warn about initializer_list deduction that isn't currently in the
5727          working draft.  */
5728       if (cxx_dialect > cxx98
5729           && flag_deduce_init_list
5730           && cand->template_decl
5731           && is_std_init_list (non_reference (type))
5732           && BRACE_ENCLOSED_INITIALIZER_P (arg))
5733         {
5734           tree tmpl = TI_TEMPLATE (cand->template_decl);
5735           tree realparm = chain_index (j, DECL_ARGUMENTS (cand->fn));
5736           tree patparm = get_pattern_parm (realparm, tmpl);
5737           tree pattype = TREE_TYPE (patparm);
5738           if (PACK_EXPANSION_P (pattype))
5739             pattype = PACK_EXPANSION_PATTERN (pattype);
5740           pattype = non_reference (pattype);
5741
5742           if (TREE_CODE (pattype) == TEMPLATE_TYPE_PARM
5743               && (cand->explicit_targs == NULL_TREE
5744                   || (TREE_VEC_LENGTH (cand->explicit_targs)
5745                       <= TEMPLATE_TYPE_IDX (pattype))))
5746             {
5747               pedwarn (input_location, 0, "deducing %qT as %qT",
5748                        non_reference (TREE_TYPE (patparm)),
5749                        non_reference (type));
5750               pedwarn (input_location, 0, "  in call to %q+D", cand->fn);
5751               pedwarn (input_location, 0,
5752                        "  (you can disable this with -fno-deduce-init-list)");
5753             }
5754         }
5755
5756       val = convert_like_with_context (conv, arg, fn, i-is_method, complain);
5757
5758       val = convert_for_arg_passing (type, val);
5759       if (val == error_mark_node)
5760         return error_mark_node;
5761       else
5762         argarray[j++] = val;
5763     }
5764
5765   /* Default arguments */
5766   for (; parm && parm != void_list_node; parm = TREE_CHAIN (parm), i++)
5767     argarray[j++] = convert_default_arg (TREE_VALUE (parm),
5768                                          TREE_PURPOSE (parm),
5769                                          fn, i - is_method);
5770   /* Ellipsis */
5771   for (; arg_index < VEC_length (tree, args); ++arg_index)
5772     {
5773       tree a = VEC_index (tree, args, arg_index);
5774       if (magic_varargs_p (fn))
5775         /* Do no conversions for magic varargs.  */
5776         a = mark_type_use (a);
5777       else
5778         a = convert_arg_to_ellipsis (a);
5779       argarray[j++] = a;
5780     }
5781
5782   gcc_assert (j <= nargs);
5783   nargs = j;
5784
5785   check_function_arguments (TYPE_ATTRIBUTES (TREE_TYPE (fn)),
5786                             nargs, argarray, TYPE_ARG_TYPES (TREE_TYPE (fn)));
5787
5788   /* Avoid actually calling copy constructors and copy assignment operators,
5789      if possible.  */
5790
5791   if (! flag_elide_constructors)
5792     /* Do things the hard way.  */;
5793   else if (cand->num_convs == 1 
5794            && (DECL_COPY_CONSTRUCTOR_P (fn) 
5795                || DECL_MOVE_CONSTRUCTOR_P (fn)))
5796     {
5797       tree targ;
5798       tree arg = argarray[num_artificial_parms_for (fn)];
5799       tree fa;
5800
5801       /* Pull out the real argument, disregarding const-correctness.  */
5802       targ = arg;
5803       while (CONVERT_EXPR_P (targ)
5804              || TREE_CODE (targ) == NON_LVALUE_EXPR)
5805         targ = TREE_OPERAND (targ, 0);
5806       if (TREE_CODE (targ) == ADDR_EXPR)
5807         {
5808           targ = TREE_OPERAND (targ, 0);
5809           if (!same_type_ignoring_top_level_qualifiers_p
5810               (TREE_TYPE (TREE_TYPE (arg)), TREE_TYPE (targ)))
5811             targ = NULL_TREE;
5812         }
5813       else
5814         targ = NULL_TREE;
5815
5816       if (targ)
5817         arg = targ;
5818       else
5819         arg = cp_build_indirect_ref (arg, RO_NULL, complain);
5820
5821       if (TREE_CODE (arg) == TARGET_EXPR
5822           && TARGET_EXPR_LIST_INIT_P (arg))
5823         {
5824           /* Copy-list-initialization doesn't require the copy constructor
5825              to be defined.  */
5826         }
5827       /* [class.copy]: the copy constructor is implicitly defined even if
5828          the implementation elided its use.  */
5829       else if (TYPE_HAS_COMPLEX_INIT_REF (DECL_CONTEXT (fn))
5830                || move_fn_p (fn))
5831         {
5832           mark_used (fn);
5833           already_used = true;
5834         }
5835
5836       /* If we're creating a temp and we already have one, don't create a
5837          new one.  If we're not creating a temp but we get one, use
5838          INIT_EXPR to collapse the temp into our target.  Otherwise, if the
5839          ctor is trivial, do a bitwise copy with a simple TARGET_EXPR for a
5840          temp or an INIT_EXPR otherwise.  */
5841       fa = (cand->first_arg != NULL_TREE
5842             ? cand->first_arg
5843             : VEC_index (tree, args, 0));
5844       if (integer_zerop (fa))
5845         {
5846           if (TREE_CODE (arg) == TARGET_EXPR)
5847             return arg;
5848           else if (TYPE_HAS_TRIVIAL_INIT_REF (DECL_CONTEXT (fn))
5849                    && !move_fn_p (fn))
5850             return build_target_expr_with_type (arg, DECL_CONTEXT (fn));
5851         }
5852       else if (TREE_CODE (arg) == TARGET_EXPR
5853                || (TYPE_HAS_TRIVIAL_INIT_REF (DECL_CONTEXT (fn))
5854                    && !move_fn_p (fn)))
5855         {
5856           tree to = stabilize_reference (cp_build_indirect_ref (fa, RO_NULL,
5857                                                                 complain));
5858
5859           val = build2 (INIT_EXPR, DECL_CONTEXT (fn), to, arg);
5860           return val;
5861         }
5862     }
5863   else if (DECL_OVERLOADED_OPERATOR_P (fn) == NOP_EXPR
5864            && copy_fn_p (fn)
5865            && TYPE_HAS_TRIVIAL_ASSIGN_REF (DECL_CONTEXT (fn)))
5866     {
5867       tree to = stabilize_reference
5868         (cp_build_indirect_ref (argarray[0], RO_NULL, complain));
5869       tree type = TREE_TYPE (to);
5870       tree as_base = CLASSTYPE_AS_BASE (type);
5871       tree arg = argarray[1];
5872
5873       if (is_really_empty_class (type))
5874         {
5875           /* Avoid copying empty classes.  */
5876           val = build2 (COMPOUND_EXPR, void_type_node, to, arg);
5877           TREE_NO_WARNING (val) = 1;
5878           val = build2 (COMPOUND_EXPR, type, val, to);
5879           TREE_NO_WARNING (val) = 1;
5880         }
5881       else if (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (as_base)))
5882         {
5883           arg = cp_build_indirect_ref (arg, RO_NULL, complain);
5884           val = build2 (MODIFY_EXPR, TREE_TYPE (to), to, arg);
5885         }
5886       else
5887         {
5888           /* We must only copy the non-tail padding parts.
5889              Use __builtin_memcpy for the bitwise copy.
5890              FIXME fix 22488 so we can go back to using MODIFY_EXPR
5891              instead of an explicit call to memcpy.  */
5892         
5893           tree arg0, arg1, arg2, t;
5894           tree test = NULL_TREE;
5895
5896           arg2 = TYPE_SIZE_UNIT (as_base);
5897           arg1 = arg;
5898           arg0 = cp_build_unary_op (ADDR_EXPR, to, 0, complain);
5899
5900           if (!can_trust_pointer_alignment ())
5901             {
5902               /* If we can't be sure about pointer alignment, a call
5903                  to __builtin_memcpy is expanded as a call to memcpy, which
5904                  is invalid with identical args.  Otherwise it is
5905                  expanded as a block move, which should be safe.  */
5906               arg0 = save_expr (arg0);
5907               arg1 = save_expr (arg1);
5908               test = build2 (EQ_EXPR, boolean_type_node, arg0, arg1);
5909             }
5910           t = implicit_built_in_decls[BUILT_IN_MEMCPY];
5911           t = build_call_n (t, 3, arg0, arg1, arg2);
5912
5913           t = convert (TREE_TYPE (arg0), t);
5914           if (test)
5915             t = build3 (COND_EXPR, TREE_TYPE (t), test, arg0, t);
5916           val = cp_build_indirect_ref (t, RO_NULL, complain);
5917           TREE_NO_WARNING (val) = 1;
5918         }
5919
5920       return val;
5921     }
5922
5923   if (!already_used)
5924     mark_used (fn);
5925
5926   if (DECL_VINDEX (fn) && (flags & LOOKUP_NONVIRTUAL) == 0)
5927     {
5928       tree t;
5929       tree binfo = lookup_base (TREE_TYPE (TREE_TYPE (argarray[0])),
5930                                 DECL_CONTEXT (fn),
5931                                 ba_any, NULL);
5932       gcc_assert (binfo && binfo != error_mark_node);
5933
5934       /* Warn about deprecated virtual functions now, since we're about
5935          to throw away the decl.  */
5936       if (TREE_DEPRECATED (fn))
5937         warn_deprecated_use (fn, NULL_TREE);
5938
5939       argarray[0] = build_base_path (PLUS_EXPR, argarray[0], binfo, 1);
5940       if (TREE_SIDE_EFFECTS (argarray[0]))
5941         argarray[0] = save_expr (argarray[0]);
5942       t = build_pointer_type (TREE_TYPE (fn));
5943       if (DECL_CONTEXT (fn) && TYPE_JAVA_INTERFACE (DECL_CONTEXT (fn)))
5944         fn = build_java_interface_fn_ref (fn, argarray[0]);
5945       else
5946         fn = build_vfn_ref (argarray[0], DECL_VINDEX (fn));
5947       TREE_TYPE (fn) = t;
5948     }
5949   else
5950     fn = build_addr_func (fn);
5951
5952   return build_cxx_call (fn, nargs, argarray);
5953 }
5954
5955 /* Build and return a call to FN, using NARGS arguments in ARGARRAY.
5956    This function performs no overload resolution, conversion, or other
5957    high-level operations.  */
5958
5959 tree
5960 build_cxx_call (tree fn, int nargs, tree *argarray)
5961 {
5962   tree fndecl;
5963
5964   fn = build_call_a (fn, nargs, argarray);
5965
5966   /* If this call might throw an exception, note that fact.  */
5967   fndecl = get_callee_fndecl (fn);
5968   if ((!fndecl || !TREE_NOTHROW (fndecl))
5969       && at_function_scope_p ()
5970       && cfun)
5971     cp_function_chain->can_throw = 1;
5972
5973   /* Check that arguments to builtin functions match the expectations.  */
5974   if (fndecl
5975       && DECL_BUILT_IN (fndecl)
5976       && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
5977       && !check_builtin_function_arguments (fndecl, nargs, argarray))
5978     return error_mark_node;
5979
5980   /* Some built-in function calls will be evaluated at compile-time in
5981      fold ().  */
5982   fn = fold_if_not_in_template (fn);
5983
5984   if (VOID_TYPE_P (TREE_TYPE (fn)))
5985     return fn;
5986
5987   fn = require_complete_type (fn);
5988   if (fn == error_mark_node)
5989     return error_mark_node;
5990
5991   if (MAYBE_CLASS_TYPE_P (TREE_TYPE (fn)))
5992     fn = build_cplus_new (TREE_TYPE (fn), fn);
5993   return convert_from_reference (fn);
5994 }
5995
5996 static GTY(()) tree java_iface_lookup_fn;
5997
5998 /* Make an expression which yields the address of the Java interface
5999    method FN.  This is achieved by generating a call to libjava's
6000    _Jv_LookupInterfaceMethodIdx().  */
6001
6002 static tree
6003 build_java_interface_fn_ref (tree fn, tree instance)
6004 {
6005   tree lookup_fn, method, idx;
6006   tree klass_ref, iface, iface_ref;
6007   int i;
6008
6009   if (!java_iface_lookup_fn)
6010     {
6011       tree ftype = build_function_type_list (ptr_type_node,
6012                                              ptr_type_node, ptr_type_node,
6013                                              java_int_type_node, NULL_TREE);
6014       java_iface_lookup_fn
6015         = add_builtin_function ("_Jv_LookupInterfaceMethodIdx", ftype,
6016                                 0, NOT_BUILT_IN, NULL, NULL_TREE);
6017     }
6018
6019   /* Look up the pointer to the runtime java.lang.Class object for `instance'.
6020      This is the first entry in the vtable.  */
6021   klass_ref = build_vtbl_ref (cp_build_indirect_ref (instance, RO_NULL, 
6022                                                      tf_warning_or_error),
6023                               integer_zero_node);
6024
6025   /* Get the java.lang.Class pointer for the interface being called.  */
6026   iface = DECL_CONTEXT (fn);
6027   iface_ref = lookup_field (iface, get_identifier ("class$"), 0, false);
6028   if (!iface_ref || TREE_CODE (iface_ref) != VAR_DECL
6029       || DECL_CONTEXT (iface_ref) != iface)
6030     {
6031       error ("could not find class$ field in java interface type %qT",
6032                 iface);
6033       return error_mark_node;
6034     }
6035   iface_ref = build_address (iface_ref);
6036   iface_ref = convert (build_pointer_type (iface), iface_ref);
6037
6038   /* Determine the itable index of FN.  */
6039   i = 1;
6040   for (method = TYPE_METHODS (iface); method; method = TREE_CHAIN (method))
6041     {
6042       if (!DECL_VIRTUAL_P (method))
6043         continue;
6044       if (fn == method)
6045         break;
6046       i++;
6047     }
6048   idx = build_int_cst (NULL_TREE, i);
6049
6050   lookup_fn = build1 (ADDR_EXPR,
6051                       build_pointer_type (TREE_TYPE (java_iface_lookup_fn)),
6052                       java_iface_lookup_fn);
6053   return build_call_nary (ptr_type_node, lookup_fn,
6054                           3, klass_ref, iface_ref, idx);
6055 }
6056
6057 /* Returns the value to use for the in-charge parameter when making a
6058    call to a function with the indicated NAME.
6059
6060    FIXME:Can't we find a neater way to do this mapping?  */
6061
6062 tree
6063 in_charge_arg_for_name (tree name)
6064 {
6065  if (name == base_ctor_identifier
6066       || name == base_dtor_identifier)
6067     return integer_zero_node;
6068   else if (name == complete_ctor_identifier)
6069     return integer_one_node;
6070   else if (name == complete_dtor_identifier)
6071     return integer_two_node;
6072   else if (name == deleting_dtor_identifier)
6073     return integer_three_node;
6074
6075   /* This function should only be called with one of the names listed
6076      above.  */
6077   gcc_unreachable ();
6078   return NULL_TREE;
6079 }
6080
6081 /* Build a call to a constructor, destructor, or an assignment
6082    operator for INSTANCE, an expression with class type.  NAME
6083    indicates the special member function to call; *ARGS are the
6084    arguments.  ARGS may be NULL.  This may change ARGS.  BINFO
6085    indicates the base of INSTANCE that is to be passed as the `this'
6086    parameter to the member function called.
6087
6088    FLAGS are the LOOKUP_* flags to use when processing the call.
6089
6090    If NAME indicates a complete object constructor, INSTANCE may be
6091    NULL_TREE.  In this case, the caller will call build_cplus_new to
6092    store the newly constructed object into a VAR_DECL.  */
6093
6094 tree
6095 build_special_member_call (tree instance, tree name, VEC(tree,gc) **args,
6096                            tree binfo, int flags, tsubst_flags_t complain)
6097 {
6098   tree fns;
6099   /* The type of the subobject to be constructed or destroyed.  */
6100   tree class_type;
6101   VEC(tree,gc) *allocated = NULL;
6102   tree ret;
6103
6104   gcc_assert (name == complete_ctor_identifier
6105               || name == base_ctor_identifier
6106               || name == complete_dtor_identifier
6107               || name == base_dtor_identifier
6108               || name == deleting_dtor_identifier
6109               || name == ansi_assopname (NOP_EXPR));
6110   if (TYPE_P (binfo))
6111     {
6112       /* Resolve the name.  */
6113       if (!complete_type_or_else (binfo, NULL_TREE))
6114         return error_mark_node;
6115
6116       binfo = TYPE_BINFO (binfo);
6117     }
6118
6119   gcc_assert (binfo != NULL_TREE);
6120
6121   class_type = BINFO_TYPE (binfo);
6122
6123   /* Handle the special case where INSTANCE is NULL_TREE.  */
6124   if (name == complete_ctor_identifier && !instance)
6125     {
6126       instance = build_int_cst (build_pointer_type (class_type), 0);
6127       instance = build1 (INDIRECT_REF, class_type, instance);
6128     }
6129   else
6130     {
6131       if (name == complete_dtor_identifier
6132           || name == base_dtor_identifier
6133           || name == deleting_dtor_identifier)
6134         gcc_assert (args == NULL || VEC_empty (tree, *args));
6135
6136       /* Convert to the base class, if necessary.  */
6137       if (!same_type_ignoring_top_level_qualifiers_p
6138           (TREE_TYPE (instance), BINFO_TYPE (binfo)))
6139         {
6140           if (name != ansi_assopname (NOP_EXPR))
6141             /* For constructors and destructors, either the base is
6142                non-virtual, or it is virtual but we are doing the
6143                conversion from a constructor or destructor for the
6144                complete object.  In either case, we can convert
6145                statically.  */
6146             instance = convert_to_base_statically (instance, binfo);
6147           else
6148             /* However, for assignment operators, we must convert
6149                dynamically if the base is virtual.  */
6150             instance = build_base_path (PLUS_EXPR, instance,
6151                                         binfo, /*nonnull=*/1);
6152         }
6153     }
6154
6155   gcc_assert (instance != NULL_TREE);
6156
6157   fns = lookup_fnfields (binfo, name, 1);
6158
6159   /* When making a call to a constructor or destructor for a subobject
6160      that uses virtual base classes, pass down a pointer to a VTT for
6161      the subobject.  */
6162   if ((name == base_ctor_identifier
6163        || name == base_dtor_identifier)
6164       && CLASSTYPE_VBASECLASSES (class_type))
6165     {
6166       tree vtt;
6167       tree sub_vtt;
6168
6169       /* If the current function is a complete object constructor
6170          or destructor, then we fetch the VTT directly.
6171          Otherwise, we look it up using the VTT we were given.  */
6172       vtt = TREE_CHAIN (CLASSTYPE_VTABLES (current_class_type));
6173       vtt = decay_conversion (vtt);
6174       vtt = build3 (COND_EXPR, TREE_TYPE (vtt),
6175                     build2 (EQ_EXPR, boolean_type_node,
6176                             current_in_charge_parm, integer_zero_node),
6177                     current_vtt_parm,
6178                     vtt);
6179       gcc_assert (BINFO_SUBVTT_INDEX (binfo));
6180       sub_vtt = build2 (POINTER_PLUS_EXPR, TREE_TYPE (vtt), vtt,
6181                         BINFO_SUBVTT_INDEX (binfo));
6182
6183       if (args == NULL)
6184         {
6185           allocated = make_tree_vector ();
6186           args = &allocated;
6187         }
6188
6189       VEC_safe_insert (tree, gc, *args, 0, sub_vtt);
6190     }
6191
6192   ret = build_new_method_call (instance, fns, args,
6193                                TYPE_BINFO (BINFO_TYPE (binfo)),
6194                                flags, /*fn=*/NULL,
6195                                complain);
6196
6197   if (allocated != NULL)
6198     release_tree_vector (allocated);
6199
6200   return ret;
6201 }
6202
6203 /* Return the NAME, as a C string.  The NAME indicates a function that
6204    is a member of TYPE.  *FREE_P is set to true if the caller must
6205    free the memory returned.
6206
6207    Rather than go through all of this, we should simply set the names
6208    of constructors and destructors appropriately, and dispense with
6209    ctor_identifier, dtor_identifier, etc.  */
6210
6211 static char *
6212 name_as_c_string (tree name, tree type, bool *free_p)
6213 {
6214   char *pretty_name;
6215
6216   /* Assume that we will not allocate memory.  */
6217   *free_p = false;
6218   /* Constructors and destructors are special.  */
6219   if (IDENTIFIER_CTOR_OR_DTOR_P (name))
6220     {
6221       pretty_name
6222         = CONST_CAST (char *, identifier_to_locale (IDENTIFIER_POINTER (constructor_name (type))));
6223       /* For a destructor, add the '~'.  */
6224       if (name == complete_dtor_identifier
6225           || name == base_dtor_identifier
6226           || name == deleting_dtor_identifier)
6227         {
6228           pretty_name = concat ("~", pretty_name, NULL);
6229           /* Remember that we need to free the memory allocated.  */
6230           *free_p = true;
6231         }
6232     }
6233   else if (IDENTIFIER_TYPENAME_P (name))
6234     {
6235       pretty_name = concat ("operator ",
6236                             type_as_string_translate (TREE_TYPE (name),
6237                                                       TFF_PLAIN_IDENTIFIER),
6238                             NULL);
6239       /* Remember that we need to free the memory allocated.  */
6240       *free_p = true;
6241     }
6242   else
6243     pretty_name = CONST_CAST (char *, identifier_to_locale (IDENTIFIER_POINTER (name)));
6244
6245   return pretty_name;
6246 }
6247
6248 /* Build a call to "INSTANCE.FN (ARGS)".  If FN_P is non-NULL, it will
6249    be set, upon return, to the function called.  ARGS may be NULL.
6250    This may change ARGS.  */
6251
6252 tree
6253 build_new_method_call (tree instance, tree fns, VEC(tree,gc) **args,
6254                        tree conversion_path, int flags,
6255                        tree *fn_p, tsubst_flags_t complain)
6256 {
6257   struct z_candidate *candidates = 0, *cand;
6258   tree explicit_targs = NULL_TREE;
6259   tree basetype = NULL_TREE;
6260   tree access_binfo;
6261   tree optype;
6262   tree first_mem_arg = NULL_TREE;
6263   tree instance_ptr;
6264   tree name;
6265   bool skip_first_for_error;
6266   VEC(tree,gc) *user_args;
6267   tree call;
6268   tree fn;
6269   int template_only = 0;
6270   bool any_viable_p;
6271   tree orig_instance;
6272   tree orig_fns;
6273   VEC(tree,gc) *orig_args = NULL;
6274   void *p;
6275
6276   gcc_assert (instance != NULL_TREE);
6277
6278   /* We don't know what function we're going to call, yet.  */
6279   if (fn_p)
6280     *fn_p = NULL_TREE;
6281
6282   if (error_operand_p (instance)
6283       || !fns || error_operand_p (fns))
6284     return error_mark_node;
6285
6286   if (!BASELINK_P (fns))
6287     {
6288       if (complain & tf_error)
6289         error ("call to non-function %qD", fns);
6290       return error_mark_node;
6291     }
6292
6293   orig_instance = instance;
6294   orig_fns = fns;
6295
6296   /* Dismantle the baselink to collect all the information we need.  */
6297   if (!conversion_path)
6298     conversion_path = BASELINK_BINFO (fns);
6299   access_binfo = BASELINK_ACCESS_BINFO (fns);
6300   optype = BASELINK_OPTYPE (fns);
6301   fns = BASELINK_FUNCTIONS (fns);
6302   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
6303     {
6304       explicit_targs = TREE_OPERAND (fns, 1);
6305       fns = TREE_OPERAND (fns, 0);
6306       template_only = 1;
6307     }
6308   gcc_assert (TREE_CODE (fns) == FUNCTION_DECL
6309               || TREE_CODE (fns) == TEMPLATE_DECL
6310               || TREE_CODE (fns) == OVERLOAD);
6311   fn = get_first_fn (fns);
6312   name = DECL_NAME (fn);
6313
6314   basetype = TYPE_MAIN_VARIANT (TREE_TYPE (instance));
6315   gcc_assert (CLASS_TYPE_P (basetype));
6316
6317   if (processing_template_decl)
6318     {
6319       orig_args = args == NULL ? NULL : make_tree_vector_copy (*args);
6320       instance = build_non_dependent_expr (instance);
6321       if (args != NULL)
6322         make_args_non_dependent (*args);
6323     }
6324
6325   user_args = args == NULL ? NULL : *args;
6326   /* Under DR 147 A::A() is an invalid constructor call,
6327      not a functional cast.  */
6328   if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
6329     {
6330       if (! (complain & tf_error))
6331         return error_mark_node;
6332
6333       permerror (input_location,
6334                  "cannot call constructor %<%T::%D%> directly",
6335                  basetype, name);
6336       permerror (input_location, "  for a function-style cast, remove the "
6337                  "redundant %<::%D%>", name);
6338       call = build_functional_cast (basetype, build_tree_list_vec (user_args),
6339                                     complain);
6340       return call;
6341     }
6342
6343   /* Figure out whether to skip the first argument for the error
6344      message we will display to users if an error occurs.  We don't
6345      want to display any compiler-generated arguments.  The "this"
6346      pointer hasn't been added yet.  However, we must remove the VTT
6347      pointer if this is a call to a base-class constructor or
6348      destructor.  */
6349   skip_first_for_error = false;
6350   if (IDENTIFIER_CTOR_OR_DTOR_P (name))
6351     {
6352       /* Callers should explicitly indicate whether they want to construct
6353          the complete object or just the part without virtual bases.  */
6354       gcc_assert (name != ctor_identifier);
6355       /* Similarly for destructors.  */
6356       gcc_assert (name != dtor_identifier);
6357       /* Remove the VTT pointer, if present.  */
6358       if ((name == base_ctor_identifier || name == base_dtor_identifier)
6359           && CLASSTYPE_VBASECLASSES (basetype))
6360         skip_first_for_error = true;
6361     }
6362
6363   /* Process the argument list.  */
6364   if (args != NULL && *args != NULL)
6365     {
6366       *args = resolve_args (*args);
6367       if (*args == NULL)
6368         return error_mark_node;
6369     }
6370
6371   instance_ptr = build_this (instance);
6372
6373   /* It's OK to call destructors and constructors on cv-qualified objects.
6374      Therefore, convert the INSTANCE_PTR to the unqualified type, if
6375      necessary.  */
6376   if (DECL_DESTRUCTOR_P (fn)
6377       || DECL_CONSTRUCTOR_P (fn))
6378     {
6379       tree type = build_pointer_type (basetype);
6380       if (!same_type_p (type, TREE_TYPE (instance_ptr)))
6381         instance_ptr = build_nop (type, instance_ptr);
6382     }
6383   if (DECL_DESTRUCTOR_P (fn))
6384     name = complete_dtor_identifier;
6385
6386   first_mem_arg = instance_ptr;
6387
6388   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
6389   p = conversion_obstack_alloc (0);
6390
6391   /* If CONSTRUCTOR_IS_DIRECT_INIT is set, this was a T{ } form
6392      initializer, not T({ }).  */
6393   if (DECL_CONSTRUCTOR_P (fn) && args != NULL && !VEC_empty (tree, *args)
6394       && BRACE_ENCLOSED_INITIALIZER_P (VEC_index (tree, *args, 0))
6395       && CONSTRUCTOR_IS_DIRECT_INIT (VEC_index (tree, *args, 0)))
6396     {
6397       gcc_assert (VEC_length (tree, *args) == 1
6398                   && !(flags & LOOKUP_ONLYCONVERTING));
6399
6400       add_list_candidates (fns, first_mem_arg, VEC_index (tree, *args, 0),
6401                            basetype, explicit_targs, template_only,
6402                            conversion_path, access_binfo, flags, &candidates);
6403     }
6404   else
6405     {
6406       add_candidates (fns, first_mem_arg, user_args, optype,
6407                       explicit_targs, template_only, conversion_path,
6408                       access_binfo, flags, &candidates);
6409     }
6410   any_viable_p = false;
6411   candidates = splice_viable (candidates, pedantic, &any_viable_p);
6412
6413   if (!any_viable_p)
6414     {
6415       if (complain & tf_error)
6416         {
6417           if (!COMPLETE_TYPE_P (basetype))
6418             cxx_incomplete_type_error (instance_ptr, basetype);
6419           else if (optype)
6420             error ("no matching function for call to %<%T::operator %T(%A)%#V%>",
6421                    basetype, optype, build_tree_list_vec (user_args),
6422                    TREE_TYPE (TREE_TYPE (instance_ptr)));
6423           else
6424             {
6425               char *pretty_name;
6426               bool free_p;
6427               tree arglist;
6428
6429               pretty_name = name_as_c_string (name, basetype, &free_p);
6430               arglist = build_tree_list_vec (user_args);
6431               if (skip_first_for_error)
6432                 arglist = TREE_CHAIN (arglist);
6433               error ("no matching function for call to %<%T::%s(%A)%#V%>",
6434                      basetype, pretty_name, arglist,
6435                      TREE_TYPE (TREE_TYPE (instance_ptr)));
6436               if (free_p)
6437                 free (pretty_name);
6438             }
6439           print_z_candidates (candidates);
6440         }
6441       call = error_mark_node;
6442     }
6443   else
6444     {
6445       cand = tourney (candidates);
6446       if (cand == 0)
6447         {
6448           char *pretty_name;
6449           bool free_p;
6450           tree arglist;
6451
6452           if (complain & tf_error)
6453             {
6454               pretty_name = name_as_c_string (name, basetype, &free_p);
6455               arglist = build_tree_list_vec (user_args);
6456               if (skip_first_for_error)
6457                 arglist = TREE_CHAIN (arglist);
6458               error ("call of overloaded %<%s(%A)%> is ambiguous", pretty_name,
6459                      arglist);
6460               print_z_candidates (candidates);
6461               if (free_p)
6462                 free (pretty_name);
6463             }
6464           call = error_mark_node;
6465         }
6466       else
6467         {
6468           fn = cand->fn;
6469
6470           if (!(flags & LOOKUP_NONVIRTUAL)
6471               && DECL_PURE_VIRTUAL_P (fn)
6472               && instance == current_class_ref
6473               && (DECL_CONSTRUCTOR_P (current_function_decl)
6474                   || DECL_DESTRUCTOR_P (current_function_decl))
6475               && (complain & tf_warning))
6476             /* This is not an error, it is runtime undefined
6477                behavior.  */
6478             warning (0, (DECL_CONSTRUCTOR_P (current_function_decl) ?
6479                       "pure virtual %q#D called from constructor"
6480                       : "pure virtual %q#D called from destructor"),
6481                      fn);
6482
6483           if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
6484               && is_dummy_object (instance_ptr))
6485             {
6486               if (complain & tf_error)
6487                 error ("cannot call member function %qD without object",
6488                        fn);
6489               call = error_mark_node;
6490             }
6491           else
6492             {
6493               if (DECL_VINDEX (fn) && ! (flags & LOOKUP_NONVIRTUAL)
6494                   && resolves_to_fixed_type_p (instance, 0))
6495                 flags |= LOOKUP_NONVIRTUAL;
6496               /* Now we know what function is being called.  */
6497               if (fn_p)
6498                 *fn_p = fn;
6499               /* Build the actual CALL_EXPR.  */
6500               call = build_over_call (cand, flags, complain);
6501               /* In an expression of the form `a->f()' where `f' turns
6502                  out to be a static member function, `a' is
6503                  none-the-less evaluated.  */
6504               if (TREE_CODE (TREE_TYPE (fn)) != METHOD_TYPE
6505                   && !is_dummy_object (instance_ptr)
6506                   && TREE_SIDE_EFFECTS (instance_ptr))
6507                 call = build2 (COMPOUND_EXPR, TREE_TYPE (call),
6508                                instance_ptr, call);
6509               else if (call != error_mark_node
6510                        && DECL_DESTRUCTOR_P (cand->fn)
6511                        && !VOID_TYPE_P (TREE_TYPE (call)))
6512                 /* An explicit call of the form "x->~X()" has type
6513                    "void".  However, on platforms where destructors
6514                    return "this" (i.e., those where
6515                    targetm.cxx.cdtor_returns_this is true), such calls
6516                    will appear to have a return value of pointer type
6517                    to the low-level call machinery.  We do not want to
6518                    change the low-level machinery, since we want to be
6519                    able to optimize "delete f()" on such platforms as
6520                    "operator delete(~X(f()))" (rather than generating
6521                    "t = f(), ~X(t), operator delete (t)").  */
6522                 call = build_nop (void_type_node, call);
6523             }
6524         }
6525     }
6526
6527   if (processing_template_decl && call != error_mark_node)
6528     {
6529       bool cast_to_void = false;
6530
6531       if (TREE_CODE (call) == COMPOUND_EXPR)
6532         call = TREE_OPERAND (call, 1);
6533       else if (TREE_CODE (call) == NOP_EXPR)
6534         {
6535           cast_to_void = true;
6536           call = TREE_OPERAND (call, 0);
6537         }
6538       if (TREE_CODE (call) == INDIRECT_REF)
6539         call = TREE_OPERAND (call, 0);
6540       call = (build_min_non_dep_call_vec
6541               (call,
6542                build_min (COMPONENT_REF, TREE_TYPE (CALL_EXPR_FN (call)),
6543                           orig_instance, orig_fns, NULL_TREE),
6544                orig_args));
6545       call = convert_from_reference (call);
6546       if (cast_to_void)
6547         call = build_nop (void_type_node, call);
6548     }
6549
6550  /* Free all the conversions we allocated.  */
6551   obstack_free (&conversion_obstack, p);
6552
6553   if (orig_args != NULL)
6554     release_tree_vector (orig_args);
6555
6556   return call;
6557 }
6558
6559 /* Returns true iff standard conversion sequence ICS1 is a proper
6560    subsequence of ICS2.  */
6561
6562 static bool
6563 is_subseq (conversion *ics1, conversion *ics2)
6564 {
6565   /* We can assume that a conversion of the same code
6566      between the same types indicates a subsequence since we only get
6567      here if the types we are converting from are the same.  */
6568
6569   while (ics1->kind == ck_rvalue
6570          || ics1->kind == ck_lvalue)
6571     ics1 = ics1->u.next;
6572
6573   while (1)
6574     {
6575       while (ics2->kind == ck_rvalue
6576              || ics2->kind == ck_lvalue)
6577         ics2 = ics2->u.next;
6578
6579       if (ics2->kind == ck_user
6580           || ics2->kind == ck_ambig
6581           || ics2->kind == ck_aggr
6582           || ics2->kind == ck_list
6583           || ics2->kind == ck_identity)
6584         /* At this point, ICS1 cannot be a proper subsequence of
6585            ICS2.  We can get a USER_CONV when we are comparing the
6586            second standard conversion sequence of two user conversion
6587            sequences.  */
6588         return false;
6589
6590       ics2 = ics2->u.next;
6591
6592       if (ics2->kind == ics1->kind
6593           && same_type_p (ics2->type, ics1->type)
6594           && same_type_p (ics2->u.next->type,
6595                           ics1->u.next->type))
6596         return true;
6597     }
6598 }
6599
6600 /* Returns nonzero iff DERIVED is derived from BASE.  The inputs may
6601    be any _TYPE nodes.  */
6602
6603 bool
6604 is_properly_derived_from (tree derived, tree base)
6605 {
6606   if (!CLASS_TYPE_P (derived) || !CLASS_TYPE_P (base))
6607     return false;
6608
6609   /* We only allow proper derivation here.  The DERIVED_FROM_P macro
6610      considers every class derived from itself.  */
6611   return (!same_type_ignoring_top_level_qualifiers_p (derived, base)
6612           && DERIVED_FROM_P (base, derived));
6613 }
6614
6615 /* We build the ICS for an implicit object parameter as a pointer
6616    conversion sequence.  However, such a sequence should be compared
6617    as if it were a reference conversion sequence.  If ICS is the
6618    implicit conversion sequence for an implicit object parameter,
6619    modify it accordingly.  */
6620
6621 static void
6622 maybe_handle_implicit_object (conversion **ics)
6623 {
6624   if ((*ics)->this_p)
6625     {
6626       /* [over.match.funcs]
6627
6628          For non-static member functions, the type of the
6629          implicit object parameter is "reference to cv X"
6630          where X is the class of which the function is a
6631          member and cv is the cv-qualification on the member
6632          function declaration.  */
6633       conversion *t = *ics;
6634       tree reference_type;
6635
6636       /* The `this' parameter is a pointer to a class type.  Make the
6637          implicit conversion talk about a reference to that same class
6638          type.  */
6639       reference_type = TREE_TYPE (t->type);
6640       reference_type = build_reference_type (reference_type);
6641
6642       if (t->kind == ck_qual)
6643         t = t->u.next;
6644       if (t->kind == ck_ptr)
6645         t = t->u.next;
6646       t = build_identity_conv (TREE_TYPE (t->type), NULL_TREE);
6647       t = direct_reference_binding (reference_type, t);
6648       t->this_p = 1;
6649       t->rvaluedness_matches_p = 0;
6650       *ics = t;
6651     }
6652 }
6653
6654 /* If *ICS is a REF_BIND set *ICS to the remainder of the conversion,
6655    and return the initial reference binding conversion. Otherwise,
6656    leave *ICS unchanged and return NULL.  */
6657
6658 static conversion *
6659 maybe_handle_ref_bind (conversion **ics)
6660 {
6661   if ((*ics)->kind == ck_ref_bind)
6662     {
6663       conversion *old_ics = *ics;
6664       *ics = old_ics->u.next;
6665       (*ics)->user_conv_p = old_ics->user_conv_p;
6666       return old_ics;
6667     }
6668
6669   return NULL;
6670 }
6671
6672 /* Compare two implicit conversion sequences according to the rules set out in
6673    [over.ics.rank].  Return values:
6674
6675       1: ics1 is better than ics2
6676      -1: ics2 is better than ics1
6677       0: ics1 and ics2 are indistinguishable */
6678
6679 static int
6680 compare_ics (conversion *ics1, conversion *ics2)
6681 {
6682   tree from_type1;
6683   tree from_type2;
6684   tree to_type1;
6685   tree to_type2;
6686   tree deref_from_type1 = NULL_TREE;
6687   tree deref_from_type2 = NULL_TREE;
6688   tree deref_to_type1 = NULL_TREE;
6689   tree deref_to_type2 = NULL_TREE;
6690   conversion_rank rank1, rank2;
6691
6692   /* REF_BINDING is nonzero if the result of the conversion sequence
6693      is a reference type.   In that case REF_CONV is the reference
6694      binding conversion. */
6695   conversion *ref_conv1;
6696   conversion *ref_conv2;
6697
6698   /* Handle implicit object parameters.  */
6699   maybe_handle_implicit_object (&ics1);
6700   maybe_handle_implicit_object (&ics2);
6701
6702   /* Handle reference parameters.  */
6703   ref_conv1 = maybe_handle_ref_bind (&ics1);
6704   ref_conv2 = maybe_handle_ref_bind (&ics2);
6705
6706   /* List-initialization sequence L1 is a better conversion sequence than
6707      list-initialization sequence L2 if L1 converts to
6708      std::initializer_list<X> for some X and L2 does not.  */
6709   if (ics1->kind == ck_list && ics2->kind != ck_list)
6710     return 1;
6711   if (ics2->kind == ck_list && ics1->kind != ck_list)
6712     return -1;
6713
6714   /* [over.ics.rank]
6715
6716      When  comparing  the  basic forms of implicit conversion sequences (as
6717      defined in _over.best.ics_)
6718
6719      --a standard conversion sequence (_over.ics.scs_) is a better
6720        conversion sequence than a user-defined conversion sequence
6721        or an ellipsis conversion sequence, and
6722
6723      --a user-defined conversion sequence (_over.ics.user_) is a
6724        better conversion sequence than an ellipsis conversion sequence
6725        (_over.ics.ellipsis_).  */
6726   rank1 = CONVERSION_RANK (ics1);
6727   rank2 = CONVERSION_RANK (ics2);
6728
6729   if (rank1 > rank2)
6730     return -1;
6731   else if (rank1 < rank2)
6732     return 1;
6733
6734   if (rank1 == cr_bad)
6735     {
6736       /* XXX Isn't this an extension? */
6737       /* Both ICS are bad.  We try to make a decision based on what
6738          would have happened if they'd been good.  */
6739       if (ics1->user_conv_p > ics2->user_conv_p
6740           || ics1->rank  > ics2->rank)
6741         return -1;
6742       else if (ics1->user_conv_p < ics2->user_conv_p
6743                || ics1->rank < ics2->rank)
6744         return 1;
6745
6746       /* We couldn't make up our minds; try to figure it out below.  */
6747     }
6748
6749   if (ics1->ellipsis_p || ics1->kind == ck_list)
6750     /* Both conversions are ellipsis conversions or both are building a
6751        std::initializer_list.  */
6752     return 0;
6753
6754   /* User-defined  conversion sequence U1 is a better conversion sequence
6755      than another user-defined conversion sequence U2 if they contain the
6756      same user-defined conversion operator or constructor and if the sec-
6757      ond standard conversion sequence of U1 is  better  than  the  second
6758      standard conversion sequence of U2.  */
6759
6760   if (ics1->user_conv_p)
6761     {
6762       conversion *t1;
6763       conversion *t2;
6764
6765       for (t1 = ics1; t1->kind != ck_user; t1 = t1->u.next)
6766         if (t1->kind == ck_ambig || t1->kind == ck_aggr)
6767           break;
6768       for (t2 = ics2; t2->kind != ck_user; t2 = t2->u.next)
6769         if (t2->kind == ck_ambig || t2->kind == ck_aggr)
6770           break;
6771
6772       if (t1->kind != t2->kind)
6773         return 0;
6774       else if (t1->kind == ck_user)
6775         {
6776           if (t1->cand->fn != t2->cand->fn)
6777             return 0;
6778         }
6779       else
6780         {
6781           /* For ambiguous or aggregate conversions, use the target type as
6782              a proxy for the conversion function.  */
6783           if (!same_type_ignoring_top_level_qualifiers_p (t1->type, t2->type))
6784             return 0;
6785         }
6786
6787       /* We can just fall through here, after setting up
6788          FROM_TYPE1 and FROM_TYPE2.  */
6789       from_type1 = t1->type;
6790       from_type2 = t2->type;
6791     }
6792   else
6793     {
6794       conversion *t1;
6795       conversion *t2;
6796
6797       /* We're dealing with two standard conversion sequences.
6798
6799          [over.ics.rank]
6800
6801          Standard conversion sequence S1 is a better conversion
6802          sequence than standard conversion sequence S2 if
6803
6804          --S1 is a proper subsequence of S2 (comparing the conversion
6805            sequences in the canonical form defined by _over.ics.scs_,
6806            excluding any Lvalue Transformation; the identity
6807            conversion sequence is considered to be a subsequence of
6808            any non-identity conversion sequence */
6809
6810       t1 = ics1;
6811       while (t1->kind != ck_identity)
6812         t1 = t1->u.next;
6813       from_type1 = t1->type;
6814
6815       t2 = ics2;
6816       while (t2->kind != ck_identity)
6817         t2 = t2->u.next;
6818       from_type2 = t2->type;
6819     }
6820
6821   /* One sequence can only be a subsequence of the other if they start with
6822      the same type.  They can start with different types when comparing the
6823      second standard conversion sequence in two user-defined conversion
6824      sequences.  */
6825   if (same_type_p (from_type1, from_type2))
6826     {
6827       if (is_subseq (ics1, ics2))
6828         return 1;
6829       if (is_subseq (ics2, ics1))
6830         return -1;
6831     }
6832
6833   /* [over.ics.rank]
6834
6835      Or, if not that,
6836
6837      --the rank of S1 is better than the rank of S2 (by the rules
6838        defined below):
6839
6840     Standard conversion sequences are ordered by their ranks: an Exact
6841     Match is a better conversion than a Promotion, which is a better
6842     conversion than a Conversion.
6843
6844     Two conversion sequences with the same rank are indistinguishable
6845     unless one of the following rules applies:
6846
6847     --A conversion that does not a convert a pointer, pointer to member,
6848       or std::nullptr_t to bool is better than one that does.
6849
6850     The ICS_STD_RANK automatically handles the pointer-to-bool rule,
6851     so that we do not have to check it explicitly.  */
6852   if (ics1->rank < ics2->rank)
6853     return 1;
6854   else if (ics2->rank < ics1->rank)
6855     return -1;
6856
6857   to_type1 = ics1->type;
6858   to_type2 = ics2->type;
6859
6860   /* A conversion from scalar arithmetic type to complex is worse than a
6861      conversion between scalar arithmetic types.  */
6862   if (same_type_p (from_type1, from_type2)
6863       && ARITHMETIC_TYPE_P (from_type1)
6864       && ARITHMETIC_TYPE_P (to_type1)
6865       && ARITHMETIC_TYPE_P (to_type2)
6866       && ((TREE_CODE (to_type1) == COMPLEX_TYPE)
6867           != (TREE_CODE (to_type2) == COMPLEX_TYPE)))
6868     {
6869       if (TREE_CODE (to_type1) == COMPLEX_TYPE)
6870         return -1;
6871       else
6872         return 1;
6873     }
6874
6875   if (TYPE_PTR_P (from_type1)
6876       && TYPE_PTR_P (from_type2)
6877       && TYPE_PTR_P (to_type1)
6878       && TYPE_PTR_P (to_type2))
6879     {
6880       deref_from_type1 = TREE_TYPE (from_type1);
6881       deref_from_type2 = TREE_TYPE (from_type2);
6882       deref_to_type1 = TREE_TYPE (to_type1);
6883       deref_to_type2 = TREE_TYPE (to_type2);
6884     }
6885   /* The rules for pointers to members A::* are just like the rules
6886      for pointers A*, except opposite: if B is derived from A then
6887      A::* converts to B::*, not vice versa.  For that reason, we
6888      switch the from_ and to_ variables here.  */
6889   else if ((TYPE_PTRMEM_P (from_type1) && TYPE_PTRMEM_P (from_type2)
6890             && TYPE_PTRMEM_P (to_type1) && TYPE_PTRMEM_P (to_type2))
6891            || (TYPE_PTRMEMFUNC_P (from_type1)
6892                && TYPE_PTRMEMFUNC_P (from_type2)
6893                && TYPE_PTRMEMFUNC_P (to_type1)
6894                && TYPE_PTRMEMFUNC_P (to_type2)))
6895     {
6896       deref_to_type1 = TYPE_PTRMEM_CLASS_TYPE (from_type1);
6897       deref_to_type2 = TYPE_PTRMEM_CLASS_TYPE (from_type2);
6898       deref_from_type1 = TYPE_PTRMEM_CLASS_TYPE (to_type1);
6899       deref_from_type2 = TYPE_PTRMEM_CLASS_TYPE (to_type2);
6900     }
6901
6902   if (deref_from_type1 != NULL_TREE
6903       && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type1))
6904       && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_from_type2)))
6905     {
6906       /* This was one of the pointer or pointer-like conversions.
6907
6908          [over.ics.rank]
6909
6910          --If class B is derived directly or indirectly from class A,
6911            conversion of B* to A* is better than conversion of B* to
6912            void*, and conversion of A* to void* is better than
6913            conversion of B* to void*.  */
6914       if (TREE_CODE (deref_to_type1) == VOID_TYPE
6915           && TREE_CODE (deref_to_type2) == VOID_TYPE)
6916         {
6917           if (is_properly_derived_from (deref_from_type1,
6918                                         deref_from_type2))
6919             return -1;
6920           else if (is_properly_derived_from (deref_from_type2,
6921                                              deref_from_type1))
6922             return 1;
6923         }
6924       else if (TREE_CODE (deref_to_type1) == VOID_TYPE
6925                || TREE_CODE (deref_to_type2) == VOID_TYPE)
6926         {
6927           if (same_type_p (deref_from_type1, deref_from_type2))
6928             {
6929               if (TREE_CODE (deref_to_type2) == VOID_TYPE)
6930                 {
6931                   if (is_properly_derived_from (deref_from_type1,
6932                                                 deref_to_type1))
6933                     return 1;
6934                 }
6935               /* We know that DEREF_TO_TYPE1 is `void' here.  */
6936               else if (is_properly_derived_from (deref_from_type1,
6937                                                  deref_to_type2))
6938                 return -1;
6939             }
6940         }
6941       else if (RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type1))
6942                && RECORD_OR_UNION_CODE_P (TREE_CODE (deref_to_type2)))
6943         {
6944           /* [over.ics.rank]
6945
6946              --If class B is derived directly or indirectly from class A
6947                and class C is derived directly or indirectly from B,
6948
6949              --conversion of C* to B* is better than conversion of C* to
6950                A*,
6951
6952              --conversion of B* to A* is better than conversion of C* to
6953                A*  */
6954           if (same_type_p (deref_from_type1, deref_from_type2))
6955             {
6956               if (is_properly_derived_from (deref_to_type1,
6957                                             deref_to_type2))
6958                 return 1;
6959               else if (is_properly_derived_from (deref_to_type2,
6960                                                  deref_to_type1))
6961                 return -1;
6962             }
6963           else if (same_type_p (deref_to_type1, deref_to_type2))
6964             {
6965               if (is_properly_derived_from (deref_from_type2,
6966                                             deref_from_type1))
6967                 return 1;
6968               else if (is_properly_derived_from (deref_from_type1,
6969                                                  deref_from_type2))
6970                 return -1;
6971             }
6972         }
6973     }
6974   else if (CLASS_TYPE_P (non_reference (from_type1))
6975            && same_type_p (from_type1, from_type2))
6976     {
6977       tree from = non_reference (from_type1);
6978
6979       /* [over.ics.rank]
6980
6981          --binding of an expression of type C to a reference of type
6982            B& is better than binding an expression of type C to a
6983            reference of type A&
6984
6985          --conversion of C to B is better than conversion of C to A,  */
6986       if (is_properly_derived_from (from, to_type1)
6987           && is_properly_derived_from (from, to_type2))
6988         {
6989           if (is_properly_derived_from (to_type1, to_type2))
6990             return 1;
6991           else if (is_properly_derived_from (to_type2, to_type1))
6992             return -1;
6993         }
6994     }
6995   else if (CLASS_TYPE_P (non_reference (to_type1))
6996            && same_type_p (to_type1, to_type2))
6997     {
6998       tree to = non_reference (to_type1);
6999
7000       /* [over.ics.rank]
7001
7002          --binding of an expression of type B to a reference of type
7003            A& is better than binding an expression of type C to a
7004            reference of type A&,
7005
7006          --conversion of B to A is better than conversion of C to A  */
7007       if (is_properly_derived_from (from_type1, to)
7008           && is_properly_derived_from (from_type2, to))
7009         {
7010           if (is_properly_derived_from (from_type2, from_type1))
7011             return 1;
7012           else if (is_properly_derived_from (from_type1, from_type2))
7013             return -1;
7014         }
7015     }
7016
7017   /* [over.ics.rank]
7018
7019      --S1 and S2 differ only in their qualification conversion and  yield
7020        similar  types  T1 and T2 (_conv.qual_), respectively, and the cv-
7021        qualification signature of type T1 is a proper subset of  the  cv-
7022        qualification signature of type T2  */
7023   if (ics1->kind == ck_qual
7024       && ics2->kind == ck_qual
7025       && same_type_p (from_type1, from_type2))
7026     {
7027       int result = comp_cv_qual_signature (to_type1, to_type2);
7028       if (result != 0)
7029         return result;
7030     }
7031
7032   /* [over.ics.rank]
7033
7034      --S1 and S2 are reference bindings (_dcl.init.ref_) and neither refers
7035      to an implicit object parameter, and either S1 binds an lvalue reference
7036      to an lvalue and S2 binds an rvalue reference or S1 binds an rvalue
7037      reference to an rvalue and S2 binds an lvalue reference
7038      (C++0x draft standard, 13.3.3.2)
7039
7040      --S1 and S2 are reference bindings (_dcl.init.ref_), and the
7041      types to which the references refer are the same type except for
7042      top-level cv-qualifiers, and the type to which the reference
7043      initialized by S2 refers is more cv-qualified than the type to
7044      which the reference initialized by S1 refers */
7045
7046   if (ref_conv1 && ref_conv2)
7047     {
7048       if (!ref_conv1->this_p && !ref_conv2->this_p
7049           && (TYPE_REF_IS_RVALUE (ref_conv1->type)
7050               != TYPE_REF_IS_RVALUE (ref_conv2->type)))
7051         {
7052           if (ref_conv1->rvaluedness_matches_p)
7053             return 1;
7054           if (ref_conv2->rvaluedness_matches_p)
7055             return -1;
7056         }
7057
7058       if (same_type_ignoring_top_level_qualifiers_p (to_type1, to_type2))
7059         return comp_cv_qualification (TREE_TYPE (ref_conv2->type),
7060                                       TREE_TYPE (ref_conv1->type));
7061     }
7062
7063   /* Neither conversion sequence is better than the other.  */
7064   return 0;
7065 }
7066
7067 /* The source type for this standard conversion sequence.  */
7068
7069 static tree
7070 source_type (conversion *t)
7071 {
7072   for (;; t = t->u.next)
7073     {
7074       if (t->kind == ck_user
7075           || t->kind == ck_ambig
7076           || t->kind == ck_identity)
7077         return t->type;
7078     }
7079   gcc_unreachable ();
7080 }
7081
7082 /* Note a warning about preferring WINNER to LOSER.  We do this by storing
7083    a pointer to LOSER and re-running joust to produce the warning if WINNER
7084    is actually used.  */
7085
7086 static void
7087 add_warning (struct z_candidate *winner, struct z_candidate *loser)
7088 {
7089   candidate_warning *cw = (candidate_warning *)
7090     conversion_obstack_alloc (sizeof (candidate_warning));
7091   cw->loser = loser;
7092   cw->next = winner->warnings;
7093   winner->warnings = cw;
7094 }
7095
7096 /* Compare two candidates for overloading as described in
7097    [over.match.best].  Return values:
7098
7099       1: cand1 is better than cand2
7100      -1: cand2 is better than cand1
7101       0: cand1 and cand2 are indistinguishable */
7102
7103 static int
7104 joust (struct z_candidate *cand1, struct z_candidate *cand2, bool warn)
7105 {
7106   int winner = 0;
7107   int off1 = 0, off2 = 0;
7108   size_t i;
7109   size_t len;
7110
7111   /* Candidates that involve bad conversions are always worse than those
7112      that don't.  */
7113   if (cand1->viable > cand2->viable)
7114     return 1;
7115   if (cand1->viable < cand2->viable)
7116     return -1;
7117
7118   /* If we have two pseudo-candidates for conversions to the same type,
7119      or two candidates for the same function, arbitrarily pick one.  */
7120   if (cand1->fn == cand2->fn
7121       && (IS_TYPE_OR_DECL_P (cand1->fn)))
7122     return 1;
7123
7124   /* a viable function F1
7125      is defined to be a better function than another viable function F2  if
7126      for  all arguments i, ICSi(F1) is not a worse conversion sequence than
7127      ICSi(F2), and then */
7128
7129   /* for some argument j, ICSj(F1) is a better conversion  sequence  than
7130      ICSj(F2) */
7131
7132   /* For comparing static and non-static member functions, we ignore
7133      the implicit object parameter of the non-static function.  The
7134      standard says to pretend that the static function has an object
7135      parm, but that won't work with operator overloading.  */
7136   len = cand1->num_convs;
7137   if (len != cand2->num_convs)
7138     {
7139       int static_1 = DECL_STATIC_FUNCTION_P (cand1->fn);
7140       int static_2 = DECL_STATIC_FUNCTION_P (cand2->fn);
7141
7142       gcc_assert (static_1 != static_2);
7143
7144       if (static_1)
7145         off2 = 1;
7146       else
7147         {
7148           off1 = 1;
7149           --len;
7150         }
7151     }
7152
7153   for (i = 0; i < len; ++i)
7154     {
7155       conversion *t1 = cand1->convs[i + off1];
7156       conversion *t2 = cand2->convs[i + off2];
7157       int comp = compare_ics (t1, t2);
7158
7159       if (comp != 0)
7160         {
7161           if (warn_sign_promo
7162               && (CONVERSION_RANK (t1) + CONVERSION_RANK (t2)
7163                   == cr_std + cr_promotion)
7164               && t1->kind == ck_std
7165               && t2->kind == ck_std
7166               && TREE_CODE (t1->type) == INTEGER_TYPE
7167               && TREE_CODE (t2->type) == INTEGER_TYPE
7168               && (TYPE_PRECISION (t1->type)
7169                   == TYPE_PRECISION (t2->type))
7170               && (TYPE_UNSIGNED (t1->u.next->type)
7171                   || (TREE_CODE (t1->u.next->type)
7172                       == ENUMERAL_TYPE)))
7173             {
7174               tree type = t1->u.next->type;
7175               tree type1, type2;
7176               struct z_candidate *w, *l;
7177               if (comp > 0)
7178                 type1 = t1->type, type2 = t2->type,
7179                   w = cand1, l = cand2;
7180               else
7181                 type1 = t2->type, type2 = t1->type,
7182                   w = cand2, l = cand1;
7183
7184               if (warn)
7185                 {
7186                   warning (OPT_Wsign_promo, "passing %qT chooses %qT over %qT",
7187                            type, type1, type2);
7188                   warning (OPT_Wsign_promo, "  in call to %qD", w->fn);
7189                 }
7190               else
7191                 add_warning (w, l);
7192             }
7193
7194           if (winner && comp != winner)
7195             {
7196               winner = 0;
7197               goto tweak;
7198             }
7199           winner = comp;
7200         }
7201     }
7202
7203   /* warn about confusing overload resolution for user-defined conversions,
7204      either between a constructor and a conversion op, or between two
7205      conversion ops.  */
7206   if (winner && warn_conversion && cand1->second_conv
7207       && (!DECL_CONSTRUCTOR_P (cand1->fn) || !DECL_CONSTRUCTOR_P (cand2->fn))
7208       && winner != compare_ics (cand1->second_conv, cand2->second_conv))
7209     {
7210       struct z_candidate *w, *l;
7211       bool give_warning = false;
7212
7213       if (winner == 1)
7214         w = cand1, l = cand2;
7215       else
7216         w = cand2, l = cand1;
7217
7218       /* We don't want to complain about `X::operator T1 ()'
7219          beating `X::operator T2 () const', when T2 is a no less
7220          cv-qualified version of T1.  */
7221       if (DECL_CONTEXT (w->fn) == DECL_CONTEXT (l->fn)
7222           && !DECL_CONSTRUCTOR_P (w->fn) && !DECL_CONSTRUCTOR_P (l->fn))
7223         {
7224           tree t = TREE_TYPE (TREE_TYPE (l->fn));
7225           tree f = TREE_TYPE (TREE_TYPE (w->fn));
7226
7227           if (TREE_CODE (t) == TREE_CODE (f) && POINTER_TYPE_P (t))
7228             {
7229               t = TREE_TYPE (t);
7230               f = TREE_TYPE (f);
7231             }
7232           if (!comp_ptr_ttypes (t, f))
7233             give_warning = true;
7234         }
7235       else
7236         give_warning = true;
7237
7238       if (!give_warning)
7239         /*NOP*/;
7240       else if (warn)
7241         {
7242           tree source = source_type (w->convs[0]);
7243           if (! DECL_CONSTRUCTOR_P (w->fn))
7244             source = TREE_TYPE (source);
7245           if (warning (OPT_Wconversion, "choosing %qD over %qD", w->fn, l->fn)
7246               && warning (OPT_Wconversion, "  for conversion from %qT to %qT",
7247                           source, w->second_conv->type)) 
7248             {
7249               inform (input_location, "  because conversion sequence for the argument is better");
7250             }
7251         }
7252       else
7253         add_warning (w, l);
7254     }
7255
7256   if (winner)
7257     return winner;
7258
7259   /* or, if not that,
7260      F1 is a non-template function and F2 is a template function
7261      specialization.  */
7262
7263   if (!cand1->template_decl && cand2->template_decl)
7264     return 1;
7265   else if (cand1->template_decl && !cand2->template_decl)
7266     return -1;
7267
7268   /* or, if not that,
7269      F1 and F2 are template functions and the function template for F1 is
7270      more specialized than the template for F2 according to the partial
7271      ordering rules.  */
7272
7273   if (cand1->template_decl && cand2->template_decl)
7274     {
7275       winner = more_specialized_fn
7276         (TI_TEMPLATE (cand1->template_decl),
7277          TI_TEMPLATE (cand2->template_decl),
7278          /* [temp.func.order]: The presence of unused ellipsis and default
7279             arguments has no effect on the partial ordering of function
7280             templates.   add_function_candidate() will not have
7281             counted the "this" argument for constructors.  */
7282          cand1->num_convs + DECL_CONSTRUCTOR_P (cand1->fn));
7283       if (winner)
7284         return winner;
7285     }
7286
7287   /* or, if not that,
7288      the  context  is  an  initialization by user-defined conversion (see
7289      _dcl.init_  and  _over.match.user_)  and  the  standard   conversion
7290      sequence  from  the return type of F1 to the destination type (i.e.,
7291      the type of the entity being initialized)  is  a  better  conversion
7292      sequence  than the standard conversion sequence from the return type
7293      of F2 to the destination type.  */
7294
7295   if (cand1->second_conv)
7296     {
7297       winner = compare_ics (cand1->second_conv, cand2->second_conv);
7298       if (winner)
7299         return winner;
7300     }
7301
7302   /* Check whether we can discard a builtin candidate, either because we
7303      have two identical ones or matching builtin and non-builtin candidates.
7304
7305      (Pedantically in the latter case the builtin which matched the user
7306      function should not be added to the overload set, but we spot it here.
7307
7308      [over.match.oper]
7309      ... the builtin candidates include ...
7310      - do not have the same parameter type list as any non-template
7311        non-member candidate.  */
7312
7313   if (TREE_CODE (cand1->fn) == IDENTIFIER_NODE
7314       || TREE_CODE (cand2->fn) == IDENTIFIER_NODE)
7315     {
7316       for (i = 0; i < len; ++i)
7317         if (!same_type_p (cand1->convs[i]->type,
7318                           cand2->convs[i]->type))
7319           break;
7320       if (i == cand1->num_convs)
7321         {
7322           if (cand1->fn == cand2->fn)
7323             /* Two built-in candidates; arbitrarily pick one.  */
7324             return 1;
7325           else if (TREE_CODE (cand1->fn) == IDENTIFIER_NODE)
7326             /* cand1 is built-in; prefer cand2.  */
7327             return -1;
7328           else
7329             /* cand2 is built-in; prefer cand1.  */
7330             return 1;
7331         }
7332     }
7333
7334   /* If the two function declarations represent the same function (this can
7335      happen with declarations in multiple scopes and arg-dependent lookup),
7336      arbitrarily choose one.  But first make sure the default args we're
7337      using match.  */
7338   if (DECL_P (cand1->fn) && DECL_P (cand2->fn)
7339       && equal_functions (cand1->fn, cand2->fn))
7340     {
7341       tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (cand1->fn));
7342       tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (cand2->fn));
7343
7344       gcc_assert (!DECL_CONSTRUCTOR_P (cand1->fn));
7345
7346       for (i = 0; i < len; ++i)
7347         {
7348           /* Don't crash if the fn is variadic.  */
7349           if (!parms1)
7350             break;
7351           parms1 = TREE_CHAIN (parms1);
7352           parms2 = TREE_CHAIN (parms2);
7353         }
7354
7355       if (off1)
7356         parms1 = TREE_CHAIN (parms1);
7357       else if (off2)
7358         parms2 = TREE_CHAIN (parms2);
7359
7360       for (; parms1; ++i)
7361         {
7362           if (!cp_tree_equal (TREE_PURPOSE (parms1),
7363                               TREE_PURPOSE (parms2)))
7364             {
7365               if (warn)
7366                 {
7367                   permerror (input_location, "default argument mismatch in "
7368                              "overload resolution");
7369                   inform (input_location,
7370                           " candidate 1: %q+#F", cand1->fn);
7371                   inform (input_location,
7372                           " candidate 2: %q+#F", cand2->fn);
7373                 }
7374               else
7375                 add_warning (cand1, cand2);
7376               break;
7377             }
7378           parms1 = TREE_CHAIN (parms1);
7379           parms2 = TREE_CHAIN (parms2);
7380         }
7381
7382       return 1;
7383     }
7384
7385 tweak:
7386
7387   /* Extension: If the worst conversion for one candidate is worse than the
7388      worst conversion for the other, take the first.  */
7389   if (!pedantic)
7390     {
7391       conversion_rank rank1 = cr_identity, rank2 = cr_identity;
7392       struct z_candidate *w = 0, *l = 0;
7393
7394       for (i = 0; i < len; ++i)
7395         {
7396           if (CONVERSION_RANK (cand1->convs[i+off1]) > rank1)
7397             rank1 = CONVERSION_RANK (cand1->convs[i+off1]);
7398           if (CONVERSION_RANK (cand2->convs[i + off2]) > rank2)
7399             rank2 = CONVERSION_RANK (cand2->convs[i + off2]);
7400         }
7401       if (rank1 < rank2)
7402         winner = 1, w = cand1, l = cand2;
7403       if (rank1 > rank2)
7404         winner = -1, w = cand2, l = cand1;
7405       if (winner)
7406         {
7407           if (warn)
7408             {
7409               pedwarn (input_location, 0,
7410               "ISO C++ says that these are ambiguous, even "
7411               "though the worst conversion for the first is better than "
7412               "the worst conversion for the second:");
7413               print_z_candidate (_("candidate 1:"), w);
7414               print_z_candidate (_("candidate 2:"), l);
7415             }
7416           else
7417             add_warning (w, l);
7418           return winner;
7419         }
7420     }
7421
7422   gcc_assert (!winner);
7423   return 0;
7424 }
7425
7426 /* Given a list of candidates for overloading, find the best one, if any.
7427    This algorithm has a worst case of O(2n) (winner is last), and a best
7428    case of O(n/2) (totally ambiguous); much better than a sorting
7429    algorithm.  */
7430
7431 static struct z_candidate *
7432 tourney (struct z_candidate *candidates)
7433 {
7434   struct z_candidate *champ = candidates, *challenger;
7435   int fate;
7436   int champ_compared_to_predecessor = 0;
7437
7438   /* Walk through the list once, comparing each current champ to the next
7439      candidate, knocking out a candidate or two with each comparison.  */
7440
7441   for (challenger = champ->next; challenger; )
7442     {
7443       fate = joust (champ, challenger, 0);
7444       if (fate == 1)
7445         challenger = challenger->next;
7446       else
7447         {
7448           if (fate == 0)
7449             {
7450               champ = challenger->next;
7451               if (champ == 0)
7452                 return NULL;
7453               champ_compared_to_predecessor = 0;
7454             }
7455           else
7456             {
7457               champ = challenger;
7458               champ_compared_to_predecessor = 1;
7459             }
7460
7461           challenger = champ->next;
7462         }
7463     }
7464
7465   /* Make sure the champ is better than all the candidates it hasn't yet
7466      been compared to.  */
7467
7468   for (challenger = candidates;
7469        challenger != champ
7470          && !(champ_compared_to_predecessor && challenger->next == champ);
7471        challenger = challenger->next)
7472     {
7473       fate = joust (champ, challenger, 0);
7474       if (fate != 1)
7475         return NULL;
7476     }
7477
7478   return champ;
7479 }
7480
7481 /* Returns nonzero if things of type FROM can be converted to TO.  */
7482
7483 bool
7484 can_convert (tree to, tree from)
7485 {
7486   return can_convert_arg (to, from, NULL_TREE, LOOKUP_IMPLICIT);
7487 }
7488
7489 /* Returns nonzero if ARG (of type FROM) can be converted to TO.  */
7490
7491 bool
7492 can_convert_arg (tree to, tree from, tree arg, int flags)
7493 {
7494   conversion *t;
7495   void *p;
7496   bool ok_p;
7497
7498   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
7499   p = conversion_obstack_alloc (0);
7500
7501   t  = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
7502                             flags);
7503   ok_p = (t && !t->bad_p);
7504
7505   /* Free all the conversions we allocated.  */
7506   obstack_free (&conversion_obstack, p);
7507
7508   return ok_p;
7509 }
7510
7511 /* Like can_convert_arg, but allows dubious conversions as well.  */
7512
7513 bool
7514 can_convert_arg_bad (tree to, tree from, tree arg, int flags)
7515 {
7516   conversion *t;
7517   void *p;
7518
7519   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
7520   p = conversion_obstack_alloc (0);
7521   /* Try to perform the conversion.  */
7522   t  = implicit_conversion (to, from, arg, /*c_cast_p=*/false,
7523                             flags);
7524   /* Free all the conversions we allocated.  */
7525   obstack_free (&conversion_obstack, p);
7526
7527   return t != NULL;
7528 }
7529
7530 /* Convert EXPR to TYPE.  Return the converted expression.
7531
7532    Note that we allow bad conversions here because by the time we get to
7533    this point we are committed to doing the conversion.  If we end up
7534    doing a bad conversion, convert_like will complain.  */
7535
7536 tree
7537 perform_implicit_conversion_flags (tree type, tree expr, tsubst_flags_t complain, int flags)
7538 {
7539   conversion *conv;
7540   void *p;
7541
7542   if (error_operand_p (expr))
7543     return error_mark_node;
7544
7545   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
7546   p = conversion_obstack_alloc (0);
7547
7548   conv = implicit_conversion (type, TREE_TYPE (expr), expr,
7549                               /*c_cast_p=*/false,
7550                               flags);
7551
7552   if (!conv)
7553     {
7554       if (complain & tf_error)
7555         {
7556           /* If expr has unknown type, then it is an overloaded function.
7557              Call instantiate_type to get good error messages.  */
7558           if (TREE_TYPE (expr) == unknown_type_node)
7559             instantiate_type (type, expr, complain);
7560           else if (invalid_nonstatic_memfn_p (expr, complain))
7561             /* We gave an error.  */;
7562           else
7563             error ("could not convert %qE to %qT", expr, type);
7564         }
7565       expr = error_mark_node;
7566     }
7567   else if (processing_template_decl)
7568     {
7569       /* In a template, we are only concerned about determining the
7570          type of non-dependent expressions, so we do not have to
7571          perform the actual conversion.  */
7572       if (TREE_TYPE (expr) != type)
7573         expr = build_nop (type, expr);
7574     }
7575   else
7576     expr = convert_like (conv, expr, complain);
7577
7578   /* Free all the conversions we allocated.  */
7579   obstack_free (&conversion_obstack, p);
7580
7581   return expr;
7582 }
7583
7584 tree
7585 perform_implicit_conversion (tree type, tree expr, tsubst_flags_t complain)
7586 {
7587   return perform_implicit_conversion_flags (type, expr, complain, LOOKUP_IMPLICIT);
7588 }
7589
7590 /* Convert EXPR to TYPE (as a direct-initialization) if that is
7591    permitted.  If the conversion is valid, the converted expression is
7592    returned.  Otherwise, NULL_TREE is returned, except in the case
7593    that TYPE is a class type; in that case, an error is issued.  If
7594    C_CAST_P is true, then this direction initialization is taking
7595    place as part of a static_cast being attempted as part of a C-style
7596    cast.  */
7597
7598 tree
7599 perform_direct_initialization_if_possible (tree type,
7600                                            tree expr,
7601                                            bool c_cast_p,
7602                                            tsubst_flags_t complain)
7603 {
7604   conversion *conv;
7605   void *p;
7606
7607   if (type == error_mark_node || error_operand_p (expr))
7608     return error_mark_node;
7609   /* [dcl.init]
7610
7611      If the destination type is a (possibly cv-qualified) class type:
7612
7613      -- If the initialization is direct-initialization ...,
7614      constructors are considered. ... If no constructor applies, or
7615      the overload resolution is ambiguous, the initialization is
7616      ill-formed.  */
7617   if (CLASS_TYPE_P (type))
7618     {
7619       VEC(tree,gc) *args = make_tree_vector_single (expr);
7620       expr = build_special_member_call (NULL_TREE, complete_ctor_identifier,
7621                                         &args, type, LOOKUP_NORMAL, complain);
7622       release_tree_vector (args);
7623       return build_cplus_new (type, expr);
7624     }
7625
7626   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
7627   p = conversion_obstack_alloc (0);
7628
7629   conv = implicit_conversion (type, TREE_TYPE (expr), expr,
7630                               c_cast_p,
7631                               LOOKUP_NORMAL);
7632   if (!conv || conv->bad_p)
7633     expr = NULL_TREE;
7634   else
7635     expr = convert_like_real (conv, expr, NULL_TREE, 0, 0,
7636                               /*issue_conversion_warnings=*/false,
7637                               c_cast_p,
7638                               complain);
7639
7640   /* Free all the conversions we allocated.  */
7641   obstack_free (&conversion_obstack, p);
7642
7643   return expr;
7644 }
7645
7646 /* DECL is a VAR_DECL whose type is a REFERENCE_TYPE.  The reference
7647    is being bound to a temporary.  Create and return a new VAR_DECL
7648    with the indicated TYPE; this variable will store the value to
7649    which the reference is bound.  */
7650
7651 tree
7652 make_temporary_var_for_ref_to_temp (tree decl, tree type)
7653 {
7654   tree var;
7655
7656   /* Create the variable.  */
7657   var = create_temporary_var (type);
7658
7659   /* Register the variable.  */
7660   if (TREE_STATIC (decl))
7661     {
7662       /* Namespace-scope or local static; give it a mangled name.  */
7663       tree name;
7664
7665       TREE_STATIC (var) = 1;
7666       name = mangle_ref_init_variable (decl);
7667       DECL_NAME (var) = name;
7668       SET_DECL_ASSEMBLER_NAME (var, name);
7669       var = pushdecl_top_level (var);
7670     }
7671   else
7672     /* Create a new cleanup level if necessary.  */
7673     maybe_push_cleanup_level (type);
7674
7675   return var;
7676 }
7677
7678 /* EXPR is the initializer for a variable DECL of reference or
7679    std::initializer_list type.  Create, push and return a new VAR_DECL
7680    for the initializer so that it will live as long as DECL.  Any
7681    cleanup for the new variable is returned through CLEANUP, and the
7682    code to initialize the new variable is returned through INITP.  */
7683
7684 tree
7685 set_up_extended_ref_temp (tree decl, tree expr, tree *cleanup, tree *initp)
7686 {
7687   tree init;
7688   tree type;
7689   tree var;
7690
7691   /* Create the temporary variable.  */
7692   type = TREE_TYPE (expr);
7693   var = make_temporary_var_for_ref_to_temp (decl, type);
7694   layout_decl (var, 0);
7695   /* If the rvalue is the result of a function call it will be
7696      a TARGET_EXPR.  If it is some other construct (such as a
7697      member access expression where the underlying object is
7698      itself the result of a function call), turn it into a
7699      TARGET_EXPR here.  It is important that EXPR be a
7700      TARGET_EXPR below since otherwise the INIT_EXPR will
7701      attempt to make a bitwise copy of EXPR to initialize
7702      VAR.  */
7703   if (TREE_CODE (expr) != TARGET_EXPR)
7704     expr = get_target_expr (expr);
7705   /* Create the INIT_EXPR that will initialize the temporary
7706      variable.  */
7707   init = build2 (INIT_EXPR, type, var, expr);
7708   if (at_function_scope_p ())
7709     {
7710       add_decl_expr (var);
7711
7712       if (TREE_STATIC (var))
7713         init = add_stmt_to_compound (init, register_dtor_fn (var));
7714       else
7715         *cleanup = cxx_maybe_build_cleanup (var);
7716
7717       /* We must be careful to destroy the temporary only
7718          after its initialization has taken place.  If the
7719          initialization throws an exception, then the
7720          destructor should not be run.  We cannot simply
7721          transform INIT into something like:
7722
7723          (INIT, ({ CLEANUP_STMT; }))
7724
7725          because emit_local_var always treats the
7726          initializer as a full-expression.  Thus, the
7727          destructor would run too early; it would run at the
7728          end of initializing the reference variable, rather
7729          than at the end of the block enclosing the
7730          reference variable.
7731
7732          The solution is to pass back a cleanup expression
7733          which the caller is responsible for attaching to
7734          the statement tree.  */
7735     }
7736   else
7737     {
7738       rest_of_decl_compilation (var, /*toplev=*/1, at_eof);
7739       if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
7740         static_aggregates = tree_cons (NULL_TREE, var,
7741                                        static_aggregates);
7742     }
7743
7744   *initp = init;
7745   return var;
7746 }
7747
7748 /* Convert EXPR to the indicated reference TYPE, in a way suitable for
7749    initializing a variable of that TYPE.  If DECL is non-NULL, it is
7750    the VAR_DECL being initialized with the EXPR.  (In that case, the
7751    type of DECL will be TYPE.)  If DECL is non-NULL, then CLEANUP must
7752    also be non-NULL, and with *CLEANUP initialized to NULL.  Upon
7753    return, if *CLEANUP is no longer NULL, it will be an expression
7754    that should be pushed as a cleanup after the returned expression
7755    is used to initialize DECL.
7756
7757    Return the converted expression.  */
7758
7759 tree
7760 initialize_reference (tree type, tree expr, tree decl, tree *cleanup,
7761                       tsubst_flags_t complain)
7762 {
7763   conversion *conv;
7764   void *p;
7765
7766   if (type == error_mark_node || error_operand_p (expr))
7767     return error_mark_node;
7768
7769   /* Get the high-water mark for the CONVERSION_OBSTACK.  */
7770   p = conversion_obstack_alloc (0);
7771
7772   conv = reference_binding (type, TREE_TYPE (expr), expr, /*c_cast_p=*/false,
7773                             LOOKUP_NORMAL);
7774   if (!conv || conv->bad_p)
7775     {
7776       if (complain & tf_error)
7777         {
7778           if (!CP_TYPE_CONST_P (TREE_TYPE (type))
7779               && !TYPE_REF_IS_RVALUE (type)
7780               && !real_lvalue_p (expr))
7781             error ("invalid initialization of non-const reference of "
7782                    "type %qT from an rvalue of type %qT",
7783                    type, TREE_TYPE (expr));
7784           else
7785             error ("invalid initialization of reference of type "
7786                    "%qT from expression of type %qT", type,
7787                    TREE_TYPE (expr));
7788         }
7789       return error_mark_node;
7790     }
7791
7792   /* If DECL is non-NULL, then this special rule applies:
7793
7794        [class.temporary]
7795
7796        The temporary to which the reference is bound or the temporary
7797        that is the complete object to which the reference is bound
7798        persists for the lifetime of the reference.
7799
7800        The temporaries created during the evaluation of the expression
7801        initializing the reference, except the temporary to which the
7802        reference is bound, are destroyed at the end of the
7803        full-expression in which they are created.
7804
7805      In that case, we store the converted expression into a new
7806      VAR_DECL in a new scope.
7807
7808      However, we want to be careful not to create temporaries when
7809      they are not required.  For example, given:
7810
7811        struct B {};
7812        struct D : public B {};
7813        D f();
7814        const B& b = f();
7815
7816      there is no need to copy the return value from "f"; we can just
7817      extend its lifetime.  Similarly, given:
7818
7819        struct S {};
7820        struct T { operator S(); };
7821        T t;
7822        const S& s = t;
7823
7824     we can extend the lifetime of the return value of the conversion
7825     operator.  */
7826   gcc_assert (conv->kind == ck_ref_bind);
7827   if (decl)
7828     {
7829       tree var;
7830       tree base_conv_type;
7831
7832       /* Skip over the REF_BIND.  */
7833       conv = conv->u.next;
7834       /* If the next conversion is a BASE_CONV, skip that too -- but
7835          remember that the conversion was required.  */
7836       if (conv->kind == ck_base)
7837         {
7838           base_conv_type = conv->type;
7839           conv = conv->u.next;
7840         }
7841       else
7842         base_conv_type = NULL_TREE;
7843       /* Perform the remainder of the conversion.  */
7844       expr = convert_like_real (conv, expr,
7845                                 /*fn=*/NULL_TREE, /*argnum=*/0,
7846                                 /*inner=*/-1,
7847                                 /*issue_conversion_warnings=*/true,
7848                                 /*c_cast_p=*/false,
7849                                 tf_warning_or_error);
7850       if (error_operand_p (expr))
7851         expr = error_mark_node;
7852       else
7853         {
7854           if (!lvalue_or_rvalue_with_address_p (expr))
7855             {
7856               tree init;
7857               var = set_up_extended_ref_temp (decl, expr, cleanup, &init);
7858               /* Use its address to initialize the reference variable.  */
7859               expr = build_address (var);
7860               if (base_conv_type)
7861                 expr = convert_to_base (expr,
7862                                         build_pointer_type (base_conv_type),
7863                                         /*check_access=*/true,
7864                                         /*nonnull=*/true, complain);
7865               expr = build2 (COMPOUND_EXPR, TREE_TYPE (expr), init, expr);
7866             }
7867           else
7868             /* Take the address of EXPR.  */
7869             expr = cp_build_unary_op (ADDR_EXPR, expr, 0, tf_warning_or_error);
7870           /* If a BASE_CONV was required, perform it now.  */
7871           if (base_conv_type)
7872             expr = (perform_implicit_conversion
7873                     (build_pointer_type (base_conv_type), expr,
7874                      tf_warning_or_error));
7875           expr = build_nop (type, expr);
7876         }
7877     }
7878   else
7879     /* Perform the conversion.  */
7880     expr = convert_like (conv, expr, tf_warning_or_error);
7881
7882   /* Free all the conversions we allocated.  */
7883   obstack_free (&conversion_obstack, p);
7884
7885   return expr;
7886 }
7887
7888 /* Returns true iff TYPE is some variant of std::initializer_list.  */
7889
7890 bool
7891 is_std_init_list (tree type)
7892 {
7893   return (CLASS_TYPE_P (type)
7894           && CP_TYPE_CONTEXT (type) == std_node
7895           && strcmp (TYPE_NAME_STRING (type), "initializer_list") == 0);
7896 }
7897
7898 /* Returns true iff DECL is a list constructor: i.e. a constructor which
7899    will accept an argument list of a single std::initializer_list<T>.  */
7900
7901 bool
7902 is_list_ctor (tree decl)
7903 {
7904   tree args = FUNCTION_FIRST_USER_PARMTYPE (decl);
7905   tree arg;
7906
7907   if (!args || args == void_list_node)
7908     return false;
7909
7910   arg = non_reference (TREE_VALUE (args));
7911   if (!is_std_init_list (arg))
7912     return false;
7913
7914   args = TREE_CHAIN (args);
7915
7916   if (args && args != void_list_node && !TREE_PURPOSE (args))
7917     /* There are more non-defaulted parms.  */
7918     return false;
7919
7920   return true;
7921 }
7922
7923 #include "gt-cp-call.h"