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