OSDN Git Service

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