Stop assuming no-debug-info functions return int
[external/binutils.git] / gdb / valops.c
1 /* Perform non-arithmetic operations on values, for GDB.
2
3    Copyright (C) 1986-2017 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "symtab.h"
22 #include "gdbtypes.h"
23 #include "value.h"
24 #include "frame.h"
25 #include "inferior.h"
26 #include "gdbcore.h"
27 #include "target.h"
28 #include "demangle.h"
29 #include "language.h"
30 #include "gdbcmd.h"
31 #include "regcache.h"
32 #include "cp-abi.h"
33 #include "block.h"
34 #include "infcall.h"
35 #include "dictionary.h"
36 #include "cp-support.h"
37 #include "dfp.h"
38 #include "tracepoint.h"
39 #include "observer.h"
40 #include "objfiles.h"
41 #include "extension.h"
42 #include "byte-vector.h"
43
44 extern unsigned int overload_debug;
45 /* Local functions.  */
46
47 static int typecmp (int staticp, int varargs, int nargs,
48                     struct field t1[], struct value *t2[]);
49
50 static struct value *search_struct_field (const char *, struct value *, 
51                                           struct type *, int);
52
53 static struct value *search_struct_method (const char *, struct value **,
54                                            struct value **,
55                                            LONGEST, int *, struct type *);
56
57 static int find_oload_champ_namespace (struct value **, int,
58                                        const char *, const char *,
59                                        struct symbol ***,
60                                        struct badness_vector **,
61                                        const int no_adl);
62
63 static
64 int find_oload_champ_namespace_loop (struct value **, int,
65                                      const char *, const char *,
66                                      int, struct symbol ***,
67                                      struct badness_vector **, int *,
68                                      const int no_adl);
69
70 static int find_oload_champ (struct value **, int, int,
71                              struct fn_field *, VEC (xmethod_worker_ptr) *,
72                              struct symbol **, struct badness_vector **);
73
74 static int oload_method_static_p (struct fn_field *, int);
75
76 enum oload_classification { STANDARD, NON_STANDARD, INCOMPATIBLE };
77
78 static enum
79 oload_classification classify_oload_match (struct badness_vector *,
80                                            int, int);
81
82 static struct value *value_struct_elt_for_reference (struct type *,
83                                                      int, struct type *,
84                                                      const char *,
85                                                      struct type *,
86                                                      int, enum noside);
87
88 static struct value *value_namespace_elt (const struct type *,
89                                           const char *, int , enum noside);
90
91 static struct value *value_maybe_namespace_elt (const struct type *,
92                                                 const char *, int,
93                                                 enum noside);
94
95 static CORE_ADDR allocate_space_in_inferior (int);
96
97 static struct value *cast_into_complex (struct type *, struct value *);
98
99 static void find_method_list (struct value **, const char *,
100                               LONGEST, struct type *, struct fn_field **, int *,
101                               VEC (xmethod_worker_ptr) **,
102                               struct type **, LONGEST *);
103
104 void _initialize_valops (void);
105
106 #if 0
107 /* Flag for whether we want to abandon failed expression evals by
108    default.  */
109
110 static int auto_abandon = 0;
111 #endif
112
113 int overload_resolution = 0;
114 static void
115 show_overload_resolution (struct ui_file *file, int from_tty,
116                           struct cmd_list_element *c, 
117                           const char *value)
118 {
119   fprintf_filtered (file, _("Overload resolution in evaluating "
120                             "C++ functions is %s.\n"),
121                     value);
122 }
123
124 /* Find the address of function name NAME in the inferior.  If OBJF_P
125    is non-NULL, *OBJF_P will be set to the OBJFILE where the function
126    is defined.  */
127
128 struct value *
129 find_function_in_inferior (const char *name, struct objfile **objf_p)
130 {
131   struct block_symbol sym;
132
133   sym = lookup_symbol (name, 0, VAR_DOMAIN, 0);
134   if (sym.symbol != NULL)
135     {
136       if (SYMBOL_CLASS (sym.symbol) != LOC_BLOCK)
137         {
138           error (_("\"%s\" exists in this program but is not a function."),
139                  name);
140         }
141
142       if (objf_p)
143         *objf_p = symbol_objfile (sym.symbol);
144
145       return value_of_variable (sym.symbol, sym.block);
146     }
147   else
148     {
149       struct bound_minimal_symbol msymbol = 
150         lookup_bound_minimal_symbol (name);
151
152       if (msymbol.minsym != NULL)
153         {
154           struct objfile *objfile = msymbol.objfile;
155           struct gdbarch *gdbarch = get_objfile_arch (objfile);
156
157           struct type *type;
158           CORE_ADDR maddr;
159           type = lookup_pointer_type (builtin_type (gdbarch)->builtin_char);
160           type = lookup_function_type (type);
161           type = lookup_pointer_type (type);
162           maddr = BMSYMBOL_VALUE_ADDRESS (msymbol);
163
164           if (objf_p)
165             *objf_p = objfile;
166
167           return value_from_pointer (type, maddr);
168         }
169       else
170         {
171           if (!target_has_execution)
172             error (_("evaluation of this expression "
173                      "requires the target program to be active"));
174           else
175             error (_("evaluation of this expression requires the "
176                      "program to have a function \"%s\"."),
177                    name);
178         }
179     }
180 }
181
182 /* Allocate NBYTES of space in the inferior using the inferior's
183    malloc and return a value that is a pointer to the allocated
184    space.  */
185
186 struct value *
187 value_allocate_space_in_inferior (int len)
188 {
189   struct objfile *objf;
190   struct value *val = find_function_in_inferior ("malloc", &objf);
191   struct gdbarch *gdbarch = get_objfile_arch (objf);
192   struct value *blocklen;
193
194   blocklen = value_from_longest (builtin_type (gdbarch)->builtin_int, len);
195   val = call_function_by_hand (val, NULL, 1, &blocklen);
196   if (value_logical_not (val))
197     {
198       if (!target_has_execution)
199         error (_("No memory available to program now: "
200                  "you need to start the target first"));
201       else
202         error (_("No memory available to program: call to malloc failed"));
203     }
204   return val;
205 }
206
207 static CORE_ADDR
208 allocate_space_in_inferior (int len)
209 {
210   return value_as_long (value_allocate_space_in_inferior (len));
211 }
212
213 /* Cast struct value VAL to type TYPE and return as a value.
214    Both type and val must be of TYPE_CODE_STRUCT or TYPE_CODE_UNION
215    for this to work.  Typedef to one of the codes is permitted.
216    Returns NULL if the cast is neither an upcast nor a downcast.  */
217
218 static struct value *
219 value_cast_structs (struct type *type, struct value *v2)
220 {
221   struct type *t1;
222   struct type *t2;
223   struct value *v;
224
225   gdb_assert (type != NULL && v2 != NULL);
226
227   t1 = check_typedef (type);
228   t2 = check_typedef (value_type (v2));
229
230   /* Check preconditions.  */
231   gdb_assert ((TYPE_CODE (t1) == TYPE_CODE_STRUCT
232                || TYPE_CODE (t1) == TYPE_CODE_UNION)
233               && !!"Precondition is that type is of STRUCT or UNION kind.");
234   gdb_assert ((TYPE_CODE (t2) == TYPE_CODE_STRUCT
235                || TYPE_CODE (t2) == TYPE_CODE_UNION)
236               && !!"Precondition is that value is of STRUCT or UNION kind");
237
238   if (TYPE_NAME (t1) != NULL
239       && TYPE_NAME (t2) != NULL
240       && !strcmp (TYPE_NAME (t1), TYPE_NAME (t2)))
241     return NULL;
242
243   /* Upcasting: look in the type of the source to see if it contains the
244      type of the target as a superclass.  If so, we'll need to
245      offset the pointer rather than just change its type.  */
246   if (TYPE_NAME (t1) != NULL)
247     {
248       v = search_struct_field (type_name_no_tag (t1),
249                                v2, t2, 1);
250       if (v)
251         return v;
252     }
253
254   /* Downcasting: look in the type of the target to see if it contains the
255      type of the source as a superclass.  If so, we'll need to
256      offset the pointer rather than just change its type.  */
257   if (TYPE_NAME (t2) != NULL)
258     {
259       /* Try downcasting using the run-time type of the value.  */
260       int full, using_enc;
261       LONGEST top;
262       struct type *real_type;
263
264       real_type = value_rtti_type (v2, &full, &top, &using_enc);
265       if (real_type)
266         {
267           v = value_full_object (v2, real_type, full, top, using_enc);
268           v = value_at_lazy (real_type, value_address (v));
269           real_type = value_type (v);
270
271           /* We might be trying to cast to the outermost enclosing
272              type, in which case search_struct_field won't work.  */
273           if (TYPE_NAME (real_type) != NULL
274               && !strcmp (TYPE_NAME (real_type), TYPE_NAME (t1)))
275             return v;
276
277           v = search_struct_field (type_name_no_tag (t2), v, real_type, 1);
278           if (v)
279             return v;
280         }
281
282       /* Try downcasting using information from the destination type
283          T2.  This wouldn't work properly for classes with virtual
284          bases, but those were handled above.  */
285       v = search_struct_field (type_name_no_tag (t2),
286                                value_zero (t1, not_lval), t1, 1);
287       if (v)
288         {
289           /* Downcasting is possible (t1 is superclass of v2).  */
290           CORE_ADDR addr2 = value_address (v2);
291
292           addr2 -= value_address (v) + value_embedded_offset (v);
293           return value_at (type, addr2);
294         }
295     }
296
297   return NULL;
298 }
299
300 /* Cast one pointer or reference type to another.  Both TYPE and
301    the type of ARG2 should be pointer types, or else both should be
302    reference types.  If SUBCLASS_CHECK is non-zero, this will force a
303    check to see whether TYPE is a superclass of ARG2's type.  If
304    SUBCLASS_CHECK is zero, then the subclass check is done only when
305    ARG2 is itself non-zero.  Returns the new pointer or reference.  */
306
307 struct value *
308 value_cast_pointers (struct type *type, struct value *arg2,
309                      int subclass_check)
310 {
311   struct type *type1 = check_typedef (type);
312   struct type *type2 = check_typedef (value_type (arg2));
313   struct type *t1 = check_typedef (TYPE_TARGET_TYPE (type1));
314   struct type *t2 = check_typedef (TYPE_TARGET_TYPE (type2));
315
316   if (TYPE_CODE (t1) == TYPE_CODE_STRUCT
317       && TYPE_CODE (t2) == TYPE_CODE_STRUCT
318       && (subclass_check || !value_logical_not (arg2)))
319     {
320       struct value *v2;
321
322       if (TYPE_IS_REFERENCE (type2))
323         v2 = coerce_ref (arg2);
324       else
325         v2 = value_ind (arg2);
326       gdb_assert (TYPE_CODE (check_typedef (value_type (v2)))
327                   == TYPE_CODE_STRUCT && !!"Why did coercion fail?");
328       v2 = value_cast_structs (t1, v2);
329       /* At this point we have what we can have, un-dereference if needed.  */
330       if (v2)
331         {
332           struct value *v = value_addr (v2);
333
334           deprecated_set_value_type (v, type);
335           return v;
336         }
337     }
338
339   /* No superclass found, just change the pointer type.  */
340   arg2 = value_copy (arg2);
341   deprecated_set_value_type (arg2, type);
342   set_value_enclosing_type (arg2, type);
343   set_value_pointed_to_offset (arg2, 0);        /* pai: chk_val */
344   return arg2;
345 }
346
347 /* Cast value ARG2 to type TYPE and return as a value.
348    More general than a C cast: accepts any two types of the same length,
349    and if ARG2 is an lvalue it can be cast into anything at all.  */
350 /* In C++, casts may change pointer or object representations.  */
351
352 struct value *
353 value_cast (struct type *type, struct value *arg2)
354 {
355   enum type_code code1;
356   enum type_code code2;
357   int scalar;
358   struct type *type2;
359
360   int convert_to_boolean = 0;
361
362   if (value_type (arg2) == type)
363     return arg2;
364
365   /* Check if we are casting struct reference to struct reference.  */
366   if (TYPE_IS_REFERENCE (check_typedef (type)))
367     {
368       /* We dereference type; then we recurse and finally
369          we generate value of the given reference.  Nothing wrong with 
370          that.  */
371       struct type *t1 = check_typedef (type);
372       struct type *dereftype = check_typedef (TYPE_TARGET_TYPE (t1));
373       struct value *val = value_cast (dereftype, arg2);
374
375       return value_ref (val, TYPE_CODE (t1));
376     }
377
378   if (TYPE_IS_REFERENCE (check_typedef (value_type (arg2))))
379     /* We deref the value and then do the cast.  */
380     return value_cast (type, coerce_ref (arg2)); 
381
382   /* Strip typedefs / resolve stubs in order to get at the type's
383      code/length, but remember the original type, to use as the
384      resulting type of the cast, in case it was a typedef.  */
385   struct type *to_type = type;
386
387   type = check_typedef (type);
388   code1 = TYPE_CODE (type);
389   arg2 = coerce_ref (arg2);
390   type2 = check_typedef (value_type (arg2));
391
392   /* You can't cast to a reference type.  See value_cast_pointers
393      instead.  */
394   gdb_assert (!TYPE_IS_REFERENCE (type));
395
396   /* A cast to an undetermined-length array_type, such as 
397      (TYPE [])OBJECT, is treated like a cast to (TYPE [N])OBJECT,
398      where N is sizeof(OBJECT)/sizeof(TYPE).  */
399   if (code1 == TYPE_CODE_ARRAY)
400     {
401       struct type *element_type = TYPE_TARGET_TYPE (type);
402       unsigned element_length = TYPE_LENGTH (check_typedef (element_type));
403
404       if (element_length > 0 && TYPE_ARRAY_UPPER_BOUND_IS_UNDEFINED (type))
405         {
406           struct type *range_type = TYPE_INDEX_TYPE (type);
407           int val_length = TYPE_LENGTH (type2);
408           LONGEST low_bound, high_bound, new_length;
409
410           if (get_discrete_bounds (range_type, &low_bound, &high_bound) < 0)
411             low_bound = 0, high_bound = 0;
412           new_length = val_length / element_length;
413           if (val_length % element_length != 0)
414             warning (_("array element type size does not "
415                        "divide object size in cast"));
416           /* FIXME-type-allocation: need a way to free this type when
417              we are done with it.  */
418           range_type = create_static_range_type ((struct type *) NULL,
419                                                  TYPE_TARGET_TYPE (range_type),
420                                                  low_bound,
421                                                  new_length + low_bound - 1);
422           deprecated_set_value_type (arg2, 
423                                      create_array_type ((struct type *) NULL,
424                                                         element_type, 
425                                                         range_type));
426           return arg2;
427         }
428     }
429
430   if (current_language->c_style_arrays
431       && TYPE_CODE (type2) == TYPE_CODE_ARRAY
432       && !TYPE_VECTOR (type2))
433     arg2 = value_coerce_array (arg2);
434
435   if (TYPE_CODE (type2) == TYPE_CODE_FUNC)
436     arg2 = value_coerce_function (arg2);
437
438   type2 = check_typedef (value_type (arg2));
439   code2 = TYPE_CODE (type2);
440
441   if (code1 == TYPE_CODE_COMPLEX)
442     return cast_into_complex (to_type, arg2);
443   if (code1 == TYPE_CODE_BOOL)
444     {
445       code1 = TYPE_CODE_INT;
446       convert_to_boolean = 1;
447     }
448   if (code1 == TYPE_CODE_CHAR)
449     code1 = TYPE_CODE_INT;
450   if (code2 == TYPE_CODE_BOOL || code2 == TYPE_CODE_CHAR)
451     code2 = TYPE_CODE_INT;
452
453   scalar = (code2 == TYPE_CODE_INT || code2 == TYPE_CODE_FLT
454             || code2 == TYPE_CODE_DECFLOAT || code2 == TYPE_CODE_ENUM
455             || code2 == TYPE_CODE_RANGE);
456
457   if ((code1 == TYPE_CODE_STRUCT || code1 == TYPE_CODE_UNION)
458       && (code2 == TYPE_CODE_STRUCT || code2 == TYPE_CODE_UNION)
459       && TYPE_NAME (type) != 0)
460     {
461       struct value *v = value_cast_structs (to_type, arg2);
462
463       if (v)
464         return v;
465     }
466
467   if (code1 == TYPE_CODE_FLT && scalar)
468     return value_from_double (to_type, value_as_double (arg2));
469   else if (code1 == TYPE_CODE_DECFLOAT && scalar)
470     {
471       enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
472       int dec_len = TYPE_LENGTH (type);
473       gdb_byte dec[16];
474
475       if (code2 == TYPE_CODE_FLT)
476         decimal_from_floating (arg2, dec, dec_len, byte_order);
477       else if (code2 == TYPE_CODE_DECFLOAT)
478         decimal_convert (value_contents (arg2), TYPE_LENGTH (type2),
479                          byte_order, dec, dec_len, byte_order);
480       else
481         /* The only option left is an integral type.  */
482         decimal_from_integral (arg2, dec, dec_len, byte_order);
483
484       return value_from_decfloat (to_type, dec);
485     }
486   else if ((code1 == TYPE_CODE_INT || code1 == TYPE_CODE_ENUM
487             || code1 == TYPE_CODE_RANGE)
488            && (scalar || code2 == TYPE_CODE_PTR
489                || code2 == TYPE_CODE_MEMBERPTR))
490     {
491       LONGEST longest;
492
493       /* When we cast pointers to integers, we mustn't use
494          gdbarch_pointer_to_address to find the address the pointer
495          represents, as value_as_long would.  GDB should evaluate
496          expressions just as the compiler would --- and the compiler
497          sees a cast as a simple reinterpretation of the pointer's
498          bits.  */
499       if (code2 == TYPE_CODE_PTR)
500         longest = extract_unsigned_integer
501                     (value_contents (arg2), TYPE_LENGTH (type2),
502                      gdbarch_byte_order (get_type_arch (type2)));
503       else
504         longest = value_as_long (arg2);
505       return value_from_longest (to_type, convert_to_boolean ?
506                                  (LONGEST) (longest ? 1 : 0) : longest);
507     }
508   else if (code1 == TYPE_CODE_PTR && (code2 == TYPE_CODE_INT  
509                                       || code2 == TYPE_CODE_ENUM 
510                                       || code2 == TYPE_CODE_RANGE))
511     {
512       /* TYPE_LENGTH (type) is the length of a pointer, but we really
513          want the length of an address! -- we are really dealing with
514          addresses (i.e., gdb representations) not pointers (i.e.,
515          target representations) here.
516
517          This allows things like "print *(int *)0x01000234" to work
518          without printing a misleading message -- which would
519          otherwise occur when dealing with a target having two byte
520          pointers and four byte addresses.  */
521
522       int addr_bit = gdbarch_addr_bit (get_type_arch (type2));
523       LONGEST longest = value_as_long (arg2);
524
525       if (addr_bit < sizeof (LONGEST) * HOST_CHAR_BIT)
526         {
527           if (longest >= ((LONGEST) 1 << addr_bit)
528               || longest <= -((LONGEST) 1 << addr_bit))
529             warning (_("value truncated"));
530         }
531       return value_from_longest (to_type, longest);
532     }
533   else if (code1 == TYPE_CODE_METHODPTR && code2 == TYPE_CODE_INT
534            && value_as_long (arg2) == 0)
535     {
536       struct value *result = allocate_value (to_type);
537
538       cplus_make_method_ptr (to_type, value_contents_writeable (result), 0, 0);
539       return result;
540     }
541   else if (code1 == TYPE_CODE_MEMBERPTR && code2 == TYPE_CODE_INT
542            && value_as_long (arg2) == 0)
543     {
544       /* The Itanium C++ ABI represents NULL pointers to members as
545          minus one, instead of biasing the normal case.  */
546       return value_from_longest (to_type, -1);
547     }
548   else if (code1 == TYPE_CODE_ARRAY && TYPE_VECTOR (type)
549            && code2 == TYPE_CODE_ARRAY && TYPE_VECTOR (type2)
550            && TYPE_LENGTH (type) != TYPE_LENGTH (type2))
551     error (_("Cannot convert between vector values of different sizes"));
552   else if (code1 == TYPE_CODE_ARRAY && TYPE_VECTOR (type) && scalar
553            && TYPE_LENGTH (type) != TYPE_LENGTH (type2))
554     error (_("can only cast scalar to vector of same size"));
555   else if (code1 == TYPE_CODE_VOID)
556     {
557       return value_zero (to_type, not_lval);
558     }
559   else if (TYPE_LENGTH (type) == TYPE_LENGTH (type2))
560     {
561       if (code1 == TYPE_CODE_PTR && code2 == TYPE_CODE_PTR)
562         return value_cast_pointers (to_type, arg2, 0);
563
564       arg2 = value_copy (arg2);
565       deprecated_set_value_type (arg2, to_type);
566       set_value_enclosing_type (arg2, to_type);
567       set_value_pointed_to_offset (arg2, 0);    /* pai: chk_val */
568       return arg2;
569     }
570   else if (VALUE_LVAL (arg2) == lval_memory)
571     return value_at_lazy (to_type, value_address (arg2));
572   else
573     {
574       error (_("Invalid cast."));
575       return 0;
576     }
577 }
578
579 /* The C++ reinterpret_cast operator.  */
580
581 struct value *
582 value_reinterpret_cast (struct type *type, struct value *arg)
583 {
584   struct value *result;
585   struct type *real_type = check_typedef (type);
586   struct type *arg_type, *dest_type;
587   int is_ref = 0;
588   enum type_code dest_code, arg_code;
589
590   /* Do reference, function, and array conversion.  */
591   arg = coerce_array (arg);
592
593   /* Attempt to preserve the type the user asked for.  */
594   dest_type = type;
595
596   /* If we are casting to a reference type, transform
597      reinterpret_cast<T&[&]>(V) to *reinterpret_cast<T*>(&V).  */
598   if (TYPE_IS_REFERENCE (real_type))
599     {
600       is_ref = 1;
601       arg = value_addr (arg);
602       dest_type = lookup_pointer_type (TYPE_TARGET_TYPE (dest_type));
603       real_type = lookup_pointer_type (real_type);
604     }
605
606   arg_type = value_type (arg);
607
608   dest_code = TYPE_CODE (real_type);
609   arg_code = TYPE_CODE (arg_type);
610
611   /* We can convert pointer types, or any pointer type to int, or int
612      type to pointer.  */
613   if ((dest_code == TYPE_CODE_PTR && arg_code == TYPE_CODE_INT)
614       || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_PTR)
615       || (dest_code == TYPE_CODE_METHODPTR && arg_code == TYPE_CODE_INT)
616       || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_METHODPTR)
617       || (dest_code == TYPE_CODE_MEMBERPTR && arg_code == TYPE_CODE_INT)
618       || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_MEMBERPTR)
619       || (dest_code == arg_code
620           && (dest_code == TYPE_CODE_PTR
621               || dest_code == TYPE_CODE_METHODPTR
622               || dest_code == TYPE_CODE_MEMBERPTR)))
623     result = value_cast (dest_type, arg);
624   else
625     error (_("Invalid reinterpret_cast"));
626
627   if (is_ref)
628     result = value_cast (type, value_ref (value_ind (result),
629                                           TYPE_CODE (type)));
630
631   return result;
632 }
633
634 /* A helper for value_dynamic_cast.  This implements the first of two
635    runtime checks: we iterate over all the base classes of the value's
636    class which are equal to the desired class; if only one of these
637    holds the value, then it is the answer.  */
638
639 static int
640 dynamic_cast_check_1 (struct type *desired_type,
641                       const gdb_byte *valaddr,
642                       LONGEST embedded_offset,
643                       CORE_ADDR address,
644                       struct value *val,
645                       struct type *search_type,
646                       CORE_ADDR arg_addr,
647                       struct type *arg_type,
648                       struct value **result)
649 {
650   int i, result_count = 0;
651
652   for (i = 0; i < TYPE_N_BASECLASSES (search_type) && result_count < 2; ++i)
653     {
654       LONGEST offset = baseclass_offset (search_type, i, valaddr,
655                                          embedded_offset,
656                                          address, val);
657
658       if (class_types_same_p (desired_type, TYPE_BASECLASS (search_type, i)))
659         {
660           if (address + embedded_offset + offset >= arg_addr
661               && address + embedded_offset + offset < arg_addr + TYPE_LENGTH (arg_type))
662             {
663               ++result_count;
664               if (!*result)
665                 *result = value_at_lazy (TYPE_BASECLASS (search_type, i),
666                                          address + embedded_offset + offset);
667             }
668         }
669       else
670         result_count += dynamic_cast_check_1 (desired_type,
671                                               valaddr,
672                                               embedded_offset + offset,
673                                               address, val,
674                                               TYPE_BASECLASS (search_type, i),
675                                               arg_addr,
676                                               arg_type,
677                                               result);
678     }
679
680   return result_count;
681 }
682
683 /* A helper for value_dynamic_cast.  This implements the second of two
684    runtime checks: we look for a unique public sibling class of the
685    argument's declared class.  */
686
687 static int
688 dynamic_cast_check_2 (struct type *desired_type,
689                       const gdb_byte *valaddr,
690                       LONGEST embedded_offset,
691                       CORE_ADDR address,
692                       struct value *val,
693                       struct type *search_type,
694                       struct value **result)
695 {
696   int i, result_count = 0;
697
698   for (i = 0; i < TYPE_N_BASECLASSES (search_type) && result_count < 2; ++i)
699     {
700       LONGEST offset;
701
702       if (! BASETYPE_VIA_PUBLIC (search_type, i))
703         continue;
704
705       offset = baseclass_offset (search_type, i, valaddr, embedded_offset,
706                                  address, val);
707       if (class_types_same_p (desired_type, TYPE_BASECLASS (search_type, i)))
708         {
709           ++result_count;
710           if (*result == NULL)
711             *result = value_at_lazy (TYPE_BASECLASS (search_type, i),
712                                      address + embedded_offset + offset);
713         }
714       else
715         result_count += dynamic_cast_check_2 (desired_type,
716                                               valaddr,
717                                               embedded_offset + offset,
718                                               address, val,
719                                               TYPE_BASECLASS (search_type, i),
720                                               result);
721     }
722
723   return result_count;
724 }
725
726 /* The C++ dynamic_cast operator.  */
727
728 struct value *
729 value_dynamic_cast (struct type *type, struct value *arg)
730 {
731   int full, using_enc;
732   LONGEST top;
733   struct type *resolved_type = check_typedef (type);
734   struct type *arg_type = check_typedef (value_type (arg));
735   struct type *class_type, *rtti_type;
736   struct value *result, *tem, *original_arg = arg;
737   CORE_ADDR addr;
738   int is_ref = TYPE_IS_REFERENCE (resolved_type);
739
740   if (TYPE_CODE (resolved_type) != TYPE_CODE_PTR
741       && !TYPE_IS_REFERENCE (resolved_type))
742     error (_("Argument to dynamic_cast must be a pointer or reference type"));
743   if (TYPE_CODE (TYPE_TARGET_TYPE (resolved_type)) != TYPE_CODE_VOID
744       && TYPE_CODE (TYPE_TARGET_TYPE (resolved_type)) != TYPE_CODE_STRUCT)
745     error (_("Argument to dynamic_cast must be pointer to class or `void *'"));
746
747   class_type = check_typedef (TYPE_TARGET_TYPE (resolved_type));
748   if (TYPE_CODE (resolved_type) == TYPE_CODE_PTR)
749     {
750       if (TYPE_CODE (arg_type) != TYPE_CODE_PTR
751           && ! (TYPE_CODE (arg_type) == TYPE_CODE_INT
752                 && value_as_long (arg) == 0))
753         error (_("Argument to dynamic_cast does not have pointer type"));
754       if (TYPE_CODE (arg_type) == TYPE_CODE_PTR)
755         {
756           arg_type = check_typedef (TYPE_TARGET_TYPE (arg_type));
757           if (TYPE_CODE (arg_type) != TYPE_CODE_STRUCT)
758             error (_("Argument to dynamic_cast does "
759                      "not have pointer to class type"));
760         }
761
762       /* Handle NULL pointers.  */
763       if (value_as_long (arg) == 0)
764         return value_zero (type, not_lval);
765
766       arg = value_ind (arg);
767     }
768   else
769     {
770       if (TYPE_CODE (arg_type) != TYPE_CODE_STRUCT)
771         error (_("Argument to dynamic_cast does not have class type"));
772     }
773
774   /* If the classes are the same, just return the argument.  */
775   if (class_types_same_p (class_type, arg_type))
776     return value_cast (type, arg);
777
778   /* If the target type is a unique base class of the argument's
779      declared type, just cast it.  */
780   if (is_ancestor (class_type, arg_type))
781     {
782       if (is_unique_ancestor (class_type, arg))
783         return value_cast (type, original_arg);
784       error (_("Ambiguous dynamic_cast"));
785     }
786
787   rtti_type = value_rtti_type (arg, &full, &top, &using_enc);
788   if (! rtti_type)
789     error (_("Couldn't determine value's most derived type for dynamic_cast"));
790
791   /* Compute the most derived object's address.  */
792   addr = value_address (arg);
793   if (full)
794     {
795       /* Done.  */
796     }
797   else if (using_enc)
798     addr += top;
799   else
800     addr += top + value_embedded_offset (arg);
801
802   /* dynamic_cast<void *> means to return a pointer to the
803      most-derived object.  */
804   if (TYPE_CODE (resolved_type) == TYPE_CODE_PTR
805       && TYPE_CODE (TYPE_TARGET_TYPE (resolved_type)) == TYPE_CODE_VOID)
806     return value_at_lazy (type, addr);
807
808   tem = value_at (type, addr);
809   type = value_type (tem);
810
811   /* The first dynamic check specified in 5.2.7.  */
812   if (is_public_ancestor (arg_type, TYPE_TARGET_TYPE (resolved_type)))
813     {
814       if (class_types_same_p (rtti_type, TYPE_TARGET_TYPE (resolved_type)))
815         return tem;
816       result = NULL;
817       if (dynamic_cast_check_1 (TYPE_TARGET_TYPE (resolved_type),
818                                 value_contents_for_printing (tem),
819                                 value_embedded_offset (tem),
820                                 value_address (tem), tem,
821                                 rtti_type, addr,
822                                 arg_type,
823                                 &result) == 1)
824         return value_cast (type,
825                            is_ref
826                            ? value_ref (result, TYPE_CODE (resolved_type))
827                            : value_addr (result));
828     }
829
830   /* The second dynamic check specified in 5.2.7.  */
831   result = NULL;
832   if (is_public_ancestor (arg_type, rtti_type)
833       && dynamic_cast_check_2 (TYPE_TARGET_TYPE (resolved_type),
834                                value_contents_for_printing (tem),
835                                value_embedded_offset (tem),
836                                value_address (tem), tem,
837                                rtti_type, &result) == 1)
838     return value_cast (type,
839                        is_ref
840                        ? value_ref (result, TYPE_CODE (resolved_type))
841                        : value_addr (result));
842
843   if (TYPE_CODE (resolved_type) == TYPE_CODE_PTR)
844     return value_zero (type, not_lval);
845
846   error (_("dynamic_cast failed"));
847 }
848
849 /* Create a value of type TYPE that is zero, and return it.  */
850
851 struct value *
852 value_zero (struct type *type, enum lval_type lv)
853 {
854   struct value *val = allocate_value (type);
855
856   VALUE_LVAL (val) = (lv == lval_computed ? not_lval : lv);
857   return val;
858 }
859
860 /* Create a not_lval value of numeric type TYPE that is one, and return it.  */
861
862 struct value *
863 value_one (struct type *type)
864 {
865   struct type *type1 = check_typedef (type);
866   struct value *val;
867
868   if (TYPE_CODE (type1) == TYPE_CODE_DECFLOAT)
869     {
870       enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
871       gdb_byte v[16];
872
873       decimal_from_string (v, TYPE_LENGTH (type), byte_order, "1");
874       val = value_from_decfloat (type, v);
875     }
876   else if (TYPE_CODE (type1) == TYPE_CODE_FLT)
877     {
878       val = value_from_double (type, (DOUBLEST) 1);
879     }
880   else if (is_integral_type (type1))
881     {
882       val = value_from_longest (type, (LONGEST) 1);
883     }
884   else if (TYPE_CODE (type1) == TYPE_CODE_ARRAY && TYPE_VECTOR (type1))
885     {
886       struct type *eltype = check_typedef (TYPE_TARGET_TYPE (type1));
887       int i;
888       LONGEST low_bound, high_bound;
889       struct value *tmp;
890
891       if (!get_array_bounds (type1, &low_bound, &high_bound))
892         error (_("Could not determine the vector bounds"));
893
894       val = allocate_value (type);
895       for (i = 0; i < high_bound - low_bound + 1; i++)
896         {
897           tmp = value_one (eltype);
898           memcpy (value_contents_writeable (val) + i * TYPE_LENGTH (eltype),
899                   value_contents_all (tmp), TYPE_LENGTH (eltype));
900         }
901     }
902   else
903     {
904       error (_("Not a numeric type."));
905     }
906
907   /* value_one result is never used for assignments to.  */
908   gdb_assert (VALUE_LVAL (val) == not_lval);
909
910   return val;
911 }
912
913 /* Helper function for value_at, value_at_lazy, and value_at_lazy_stack.
914    The type of the created value may differ from the passed type TYPE.
915    Make sure to retrieve the returned values's new type after this call
916    e.g. in case the type is a variable length array.  */
917
918 static struct value *
919 get_value_at (struct type *type, CORE_ADDR addr, int lazy)
920 {
921   struct value *val;
922
923   if (TYPE_CODE (check_typedef (type)) == TYPE_CODE_VOID)
924     error (_("Attempt to dereference a generic pointer."));
925
926   val = value_from_contents_and_address (type, NULL, addr);
927
928   if (!lazy)
929     value_fetch_lazy (val);
930
931   return val;
932 }
933
934 /* Return a value with type TYPE located at ADDR.
935
936    Call value_at only if the data needs to be fetched immediately;
937    if we can be 'lazy' and defer the fetch, perhaps indefinately, call
938    value_at_lazy instead.  value_at_lazy simply records the address of
939    the data and sets the lazy-evaluation-required flag.  The lazy flag
940    is tested in the value_contents macro, which is used if and when
941    the contents are actually required.  The type of the created value
942    may differ from the passed type TYPE.  Make sure to retrieve the
943    returned values's new type after this call e.g. in case the type
944    is a variable length array.
945
946    Note: value_at does *NOT* handle embedded offsets; perform such
947    adjustments before or after calling it.  */
948
949 struct value *
950 value_at (struct type *type, CORE_ADDR addr)
951 {
952   return get_value_at (type, addr, 0);
953 }
954
955 /* Return a lazy value with type TYPE located at ADDR (cf. value_at).
956    The type of the created value may differ from the passed type TYPE.
957    Make sure to retrieve the returned values's new type after this call
958    e.g. in case the type is a variable length array.  */
959
960 struct value *
961 value_at_lazy (struct type *type, CORE_ADDR addr)
962 {
963   return get_value_at (type, addr, 1);
964 }
965
966 void
967 read_value_memory (struct value *val, LONGEST bit_offset,
968                    int stack, CORE_ADDR memaddr,
969                    gdb_byte *buffer, size_t length)
970 {
971   ULONGEST xfered_total = 0;
972   struct gdbarch *arch = get_value_arch (val);
973   int unit_size = gdbarch_addressable_memory_unit_size (arch);
974   enum target_object object;
975
976   object = stack ? TARGET_OBJECT_STACK_MEMORY : TARGET_OBJECT_MEMORY;
977
978   while (xfered_total < length)
979     {
980       enum target_xfer_status status;
981       ULONGEST xfered_partial;
982
983       status = target_xfer_partial (current_target.beneath,
984                                     object, NULL,
985                                     buffer + xfered_total * unit_size, NULL,
986                                     memaddr + xfered_total,
987                                     length - xfered_total,
988                                     &xfered_partial);
989
990       if (status == TARGET_XFER_OK)
991         /* nothing */;
992       else if (status == TARGET_XFER_UNAVAILABLE)
993         mark_value_bits_unavailable (val, (xfered_total * HOST_CHAR_BIT
994                                            + bit_offset),
995                                      xfered_partial * HOST_CHAR_BIT);
996       else if (status == TARGET_XFER_EOF)
997         memory_error (TARGET_XFER_E_IO, memaddr + xfered_total);
998       else
999         memory_error (status, memaddr + xfered_total);
1000
1001       xfered_total += xfered_partial;
1002       QUIT;
1003     }
1004 }
1005
1006 /* Store the contents of FROMVAL into the location of TOVAL.
1007    Return a new value with the location of TOVAL and contents of FROMVAL.  */
1008
1009 struct value *
1010 value_assign (struct value *toval, struct value *fromval)
1011 {
1012   struct type *type;
1013   struct value *val;
1014   struct frame_id old_frame;
1015
1016   if (!deprecated_value_modifiable (toval))
1017     error (_("Left operand of assignment is not a modifiable lvalue."));
1018
1019   toval = coerce_ref (toval);
1020
1021   type = value_type (toval);
1022   if (VALUE_LVAL (toval) != lval_internalvar)
1023     fromval = value_cast (type, fromval);
1024   else
1025     {
1026       /* Coerce arrays and functions to pointers, except for arrays
1027          which only live in GDB's storage.  */
1028       if (!value_must_coerce_to_target (fromval))
1029         fromval = coerce_array (fromval);
1030     }
1031
1032   type = check_typedef (type);
1033
1034   /* Since modifying a register can trash the frame chain, and
1035      modifying memory can trash the frame cache, we save the old frame
1036      and then restore the new frame afterwards.  */
1037   old_frame = get_frame_id (deprecated_safe_get_selected_frame ());
1038
1039   switch (VALUE_LVAL (toval))
1040     {
1041     case lval_internalvar:
1042       set_internalvar (VALUE_INTERNALVAR (toval), fromval);
1043       return value_of_internalvar (get_type_arch (type),
1044                                    VALUE_INTERNALVAR (toval));
1045
1046     case lval_internalvar_component:
1047       {
1048         LONGEST offset = value_offset (toval);
1049
1050         /* Are we dealing with a bitfield?
1051
1052            It is important to mention that `value_parent (toval)' is
1053            non-NULL iff `value_bitsize (toval)' is non-zero.  */
1054         if (value_bitsize (toval))
1055           {
1056             /* VALUE_INTERNALVAR below refers to the parent value, while
1057                the offset is relative to this parent value.  */
1058             gdb_assert (value_parent (value_parent (toval)) == NULL);
1059             offset += value_offset (value_parent (toval));
1060           }
1061
1062         set_internalvar_component (VALUE_INTERNALVAR (toval),
1063                                    offset,
1064                                    value_bitpos (toval),
1065                                    value_bitsize (toval),
1066                                    fromval);
1067       }
1068       break;
1069
1070     case lval_memory:
1071       {
1072         const gdb_byte *dest_buffer;
1073         CORE_ADDR changed_addr;
1074         int changed_len;
1075         gdb_byte buffer[sizeof (LONGEST)];
1076
1077         if (value_bitsize (toval))
1078           {
1079             struct value *parent = value_parent (toval);
1080
1081             changed_addr = value_address (parent) + value_offset (toval);
1082             changed_len = (value_bitpos (toval)
1083                            + value_bitsize (toval)
1084                            + HOST_CHAR_BIT - 1)
1085               / HOST_CHAR_BIT;
1086
1087             /* If we can read-modify-write exactly the size of the
1088                containing type (e.g. short or int) then do so.  This
1089                is safer for volatile bitfields mapped to hardware
1090                registers.  */
1091             if (changed_len < TYPE_LENGTH (type)
1092                 && TYPE_LENGTH (type) <= (int) sizeof (LONGEST)
1093                 && ((LONGEST) changed_addr % TYPE_LENGTH (type)) == 0)
1094               changed_len = TYPE_LENGTH (type);
1095
1096             if (changed_len > (int) sizeof (LONGEST))
1097               error (_("Can't handle bitfields which "
1098                        "don't fit in a %d bit word."),
1099                      (int) sizeof (LONGEST) * HOST_CHAR_BIT);
1100
1101             read_memory (changed_addr, buffer, changed_len);
1102             modify_field (type, buffer, value_as_long (fromval),
1103                           value_bitpos (toval), value_bitsize (toval));
1104             dest_buffer = buffer;
1105           }
1106         else
1107           {
1108             changed_addr = value_address (toval);
1109             changed_len = type_length_units (type);
1110             dest_buffer = value_contents (fromval);
1111           }
1112
1113         write_memory_with_notification (changed_addr, dest_buffer, changed_len);
1114       }
1115       break;
1116
1117     case lval_register:
1118       {
1119         struct frame_info *frame;
1120         struct gdbarch *gdbarch;
1121         int value_reg;
1122
1123         /* Figure out which frame this is in currently.
1124         
1125            We use VALUE_FRAME_ID for obtaining the value's frame id instead of
1126            VALUE_NEXT_FRAME_ID due to requiring a frame which may be passed to
1127            put_frame_register_bytes() below.  That function will (eventually)
1128            perform the necessary unwind operation by first obtaining the next
1129            frame.  */
1130         frame = frame_find_by_id (VALUE_FRAME_ID (toval));
1131
1132         value_reg = VALUE_REGNUM (toval);
1133
1134         if (!frame)
1135           error (_("Value being assigned to is no longer active."));
1136
1137         gdbarch = get_frame_arch (frame);
1138
1139         if (value_bitsize (toval))
1140           {
1141             struct value *parent = value_parent (toval);
1142             LONGEST offset = value_offset (parent) + value_offset (toval);
1143             int changed_len;
1144             gdb_byte buffer[sizeof (LONGEST)];
1145             int optim, unavail;
1146
1147             changed_len = (value_bitpos (toval)
1148                            + value_bitsize (toval)
1149                            + HOST_CHAR_BIT - 1)
1150                           / HOST_CHAR_BIT;
1151
1152             if (changed_len > (int) sizeof (LONGEST))
1153               error (_("Can't handle bitfields which "
1154                        "don't fit in a %d bit word."),
1155                      (int) sizeof (LONGEST) * HOST_CHAR_BIT);
1156
1157             if (!get_frame_register_bytes (frame, value_reg, offset,
1158                                            changed_len, buffer,
1159                                            &optim, &unavail))
1160               {
1161                 if (optim)
1162                   throw_error (OPTIMIZED_OUT_ERROR,
1163                                _("value has been optimized out"));
1164                 if (unavail)
1165                   throw_error (NOT_AVAILABLE_ERROR,
1166                                _("value is not available"));
1167               }
1168
1169             modify_field (type, buffer, value_as_long (fromval),
1170                           value_bitpos (toval), value_bitsize (toval));
1171
1172             put_frame_register_bytes (frame, value_reg, offset,
1173                                       changed_len, buffer);
1174           }
1175         else
1176           {
1177             if (gdbarch_convert_register_p (gdbarch, VALUE_REGNUM (toval),
1178                                             type))
1179               {
1180                 /* If TOVAL is a special machine register requiring
1181                    conversion of program values to a special raw
1182                    format.  */
1183                 gdbarch_value_to_register (gdbarch, frame,
1184                                            VALUE_REGNUM (toval), type,
1185                                            value_contents (fromval));
1186               }
1187             else
1188               {
1189                 put_frame_register_bytes (frame, value_reg,
1190                                           value_offset (toval),
1191                                           TYPE_LENGTH (type),
1192                                           value_contents (fromval));
1193               }
1194           }
1195
1196         observer_notify_register_changed (frame, value_reg);
1197         break;
1198       }
1199
1200     case lval_computed:
1201       {
1202         const struct lval_funcs *funcs = value_computed_funcs (toval);
1203
1204         if (funcs->write != NULL)
1205           {
1206             funcs->write (toval, fromval);
1207             break;
1208           }
1209       }
1210       /* Fall through.  */
1211
1212     default:
1213       error (_("Left operand of assignment is not an lvalue."));
1214     }
1215
1216   /* Assigning to the stack pointer, frame pointer, and other
1217      (architecture and calling convention specific) registers may
1218      cause the frame cache and regcache to be out of date.  Assigning to memory
1219      also can.  We just do this on all assignments to registers or
1220      memory, for simplicity's sake; I doubt the slowdown matters.  */
1221   switch (VALUE_LVAL (toval))
1222     {
1223     case lval_memory:
1224     case lval_register:
1225     case lval_computed:
1226
1227       observer_notify_target_changed (&current_target);
1228
1229       /* Having destroyed the frame cache, restore the selected
1230          frame.  */
1231
1232       /* FIXME: cagney/2002-11-02: There has to be a better way of
1233          doing this.  Instead of constantly saving/restoring the
1234          frame.  Why not create a get_selected_frame() function that,
1235          having saved the selected frame's ID can automatically
1236          re-find the previously selected frame automatically.  */
1237
1238       {
1239         struct frame_info *fi = frame_find_by_id (old_frame);
1240
1241         if (fi != NULL)
1242           select_frame (fi);
1243       }
1244
1245       break;
1246     default:
1247       break;
1248     }
1249   
1250   /* If the field does not entirely fill a LONGEST, then zero the sign
1251      bits.  If the field is signed, and is negative, then sign
1252      extend.  */
1253   if ((value_bitsize (toval) > 0)
1254       && (value_bitsize (toval) < 8 * (int) sizeof (LONGEST)))
1255     {
1256       LONGEST fieldval = value_as_long (fromval);
1257       LONGEST valmask = (((ULONGEST) 1) << value_bitsize (toval)) - 1;
1258
1259       fieldval &= valmask;
1260       if (!TYPE_UNSIGNED (type) 
1261           && (fieldval & (valmask ^ (valmask >> 1))))
1262         fieldval |= ~valmask;
1263
1264       fromval = value_from_longest (type, fieldval);
1265     }
1266
1267   /* The return value is a copy of TOVAL so it shares its location
1268      information, but its contents are updated from FROMVAL.  This
1269      implies the returned value is not lazy, even if TOVAL was.  */
1270   val = value_copy (toval);
1271   set_value_lazy (val, 0);
1272   memcpy (value_contents_raw (val), value_contents (fromval),
1273           TYPE_LENGTH (type));
1274
1275   /* We copy over the enclosing type and pointed-to offset from FROMVAL
1276      in the case of pointer types.  For object types, the enclosing type
1277      and embedded offset must *not* be copied: the target object refered
1278      to by TOVAL retains its original dynamic type after assignment.  */
1279   if (TYPE_CODE (type) == TYPE_CODE_PTR)
1280     {
1281       set_value_enclosing_type (val, value_enclosing_type (fromval));
1282       set_value_pointed_to_offset (val, value_pointed_to_offset (fromval));
1283     }
1284
1285   return val;
1286 }
1287
1288 /* Extend a value VAL to COUNT repetitions of its type.  */
1289
1290 struct value *
1291 value_repeat (struct value *arg1, int count)
1292 {
1293   struct value *val;
1294
1295   if (VALUE_LVAL (arg1) != lval_memory)
1296     error (_("Only values in memory can be extended with '@'."));
1297   if (count < 1)
1298     error (_("Invalid number %d of repetitions."), count);
1299
1300   val = allocate_repeat_value (value_enclosing_type (arg1), count);
1301
1302   VALUE_LVAL (val) = lval_memory;
1303   set_value_address (val, value_address (arg1));
1304
1305   read_value_memory (val, 0, value_stack (val), value_address (val),
1306                      value_contents_all_raw (val),
1307                      type_length_units (value_enclosing_type (val)));
1308
1309   return val;
1310 }
1311
1312 struct value *
1313 value_of_variable (struct symbol *var, const struct block *b)
1314 {
1315   struct frame_info *frame = NULL;
1316
1317   if (symbol_read_needs_frame (var))
1318     frame = get_selected_frame (_("No frame selected."));
1319
1320   return read_var_value (var, b, frame);
1321 }
1322
1323 struct value *
1324 address_of_variable (struct symbol *var, const struct block *b)
1325 {
1326   struct type *type = SYMBOL_TYPE (var);
1327   struct value *val;
1328
1329   /* Evaluate it first; if the result is a memory address, we're fine.
1330      Lazy evaluation pays off here.  */
1331
1332   val = value_of_variable (var, b);
1333   type = value_type (val);
1334
1335   if ((VALUE_LVAL (val) == lval_memory && value_lazy (val))
1336       || TYPE_CODE (type) == TYPE_CODE_FUNC)
1337     {
1338       CORE_ADDR addr = value_address (val);
1339
1340       return value_from_pointer (lookup_pointer_type (type), addr);
1341     }
1342
1343   /* Not a memory address; check what the problem was.  */
1344   switch (VALUE_LVAL (val))
1345     {
1346     case lval_register:
1347       {
1348         struct frame_info *frame;
1349         const char *regname;
1350
1351         frame = frame_find_by_id (VALUE_NEXT_FRAME_ID (val));
1352         gdb_assert (frame);
1353
1354         regname = gdbarch_register_name (get_frame_arch (frame),
1355                                          VALUE_REGNUM (val));
1356         gdb_assert (regname && *regname);
1357
1358         error (_("Address requested for identifier "
1359                  "\"%s\" which is in register $%s"),
1360                SYMBOL_PRINT_NAME (var), regname);
1361         break;
1362       }
1363
1364     default:
1365       error (_("Can't take address of \"%s\" which isn't an lvalue."),
1366              SYMBOL_PRINT_NAME (var));
1367       break;
1368     }
1369
1370   return val;
1371 }
1372
1373 /* Return one if VAL does not live in target memory, but should in order
1374    to operate on it.  Otherwise return zero.  */
1375
1376 int
1377 value_must_coerce_to_target (struct value *val)
1378 {
1379   struct type *valtype;
1380
1381   /* The only lval kinds which do not live in target memory.  */
1382   if (VALUE_LVAL (val) != not_lval
1383       && VALUE_LVAL (val) != lval_internalvar
1384       && VALUE_LVAL (val) != lval_xcallable)
1385     return 0;
1386
1387   valtype = check_typedef (value_type (val));
1388
1389   switch (TYPE_CODE (valtype))
1390     {
1391     case TYPE_CODE_ARRAY:
1392       return TYPE_VECTOR (valtype) ? 0 : 1;
1393     case TYPE_CODE_STRING:
1394       return 1;
1395     default:
1396       return 0;
1397     }
1398 }
1399
1400 /* Make sure that VAL lives in target memory if it's supposed to.  For
1401    instance, strings are constructed as character arrays in GDB's
1402    storage, and this function copies them to the target.  */
1403
1404 struct value *
1405 value_coerce_to_target (struct value *val)
1406 {
1407   LONGEST length;
1408   CORE_ADDR addr;
1409
1410   if (!value_must_coerce_to_target (val))
1411     return val;
1412
1413   length = TYPE_LENGTH (check_typedef (value_type (val)));
1414   addr = allocate_space_in_inferior (length);
1415   write_memory (addr, value_contents (val), length);
1416   return value_at_lazy (value_type (val), addr);
1417 }
1418
1419 /* Given a value which is an array, return a value which is a pointer
1420    to its first element, regardless of whether or not the array has a
1421    nonzero lower bound.
1422
1423    FIXME: A previous comment here indicated that this routine should
1424    be substracting the array's lower bound.  It's not clear to me that
1425    this is correct.  Given an array subscripting operation, it would
1426    certainly work to do the adjustment here, essentially computing:
1427
1428    (&array[0] - (lowerbound * sizeof array[0])) + (index * sizeof array[0])
1429
1430    However I believe a more appropriate and logical place to account
1431    for the lower bound is to do so in value_subscript, essentially
1432    computing:
1433
1434    (&array[0] + ((index - lowerbound) * sizeof array[0]))
1435
1436    As further evidence consider what would happen with operations
1437    other than array subscripting, where the caller would get back a
1438    value that had an address somewhere before the actual first element
1439    of the array, and the information about the lower bound would be
1440    lost because of the coercion to pointer type.  */
1441
1442 struct value *
1443 value_coerce_array (struct value *arg1)
1444 {
1445   struct type *type = check_typedef (value_type (arg1));
1446
1447   /* If the user tries to do something requiring a pointer with an
1448      array that has not yet been pushed to the target, then this would
1449      be a good time to do so.  */
1450   arg1 = value_coerce_to_target (arg1);
1451
1452   if (VALUE_LVAL (arg1) != lval_memory)
1453     error (_("Attempt to take address of value not located in memory."));
1454
1455   return value_from_pointer (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
1456                              value_address (arg1));
1457 }
1458
1459 /* Given a value which is a function, return a value which is a pointer
1460    to it.  */
1461
1462 struct value *
1463 value_coerce_function (struct value *arg1)
1464 {
1465   struct value *retval;
1466
1467   if (VALUE_LVAL (arg1) != lval_memory)
1468     error (_("Attempt to take address of value not located in memory."));
1469
1470   retval = value_from_pointer (lookup_pointer_type (value_type (arg1)),
1471                                value_address (arg1));
1472   return retval;
1473 }
1474
1475 /* Return a pointer value for the object for which ARG1 is the
1476    contents.  */
1477
1478 struct value *
1479 value_addr (struct value *arg1)
1480 {
1481   struct value *arg2;
1482   struct type *type = check_typedef (value_type (arg1));
1483
1484   if (TYPE_IS_REFERENCE (type))
1485     {
1486       if (value_bits_synthetic_pointer (arg1, value_embedded_offset (arg1),
1487           TARGET_CHAR_BIT * TYPE_LENGTH (type)))
1488         arg1 = coerce_ref (arg1);
1489       else
1490         {
1491           /* Copy the value, but change the type from (T&) to (T*).  We
1492              keep the same location information, which is efficient, and
1493              allows &(&X) to get the location containing the reference.
1494              Do the same to its enclosing type for consistency.  */
1495           struct type *type_ptr
1496             = lookup_pointer_type (TYPE_TARGET_TYPE (type));
1497           struct type *enclosing_type
1498             = check_typedef (value_enclosing_type (arg1));
1499           struct type *enclosing_type_ptr
1500             = lookup_pointer_type (TYPE_TARGET_TYPE (enclosing_type));
1501
1502           arg2 = value_copy (arg1);
1503           deprecated_set_value_type (arg2, type_ptr);
1504           set_value_enclosing_type (arg2, enclosing_type_ptr);
1505
1506           return arg2;
1507         }
1508     }
1509   if (TYPE_CODE (type) == TYPE_CODE_FUNC)
1510     return value_coerce_function (arg1);
1511
1512   /* If this is an array that has not yet been pushed to the target,
1513      then this would be a good time to force it to memory.  */
1514   arg1 = value_coerce_to_target (arg1);
1515
1516   if (VALUE_LVAL (arg1) != lval_memory)
1517     error (_("Attempt to take address of value not located in memory."));
1518
1519   /* Get target memory address.  */
1520   arg2 = value_from_pointer (lookup_pointer_type (value_type (arg1)),
1521                              (value_address (arg1)
1522                               + value_embedded_offset (arg1)));
1523
1524   /* This may be a pointer to a base subobject; so remember the
1525      full derived object's type ...  */
1526   set_value_enclosing_type (arg2,
1527                             lookup_pointer_type (value_enclosing_type (arg1)));
1528   /* ... and also the relative position of the subobject in the full
1529      object.  */
1530   set_value_pointed_to_offset (arg2, value_embedded_offset (arg1));
1531   return arg2;
1532 }
1533
1534 /* Return a reference value for the object for which ARG1 is the
1535    contents.  */
1536
1537 struct value *
1538 value_ref (struct value *arg1, enum type_code refcode)
1539 {
1540   struct value *arg2;
1541   struct type *type = check_typedef (value_type (arg1));
1542
1543   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
1544
1545   if ((TYPE_CODE (type) == TYPE_CODE_REF
1546        || TYPE_CODE (type) == TYPE_CODE_RVALUE_REF)
1547       && TYPE_CODE (type) == refcode)
1548     return arg1;
1549
1550   arg2 = value_addr (arg1);
1551   deprecated_set_value_type (arg2, lookup_reference_type (type, refcode));
1552   return arg2;
1553 }
1554
1555 /* Given a value of a pointer type, apply the C unary * operator to
1556    it.  */
1557
1558 struct value *
1559 value_ind (struct value *arg1)
1560 {
1561   struct type *base_type;
1562   struct value *arg2;
1563
1564   arg1 = coerce_array (arg1);
1565
1566   base_type = check_typedef (value_type (arg1));
1567
1568   if (VALUE_LVAL (arg1) == lval_computed)
1569     {
1570       const struct lval_funcs *funcs = value_computed_funcs (arg1);
1571
1572       if (funcs->indirect)
1573         {
1574           struct value *result = funcs->indirect (arg1);
1575
1576           if (result)
1577             return result;
1578         }
1579     }
1580
1581   if (TYPE_CODE (base_type) == TYPE_CODE_PTR)
1582     {
1583       struct type *enc_type;
1584
1585       /* We may be pointing to something embedded in a larger object.
1586          Get the real type of the enclosing object.  */
1587       enc_type = check_typedef (value_enclosing_type (arg1));
1588       enc_type = TYPE_TARGET_TYPE (enc_type);
1589
1590       if (TYPE_CODE (check_typedef (enc_type)) == TYPE_CODE_FUNC
1591           || TYPE_CODE (check_typedef (enc_type)) == TYPE_CODE_METHOD)
1592         /* For functions, go through find_function_addr, which knows
1593            how to handle function descriptors.  */
1594         arg2 = value_at_lazy (enc_type, 
1595                               find_function_addr (arg1, NULL));
1596       else
1597         /* Retrieve the enclosing object pointed to.  */
1598         arg2 = value_at_lazy (enc_type, 
1599                               (value_as_address (arg1)
1600                                - value_pointed_to_offset (arg1)));
1601
1602       enc_type = value_type (arg2);
1603       return readjust_indirect_value_type (arg2, enc_type, base_type, arg1);
1604     }
1605
1606   error (_("Attempt to take contents of a non-pointer value."));
1607   return 0;                     /* For lint -- never reached.  */
1608 }
1609 \f
1610 /* Create a value for an array by allocating space in GDB, copying the
1611    data into that space, and then setting up an array value.
1612
1613    The array bounds are set from LOWBOUND and HIGHBOUND, and the array
1614    is populated from the values passed in ELEMVEC.
1615
1616    The element type of the array is inherited from the type of the
1617    first element, and all elements must have the same size (though we
1618    don't currently enforce any restriction on their types).  */
1619
1620 struct value *
1621 value_array (int lowbound, int highbound, struct value **elemvec)
1622 {
1623   int nelem;
1624   int idx;
1625   ULONGEST typelength;
1626   struct value *val;
1627   struct type *arraytype;
1628
1629   /* Validate that the bounds are reasonable and that each of the
1630      elements have the same size.  */
1631
1632   nelem = highbound - lowbound + 1;
1633   if (nelem <= 0)
1634     {
1635       error (_("bad array bounds (%d, %d)"), lowbound, highbound);
1636     }
1637   typelength = type_length_units (value_enclosing_type (elemvec[0]));
1638   for (idx = 1; idx < nelem; idx++)
1639     {
1640       if (type_length_units (value_enclosing_type (elemvec[idx]))
1641           != typelength)
1642         {
1643           error (_("array elements must all be the same size"));
1644         }
1645     }
1646
1647   arraytype = lookup_array_range_type (value_enclosing_type (elemvec[0]),
1648                                        lowbound, highbound);
1649
1650   if (!current_language->c_style_arrays)
1651     {
1652       val = allocate_value (arraytype);
1653       for (idx = 0; idx < nelem; idx++)
1654         value_contents_copy (val, idx * typelength, elemvec[idx], 0,
1655                              typelength);
1656       return val;
1657     }
1658
1659   /* Allocate space to store the array, and then initialize it by
1660      copying in each element.  */
1661
1662   val = allocate_value (arraytype);
1663   for (idx = 0; idx < nelem; idx++)
1664     value_contents_copy (val, idx * typelength, elemvec[idx], 0, typelength);
1665   return val;
1666 }
1667
1668 struct value *
1669 value_cstring (const char *ptr, ssize_t len, struct type *char_type)
1670 {
1671   struct value *val;
1672   int lowbound = current_language->string_lower_bound;
1673   ssize_t highbound = len / TYPE_LENGTH (char_type);
1674   struct type *stringtype
1675     = lookup_array_range_type (char_type, lowbound, highbound + lowbound - 1);
1676
1677   val = allocate_value (stringtype);
1678   memcpy (value_contents_raw (val), ptr, len);
1679   return val;
1680 }
1681
1682 /* Create a value for a string constant by allocating space in the
1683    inferior, copying the data into that space, and returning the
1684    address with type TYPE_CODE_STRING.  PTR points to the string
1685    constant data; LEN is number of characters.
1686
1687    Note that string types are like array of char types with a lower
1688    bound of zero and an upper bound of LEN - 1.  Also note that the
1689    string may contain embedded null bytes.  */
1690
1691 struct value *
1692 value_string (const char *ptr, ssize_t len, struct type *char_type)
1693 {
1694   struct value *val;
1695   int lowbound = current_language->string_lower_bound;
1696   ssize_t highbound = len / TYPE_LENGTH (char_type);
1697   struct type *stringtype
1698     = lookup_string_range_type (char_type, lowbound, highbound + lowbound - 1);
1699
1700   val = allocate_value (stringtype);
1701   memcpy (value_contents_raw (val), ptr, len);
1702   return val;
1703 }
1704
1705 \f
1706 /* See if we can pass arguments in T2 to a function which takes
1707    arguments of types T1.  T1 is a list of NARGS arguments, and T2 is
1708    a NULL-terminated vector.  If some arguments need coercion of some
1709    sort, then the coerced values are written into T2.  Return value is
1710    0 if the arguments could be matched, or the position at which they
1711    differ if not.
1712
1713    STATICP is nonzero if the T1 argument list came from a static
1714    member function.  T2 will still include the ``this'' pointer, but
1715    it will be skipped.
1716
1717    For non-static member functions, we ignore the first argument,
1718    which is the type of the instance variable.  This is because we
1719    want to handle calls with objects from derived classes.  This is
1720    not entirely correct: we should actually check to make sure that a
1721    requested operation is type secure, shouldn't we?  FIXME.  */
1722
1723 static int
1724 typecmp (int staticp, int varargs, int nargs,
1725          struct field t1[], struct value *t2[])
1726 {
1727   int i;
1728
1729   if (t2 == 0)
1730     internal_error (__FILE__, __LINE__, 
1731                     _("typecmp: no argument list"));
1732
1733   /* Skip ``this'' argument if applicable.  T2 will always include
1734      THIS.  */
1735   if (staticp)
1736     t2 ++;
1737
1738   for (i = 0;
1739        (i < nargs) && TYPE_CODE (t1[i].type) != TYPE_CODE_VOID;
1740        i++)
1741     {
1742       struct type *tt1, *tt2;
1743
1744       if (!t2[i])
1745         return i + 1;
1746
1747       tt1 = check_typedef (t1[i].type);
1748       tt2 = check_typedef (value_type (t2[i]));
1749
1750       if (TYPE_IS_REFERENCE (tt1)
1751           /* We should be doing hairy argument matching, as below.  */
1752           && (TYPE_CODE (check_typedef (TYPE_TARGET_TYPE (tt1)))
1753               == TYPE_CODE (tt2)))
1754         {
1755           if (TYPE_CODE (tt2) == TYPE_CODE_ARRAY)
1756             t2[i] = value_coerce_array (t2[i]);
1757           else
1758             t2[i] = value_ref (t2[i], TYPE_CODE (tt1));
1759           continue;
1760         }
1761
1762       /* djb - 20000715 - Until the new type structure is in the
1763          place, and we can attempt things like implicit conversions,
1764          we need to do this so you can take something like a map<const
1765          char *>, and properly access map["hello"], because the
1766          argument to [] will be a reference to a pointer to a char,
1767          and the argument will be a pointer to a char.  */
1768       while (TYPE_IS_REFERENCE (tt1) || TYPE_CODE (tt1) == TYPE_CODE_PTR)
1769         {
1770           tt1 = check_typedef( TYPE_TARGET_TYPE(tt1) );
1771         }
1772       while (TYPE_CODE(tt2) == TYPE_CODE_ARRAY
1773              || TYPE_CODE(tt2) == TYPE_CODE_PTR
1774              || TYPE_IS_REFERENCE (tt2))
1775         {
1776           tt2 = check_typedef (TYPE_TARGET_TYPE(tt2));
1777         }
1778       if (TYPE_CODE (tt1) == TYPE_CODE (tt2))
1779         continue;
1780       /* Array to pointer is a `trivial conversion' according to the
1781          ARM.  */
1782
1783       /* We should be doing much hairier argument matching (see
1784          section 13.2 of the ARM), but as a quick kludge, just check
1785          for the same type code.  */
1786       if (TYPE_CODE (t1[i].type) != TYPE_CODE (value_type (t2[i])))
1787         return i + 1;
1788     }
1789   if (varargs || t2[i] == NULL)
1790     return 0;
1791   return i + 1;
1792 }
1793
1794 /* Helper class for do_search_struct_field that updates *RESULT_PTR
1795    and *LAST_BOFFSET, and possibly throws an exception if the field
1796    search has yielded ambiguous results.  */
1797
1798 static void
1799 update_search_result (struct value **result_ptr, struct value *v,
1800                       LONGEST *last_boffset, LONGEST boffset,
1801                       const char *name, struct type *type)
1802 {
1803   if (v != NULL)
1804     {
1805       if (*result_ptr != NULL
1806           /* The result is not ambiguous if all the classes that are
1807              found occupy the same space.  */
1808           && *last_boffset != boffset)
1809         error (_("base class '%s' is ambiguous in type '%s'"),
1810                name, TYPE_SAFE_NAME (type));
1811       *result_ptr = v;
1812       *last_boffset = boffset;
1813     }
1814 }
1815
1816 /* A helper for search_struct_field.  This does all the work; most
1817    arguments are as passed to search_struct_field.  The result is
1818    stored in *RESULT_PTR, which must be initialized to NULL.
1819    OUTERMOST_TYPE is the type of the initial type passed to
1820    search_struct_field; this is used for error reporting when the
1821    lookup is ambiguous.  */
1822
1823 static void
1824 do_search_struct_field (const char *name, struct value *arg1, LONGEST offset,
1825                         struct type *type, int looking_for_baseclass,
1826                         struct value **result_ptr,
1827                         LONGEST *last_boffset,
1828                         struct type *outermost_type)
1829 {
1830   int i;
1831   int nbases;
1832
1833   type = check_typedef (type);
1834   nbases = TYPE_N_BASECLASSES (type);
1835
1836   if (!looking_for_baseclass)
1837     for (i = TYPE_NFIELDS (type) - 1; i >= nbases; i--)
1838       {
1839         const char *t_field_name = TYPE_FIELD_NAME (type, i);
1840
1841         if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
1842           {
1843             struct value *v;
1844
1845             if (field_is_static (&TYPE_FIELD (type, i)))
1846               v = value_static_field (type, i);
1847             else
1848               v = value_primitive_field (arg1, offset, i, type);
1849             *result_ptr = v;
1850             return;
1851           }
1852
1853         if (t_field_name
1854             && t_field_name[0] == '\0')
1855           {
1856             struct type *field_type = TYPE_FIELD_TYPE (type, i);
1857
1858             if (TYPE_CODE (field_type) == TYPE_CODE_UNION
1859                 || TYPE_CODE (field_type) == TYPE_CODE_STRUCT)
1860               {
1861                 /* Look for a match through the fields of an anonymous
1862                    union, or anonymous struct.  C++ provides anonymous
1863                    unions.
1864
1865                    In the GNU Chill (now deleted from GDB)
1866                    implementation of variant record types, each
1867                    <alternative field> has an (anonymous) union type,
1868                    each member of the union represents a <variant
1869                    alternative>.  Each <variant alternative> is
1870                    represented as a struct, with a member for each
1871                    <variant field>.  */
1872
1873                 struct value *v = NULL;
1874                 LONGEST new_offset = offset;
1875
1876                 /* This is pretty gross.  In G++, the offset in an
1877                    anonymous union is relative to the beginning of the
1878                    enclosing struct.  In the GNU Chill (now deleted
1879                    from GDB) implementation of variant records, the
1880                    bitpos is zero in an anonymous union field, so we
1881                    have to add the offset of the union here.  */
1882                 if (TYPE_CODE (field_type) == TYPE_CODE_STRUCT
1883                     || (TYPE_NFIELDS (field_type) > 0
1884                         && TYPE_FIELD_BITPOS (field_type, 0) == 0))
1885                   new_offset += TYPE_FIELD_BITPOS (type, i) / 8;
1886
1887                 do_search_struct_field (name, arg1, new_offset, 
1888                                         field_type,
1889                                         looking_for_baseclass, &v,
1890                                         last_boffset,
1891                                         outermost_type);
1892                 if (v)
1893                   {
1894                     *result_ptr = v;
1895                     return;
1896                   }
1897               }
1898           }
1899       }
1900
1901   for (i = 0; i < nbases; i++)
1902     {
1903       struct value *v = NULL;
1904       struct type *basetype = check_typedef (TYPE_BASECLASS (type, i));
1905       /* If we are looking for baseclasses, this is what we get when
1906          we hit them.  But it could happen that the base part's member
1907          name is not yet filled in.  */
1908       int found_baseclass = (looking_for_baseclass
1909                              && TYPE_BASECLASS_NAME (type, i) != NULL
1910                              && (strcmp_iw (name, 
1911                                             TYPE_BASECLASS_NAME (type, 
1912                                                                  i)) == 0));
1913       LONGEST boffset = value_embedded_offset (arg1) + offset;
1914
1915       if (BASETYPE_VIA_VIRTUAL (type, i))
1916         {
1917           struct value *v2;
1918
1919           boffset = baseclass_offset (type, i,
1920                                       value_contents_for_printing (arg1),
1921                                       value_embedded_offset (arg1) + offset,
1922                                       value_address (arg1),
1923                                       arg1);
1924
1925           /* The virtual base class pointer might have been clobbered
1926              by the user program.  Make sure that it still points to a
1927              valid memory location.  */
1928
1929           boffset += value_embedded_offset (arg1) + offset;
1930           if (boffset < 0
1931               || boffset >= TYPE_LENGTH (value_enclosing_type (arg1)))
1932             {
1933               CORE_ADDR base_addr;
1934
1935               base_addr = value_address (arg1) + boffset;
1936               v2 = value_at_lazy (basetype, base_addr);
1937               if (target_read_memory (base_addr, 
1938                                       value_contents_raw (v2),
1939                                       TYPE_LENGTH (value_type (v2))) != 0)
1940                 error (_("virtual baseclass botch"));
1941             }
1942           else
1943             {
1944               v2 = value_copy (arg1);
1945               deprecated_set_value_type (v2, basetype);
1946               set_value_embedded_offset (v2, boffset);
1947             }
1948
1949           if (found_baseclass)
1950             v = v2;
1951           else
1952             {
1953               do_search_struct_field (name, v2, 0,
1954                                       TYPE_BASECLASS (type, i),
1955                                       looking_for_baseclass,
1956                                       result_ptr, last_boffset,
1957                                       outermost_type);
1958             }
1959         }
1960       else if (found_baseclass)
1961         v = value_primitive_field (arg1, offset, i, type);
1962       else
1963         {
1964           do_search_struct_field (name, arg1,
1965                                   offset + TYPE_BASECLASS_BITPOS (type, 
1966                                                                   i) / 8,
1967                                   basetype, looking_for_baseclass,
1968                                   result_ptr, last_boffset,
1969                                   outermost_type);
1970         }
1971
1972       update_search_result (result_ptr, v, last_boffset,
1973                             boffset, name, outermost_type);
1974     }
1975 }
1976
1977 /* Helper function used by value_struct_elt to recurse through
1978    baseclasses.  Look for a field NAME in ARG1.  Search in it assuming
1979    it has (class) type TYPE.  If found, return value, else return NULL.
1980
1981    If LOOKING_FOR_BASECLASS, then instead of looking for struct
1982    fields, look for a baseclass named NAME.  */
1983
1984 static struct value *
1985 search_struct_field (const char *name, struct value *arg1,
1986                      struct type *type, int looking_for_baseclass)
1987 {
1988   struct value *result = NULL;
1989   LONGEST boffset = 0;
1990
1991   do_search_struct_field (name, arg1, 0, type, looking_for_baseclass,
1992                           &result, &boffset, type);
1993   return result;
1994 }
1995
1996 /* Helper function used by value_struct_elt to recurse through
1997    baseclasses.  Look for a field NAME in ARG1.  Adjust the address of
1998    ARG1 by OFFSET bytes, and search in it assuming it has (class) type
1999    TYPE.
2000
2001    If found, return value, else if name matched and args not return
2002    (value) -1, else return NULL.  */
2003
2004 static struct value *
2005 search_struct_method (const char *name, struct value **arg1p,
2006                       struct value **args, LONGEST offset,
2007                       int *static_memfuncp, struct type *type)
2008 {
2009   int i;
2010   struct value *v;
2011   int name_matched = 0;
2012   char dem_opname[64];
2013
2014   type = check_typedef (type);
2015   for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2016     {
2017       const char *t_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2018
2019       /* FIXME!  May need to check for ARM demangling here.  */
2020       if (startswith (t_field_name, "__") ||
2021           startswith (t_field_name, "op") ||
2022           startswith (t_field_name, "type"))
2023         {
2024           if (cplus_demangle_opname (t_field_name, dem_opname, DMGL_ANSI))
2025             t_field_name = dem_opname;
2026           else if (cplus_demangle_opname (t_field_name, dem_opname, 0))
2027             t_field_name = dem_opname;
2028         }
2029       if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
2030         {
2031           int j = TYPE_FN_FIELDLIST_LENGTH (type, i) - 1;
2032           struct fn_field *f = TYPE_FN_FIELDLIST1 (type, i);
2033
2034           name_matched = 1;
2035           check_stub_method_group (type, i);
2036           if (j > 0 && args == 0)
2037             error (_("cannot resolve overloaded method "
2038                      "`%s': no arguments supplied"), name);
2039           else if (j == 0 && args == 0)
2040             {
2041               v = value_fn_field (arg1p, f, j, type, offset);
2042               if (v != NULL)
2043                 return v;
2044             }
2045           else
2046             while (j >= 0)
2047               {
2048                 if (!typecmp (TYPE_FN_FIELD_STATIC_P (f, j),
2049                               TYPE_VARARGS (TYPE_FN_FIELD_TYPE (f, j)),
2050                               TYPE_NFIELDS (TYPE_FN_FIELD_TYPE (f, j)),
2051                               TYPE_FN_FIELD_ARGS (f, j), args))
2052                   {
2053                     if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
2054                       return value_virtual_fn_field (arg1p, f, j, 
2055                                                      type, offset);
2056                     if (TYPE_FN_FIELD_STATIC_P (f, j) 
2057                         && static_memfuncp)
2058                       *static_memfuncp = 1;
2059                     v = value_fn_field (arg1p, f, j, type, offset);
2060                     if (v != NULL)
2061                       return v;       
2062                   }
2063                 j--;
2064               }
2065         }
2066     }
2067
2068   for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2069     {
2070       LONGEST base_offset;
2071       LONGEST this_offset;
2072
2073       if (BASETYPE_VIA_VIRTUAL (type, i))
2074         {
2075           struct type *baseclass = check_typedef (TYPE_BASECLASS (type, i));
2076           struct value *base_val;
2077           const gdb_byte *base_valaddr;
2078
2079           /* The virtual base class pointer might have been
2080              clobbered by the user program.  Make sure that it
2081              still points to a valid memory location.  */
2082
2083           if (offset < 0 || offset >= TYPE_LENGTH (type))
2084             {
2085               CORE_ADDR address;
2086
2087               gdb::byte_vector tmp (TYPE_LENGTH (baseclass));
2088               address = value_address (*arg1p);
2089
2090               if (target_read_memory (address + offset,
2091                                       tmp.data (), TYPE_LENGTH (baseclass)) != 0)
2092                 error (_("virtual baseclass botch"));
2093
2094               base_val = value_from_contents_and_address (baseclass,
2095                                                           tmp.data (),
2096                                                           address + offset);
2097               base_valaddr = value_contents_for_printing (base_val);
2098               this_offset = 0;
2099             }
2100           else
2101             {
2102               base_val = *arg1p;
2103               base_valaddr = value_contents_for_printing (*arg1p);
2104               this_offset = offset;
2105             }
2106
2107           base_offset = baseclass_offset (type, i, base_valaddr,
2108                                           this_offset, value_address (base_val),
2109                                           base_val);
2110         }
2111       else
2112         {
2113           base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2114         }
2115       v = search_struct_method (name, arg1p, args, base_offset + offset,
2116                                 static_memfuncp, TYPE_BASECLASS (type, i));
2117       if (v == (struct value *) - 1)
2118         {
2119           name_matched = 1;
2120         }
2121       else if (v)
2122         {
2123           /* FIXME-bothner:  Why is this commented out?  Why is it here?  */
2124           /* *arg1p = arg1_tmp; */
2125           return v;
2126         }
2127     }
2128   if (name_matched)
2129     return (struct value *) - 1;
2130   else
2131     return NULL;
2132 }
2133
2134 /* Given *ARGP, a value of type (pointer to a)* structure/union,
2135    extract the component named NAME from the ultimate target
2136    structure/union and return it as a value with its appropriate type.
2137    ERR is used in the error message if *ARGP's type is wrong.
2138
2139    C++: ARGS is a list of argument types to aid in the selection of
2140    an appropriate method.  Also, handle derived types.
2141
2142    STATIC_MEMFUNCP, if non-NULL, points to a caller-supplied location
2143    where the truthvalue of whether the function that was resolved was
2144    a static member function or not is stored.
2145
2146    ERR is an error message to be printed in case the field is not
2147    found.  */
2148
2149 struct value *
2150 value_struct_elt (struct value **argp, struct value **args,
2151                   const char *name, int *static_memfuncp, const char *err)
2152 {
2153   struct type *t;
2154   struct value *v;
2155
2156   *argp = coerce_array (*argp);
2157
2158   t = check_typedef (value_type (*argp));
2159
2160   /* Follow pointers until we get to a non-pointer.  */
2161
2162   while (TYPE_CODE (t) == TYPE_CODE_PTR || TYPE_IS_REFERENCE (t))
2163     {
2164       *argp = value_ind (*argp);
2165       /* Don't coerce fn pointer to fn and then back again!  */
2166       if (TYPE_CODE (check_typedef (value_type (*argp))) != TYPE_CODE_FUNC)
2167         *argp = coerce_array (*argp);
2168       t = check_typedef (value_type (*argp));
2169     }
2170
2171   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
2172       && TYPE_CODE (t) != TYPE_CODE_UNION)
2173     error (_("Attempt to extract a component of a value that is not a %s."),
2174            err);
2175
2176   /* Assume it's not, unless we see that it is.  */
2177   if (static_memfuncp)
2178     *static_memfuncp = 0;
2179
2180   if (!args)
2181     {
2182       /* if there are no arguments ...do this...  */
2183
2184       /* Try as a field first, because if we succeed, there is less
2185          work to be done.  */
2186       v = search_struct_field (name, *argp, t, 0);
2187       if (v)
2188         return v;
2189
2190       /* C++: If it was not found as a data field, then try to
2191          return it as a pointer to a method.  */
2192       v = search_struct_method (name, argp, args, 0, 
2193                                 static_memfuncp, t);
2194
2195       if (v == (struct value *) - 1)
2196         error (_("Cannot take address of method %s."), name);
2197       else if (v == 0)
2198         {
2199           if (TYPE_NFN_FIELDS (t))
2200             error (_("There is no member or method named %s."), name);
2201           else
2202             error (_("There is no member named %s."), name);
2203         }
2204       return v;
2205     }
2206
2207   v = search_struct_method (name, argp, args, 0, 
2208                             static_memfuncp, t);
2209   
2210   if (v == (struct value *) - 1)
2211     {
2212       error (_("One of the arguments you tried to pass to %s could not "
2213                "be converted to what the function wants."), name);
2214     }
2215   else if (v == 0)
2216     {
2217       /* See if user tried to invoke data as function.  If so, hand it
2218          back.  If it's not callable (i.e., a pointer to function),
2219          gdb should give an error.  */
2220       v = search_struct_field (name, *argp, t, 0);
2221       /* If we found an ordinary field, then it is not a method call.
2222          So, treat it as if it were a static member function.  */
2223       if (v && static_memfuncp)
2224         *static_memfuncp = 1;
2225     }
2226
2227   if (!v)
2228     throw_error (NOT_FOUND_ERROR,
2229                  _("Structure has no component named %s."), name);
2230   return v;
2231 }
2232
2233 /* Given *ARGP, a value of type structure or union, or a pointer/reference
2234    to a structure or union, extract and return its component (field) of
2235    type FTYPE at the specified BITPOS.
2236    Throw an exception on error.  */
2237
2238 struct value *
2239 value_struct_elt_bitpos (struct value **argp, int bitpos, struct type *ftype,
2240                          const char *err)
2241 {
2242   struct type *t;
2243   int i;
2244
2245   *argp = coerce_array (*argp);
2246
2247   t = check_typedef (value_type (*argp));
2248
2249   while (TYPE_CODE (t) == TYPE_CODE_PTR || TYPE_IS_REFERENCE (t))
2250     {
2251       *argp = value_ind (*argp);
2252       if (TYPE_CODE (check_typedef (value_type (*argp))) != TYPE_CODE_FUNC)
2253         *argp = coerce_array (*argp);
2254       t = check_typedef (value_type (*argp));
2255     }
2256
2257   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
2258       && TYPE_CODE (t) != TYPE_CODE_UNION)
2259     error (_("Attempt to extract a component of a value that is not a %s."),
2260            err);
2261
2262   for (i = TYPE_N_BASECLASSES (t); i < TYPE_NFIELDS (t); i++)
2263     {
2264       if (!field_is_static (&TYPE_FIELD (t, i))
2265           && bitpos == TYPE_FIELD_BITPOS (t, i)
2266           && types_equal (ftype, TYPE_FIELD_TYPE (t, i)))
2267         return value_primitive_field (*argp, 0, i, t);
2268     }
2269
2270   error (_("No field with matching bitpos and type."));
2271
2272   /* Never hit.  */
2273   return NULL;
2274 }
2275
2276 /* Search through the methods of an object (and its bases) to find a
2277    specified method.  Return the pointer to the fn_field list FN_LIST of
2278    overloaded instances defined in the source language.  If available
2279    and matching, a vector of matching xmethods defined in extension
2280    languages are also returned in XM_WORKER_VEC
2281
2282    Helper function for value_find_oload_list.
2283    ARGP is a pointer to a pointer to a value (the object).
2284    METHOD is a string containing the method name.
2285    OFFSET is the offset within the value.
2286    TYPE is the assumed type of the object.
2287    FN_LIST is the pointer to matching overloaded instances defined in
2288       source language.  Since this is a recursive function, *FN_LIST
2289       should be set to NULL when calling this function.
2290    NUM_FNS is the number of overloaded instances.  *NUM_FNS should be set to
2291       0 when calling this function.
2292    XM_WORKER_VEC is the vector of matching xmethod workers.  *XM_WORKER_VEC
2293       should also be set to NULL when calling this function.
2294    BASETYPE is set to the actual type of the subobject where the
2295       method is found.
2296    BOFFSET is the offset of the base subobject where the method is found.  */
2297
2298 static void
2299 find_method_list (struct value **argp, const char *method,
2300                   LONGEST offset, struct type *type,
2301                   struct fn_field **fn_list, int *num_fns,
2302                   VEC (xmethod_worker_ptr) **xm_worker_vec,
2303                   struct type **basetype, LONGEST *boffset)
2304 {
2305   int i;
2306   struct fn_field *f = NULL;
2307   VEC (xmethod_worker_ptr) *worker_vec = NULL, *new_vec = NULL;
2308
2309   gdb_assert (fn_list != NULL && xm_worker_vec != NULL);
2310   type = check_typedef (type);
2311
2312   /* First check in object itself.
2313      This function is called recursively to search through base classes.
2314      If there is a source method match found at some stage, then we need not
2315      look for source methods in consequent recursive calls.  */
2316   if ((*fn_list) == NULL)
2317     {
2318       for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2319         {
2320           /* pai: FIXME What about operators and type conversions?  */
2321           const char *fn_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2322
2323           if (fn_field_name && (strcmp_iw (fn_field_name, method) == 0))
2324             {
2325               int len = TYPE_FN_FIELDLIST_LENGTH (type, i);
2326               f = TYPE_FN_FIELDLIST1 (type, i);
2327               *fn_list = f;
2328
2329               *num_fns = len;
2330               *basetype = type;
2331               *boffset = offset;
2332
2333               /* Resolve any stub methods.  */
2334               check_stub_method_group (type, i);
2335
2336               break;
2337             }
2338         }
2339     }
2340
2341   /* Unlike source methods, xmethods can be accumulated over successive
2342      recursive calls.  In other words, an xmethod named 'm' in a class
2343      will not hide an xmethod named 'm' in its base class(es).  We want
2344      it to be this way because xmethods are after all convenience functions
2345      and hence there is no point restricting them with something like method
2346      hiding.  Moreover, if hiding is done for xmethods as well, then we will
2347      have to provide a mechanism to un-hide (like the 'using' construct).  */
2348   worker_vec = get_matching_xmethod_workers (type, method);
2349   new_vec = VEC_merge (xmethod_worker_ptr, *xm_worker_vec, worker_vec);
2350
2351   VEC_free (xmethod_worker_ptr, *xm_worker_vec);
2352   VEC_free (xmethod_worker_ptr, worker_vec);
2353   *xm_worker_vec = new_vec;
2354
2355   /* If source methods are not found in current class, look for them in the
2356      base classes.  We also have to go through the base classes to gather
2357      extension methods.  */
2358   for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2359     {
2360       LONGEST base_offset;
2361
2362       if (BASETYPE_VIA_VIRTUAL (type, i))
2363         {
2364           base_offset = baseclass_offset (type, i,
2365                                           value_contents_for_printing (*argp),
2366                                           value_offset (*argp) + offset,
2367                                           value_address (*argp), *argp);
2368         }
2369       else /* Non-virtual base, simply use bit position from debug
2370               info.  */
2371         {
2372           base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2373         }
2374
2375       find_method_list (argp, method, base_offset + offset,
2376                         TYPE_BASECLASS (type, i), fn_list, num_fns,
2377                         xm_worker_vec, basetype, boffset);
2378     }
2379 }
2380
2381 /* Return the list of overloaded methods of a specified name.  The methods
2382    could be those GDB finds in the binary, or xmethod.  Methods found in
2383    the binary are returned in FN_LIST, and xmethods are returned in
2384    XM_WORKER_VEC.
2385
2386    ARGP is a pointer to a pointer to a value (the object).
2387    METHOD is the method name.
2388    OFFSET is the offset within the value contents.
2389    FN_LIST is the pointer to matching overloaded instances defined in
2390       source language.
2391    NUM_FNS is the number of overloaded instances.
2392    XM_WORKER_VEC is the vector of matching xmethod workers defined in
2393       extension languages.
2394    BASETYPE is set to the type of the base subobject that defines the
2395       method.
2396    BOFFSET is the offset of the base subobject which defines the method.  */
2397
2398 static void
2399 value_find_oload_method_list (struct value **argp, const char *method,
2400                               LONGEST offset, struct fn_field **fn_list,
2401                               int *num_fns,
2402                               VEC (xmethod_worker_ptr) **xm_worker_vec,
2403                               struct type **basetype, LONGEST *boffset)
2404 {
2405   struct type *t;
2406
2407   t = check_typedef (value_type (*argp));
2408
2409   /* Code snarfed from value_struct_elt.  */
2410   while (TYPE_CODE (t) == TYPE_CODE_PTR || TYPE_IS_REFERENCE (t))
2411     {
2412       *argp = value_ind (*argp);
2413       /* Don't coerce fn pointer to fn and then back again!  */
2414       if (TYPE_CODE (check_typedef (value_type (*argp))) != TYPE_CODE_FUNC)
2415         *argp = coerce_array (*argp);
2416       t = check_typedef (value_type (*argp));
2417     }
2418
2419   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
2420       && TYPE_CODE (t) != TYPE_CODE_UNION)
2421     error (_("Attempt to extract a component of a "
2422              "value that is not a struct or union"));
2423
2424   gdb_assert (fn_list != NULL && xm_worker_vec != NULL);
2425
2426   /* Clear the lists.  */
2427   *fn_list = NULL;
2428   *num_fns = 0;
2429   *xm_worker_vec = NULL;
2430
2431   find_method_list (argp, method, 0, t, fn_list, num_fns, xm_worker_vec,
2432                     basetype, boffset);
2433 }
2434
2435 /* Given an array of arguments (ARGS) (which includes an
2436    entry for "this" in the case of C++ methods), the number of
2437    arguments NARGS, the NAME of a function, and whether it's a method or
2438    not (METHOD), find the best function that matches on the argument types
2439    according to the overload resolution rules.
2440
2441    METHOD can be one of three values:
2442      NON_METHOD for non-member functions.
2443      METHOD: for member functions.
2444      BOTH: used for overload resolution of operators where the
2445        candidates are expected to be either member or non member
2446        functions.  In this case the first argument ARGTYPES
2447        (representing 'this') is expected to be a reference to the
2448        target object, and will be dereferenced when attempting the
2449        non-member search.
2450
2451    In the case of class methods, the parameter OBJ is an object value
2452    in which to search for overloaded methods.
2453
2454    In the case of non-method functions, the parameter FSYM is a symbol
2455    corresponding to one of the overloaded functions.
2456
2457    Return value is an integer: 0 -> good match, 10 -> debugger applied
2458    non-standard coercions, 100 -> incompatible.
2459
2460    If a method is being searched for, VALP will hold the value.
2461    If a non-method is being searched for, SYMP will hold the symbol 
2462    for it.
2463
2464    If a method is being searched for, and it is a static method,
2465    then STATICP will point to a non-zero value.
2466
2467    If NO_ADL argument dependent lookup is disabled.  This is used to prevent
2468    ADL overload candidates when performing overload resolution for a fully
2469    qualified name.
2470
2471    If NOSIDE is EVAL_AVOID_SIDE_EFFECTS, then OBJP's memory cannot be
2472    read while picking the best overload match (it may be all zeroes and thus
2473    not have a vtable pointer), in which case skip virtual function lookup.
2474    This is ok as typically EVAL_AVOID_SIDE_EFFECTS is only used to determine
2475    the result type.
2476
2477    Note: This function does *not* check the value of
2478    overload_resolution.  Caller must check it to see whether overload
2479    resolution is permitted.  */
2480
2481 int
2482 find_overload_match (struct value **args, int nargs,
2483                      const char *name, enum oload_search_type method,
2484                      struct value **objp, struct symbol *fsym,
2485                      struct value **valp, struct symbol **symp, 
2486                      int *staticp, const int no_adl,
2487                      const enum noside noside)
2488 {
2489   struct value *obj = (objp ? *objp : NULL);
2490   struct type *obj_type = obj ? value_type (obj) : NULL;
2491   /* Index of best overloaded function.  */
2492   int func_oload_champ = -1;
2493   int method_oload_champ = -1;
2494   int src_method_oload_champ = -1;
2495   int ext_method_oload_champ = -1;
2496
2497   /* The measure for the current best match.  */
2498   struct badness_vector *method_badness = NULL;
2499   struct badness_vector *func_badness = NULL;
2500   struct badness_vector *ext_method_badness = NULL;
2501   struct badness_vector *src_method_badness = NULL;
2502
2503   struct value *temp = obj;
2504   /* For methods, the list of overloaded methods.  */
2505   struct fn_field *fns_ptr = NULL;
2506   /* For non-methods, the list of overloaded function symbols.  */
2507   struct symbol **oload_syms = NULL;
2508   /* For xmethods, the VEC of xmethod workers.  */
2509   VEC (xmethod_worker_ptr) *xm_worker_vec = NULL;
2510   /* Number of overloaded instances being considered.  */
2511   int num_fns = 0;
2512   struct type *basetype = NULL;
2513   LONGEST boffset;
2514
2515   struct cleanup *all_cleanups = make_cleanup (null_cleanup, NULL);
2516
2517   const char *obj_type_name = NULL;
2518   const char *func_name = NULL;
2519   enum oload_classification match_quality;
2520   enum oload_classification method_match_quality = INCOMPATIBLE;
2521   enum oload_classification src_method_match_quality = INCOMPATIBLE;
2522   enum oload_classification ext_method_match_quality = INCOMPATIBLE;
2523   enum oload_classification func_match_quality = INCOMPATIBLE;
2524
2525   /* Get the list of overloaded methods or functions.  */
2526   if (method == METHOD || method == BOTH)
2527     {
2528       gdb_assert (obj);
2529
2530       /* OBJ may be a pointer value rather than the object itself.  */
2531       obj = coerce_ref (obj);
2532       while (TYPE_CODE (check_typedef (value_type (obj))) == TYPE_CODE_PTR)
2533         obj = coerce_ref (value_ind (obj));
2534       obj_type_name = TYPE_NAME (value_type (obj));
2535
2536       /* First check whether this is a data member, e.g. a pointer to
2537          a function.  */
2538       if (TYPE_CODE (check_typedef (value_type (obj))) == TYPE_CODE_STRUCT)
2539         {
2540           *valp = search_struct_field (name, obj,
2541                                        check_typedef (value_type (obj)), 0);
2542           if (*valp)
2543             {
2544               *staticp = 1;
2545               do_cleanups (all_cleanups);
2546               return 0;
2547             }
2548         }
2549
2550       /* Retrieve the list of methods with the name NAME.  */
2551       value_find_oload_method_list (&temp, name, 0, &fns_ptr, &num_fns,
2552                                     &xm_worker_vec, &basetype, &boffset);
2553       /* If this is a method only search, and no methods were found
2554          the search has faild.  */
2555       if (method == METHOD && (!fns_ptr || !num_fns) && !xm_worker_vec)
2556         error (_("Couldn't find method %s%s%s"),
2557                obj_type_name,
2558                (obj_type_name && *obj_type_name) ? "::" : "",
2559                name);
2560       /* If we are dealing with stub method types, they should have
2561          been resolved by find_method_list via
2562          value_find_oload_method_list above.  */
2563       if (fns_ptr)
2564         {
2565           gdb_assert (TYPE_SELF_TYPE (fns_ptr[0].type) != NULL);
2566
2567           src_method_oload_champ = find_oload_champ (args, nargs,
2568                                                      num_fns, fns_ptr, NULL,
2569                                                      NULL, &src_method_badness);
2570
2571           src_method_match_quality = classify_oload_match
2572             (src_method_badness, nargs,
2573              oload_method_static_p (fns_ptr, src_method_oload_champ));
2574
2575           make_cleanup (xfree, src_method_badness);
2576         }
2577
2578       if (VEC_length (xmethod_worker_ptr, xm_worker_vec) > 0)
2579         {
2580           ext_method_oload_champ = find_oload_champ (args, nargs,
2581                                                      0, NULL, xm_worker_vec,
2582                                                      NULL, &ext_method_badness);
2583           ext_method_match_quality = classify_oload_match (ext_method_badness,
2584                                                            nargs, 0);
2585           make_cleanup (xfree, ext_method_badness);
2586           make_cleanup (free_xmethod_worker_vec, xm_worker_vec);
2587         }
2588
2589       if (src_method_oload_champ >= 0 && ext_method_oload_champ >= 0)
2590         {
2591           switch (compare_badness (ext_method_badness, src_method_badness))
2592             {
2593               case 0: /* Src method and xmethod are equally good.  */
2594                 /* If src method and xmethod are equally good, then
2595                    xmethod should be the winner.  Hence, fall through to the
2596                    case where a xmethod is better than the source
2597                    method, except when the xmethod match quality is
2598                    non-standard.  */
2599                 /* FALLTHROUGH */
2600               case 1: /* Src method and ext method are incompatible.  */
2601                 /* If ext method match is not standard, then let source method
2602                    win.  Otherwise, fallthrough to let xmethod win.  */
2603                 if (ext_method_match_quality != STANDARD)
2604                   {
2605                     method_oload_champ = src_method_oload_champ;
2606                     method_badness = src_method_badness;
2607                     ext_method_oload_champ = -1;
2608                     method_match_quality = src_method_match_quality;
2609                     break;
2610                   }
2611                 /* FALLTHROUGH */
2612               case 2: /* Ext method is champion.  */
2613                 method_oload_champ = ext_method_oload_champ;
2614                 method_badness = ext_method_badness;
2615                 src_method_oload_champ = -1;
2616                 method_match_quality = ext_method_match_quality;
2617                 break;
2618               case 3: /* Src method is champion.  */
2619                 method_oload_champ = src_method_oload_champ;
2620                 method_badness = src_method_badness;
2621                 ext_method_oload_champ = -1;
2622                 method_match_quality = src_method_match_quality;
2623                 break;
2624               default:
2625                 gdb_assert_not_reached ("Unexpected overload comparison "
2626                                         "result");
2627                 break;
2628             }
2629         }
2630       else if (src_method_oload_champ >= 0)
2631         {
2632           method_oload_champ = src_method_oload_champ;
2633           method_badness = src_method_badness;
2634           method_match_quality = src_method_match_quality;
2635         }
2636       else if (ext_method_oload_champ >= 0)
2637         {
2638           method_oload_champ = ext_method_oload_champ;
2639           method_badness = ext_method_badness;
2640           method_match_quality = ext_method_match_quality;
2641         }
2642     }
2643
2644   if (method == NON_METHOD || method == BOTH)
2645     {
2646       const char *qualified_name = NULL;
2647
2648       /* If the overload match is being search for both as a method
2649          and non member function, the first argument must now be
2650          dereferenced.  */
2651       if (method == BOTH)
2652         args[0] = value_ind (args[0]);
2653
2654       if (fsym)
2655         {
2656           qualified_name = SYMBOL_NATURAL_NAME (fsym);
2657
2658           /* If we have a function with a C++ name, try to extract just
2659              the function part.  Do not try this for non-functions (e.g.
2660              function pointers).  */
2661           if (qualified_name
2662               && TYPE_CODE (check_typedef (SYMBOL_TYPE (fsym)))
2663               == TYPE_CODE_FUNC)
2664             {
2665               char *temp;
2666
2667               temp = cp_func_name (qualified_name);
2668
2669               /* If cp_func_name did not remove anything, the name of the
2670                  symbol did not include scope or argument types - it was
2671                  probably a C-style function.  */
2672               if (temp)
2673                 {
2674                   make_cleanup (xfree, temp);
2675                   if (strcmp (temp, qualified_name) == 0)
2676                     func_name = NULL;
2677                   else
2678                     func_name = temp;
2679                 }
2680             }
2681         }
2682       else
2683         {
2684           func_name = name;
2685           qualified_name = name;
2686         }
2687
2688       /* If there was no C++ name, this must be a C-style function or
2689          not a function at all.  Just return the same symbol.  Do the
2690          same if cp_func_name fails for some reason.  */
2691       if (func_name == NULL)
2692         {
2693           *symp = fsym;
2694           do_cleanups (all_cleanups);
2695           return 0;
2696         }
2697
2698       func_oload_champ = find_oload_champ_namespace (args, nargs,
2699                                                      func_name,
2700                                                      qualified_name,
2701                                                      &oload_syms,
2702                                                      &func_badness,
2703                                                      no_adl);
2704
2705       if (func_oload_champ >= 0)
2706         func_match_quality = classify_oload_match (func_badness, nargs, 0);
2707
2708       make_cleanup (xfree, oload_syms);
2709       make_cleanup (xfree, func_badness);
2710     }
2711
2712   /* Did we find a match ?  */
2713   if (method_oload_champ == -1 && func_oload_champ == -1)
2714     throw_error (NOT_FOUND_ERROR,
2715                  _("No symbol \"%s\" in current context."),
2716                  name);
2717
2718   /* If we have found both a method match and a function
2719      match, find out which one is better, and calculate match
2720      quality.  */
2721   if (method_oload_champ >= 0 && func_oload_champ >= 0)
2722     {
2723       switch (compare_badness (func_badness, method_badness))
2724         {
2725           case 0: /* Top two contenders are equally good.  */
2726             /* FIXME: GDB does not support the general ambiguous case.
2727              All candidates should be collected and presented the
2728              user.  */
2729             error (_("Ambiguous overload resolution"));
2730             break;
2731           case 1: /* Incomparable top contenders.  */
2732             /* This is an error incompatible candidates
2733                should not have been proposed.  */
2734             error (_("Internal error: incompatible "
2735                      "overload candidates proposed"));
2736             break;
2737           case 2: /* Function champion.  */
2738             method_oload_champ = -1;
2739             match_quality = func_match_quality;
2740             break;
2741           case 3: /* Method champion.  */
2742             func_oload_champ = -1;
2743             match_quality = method_match_quality;
2744             break;
2745           default:
2746             error (_("Internal error: unexpected overload comparison result"));
2747             break;
2748         }
2749     }
2750   else
2751     {
2752       /* We have either a method match or a function match.  */
2753       if (method_oload_champ >= 0)
2754         match_quality = method_match_quality;
2755       else
2756         match_quality = func_match_quality;
2757     }
2758
2759   if (match_quality == INCOMPATIBLE)
2760     {
2761       if (method == METHOD)
2762         error (_("Cannot resolve method %s%s%s to any overloaded instance"),
2763                obj_type_name,
2764                (obj_type_name && *obj_type_name) ? "::" : "",
2765                name);
2766       else
2767         error (_("Cannot resolve function %s to any overloaded instance"),
2768                func_name);
2769     }
2770   else if (match_quality == NON_STANDARD)
2771     {
2772       if (method == METHOD)
2773         warning (_("Using non-standard conversion to match "
2774                    "method %s%s%s to supplied arguments"),
2775                  obj_type_name,
2776                  (obj_type_name && *obj_type_name) ? "::" : "",
2777                  name);
2778       else
2779         warning (_("Using non-standard conversion to match "
2780                    "function %s to supplied arguments"),
2781                  func_name);
2782     }
2783
2784   if (staticp != NULL)
2785     *staticp = oload_method_static_p (fns_ptr, method_oload_champ);
2786
2787   if (method_oload_champ >= 0)
2788     {
2789       if (src_method_oload_champ >= 0)
2790         {
2791           if (TYPE_FN_FIELD_VIRTUAL_P (fns_ptr, method_oload_champ)
2792               && noside != EVAL_AVOID_SIDE_EFFECTS)
2793             {
2794               *valp = value_virtual_fn_field (&temp, fns_ptr,
2795                                               method_oload_champ, basetype,
2796                                               boffset);
2797             }
2798           else
2799             *valp = value_fn_field (&temp, fns_ptr, method_oload_champ,
2800                                     basetype, boffset);
2801         }
2802       else
2803         {
2804           *valp = value_of_xmethod (clone_xmethod_worker
2805             (VEC_index (xmethod_worker_ptr, xm_worker_vec,
2806                         ext_method_oload_champ)));
2807         }
2808     }
2809   else
2810     *symp = oload_syms[func_oload_champ];
2811
2812   if (objp)
2813     {
2814       struct type *temp_type = check_typedef (value_type (temp));
2815       struct type *objtype = check_typedef (obj_type);
2816
2817       if (TYPE_CODE (temp_type) != TYPE_CODE_PTR
2818           && (TYPE_CODE (objtype) == TYPE_CODE_PTR
2819               || TYPE_IS_REFERENCE (objtype)))
2820         {
2821           temp = value_addr (temp);
2822         }
2823       *objp = temp;
2824     }
2825
2826   do_cleanups (all_cleanups);
2827
2828   switch (match_quality)
2829     {
2830     case INCOMPATIBLE:
2831       return 100;
2832     case NON_STANDARD:
2833       return 10;
2834     default:                            /* STANDARD */
2835       return 0;
2836     }
2837 }
2838
2839 /* Find the best overload match, searching for FUNC_NAME in namespaces
2840    contained in QUALIFIED_NAME until it either finds a good match or
2841    runs out of namespaces.  It stores the overloaded functions in
2842    *OLOAD_SYMS, and the badness vector in *OLOAD_CHAMP_BV.  The
2843    calling function is responsible for freeing *OLOAD_SYMS and
2844    *OLOAD_CHAMP_BV.  If NO_ADL, argument dependent lookup is not 
2845    performned.  */
2846
2847 static int
2848 find_oload_champ_namespace (struct value **args, int nargs,
2849                             const char *func_name,
2850                             const char *qualified_name,
2851                             struct symbol ***oload_syms,
2852                             struct badness_vector **oload_champ_bv,
2853                             const int no_adl)
2854 {
2855   int oload_champ;
2856
2857   find_oload_champ_namespace_loop (args, nargs,
2858                                    func_name,
2859                                    qualified_name, 0,
2860                                    oload_syms, oload_champ_bv,
2861                                    &oload_champ,
2862                                    no_adl);
2863
2864   return oload_champ;
2865 }
2866
2867 /* Helper function for find_oload_champ_namespace; NAMESPACE_LEN is
2868    how deep we've looked for namespaces, and the champ is stored in
2869    OLOAD_CHAMP.  The return value is 1 if the champ is a good one, 0
2870    if it isn't.  Other arguments are the same as in
2871    find_oload_champ_namespace
2872
2873    It is the caller's responsibility to free *OLOAD_SYMS and
2874    *OLOAD_CHAMP_BV.  */
2875
2876 static int
2877 find_oload_champ_namespace_loop (struct value **args, int nargs,
2878                                  const char *func_name,
2879                                  const char *qualified_name,
2880                                  int namespace_len,
2881                                  struct symbol ***oload_syms,
2882                                  struct badness_vector **oload_champ_bv,
2883                                  int *oload_champ,
2884                                  const int no_adl)
2885 {
2886   int next_namespace_len = namespace_len;
2887   int searched_deeper = 0;
2888   int num_fns = 0;
2889   struct cleanup *old_cleanups;
2890   int new_oload_champ;
2891   struct symbol **new_oload_syms;
2892   struct badness_vector *new_oload_champ_bv;
2893   char *new_namespace;
2894
2895   if (next_namespace_len != 0)
2896     {
2897       gdb_assert (qualified_name[next_namespace_len] == ':');
2898       next_namespace_len +=  2;
2899     }
2900   next_namespace_len +=
2901     cp_find_first_component (qualified_name + next_namespace_len);
2902
2903   /* Initialize these to values that can safely be xfree'd.  */
2904   *oload_syms = NULL;
2905   *oload_champ_bv = NULL;
2906
2907   /* First, see if we have a deeper namespace we can search in.
2908      If we get a good match there, use it.  */
2909
2910   if (qualified_name[next_namespace_len] == ':')
2911     {
2912       searched_deeper = 1;
2913
2914       if (find_oload_champ_namespace_loop (args, nargs,
2915                                            func_name, qualified_name,
2916                                            next_namespace_len,
2917                                            oload_syms, oload_champ_bv,
2918                                            oload_champ, no_adl))
2919         {
2920           return 1;
2921         }
2922     };
2923
2924   /* If we reach here, either we're in the deepest namespace or we
2925      didn't find a good match in a deeper namespace.  But, in the
2926      latter case, we still have a bad match in a deeper namespace;
2927      note that we might not find any match at all in the current
2928      namespace.  (There's always a match in the deepest namespace,
2929      because this overload mechanism only gets called if there's a
2930      function symbol to start off with.)  */
2931
2932   old_cleanups = make_cleanup (xfree, *oload_syms);
2933   make_cleanup (xfree, *oload_champ_bv);
2934   new_namespace = (char *) alloca (namespace_len + 1);
2935   strncpy (new_namespace, qualified_name, namespace_len);
2936   new_namespace[namespace_len] = '\0';
2937   new_oload_syms = make_symbol_overload_list (func_name,
2938                                               new_namespace);
2939
2940   /* If we have reached the deepest level perform argument
2941      determined lookup.  */
2942   if (!searched_deeper && !no_adl)
2943     {
2944       int ix;
2945       struct type **arg_types;
2946
2947       /* Prepare list of argument types for overload resolution.  */
2948       arg_types = (struct type **)
2949         alloca (nargs * (sizeof (struct type *)));
2950       for (ix = 0; ix < nargs; ix++)
2951         arg_types[ix] = value_type (args[ix]);
2952       make_symbol_overload_list_adl (arg_types, nargs, func_name);
2953     }
2954
2955   while (new_oload_syms[num_fns])
2956     ++num_fns;
2957
2958   new_oload_champ = find_oload_champ (args, nargs, num_fns,
2959                                       NULL, NULL, new_oload_syms,
2960                                       &new_oload_champ_bv);
2961
2962   /* Case 1: We found a good match.  Free earlier matches (if any),
2963      and return it.  Case 2: We didn't find a good match, but we're
2964      not the deepest function.  Then go with the bad match that the
2965      deeper function found.  Case 3: We found a bad match, and we're
2966      the deepest function.  Then return what we found, even though
2967      it's a bad match.  */
2968
2969   if (new_oload_champ != -1
2970       && classify_oload_match (new_oload_champ_bv, nargs, 0) == STANDARD)
2971     {
2972       *oload_syms = new_oload_syms;
2973       *oload_champ = new_oload_champ;
2974       *oload_champ_bv = new_oload_champ_bv;
2975       do_cleanups (old_cleanups);
2976       return 1;
2977     }
2978   else if (searched_deeper)
2979     {
2980       xfree (new_oload_syms);
2981       xfree (new_oload_champ_bv);
2982       discard_cleanups (old_cleanups);
2983       return 0;
2984     }
2985   else
2986     {
2987       *oload_syms = new_oload_syms;
2988       *oload_champ = new_oload_champ;
2989       *oload_champ_bv = new_oload_champ_bv;
2990       do_cleanups (old_cleanups);
2991       return 0;
2992     }
2993 }
2994
2995 /* Look for a function to take NARGS args of ARGS.  Find
2996    the best match from among the overloaded methods or functions
2997    given by FNS_PTR or OLOAD_SYMS or XM_WORKER_VEC, respectively.
2998    One, and only one of FNS_PTR, OLOAD_SYMS and XM_WORKER_VEC can be
2999    non-NULL.
3000
3001    If XM_WORKER_VEC is NULL, then the length of the arrays FNS_PTR
3002    or OLOAD_SYMS (whichever is non-NULL) is specified in NUM_FNS.
3003
3004    Return the index of the best match; store an indication of the
3005    quality of the match in OLOAD_CHAMP_BV.
3006
3007    It is the caller's responsibility to free *OLOAD_CHAMP_BV.  */
3008
3009 static int
3010 find_oload_champ (struct value **args, int nargs,
3011                   int num_fns, struct fn_field *fns_ptr,
3012                   VEC (xmethod_worker_ptr) *xm_worker_vec,
3013                   struct symbol **oload_syms,
3014                   struct badness_vector **oload_champ_bv)
3015 {
3016   int ix;
3017   int fn_count;
3018   /* A measure of how good an overloaded instance is.  */
3019   struct badness_vector *bv;
3020   /* Index of best overloaded function.  */
3021   int oload_champ = -1;
3022   /* Current ambiguity state for overload resolution.  */
3023   int oload_ambiguous = 0;
3024   /* 0 => no ambiguity, 1 => two good funcs, 2 => incomparable funcs.  */
3025
3026   /* A champion can be found among methods alone, or among functions
3027      alone, or in xmethods alone, but not in more than one of these
3028      groups.  */
3029   gdb_assert ((fns_ptr != NULL) + (oload_syms != NULL) + (xm_worker_vec != NULL)
3030               == 1);
3031
3032   *oload_champ_bv = NULL;
3033
3034   fn_count = (xm_worker_vec != NULL
3035               ? VEC_length (xmethod_worker_ptr, xm_worker_vec)
3036               : num_fns);
3037   /* Consider each candidate in turn.  */
3038   for (ix = 0; ix < fn_count; ix++)
3039     {
3040       int jj;
3041       int static_offset = 0;
3042       int nparms;
3043       struct type **parm_types;
3044       struct xmethod_worker *worker = NULL;
3045
3046       if (xm_worker_vec != NULL)
3047         {
3048           worker = VEC_index (xmethod_worker_ptr, xm_worker_vec, ix);
3049           parm_types = get_xmethod_arg_types (worker, &nparms);
3050         }
3051       else
3052         {
3053           if (fns_ptr != NULL)
3054             {
3055               nparms = TYPE_NFIELDS (TYPE_FN_FIELD_TYPE (fns_ptr, ix));
3056               static_offset = oload_method_static_p (fns_ptr, ix);
3057             }
3058           else
3059             nparms = TYPE_NFIELDS (SYMBOL_TYPE (oload_syms[ix]));
3060
3061           parm_types = XNEWVEC (struct type *, nparms);
3062           for (jj = 0; jj < nparms; jj++)
3063             parm_types[jj] = (fns_ptr != NULL
3064                               ? (TYPE_FN_FIELD_ARGS (fns_ptr, ix)[jj].type)
3065                               : TYPE_FIELD_TYPE (SYMBOL_TYPE (oload_syms[ix]),
3066                                                  jj));
3067         }
3068
3069       /* Compare parameter types to supplied argument types.  Skip
3070          THIS for static methods.  */
3071       bv = rank_function (parm_types, nparms, 
3072                           args + static_offset,
3073                           nargs - static_offset);
3074
3075       if (!*oload_champ_bv)
3076         {
3077           *oload_champ_bv = bv;
3078           oload_champ = 0;
3079         }
3080       else /* See whether current candidate is better or worse than
3081               previous best.  */
3082         switch (compare_badness (bv, *oload_champ_bv))
3083           {
3084           case 0:               /* Top two contenders are equally good.  */
3085             oload_ambiguous = 1;
3086             break;
3087           case 1:               /* Incomparable top contenders.  */
3088             oload_ambiguous = 2;
3089             break;
3090           case 2:               /* New champion, record details.  */
3091             *oload_champ_bv = bv;
3092             oload_ambiguous = 0;
3093             oload_champ = ix;
3094             break;
3095           case 3:
3096           default:
3097             break;
3098           }
3099       xfree (parm_types);
3100       if (overload_debug)
3101         {
3102           if (fns_ptr != NULL)
3103             fprintf_filtered (gdb_stderr,
3104                               "Overloaded method instance %s, # of parms %d\n",
3105                               fns_ptr[ix].physname, nparms);
3106           else if (xm_worker_vec != NULL)
3107             fprintf_filtered (gdb_stderr,
3108                               "Xmethod worker, # of parms %d\n",
3109                               nparms);
3110           else
3111             fprintf_filtered (gdb_stderr,
3112                               "Overloaded function instance "
3113                               "%s # of parms %d\n",
3114                               SYMBOL_DEMANGLED_NAME (oload_syms[ix]), 
3115                               nparms);
3116           for (jj = 0; jj < nargs - static_offset; jj++)
3117             fprintf_filtered (gdb_stderr,
3118                               "...Badness @ %d : %d\n", 
3119                               jj, bv->rank[jj].rank);
3120           fprintf_filtered (gdb_stderr, "Overload resolution "
3121                             "champion is %d, ambiguous? %d\n", 
3122                             oload_champ, oload_ambiguous);
3123         }
3124     }
3125
3126   return oload_champ;
3127 }
3128
3129 /* Return 1 if we're looking at a static method, 0 if we're looking at
3130    a non-static method or a function that isn't a method.  */
3131
3132 static int
3133 oload_method_static_p (struct fn_field *fns_ptr, int index)
3134 {
3135   if (fns_ptr && index >= 0 && TYPE_FN_FIELD_STATIC_P (fns_ptr, index))
3136     return 1;
3137   else
3138     return 0;
3139 }
3140
3141 /* Check how good an overload match OLOAD_CHAMP_BV represents.  */
3142
3143 static enum oload_classification
3144 classify_oload_match (struct badness_vector *oload_champ_bv,
3145                       int nargs,
3146                       int static_offset)
3147 {
3148   int ix;
3149   enum oload_classification worst = STANDARD;
3150
3151   for (ix = 1; ix <= nargs - static_offset; ix++)
3152     {
3153       /* If this conversion is as bad as INCOMPATIBLE_TYPE_BADNESS
3154          or worse return INCOMPATIBLE.  */
3155       if (compare_ranks (oload_champ_bv->rank[ix],
3156                          INCOMPATIBLE_TYPE_BADNESS) <= 0)
3157         return INCOMPATIBLE;    /* Truly mismatched types.  */
3158       /* Otherwise If this conversion is as bad as
3159          NS_POINTER_CONVERSION_BADNESS or worse return NON_STANDARD.  */
3160       else if (compare_ranks (oload_champ_bv->rank[ix],
3161                               NS_POINTER_CONVERSION_BADNESS) <= 0)
3162         worst = NON_STANDARD;   /* Non-standard type conversions
3163                                    needed.  */
3164     }
3165
3166   /* If no INCOMPATIBLE classification was found, return the worst one
3167      that was found (if any).  */
3168   return worst;
3169 }
3170
3171 /* C++: return 1 is NAME is a legitimate name for the destructor of
3172    type TYPE.  If TYPE does not have a destructor, or if NAME is
3173    inappropriate for TYPE, an error is signaled.  Parameter TYPE should not yet
3174    have CHECK_TYPEDEF applied, this function will apply it itself.  */
3175
3176 int
3177 destructor_name_p (const char *name, struct type *type)
3178 {
3179   if (name[0] == '~')
3180     {
3181       const char *dname = type_name_no_tag_or_error (type);
3182       const char *cp = strchr (dname, '<');
3183       unsigned int len;
3184
3185       /* Do not compare the template part for template classes.  */
3186       if (cp == NULL)
3187         len = strlen (dname);
3188       else
3189         len = cp - dname;
3190       if (strlen (name + 1) != len || strncmp (dname, name + 1, len) != 0)
3191         error (_("name of destructor must equal name of class"));
3192       else
3193         return 1;
3194     }
3195   return 0;
3196 }
3197
3198 /* Find an enum constant named NAME in TYPE.  TYPE must be an "enum
3199    class".  If the name is found, return a value representing it;
3200    otherwise throw an exception.  */
3201
3202 static struct value *
3203 enum_constant_from_type (struct type *type, const char *name)
3204 {
3205   int i;
3206   int name_len = strlen (name);
3207
3208   gdb_assert (TYPE_CODE (type) == TYPE_CODE_ENUM
3209               && TYPE_DECLARED_CLASS (type));
3210
3211   for (i = TYPE_N_BASECLASSES (type); i < TYPE_NFIELDS (type); ++i)
3212     {
3213       const char *fname = TYPE_FIELD_NAME (type, i);
3214       int len;
3215
3216       if (TYPE_FIELD_LOC_KIND (type, i) != FIELD_LOC_KIND_ENUMVAL
3217           || fname == NULL)
3218         continue;
3219
3220       /* Look for the trailing "::NAME", since enum class constant
3221          names are qualified here.  */
3222       len = strlen (fname);
3223       if (len + 2 >= name_len
3224           && fname[len - name_len - 2] == ':'
3225           && fname[len - name_len - 1] == ':'
3226           && strcmp (&fname[len - name_len], name) == 0)
3227         return value_from_longest (type, TYPE_FIELD_ENUMVAL (type, i));
3228     }
3229
3230   error (_("no constant named \"%s\" in enum \"%s\""),
3231          name, TYPE_TAG_NAME (type));
3232 }
3233
3234 /* C++: Given an aggregate type CURTYPE, and a member name NAME,
3235    return the appropriate member (or the address of the member, if
3236    WANT_ADDRESS).  This function is used to resolve user expressions
3237    of the form "DOMAIN::NAME".  For more details on what happens, see
3238    the comment before value_struct_elt_for_reference.  */
3239
3240 struct value *
3241 value_aggregate_elt (struct type *curtype, const char *name,
3242                      struct type *expect_type, int want_address,
3243                      enum noside noside)
3244 {
3245   switch (TYPE_CODE (curtype))
3246     {
3247     case TYPE_CODE_STRUCT:
3248     case TYPE_CODE_UNION:
3249       return value_struct_elt_for_reference (curtype, 0, curtype, 
3250                                              name, expect_type,
3251                                              want_address, noside);
3252     case TYPE_CODE_NAMESPACE:
3253       return value_namespace_elt (curtype, name, 
3254                                   want_address, noside);
3255
3256     case TYPE_CODE_ENUM:
3257       return enum_constant_from_type (curtype, name);
3258
3259     default:
3260       internal_error (__FILE__, __LINE__,
3261                       _("non-aggregate type in value_aggregate_elt"));
3262     }
3263 }
3264
3265 /* Compares the two method/function types T1 and T2 for "equality" 
3266    with respect to the methods' parameters.  If the types of the
3267    two parameter lists are the same, returns 1; 0 otherwise.  This
3268    comparison may ignore any artificial parameters in T1 if
3269    SKIP_ARTIFICIAL is non-zero.  This function will ALWAYS skip
3270    the first artificial parameter in T1, assumed to be a 'this' pointer.
3271
3272    The type T2 is expected to have come from make_params (in eval.c).  */
3273
3274 static int
3275 compare_parameters (struct type *t1, struct type *t2, int skip_artificial)
3276 {
3277   int start = 0;
3278
3279   if (TYPE_NFIELDS (t1) > 0 && TYPE_FIELD_ARTIFICIAL (t1, 0))
3280     ++start;
3281
3282   /* If skipping artificial fields, find the first real field
3283      in T1.  */
3284   if (skip_artificial)
3285     {
3286       while (start < TYPE_NFIELDS (t1)
3287              && TYPE_FIELD_ARTIFICIAL (t1, start))
3288         ++start;
3289     }
3290
3291   /* Now compare parameters.  */
3292
3293   /* Special case: a method taking void.  T1 will contain no
3294      non-artificial fields, and T2 will contain TYPE_CODE_VOID.  */
3295   if ((TYPE_NFIELDS (t1) - start) == 0 && TYPE_NFIELDS (t2) == 1
3296       && TYPE_CODE (TYPE_FIELD_TYPE (t2, 0)) == TYPE_CODE_VOID)
3297     return 1;
3298
3299   if ((TYPE_NFIELDS (t1) - start) == TYPE_NFIELDS (t2))
3300     {
3301       int i;
3302
3303       for (i = 0; i < TYPE_NFIELDS (t2); ++i)
3304         {
3305           if (compare_ranks (rank_one_type (TYPE_FIELD_TYPE (t1, start + i),
3306                                             TYPE_FIELD_TYPE (t2, i), NULL),
3307                              EXACT_MATCH_BADNESS) != 0)
3308             return 0;
3309         }
3310
3311       return 1;
3312     }
3313
3314   return 0;
3315 }
3316
3317 /* C++: Given an aggregate type CURTYPE, and a member name NAME,
3318    return the address of this member as a "pointer to member" type.
3319    If INTYPE is non-null, then it will be the type of the member we
3320    are looking for.  This will help us resolve "pointers to member
3321    functions".  This function is used to resolve user expressions of
3322    the form "DOMAIN::NAME".  */
3323
3324 static struct value *
3325 value_struct_elt_for_reference (struct type *domain, int offset,
3326                                 struct type *curtype, const char *name,
3327                                 struct type *intype, 
3328                                 int want_address,
3329                                 enum noside noside)
3330 {
3331   struct type *t = curtype;
3332   int i;
3333   struct value *v, *result;
3334
3335   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
3336       && TYPE_CODE (t) != TYPE_CODE_UNION)
3337     error (_("Internal error: non-aggregate type "
3338              "to value_struct_elt_for_reference"));
3339
3340   for (i = TYPE_NFIELDS (t) - 1; i >= TYPE_N_BASECLASSES (t); i--)
3341     {
3342       const char *t_field_name = TYPE_FIELD_NAME (t, i);
3343
3344       if (t_field_name && strcmp (t_field_name, name) == 0)
3345         {
3346           if (field_is_static (&TYPE_FIELD (t, i)))
3347             {
3348               v = value_static_field (t, i);
3349               if (want_address)
3350                 v = value_addr (v);
3351               return v;
3352             }
3353           if (TYPE_FIELD_PACKED (t, i))
3354             error (_("pointers to bitfield members not allowed"));
3355
3356           if (want_address)
3357             return value_from_longest
3358               (lookup_memberptr_type (TYPE_FIELD_TYPE (t, i), domain),
3359                offset + (LONGEST) (TYPE_FIELD_BITPOS (t, i) >> 3));
3360           else if (noside != EVAL_NORMAL)
3361             return allocate_value (TYPE_FIELD_TYPE (t, i));
3362           else
3363             {
3364               /* Try to evaluate NAME as a qualified name with implicit
3365                  this pointer.  In this case, attempt to return the
3366                  equivalent to `this->*(&TYPE::NAME)'.  */
3367               v = value_of_this_silent (current_language);
3368               if (v != NULL)
3369                 {
3370                   struct value *ptr;
3371                   long mem_offset;
3372                   struct type *type, *tmp;
3373
3374                   ptr = value_aggregate_elt (domain, name, NULL, 1, noside);
3375                   type = check_typedef (value_type (ptr));
3376                   gdb_assert (type != NULL
3377                               && TYPE_CODE (type) == TYPE_CODE_MEMBERPTR);
3378                   tmp = lookup_pointer_type (TYPE_SELF_TYPE (type));
3379                   v = value_cast_pointers (tmp, v, 1);
3380                   mem_offset = value_as_long (ptr);
3381                   tmp = lookup_pointer_type (TYPE_TARGET_TYPE (type));
3382                   result = value_from_pointer (tmp,
3383                                                value_as_long (v) + mem_offset);
3384                   return value_ind (result);
3385                 }
3386
3387               error (_("Cannot reference non-static field \"%s\""), name);
3388             }
3389         }
3390     }
3391
3392   /* C++: If it was not found as a data field, then try to return it
3393      as a pointer to a method.  */
3394
3395   /* Perform all necessary dereferencing.  */
3396   while (intype && TYPE_CODE (intype) == TYPE_CODE_PTR)
3397     intype = TYPE_TARGET_TYPE (intype);
3398
3399   for (i = TYPE_NFN_FIELDS (t) - 1; i >= 0; --i)
3400     {
3401       const char *t_field_name = TYPE_FN_FIELDLIST_NAME (t, i);
3402       char dem_opname[64];
3403
3404       if (startswith (t_field_name, "__") 
3405           || startswith (t_field_name, "op") 
3406           || startswith (t_field_name, "type"))
3407         {
3408           if (cplus_demangle_opname (t_field_name, 
3409                                      dem_opname, DMGL_ANSI))
3410             t_field_name = dem_opname;
3411           else if (cplus_demangle_opname (t_field_name, 
3412                                           dem_opname, 0))
3413             t_field_name = dem_opname;
3414         }
3415       if (t_field_name && strcmp (t_field_name, name) == 0)
3416         {
3417           int j;
3418           int len = TYPE_FN_FIELDLIST_LENGTH (t, i);
3419           struct fn_field *f = TYPE_FN_FIELDLIST1 (t, i);
3420
3421           check_stub_method_group (t, i);
3422
3423           if (intype)
3424             {
3425               for (j = 0; j < len; ++j)
3426                 {
3427                   if (compare_parameters (TYPE_FN_FIELD_TYPE (f, j), intype, 0)
3428                       || compare_parameters (TYPE_FN_FIELD_TYPE (f, j),
3429                                              intype, 1))
3430                     break;
3431                 }
3432
3433               if (j == len)
3434                 error (_("no member function matches "
3435                          "that type instantiation"));
3436             }
3437           else
3438             {
3439               int ii;
3440
3441               j = -1;
3442               for (ii = 0; ii < len; ++ii)
3443                 {
3444                   /* Skip artificial methods.  This is necessary if,
3445                      for example, the user wants to "print
3446                      subclass::subclass" with only one user-defined
3447                      constructor.  There is no ambiguity in this case.
3448                      We are careful here to allow artificial methods
3449                      if they are the unique result.  */
3450                   if (TYPE_FN_FIELD_ARTIFICIAL (f, ii))
3451                     {
3452                       if (j == -1)
3453                         j = ii;
3454                       continue;
3455                     }
3456
3457                   /* Desired method is ambiguous if more than one
3458                      method is defined.  */
3459                   if (j != -1 && !TYPE_FN_FIELD_ARTIFICIAL (f, j))
3460                     error (_("non-unique member `%s' requires "
3461                              "type instantiation"), name);
3462
3463                   j = ii;
3464                 }
3465
3466               if (j == -1)
3467                 error (_("no matching member function"));
3468             }
3469
3470           if (TYPE_FN_FIELD_STATIC_P (f, j))
3471             {
3472               struct symbol *s = 
3473                 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3474                                0, VAR_DOMAIN, 0).symbol;
3475
3476               if (s == NULL)
3477                 return NULL;
3478
3479               if (want_address)
3480                 return value_addr (read_var_value (s, 0, 0));
3481               else
3482                 return read_var_value (s, 0, 0);
3483             }
3484
3485           if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
3486             {
3487               if (want_address)
3488                 {
3489                   result = allocate_value
3490                     (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3491                   cplus_make_method_ptr (value_type (result),
3492                                          value_contents_writeable (result),
3493                                          TYPE_FN_FIELD_VOFFSET (f, j), 1);
3494                 }
3495               else if (noside == EVAL_AVOID_SIDE_EFFECTS)
3496                 return allocate_value (TYPE_FN_FIELD_TYPE (f, j));
3497               else
3498                 error (_("Cannot reference virtual member function \"%s\""),
3499                        name);
3500             }
3501           else
3502             {
3503               struct symbol *s = 
3504                 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3505                                0, VAR_DOMAIN, 0).symbol;
3506
3507               if (s == NULL)
3508                 return NULL;
3509
3510               v = read_var_value (s, 0, 0);
3511               if (!want_address)
3512                 result = v;
3513               else
3514                 {
3515                   result = allocate_value (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3516                   cplus_make_method_ptr (value_type (result),
3517                                          value_contents_writeable (result),
3518                                          value_address (v), 0);
3519                 }
3520             }
3521           return result;
3522         }
3523     }
3524   for (i = TYPE_N_BASECLASSES (t) - 1; i >= 0; i--)
3525     {
3526       struct value *v;
3527       int base_offset;
3528
3529       if (BASETYPE_VIA_VIRTUAL (t, i))
3530         base_offset = 0;
3531       else
3532         base_offset = TYPE_BASECLASS_BITPOS (t, i) / 8;
3533       v = value_struct_elt_for_reference (domain,
3534                                           offset + base_offset,
3535                                           TYPE_BASECLASS (t, i),
3536                                           name, intype, 
3537                                           want_address, noside);
3538       if (v)
3539         return v;
3540     }
3541
3542   /* As a last chance, pretend that CURTYPE is a namespace, and look
3543      it up that way; this (frequently) works for types nested inside
3544      classes.  */
3545
3546   return value_maybe_namespace_elt (curtype, name, 
3547                                     want_address, noside);
3548 }
3549
3550 /* C++: Return the member NAME of the namespace given by the type
3551    CURTYPE.  */
3552
3553 static struct value *
3554 value_namespace_elt (const struct type *curtype,
3555                      const char *name, int want_address,
3556                      enum noside noside)
3557 {
3558   struct value *retval = value_maybe_namespace_elt (curtype, name,
3559                                                     want_address, 
3560                                                     noside);
3561
3562   if (retval == NULL)
3563     error (_("No symbol \"%s\" in namespace \"%s\"."), 
3564            name, TYPE_TAG_NAME (curtype));
3565
3566   return retval;
3567 }
3568
3569 /* A helper function used by value_namespace_elt and
3570    value_struct_elt_for_reference.  It looks up NAME inside the
3571    context CURTYPE; this works if CURTYPE is a namespace or if CURTYPE
3572    is a class and NAME refers to a type in CURTYPE itself (as opposed
3573    to, say, some base class of CURTYPE).  */
3574
3575 static struct value *
3576 value_maybe_namespace_elt (const struct type *curtype,
3577                            const char *name, int want_address,
3578                            enum noside noside)
3579 {
3580   const char *namespace_name = TYPE_TAG_NAME (curtype);
3581   struct block_symbol sym;
3582   struct value *result;
3583
3584   sym = cp_lookup_symbol_namespace (namespace_name, name,
3585                                     get_selected_block (0), VAR_DOMAIN);
3586
3587   if (sym.symbol == NULL)
3588     return NULL;
3589   else if ((noside == EVAL_AVOID_SIDE_EFFECTS)
3590            && (SYMBOL_CLASS (sym.symbol) == LOC_TYPEDEF))
3591     result = allocate_value (SYMBOL_TYPE (sym.symbol));
3592   else
3593     result = value_of_variable (sym.symbol, sym.block);
3594
3595   if (want_address)
3596     result = value_addr (result);
3597
3598   return result;
3599 }
3600
3601 /* Given a pointer or a reference value V, find its real (RTTI) type.
3602
3603    Other parameters FULL, TOP, USING_ENC as with value_rtti_type()
3604    and refer to the values computed for the object pointed to.  */
3605
3606 struct type *
3607 value_rtti_indirect_type (struct value *v, int *full, 
3608                           LONGEST *top, int *using_enc)
3609 {
3610   struct value *target = NULL;
3611   struct type *type, *real_type, *target_type;
3612
3613   type = value_type (v);
3614   type = check_typedef (type);
3615   if (TYPE_IS_REFERENCE (type))
3616     target = coerce_ref (v);
3617   else if (TYPE_CODE (type) == TYPE_CODE_PTR)
3618     {
3619
3620       TRY
3621         {
3622           target = value_ind (v);
3623         }
3624       CATCH (except, RETURN_MASK_ERROR)
3625         {
3626           if (except.error == MEMORY_ERROR)
3627             {
3628               /* value_ind threw a memory error. The pointer is NULL or
3629                  contains an uninitialized value: we can't determine any
3630                  type.  */
3631               return NULL;
3632             }
3633           throw_exception (except);
3634         }
3635       END_CATCH
3636     }
3637   else
3638     return NULL;
3639
3640   real_type = value_rtti_type (target, full, top, using_enc);
3641
3642   if (real_type)
3643     {
3644       /* Copy qualifiers to the referenced object.  */
3645       target_type = value_type (target);
3646       real_type = make_cv_type (TYPE_CONST (target_type),
3647                                 TYPE_VOLATILE (target_type), real_type, NULL);
3648       if (TYPE_IS_REFERENCE (type))
3649         real_type = lookup_reference_type (real_type, TYPE_CODE (type));
3650       else if (TYPE_CODE (type) == TYPE_CODE_PTR)
3651         real_type = lookup_pointer_type (real_type);
3652       else
3653         internal_error (__FILE__, __LINE__, _("Unexpected value type."));
3654
3655       /* Copy qualifiers to the pointer/reference.  */
3656       real_type = make_cv_type (TYPE_CONST (type), TYPE_VOLATILE (type),
3657                                 real_type, NULL);
3658     }
3659
3660   return real_type;
3661 }
3662
3663 /* Given a value pointed to by ARGP, check its real run-time type, and
3664    if that is different from the enclosing type, create a new value
3665    using the real run-time type as the enclosing type (and of the same
3666    type as ARGP) and return it, with the embedded offset adjusted to
3667    be the correct offset to the enclosed object.  RTYPE is the type,
3668    and XFULL, XTOP, and XUSING_ENC are the other parameters, computed
3669    by value_rtti_type().  If these are available, they can be supplied
3670    and a second call to value_rtti_type() is avoided.  (Pass RTYPE ==
3671    NULL if they're not available.  */
3672
3673 struct value *
3674 value_full_object (struct value *argp, 
3675                    struct type *rtype, 
3676                    int xfull, int xtop,
3677                    int xusing_enc)
3678 {
3679   struct type *real_type;
3680   int full = 0;
3681   LONGEST top = -1;
3682   int using_enc = 0;
3683   struct value *new_val;
3684
3685   if (rtype)
3686     {
3687       real_type = rtype;
3688       full = xfull;
3689       top = xtop;
3690       using_enc = xusing_enc;
3691     }
3692   else
3693     real_type = value_rtti_type (argp, &full, &top, &using_enc);
3694
3695   /* If no RTTI data, or if object is already complete, do nothing.  */
3696   if (!real_type || real_type == value_enclosing_type (argp))
3697     return argp;
3698
3699   /* In a destructor we might see a real type that is a superclass of
3700      the object's type.  In this case it is better to leave the object
3701      as-is.  */
3702   if (full
3703       && TYPE_LENGTH (real_type) < TYPE_LENGTH (value_enclosing_type (argp)))
3704     return argp;
3705
3706   /* If we have the full object, but for some reason the enclosing
3707      type is wrong, set it.  */
3708   /* pai: FIXME -- sounds iffy */
3709   if (full)
3710     {
3711       argp = value_copy (argp);
3712       set_value_enclosing_type (argp, real_type);
3713       return argp;
3714     }
3715
3716   /* Check if object is in memory.  */
3717   if (VALUE_LVAL (argp) != lval_memory)
3718     {
3719       warning (_("Couldn't retrieve complete object of RTTI "
3720                  "type %s; object may be in register(s)."), 
3721                TYPE_NAME (real_type));
3722
3723       return argp;
3724     }
3725
3726   /* All other cases -- retrieve the complete object.  */
3727   /* Go back by the computed top_offset from the beginning of the
3728      object, adjusting for the embedded offset of argp if that's what
3729      value_rtti_type used for its computation.  */
3730   new_val = value_at_lazy (real_type, value_address (argp) - top +
3731                            (using_enc ? 0 : value_embedded_offset (argp)));
3732   deprecated_set_value_type (new_val, value_type (argp));
3733   set_value_embedded_offset (new_val, (using_enc
3734                                        ? top + value_embedded_offset (argp)
3735                                        : top));
3736   return new_val;
3737 }
3738
3739
3740 /* Return the value of the local variable, if one exists.  Throw error
3741    otherwise, such as if the request is made in an inappropriate context.  */
3742
3743 struct value *
3744 value_of_this (const struct language_defn *lang)
3745 {
3746   struct block_symbol sym;
3747   const struct block *b;
3748   struct frame_info *frame;
3749
3750   if (!lang->la_name_of_this)
3751     error (_("no `this' in current language"));
3752
3753   frame = get_selected_frame (_("no frame selected"));
3754
3755   b = get_frame_block (frame, NULL);
3756
3757   sym = lookup_language_this (lang, b);
3758   if (sym.symbol == NULL)
3759     error (_("current stack frame does not contain a variable named `%s'"),
3760            lang->la_name_of_this);
3761
3762   return read_var_value (sym.symbol, sym.block, frame);
3763 }
3764
3765 /* Return the value of the local variable, if one exists.  Return NULL
3766    otherwise.  Never throw error.  */
3767
3768 struct value *
3769 value_of_this_silent (const struct language_defn *lang)
3770 {
3771   struct value *ret = NULL;
3772
3773   TRY
3774     {
3775       ret = value_of_this (lang);
3776     }
3777   CATCH (except, RETURN_MASK_ERROR)
3778     {
3779     }
3780   END_CATCH
3781
3782   return ret;
3783 }
3784
3785 /* Create a slice (sub-string, sub-array) of ARRAY, that is LENGTH
3786    elements long, starting at LOWBOUND.  The result has the same lower
3787    bound as the original ARRAY.  */
3788
3789 struct value *
3790 value_slice (struct value *array, int lowbound, int length)
3791 {
3792   struct type *slice_range_type, *slice_type, *range_type;
3793   LONGEST lowerbound, upperbound;
3794   struct value *slice;
3795   struct type *array_type;
3796
3797   array_type = check_typedef (value_type (array));
3798   if (TYPE_CODE (array_type) != TYPE_CODE_ARRAY
3799       && TYPE_CODE (array_type) != TYPE_CODE_STRING)
3800     error (_("cannot take slice of non-array"));
3801
3802   range_type = TYPE_INDEX_TYPE (array_type);
3803   if (get_discrete_bounds (range_type, &lowerbound, &upperbound) < 0)
3804     error (_("slice from bad array or bitstring"));
3805
3806   if (lowbound < lowerbound || length < 0
3807       || lowbound + length - 1 > upperbound)
3808     error (_("slice out of range"));
3809
3810   /* FIXME-type-allocation: need a way to free this type when we are
3811      done with it.  */
3812   slice_range_type = create_static_range_type ((struct type *) NULL,
3813                                                TYPE_TARGET_TYPE (range_type),
3814                                                lowbound,
3815                                                lowbound + length - 1);
3816
3817   {
3818     struct type *element_type = TYPE_TARGET_TYPE (array_type);
3819     LONGEST offset
3820       = (lowbound - lowerbound) * TYPE_LENGTH (check_typedef (element_type));
3821
3822     slice_type = create_array_type ((struct type *) NULL,
3823                                     element_type,
3824                                     slice_range_type);
3825     TYPE_CODE (slice_type) = TYPE_CODE (array_type);
3826
3827     if (VALUE_LVAL (array) == lval_memory && value_lazy (array))
3828       slice = allocate_value_lazy (slice_type);
3829     else
3830       {
3831         slice = allocate_value (slice_type);
3832         value_contents_copy (slice, 0, array, offset,
3833                              type_length_units (slice_type));
3834       }
3835
3836     set_value_component_location (slice, array);
3837     set_value_offset (slice, value_offset (array) + offset);
3838   }
3839
3840   return slice;
3841 }
3842
3843 /* Create a value for a FORTRAN complex number.  Currently most of the
3844    time values are coerced to COMPLEX*16 (i.e. a complex number
3845    composed of 2 doubles.  This really should be a smarter routine
3846    that figures out precision inteligently as opposed to assuming
3847    doubles.  FIXME: fmb  */
3848
3849 struct value *
3850 value_literal_complex (struct value *arg1, 
3851                        struct value *arg2,
3852                        struct type *type)
3853 {
3854   struct value *val;
3855   struct type *real_type = TYPE_TARGET_TYPE (type);
3856
3857   val = allocate_value (type);
3858   arg1 = value_cast (real_type, arg1);
3859   arg2 = value_cast (real_type, arg2);
3860
3861   memcpy (value_contents_raw (val),
3862           value_contents (arg1), TYPE_LENGTH (real_type));
3863   memcpy (value_contents_raw (val) + TYPE_LENGTH (real_type),
3864           value_contents (arg2), TYPE_LENGTH (real_type));
3865   return val;
3866 }
3867
3868 /* Cast a value into the appropriate complex data type.  */
3869
3870 static struct value *
3871 cast_into_complex (struct type *type, struct value *val)
3872 {
3873   struct type *real_type = TYPE_TARGET_TYPE (type);
3874
3875   if (TYPE_CODE (value_type (val)) == TYPE_CODE_COMPLEX)
3876     {
3877       struct type *val_real_type = TYPE_TARGET_TYPE (value_type (val));
3878       struct value *re_val = allocate_value (val_real_type);
3879       struct value *im_val = allocate_value (val_real_type);
3880
3881       memcpy (value_contents_raw (re_val),
3882               value_contents (val), TYPE_LENGTH (val_real_type));
3883       memcpy (value_contents_raw (im_val),
3884               value_contents (val) + TYPE_LENGTH (val_real_type),
3885               TYPE_LENGTH (val_real_type));
3886
3887       return value_literal_complex (re_val, im_val, type);
3888     }
3889   else if (TYPE_CODE (value_type (val)) == TYPE_CODE_FLT
3890            || TYPE_CODE (value_type (val)) == TYPE_CODE_INT)
3891     return value_literal_complex (val, 
3892                                   value_zero (real_type, not_lval), 
3893                                   type);
3894   else
3895     error (_("cannot cast non-number to complex"));
3896 }
3897
3898 void
3899 _initialize_valops (void)
3900 {
3901   add_setshow_boolean_cmd ("overload-resolution", class_support,
3902                            &overload_resolution, _("\
3903 Set overload resolution in evaluating C++ functions."), _("\
3904 Show overload resolution in evaluating C++ functions."), 
3905                            NULL, NULL,
3906                            show_overload_resolution,
3907                            &setlist, &showlist);
3908   overload_resolution = 1;
3909 }