OSDN Git Service

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