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