]> Git Repo - binutils.git/blob - gdb/gdbtypes.c
gdb: add type::target_type / type::set_target_type
[binutils.git] / gdb / gdbtypes.c
1 /* Support routines for manipulating internal types for GDB.
2
3    Copyright (C) 1992-2022 Free Software Foundation, Inc.
4
5    Contributed by Cygnus Support, using pieces from other GDB modules.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23 #include "bfd.h"
24 #include "symtab.h"
25 #include "symfile.h"
26 #include "objfiles.h"
27 #include "gdbtypes.h"
28 #include "expression.h"
29 #include "language.h"
30 #include "target.h"
31 #include "value.h"
32 #include "demangle.h"
33 #include "complaints.h"
34 #include "gdbcmd.h"
35 #include "cp-abi.h"
36 #include "hashtab.h"
37 #include "cp-support.h"
38 #include "bcache.h"
39 #include "dwarf2/loc.h"
40 #include "dwarf2/read.h"
41 #include "gdbcore.h"
42 #include "floatformat.h"
43 #include "f-lang.h"
44 #include <algorithm>
45 #include "gmp-utils.h"
46
47 /* The value of an invalid conversion badness.  */
48 #define INVALID_CONVERSION 100
49
50 static struct dynamic_prop_list *
51 copy_dynamic_prop_list (struct obstack *, struct dynamic_prop_list *);
52
53 /* Initialize BADNESS constants.  */
54
55 const struct rank LENGTH_MISMATCH_BADNESS = {INVALID_CONVERSION,0};
56
57 const struct rank TOO_FEW_PARAMS_BADNESS = {INVALID_CONVERSION,0};
58 const struct rank INCOMPATIBLE_TYPE_BADNESS = {INVALID_CONVERSION,0};
59
60 const struct rank EXACT_MATCH_BADNESS = {0,0};
61
62 const struct rank INTEGER_PROMOTION_BADNESS = {1,0};
63 const struct rank FLOAT_PROMOTION_BADNESS = {1,0};
64 const struct rank BASE_PTR_CONVERSION_BADNESS = {1,0};
65 const struct rank CV_CONVERSION_BADNESS = {1, 0};
66 const struct rank INTEGER_CONVERSION_BADNESS = {2,0};
67 const struct rank FLOAT_CONVERSION_BADNESS = {2,0};
68 const struct rank INT_FLOAT_CONVERSION_BADNESS = {2,0};
69 const struct rank VOID_PTR_CONVERSION_BADNESS = {2,0};
70 const struct rank BOOL_CONVERSION_BADNESS = {3,0};
71 const struct rank BASE_CONVERSION_BADNESS = {2,0};
72 const struct rank REFERENCE_CONVERSION_BADNESS = {2,0};
73 const struct rank REFERENCE_SEE_THROUGH_BADNESS = {0,1};
74 const struct rank NULL_POINTER_CONVERSION_BADNESS = {2,0};
75 const struct rank NS_POINTER_CONVERSION_BADNESS = {10,0};
76 const struct rank NS_INTEGER_POINTER_CONVERSION_BADNESS = {3,0};
77
78 /* Floatformat pairs.  */
79 const struct floatformat *floatformats_ieee_half[BFD_ENDIAN_UNKNOWN] = {
80   &floatformat_ieee_half_big,
81   &floatformat_ieee_half_little
82 };
83 const struct floatformat *floatformats_ieee_single[BFD_ENDIAN_UNKNOWN] = {
84   &floatformat_ieee_single_big,
85   &floatformat_ieee_single_little
86 };
87 const struct floatformat *floatformats_ieee_double[BFD_ENDIAN_UNKNOWN] = {
88   &floatformat_ieee_double_big,
89   &floatformat_ieee_double_little
90 };
91 const struct floatformat *floatformats_ieee_quad[BFD_ENDIAN_UNKNOWN] = {
92   &floatformat_ieee_quad_big,
93   &floatformat_ieee_quad_little
94 };
95 const struct floatformat *floatformats_ieee_double_littlebyte_bigword[BFD_ENDIAN_UNKNOWN] = {
96   &floatformat_ieee_double_big,
97   &floatformat_ieee_double_littlebyte_bigword
98 };
99 const struct floatformat *floatformats_i387_ext[BFD_ENDIAN_UNKNOWN] = {
100   &floatformat_i387_ext,
101   &floatformat_i387_ext
102 };
103 const struct floatformat *floatformats_m68881_ext[BFD_ENDIAN_UNKNOWN] = {
104   &floatformat_m68881_ext,
105   &floatformat_m68881_ext
106 };
107 const struct floatformat *floatformats_arm_ext[BFD_ENDIAN_UNKNOWN] = {
108   &floatformat_arm_ext_big,
109   &floatformat_arm_ext_littlebyte_bigword
110 };
111 const struct floatformat *floatformats_ia64_spill[BFD_ENDIAN_UNKNOWN] = {
112   &floatformat_ia64_spill_big,
113   &floatformat_ia64_spill_little
114 };
115 const struct floatformat *floatformats_vax_f[BFD_ENDIAN_UNKNOWN] = {
116   &floatformat_vax_f,
117   &floatformat_vax_f
118 };
119 const struct floatformat *floatformats_vax_d[BFD_ENDIAN_UNKNOWN] = {
120   &floatformat_vax_d,
121   &floatformat_vax_d
122 };
123 const struct floatformat *floatformats_ibm_long_double[BFD_ENDIAN_UNKNOWN] = {
124   &floatformat_ibm_long_double_big,
125   &floatformat_ibm_long_double_little
126 };
127 const struct floatformat *floatformats_bfloat16[BFD_ENDIAN_UNKNOWN] = {
128   &floatformat_bfloat16_big,
129   &floatformat_bfloat16_little
130 };
131
132 /* Should opaque types be resolved?  */
133
134 static bool opaque_type_resolution = true;
135
136 /* See gdbtypes.h.  */
137
138 unsigned int overload_debug = 0;
139
140 /* A flag to enable strict type checking.  */
141
142 static bool strict_type_checking = true;
143
144 /* A function to show whether opaque types are resolved.  */
145
146 static void
147 show_opaque_type_resolution (struct ui_file *file, int from_tty,
148                              struct cmd_list_element *c, 
149                              const char *value)
150 {
151   gdb_printf (file, _("Resolution of opaque struct/class/union types "
152                       "(if set before loading symbols) is %s.\n"),
153               value);
154 }
155
156 /* A function to show whether C++ overload debugging is enabled.  */
157
158 static void
159 show_overload_debug (struct ui_file *file, int from_tty,
160                      struct cmd_list_element *c, const char *value)
161 {
162   gdb_printf (file, _("Debugging of C++ overloading is %s.\n"), 
163               value);
164 }
165
166 /* A function to show the status of strict type checking.  */
167
168 static void
169 show_strict_type_checking (struct ui_file *file, int from_tty,
170                            struct cmd_list_element *c, const char *value)
171 {
172   gdb_printf (file, _("Strict type checking is %s.\n"), value);
173 }
174
175 \f
176 /* Allocate a new OBJFILE-associated type structure and fill it
177    with some defaults.  Space for the type structure is allocated
178    on the objfile's objfile_obstack.  */
179
180 struct type *
181 alloc_type (struct objfile *objfile)
182 {
183   struct type *type;
184
185   gdb_assert (objfile != NULL);
186
187   /* Alloc the structure and start off with all fields zeroed.  */
188   type = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct type);
189   TYPE_MAIN_TYPE (type) = OBSTACK_ZALLOC (&objfile->objfile_obstack,
190                                           struct main_type);
191   OBJSTAT (objfile, n_types++);
192
193   type->set_owner (objfile);
194
195   /* Initialize the fields that might not be zero.  */
196
197   type->set_code (TYPE_CODE_UNDEF);
198   TYPE_CHAIN (type) = type;     /* Chain back to itself.  */
199
200   return type;
201 }
202
203 /* Allocate a new GDBARCH-associated type structure and fill it
204    with some defaults.  Space for the type structure is allocated
205    on the obstack associated with GDBARCH.  */
206
207 struct type *
208 alloc_type_arch (struct gdbarch *gdbarch)
209 {
210   struct type *type;
211
212   gdb_assert (gdbarch != NULL);
213
214   /* Alloc the structure and start off with all fields zeroed.  */
215
216   type = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct type);
217   TYPE_MAIN_TYPE (type) = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct main_type);
218
219   type->set_owner (gdbarch);
220
221   /* Initialize the fields that might not be zero.  */
222
223   type->set_code (TYPE_CODE_UNDEF);
224   TYPE_CHAIN (type) = type;     /* Chain back to itself.  */
225
226   return type;
227 }
228
229 /* If TYPE is objfile-associated, allocate a new type structure
230    associated with the same objfile.  If TYPE is gdbarch-associated,
231    allocate a new type structure associated with the same gdbarch.  */
232
233 struct type *
234 alloc_type_copy (const struct type *type)
235 {
236   if (type->is_objfile_owned ())
237     return alloc_type (type->objfile_owner ());
238   else
239     return alloc_type_arch (type->arch_owner ());
240 }
241
242 /* See gdbtypes.h.  */
243
244 gdbarch *
245 type::arch () const
246 {
247   struct gdbarch *arch;
248
249   if (this->is_objfile_owned ())
250     arch = this->objfile_owner ()->arch ();
251   else
252     arch = this->arch_owner ();
253
254   /* The ARCH can be NULL if TYPE is associated with neither an objfile nor
255      a gdbarch, however, this is very rare, and even then, in most cases
256      that type::arch is called, we assume that a non-NULL value is
257      returned.  */
258   gdb_assert (arch != nullptr);
259   return arch;
260 }
261
262 /* See gdbtypes.h.  */
263
264 struct type *
265 get_target_type (struct type *type)
266 {
267   if (type != NULL)
268     {
269       type = TYPE_TARGET_TYPE (type);
270       if (type != NULL)
271         type = check_typedef (type);
272     }
273
274   return type;
275 }
276
277 /* See gdbtypes.h.  */
278
279 unsigned int
280 type_length_units (struct type *type)
281 {
282   int unit_size = gdbarch_addressable_memory_unit_size (type->arch ());
283
284   return TYPE_LENGTH (type) / unit_size;
285 }
286
287 /* Alloc a new type instance structure, fill it with some defaults,
288    and point it at OLDTYPE.  Allocate the new type instance from the
289    same place as OLDTYPE.  */
290
291 static struct type *
292 alloc_type_instance (struct type *oldtype)
293 {
294   struct type *type;
295
296   /* Allocate the structure.  */
297
298   if (!oldtype->is_objfile_owned ())
299     type = GDBARCH_OBSTACK_ZALLOC (oldtype->arch_owner (), struct type);
300   else
301     type = OBSTACK_ZALLOC (&oldtype->objfile_owner ()->objfile_obstack,
302                            struct type);
303
304   TYPE_MAIN_TYPE (type) = TYPE_MAIN_TYPE (oldtype);
305
306   TYPE_CHAIN (type) = type;     /* Chain back to itself for now.  */
307
308   return type;
309 }
310
311 /* Clear all remnants of the previous type at TYPE, in preparation for
312    replacing it with something else.  Preserve owner information.  */
313
314 static void
315 smash_type (struct type *type)
316 {
317   bool objfile_owned = type->is_objfile_owned ();
318   objfile *objfile = type->objfile_owner ();
319   gdbarch *arch = type->arch_owner ();
320
321   memset (TYPE_MAIN_TYPE (type), 0, sizeof (struct main_type));
322
323   /* Restore owner information.  */
324   if (objfile_owned)
325     type->set_owner (objfile);
326   else
327     type->set_owner (arch);
328
329   /* For now, delete the rings.  */
330   TYPE_CHAIN (type) = type;
331
332   /* For now, leave the pointer/reference types alone.  */
333 }
334
335 /* Lookup a pointer to a type TYPE.  TYPEPTR, if nonzero, points
336    to a pointer to memory where the pointer type should be stored.
337    If *TYPEPTR is zero, update it to point to the pointer type we return.
338    We allocate new memory if needed.  */
339
340 struct type *
341 make_pointer_type (struct type *type, struct type **typeptr)
342 {
343   struct type *ntype;   /* New type */
344   struct type *chain;
345
346   ntype = TYPE_POINTER_TYPE (type);
347
348   if (ntype)
349     {
350       if (typeptr == 0)
351         return ntype;           /* Don't care about alloc, 
352                                    and have new type.  */
353       else if (*typeptr == 0)
354         {
355           *typeptr = ntype;     /* Tracking alloc, and have new type.  */
356           return ntype;
357         }
358     }
359
360   if (typeptr == 0 || *typeptr == 0)    /* We'll need to allocate one.  */
361     {
362       ntype = alloc_type_copy (type);
363       if (typeptr)
364         *typeptr = ntype;
365     }
366   else                  /* We have storage, but need to reset it.  */
367     {
368       ntype = *typeptr;
369       chain = TYPE_CHAIN (ntype);
370       smash_type (ntype);
371       TYPE_CHAIN (ntype) = chain;
372     }
373
374   ntype->set_target_type (type);
375   TYPE_POINTER_TYPE (type) = ntype;
376
377   /* FIXME!  Assumes the machine has only one representation for pointers!  */
378
379   TYPE_LENGTH (ntype) = gdbarch_ptr_bit (type->arch ()) / TARGET_CHAR_BIT;
380   ntype->set_code (TYPE_CODE_PTR);
381
382   /* Mark pointers as unsigned.  The target converts between pointers
383      and addresses (CORE_ADDRs) using gdbarch_pointer_to_address and
384      gdbarch_address_to_pointer.  */
385   ntype->set_is_unsigned (true);
386
387   /* Update the length of all the other variants of this type.  */
388   chain = TYPE_CHAIN (ntype);
389   while (chain != ntype)
390     {
391       TYPE_LENGTH (chain) = TYPE_LENGTH (ntype);
392       chain = TYPE_CHAIN (chain);
393     }
394
395   return ntype;
396 }
397
398 /* Given a type TYPE, return a type of pointers to that type.
399    May need to construct such a type if this is the first use.  */
400
401 struct type *
402 lookup_pointer_type (struct type *type)
403 {
404   return make_pointer_type (type, (struct type **) 0);
405 }
406
407 /* Lookup a C++ `reference' to a type TYPE.  TYPEPTR, if nonzero,
408    points to a pointer to memory where the reference type should be
409    stored.  If *TYPEPTR is zero, update it to point to the reference
410    type we return.  We allocate new memory if needed. REFCODE denotes
411    the kind of reference type to lookup (lvalue or rvalue reference).  */
412
413 struct type *
414 make_reference_type (struct type *type, struct type **typeptr,
415                       enum type_code refcode)
416 {
417   struct type *ntype;   /* New type */
418   struct type **reftype;
419   struct type *chain;
420
421   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
422
423   ntype = (refcode == TYPE_CODE_REF ? TYPE_REFERENCE_TYPE (type)
424            : TYPE_RVALUE_REFERENCE_TYPE (type));
425
426   if (ntype)
427     {
428       if (typeptr == 0)
429         return ntype;           /* Don't care about alloc, 
430                                    and have new type.  */
431       else if (*typeptr == 0)
432         {
433           *typeptr = ntype;     /* Tracking alloc, and have new type.  */
434           return ntype;
435         }
436     }
437
438   if (typeptr == 0 || *typeptr == 0)    /* We'll need to allocate one.  */
439     {
440       ntype = alloc_type_copy (type);
441       if (typeptr)
442         *typeptr = ntype;
443     }
444   else                  /* We have storage, but need to reset it.  */
445     {
446       ntype = *typeptr;
447       chain = TYPE_CHAIN (ntype);
448       smash_type (ntype);
449       TYPE_CHAIN (ntype) = chain;
450     }
451
452   ntype->set_target_type (type);
453   reftype = (refcode == TYPE_CODE_REF ? &TYPE_REFERENCE_TYPE (type)
454              : &TYPE_RVALUE_REFERENCE_TYPE (type));
455
456   *reftype = ntype;
457
458   /* FIXME!  Assume the machine has only one representation for
459      references, and that it matches the (only) representation for
460      pointers!  */
461
462   TYPE_LENGTH (ntype) = gdbarch_ptr_bit (type->arch ()) / TARGET_CHAR_BIT;
463   ntype->set_code (refcode);
464
465   *reftype = ntype;
466
467   /* Update the length of all the other variants of this type.  */
468   chain = TYPE_CHAIN (ntype);
469   while (chain != ntype)
470     {
471       TYPE_LENGTH (chain) = TYPE_LENGTH (ntype);
472       chain = TYPE_CHAIN (chain);
473     }
474
475   return ntype;
476 }
477
478 /* Same as above, but caller doesn't care about memory allocation
479    details.  */
480
481 struct type *
482 lookup_reference_type (struct type *type, enum type_code refcode)
483 {
484   return make_reference_type (type, (struct type **) 0, refcode);
485 }
486
487 /* Lookup the lvalue reference type for the type TYPE.  */
488
489 struct type *
490 lookup_lvalue_reference_type (struct type *type)
491 {
492   return lookup_reference_type (type, TYPE_CODE_REF);
493 }
494
495 /* Lookup the rvalue reference type for the type TYPE.  */
496
497 struct type *
498 lookup_rvalue_reference_type (struct type *type)
499 {
500   return lookup_reference_type (type, TYPE_CODE_RVALUE_REF);
501 }
502
503 /* Lookup a function type that returns type TYPE.  TYPEPTR, if
504    nonzero, points to a pointer to memory where the function type
505    should be stored.  If *TYPEPTR is zero, update it to point to the
506    function type we return.  We allocate new memory if needed.  */
507
508 struct type *
509 make_function_type (struct type *type, struct type **typeptr)
510 {
511   struct type *ntype;   /* New type */
512
513   if (typeptr == 0 || *typeptr == 0)    /* We'll need to allocate one.  */
514     {
515       ntype = alloc_type_copy (type);
516       if (typeptr)
517         *typeptr = ntype;
518     }
519   else                  /* We have storage, but need to reset it.  */
520     {
521       ntype = *typeptr;
522       smash_type (ntype);
523     }
524
525   ntype->set_target_type (type);
526
527   TYPE_LENGTH (ntype) = 1;
528   ntype->set_code (TYPE_CODE_FUNC);
529
530   INIT_FUNC_SPECIFIC (ntype);
531
532   return ntype;
533 }
534
535 /* Given a type TYPE, return a type of functions that return that type.
536    May need to construct such a type if this is the first use.  */
537
538 struct type *
539 lookup_function_type (struct type *type)
540 {
541   return make_function_type (type, (struct type **) 0);
542 }
543
544 /* Given a type TYPE and argument types, return the appropriate
545    function type.  If the final type in PARAM_TYPES is NULL, make a
546    varargs function.  */
547
548 struct type *
549 lookup_function_type_with_arguments (struct type *type,
550                                      int nparams,
551                                      struct type **param_types)
552 {
553   struct type *fn = make_function_type (type, (struct type **) 0);
554   int i;
555
556   if (nparams > 0)
557     {
558       if (param_types[nparams - 1] == NULL)
559         {
560           --nparams;
561           fn->set_has_varargs (true);
562         }
563       else if (check_typedef (param_types[nparams - 1])->code ()
564                == TYPE_CODE_VOID)
565         {
566           --nparams;
567           /* Caller should have ensured this.  */
568           gdb_assert (nparams == 0);
569           fn->set_is_prototyped (true);
570         }
571       else
572         fn->set_is_prototyped (true);
573     }
574
575   fn->set_num_fields (nparams);
576   fn->set_fields
577     ((struct field *) TYPE_ZALLOC (fn, nparams * sizeof (struct field)));
578   for (i = 0; i < nparams; ++i)
579     fn->field (i).set_type (param_types[i]);
580
581   return fn;
582 }
583
584 /* Identify address space identifier by name -- return a
585    type_instance_flags.  */
586
587 type_instance_flags
588 address_space_name_to_type_instance_flags (struct gdbarch *gdbarch,
589                                            const char *space_identifier)
590 {
591   type_instance_flags type_flags;
592
593   /* Check for known address space delimiters.  */
594   if (!strcmp (space_identifier, "code"))
595     return TYPE_INSTANCE_FLAG_CODE_SPACE;
596   else if (!strcmp (space_identifier, "data"))
597     return TYPE_INSTANCE_FLAG_DATA_SPACE;
598   else if (gdbarch_address_class_name_to_type_flags_p (gdbarch)
599            && gdbarch_address_class_name_to_type_flags (gdbarch,
600                                                         space_identifier,
601                                                         &type_flags))
602     return type_flags;
603   else
604     error (_("Unknown address space specifier: \"%s\""), space_identifier);
605 }
606
607 /* Identify address space identifier by type_instance_flags and return
608    the string version of the adress space name.  */
609
610 const char *
611 address_space_type_instance_flags_to_name (struct gdbarch *gdbarch,
612                                            type_instance_flags space_flag)
613 {
614   if (space_flag & TYPE_INSTANCE_FLAG_CODE_SPACE)
615     return "code";
616   else if (space_flag & TYPE_INSTANCE_FLAG_DATA_SPACE)
617     return "data";
618   else if ((space_flag & TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
619            && gdbarch_address_class_type_flags_to_name_p (gdbarch))
620     return gdbarch_address_class_type_flags_to_name (gdbarch, space_flag);
621   else
622     return NULL;
623 }
624
625 /* Create a new type with instance flags NEW_FLAGS, based on TYPE.
626
627    If STORAGE is non-NULL, create the new type instance there.
628    STORAGE must be in the same obstack as TYPE.  */
629
630 static struct type *
631 make_qualified_type (struct type *type, type_instance_flags new_flags,
632                      struct type *storage)
633 {
634   struct type *ntype;
635
636   ntype = type;
637   do
638     {
639       if (ntype->instance_flags () == new_flags)
640         return ntype;
641       ntype = TYPE_CHAIN (ntype);
642     }
643   while (ntype != type);
644
645   /* Create a new type instance.  */
646   if (storage == NULL)
647     ntype = alloc_type_instance (type);
648   else
649     {
650       /* If STORAGE was provided, it had better be in the same objfile
651          as TYPE.  Otherwise, we can't link it into TYPE's cv chain:
652          if one objfile is freed and the other kept, we'd have
653          dangling pointers.  */
654       gdb_assert (type->objfile_owner () == storage->objfile_owner ());
655
656       ntype = storage;
657       TYPE_MAIN_TYPE (ntype) = TYPE_MAIN_TYPE (type);
658       TYPE_CHAIN (ntype) = ntype;
659     }
660
661   /* Pointers or references to the original type are not relevant to
662      the new type.  */
663   TYPE_POINTER_TYPE (ntype) = (struct type *) 0;
664   TYPE_REFERENCE_TYPE (ntype) = (struct type *) 0;
665
666   /* Chain the new qualified type to the old type.  */
667   TYPE_CHAIN (ntype) = TYPE_CHAIN (type);
668   TYPE_CHAIN (type) = ntype;
669
670   /* Now set the instance flags and return the new type.  */
671   ntype->set_instance_flags (new_flags);
672
673   /* Set length of new type to that of the original type.  */
674   TYPE_LENGTH (ntype) = TYPE_LENGTH (type);
675
676   return ntype;
677 }
678
679 /* Make an address-space-delimited variant of a type -- a type that
680    is identical to the one supplied except that it has an address
681    space attribute attached to it (such as "code" or "data").
682
683    The space attributes "code" and "data" are for Harvard
684    architectures.  The address space attributes are for architectures
685    which have alternately sized pointers or pointers with alternate
686    representations.  */
687
688 struct type *
689 make_type_with_address_space (struct type *type,
690                               type_instance_flags space_flag)
691 {
692   type_instance_flags new_flags = ((type->instance_flags ()
693                                     & ~(TYPE_INSTANCE_FLAG_CODE_SPACE
694                                         | TYPE_INSTANCE_FLAG_DATA_SPACE
695                                         | TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL))
696                                    | space_flag);
697
698   return make_qualified_type (type, new_flags, NULL);
699 }
700
701 /* Make a "c-v" variant of a type -- a type that is identical to the
702    one supplied except that it may have const or volatile attributes
703    CNST is a flag for setting the const attribute
704    VOLTL is a flag for setting the volatile attribute
705    TYPE is the base type whose variant we are creating.
706
707    If TYPEPTR and *TYPEPTR are non-zero, then *TYPEPTR points to
708    storage to hold the new qualified type; *TYPEPTR and TYPE must be
709    in the same objfile.  Otherwise, allocate fresh memory for the new
710    type whereever TYPE lives.  If TYPEPTR is non-zero, set it to the
711    new type we construct.  */
712
713 struct type *
714 make_cv_type (int cnst, int voltl, 
715               struct type *type, 
716               struct type **typeptr)
717 {
718   struct type *ntype;   /* New type */
719
720   type_instance_flags new_flags = (type->instance_flags ()
721                                    & ~(TYPE_INSTANCE_FLAG_CONST
722                                        | TYPE_INSTANCE_FLAG_VOLATILE));
723
724   if (cnst)
725     new_flags |= TYPE_INSTANCE_FLAG_CONST;
726
727   if (voltl)
728     new_flags |= TYPE_INSTANCE_FLAG_VOLATILE;
729
730   if (typeptr && *typeptr != NULL)
731     {
732       /* TYPE and *TYPEPTR must be in the same objfile.  We can't have
733          a C-V variant chain that threads across objfiles: if one
734          objfile gets freed, then the other has a broken C-V chain.
735
736          This code used to try to copy over the main type from TYPE to
737          *TYPEPTR if they were in different objfiles, but that's
738          wrong, too: TYPE may have a field list or member function
739          lists, which refer to types of their own, etc. etc.  The
740          whole shebang would need to be copied over recursively; you
741          can't have inter-objfile pointers.  The only thing to do is
742          to leave stub types as stub types, and look them up afresh by
743          name each time you encounter them.  */
744       gdb_assert ((*typeptr)->objfile_owner () == type->objfile_owner ());
745     }
746   
747   ntype = make_qualified_type (type, new_flags, 
748                                typeptr ? *typeptr : NULL);
749
750   if (typeptr != NULL)
751     *typeptr = ntype;
752
753   return ntype;
754 }
755
756 /* Make a 'restrict'-qualified version of TYPE.  */
757
758 struct type *
759 make_restrict_type (struct type *type)
760 {
761   return make_qualified_type (type,
762                               (type->instance_flags ()
763                                | TYPE_INSTANCE_FLAG_RESTRICT),
764                               NULL);
765 }
766
767 /* Make a type without const, volatile, or restrict.  */
768
769 struct type *
770 make_unqualified_type (struct type *type)
771 {
772   return make_qualified_type (type,
773                               (type->instance_flags ()
774                                & ~(TYPE_INSTANCE_FLAG_CONST
775                                    | TYPE_INSTANCE_FLAG_VOLATILE
776                                    | TYPE_INSTANCE_FLAG_RESTRICT)),
777                               NULL);
778 }
779
780 /* Make a '_Atomic'-qualified version of TYPE.  */
781
782 struct type *
783 make_atomic_type (struct type *type)
784 {
785   return make_qualified_type (type,
786                               (type->instance_flags ()
787                                | TYPE_INSTANCE_FLAG_ATOMIC),
788                               NULL);
789 }
790
791 /* Replace the contents of ntype with the type *type.  This changes the
792    contents, rather than the pointer for TYPE_MAIN_TYPE (ntype); thus
793    the changes are propogated to all types in the TYPE_CHAIN.
794
795    In order to build recursive types, it's inevitable that we'll need
796    to update types in place --- but this sort of indiscriminate
797    smashing is ugly, and needs to be replaced with something more
798    controlled.  TYPE_MAIN_TYPE is a step in this direction; it's not
799    clear if more steps are needed.  */
800
801 void
802 replace_type (struct type *ntype, struct type *type)
803 {
804   struct type *chain;
805
806   /* These two types had better be in the same objfile.  Otherwise,
807      the assignment of one type's main type structure to the other
808      will produce a type with references to objects (names; field
809      lists; etc.) allocated on an objfile other than its own.  */
810   gdb_assert (ntype->objfile_owner () == type->objfile_owner ());
811
812   *TYPE_MAIN_TYPE (ntype) = *TYPE_MAIN_TYPE (type);
813
814   /* The type length is not a part of the main type.  Update it for
815      each type on the variant chain.  */
816   chain = ntype;
817   do
818     {
819       /* Assert that this element of the chain has no address-class bits
820          set in its flags.  Such type variants might have type lengths
821          which are supposed to be different from the non-address-class
822          variants.  This assertion shouldn't ever be triggered because
823          symbol readers which do construct address-class variants don't
824          call replace_type().  */
825       gdb_assert (TYPE_ADDRESS_CLASS_ALL (chain) == 0);
826
827       TYPE_LENGTH (chain) = TYPE_LENGTH (type);
828       chain = TYPE_CHAIN (chain);
829     }
830   while (ntype != chain);
831
832   /* Assert that the two types have equivalent instance qualifiers.
833      This should be true for at least all of our debug readers.  */
834   gdb_assert (ntype->instance_flags () == type->instance_flags ());
835 }
836
837 /* Implement direct support for MEMBER_TYPE in GNU C++.
838    May need to construct such a type if this is the first use.
839    The TYPE is the type of the member.  The DOMAIN is the type
840    of the aggregate that the member belongs to.  */
841
842 struct type *
843 lookup_memberptr_type (struct type *type, struct type *domain)
844 {
845   struct type *mtype;
846
847   mtype = alloc_type_copy (type);
848   smash_to_memberptr_type (mtype, domain, type);
849   return mtype;
850 }
851
852 /* Return a pointer-to-method type, for a method of type TO_TYPE.  */
853
854 struct type *
855 lookup_methodptr_type (struct type *to_type)
856 {
857   struct type *mtype;
858
859   mtype = alloc_type_copy (to_type);
860   smash_to_methodptr_type (mtype, to_type);
861   return mtype;
862 }
863
864 /* Allocate a stub method whose return type is TYPE.  This apparently
865    happens for speed of symbol reading, since parsing out the
866    arguments to the method is cpu-intensive, the way we are doing it.
867    So, we will fill in arguments later.  This always returns a fresh
868    type.  */
869
870 struct type *
871 allocate_stub_method (struct type *type)
872 {
873   struct type *mtype;
874
875   mtype = alloc_type_copy (type);
876   mtype->set_code (TYPE_CODE_METHOD);
877   TYPE_LENGTH (mtype) = 1;
878   mtype->set_is_stub (true);
879   mtype->set_target_type (type);
880   /* TYPE_SELF_TYPE (mtype) = unknown yet */
881   return mtype;
882 }
883
884 /* See gdbtypes.h.  */
885
886 bool
887 operator== (const dynamic_prop &l, const dynamic_prop &r)
888 {
889   if (l.kind () != r.kind ())
890     return false;
891
892   switch (l.kind ())
893     {
894     case PROP_UNDEFINED:
895       return true;
896     case PROP_CONST:
897       return l.const_val () == r.const_val ();
898     case PROP_ADDR_OFFSET:
899     case PROP_LOCEXPR:
900     case PROP_LOCLIST:
901       return l.baton () == r.baton ();
902     case PROP_VARIANT_PARTS:
903       return l.variant_parts () == r.variant_parts ();
904     case PROP_TYPE:
905       return l.original_type () == r.original_type ();
906     }
907
908   gdb_assert_not_reached ("unhandled dynamic_prop kind");
909 }
910
911 /* See gdbtypes.h.  */
912
913 bool
914 operator== (const range_bounds &l, const range_bounds &r)
915 {
916 #define FIELD_EQ(FIELD) (l.FIELD == r.FIELD)
917
918   return (FIELD_EQ (low)
919           && FIELD_EQ (high)
920           && FIELD_EQ (flag_upper_bound_is_count)
921           && FIELD_EQ (flag_bound_evaluated)
922           && FIELD_EQ (bias));
923
924 #undef FIELD_EQ
925 }
926
927 /* Create a range type with a dynamic range from LOW_BOUND to
928    HIGH_BOUND, inclusive.  See create_range_type for further details. */
929
930 struct type *
931 create_range_type (struct type *result_type, struct type *index_type,
932                    const struct dynamic_prop *low_bound,
933                    const struct dynamic_prop *high_bound,
934                    LONGEST bias)
935 {
936   /* The INDEX_TYPE should be a type capable of holding the upper and lower
937      bounds, as such a zero sized, or void type makes no sense.  */
938   gdb_assert (index_type->code () != TYPE_CODE_VOID);
939   gdb_assert (TYPE_LENGTH (index_type) > 0);
940
941   if (result_type == NULL)
942     result_type = alloc_type_copy (index_type);
943   result_type->set_code (TYPE_CODE_RANGE);
944   result_type->set_target_type (index_type);
945   if (index_type->is_stub ())
946     result_type->set_target_is_stub (true);
947   else
948     TYPE_LENGTH (result_type) = TYPE_LENGTH (check_typedef (index_type));
949
950   range_bounds *bounds
951     = (struct range_bounds *) TYPE_ZALLOC (result_type, sizeof (range_bounds));
952   bounds->low = *low_bound;
953   bounds->high = *high_bound;
954   bounds->bias = bias;
955   bounds->stride.set_const_val (0);
956
957   result_type->set_bounds (bounds);
958
959   if (index_type->code () == TYPE_CODE_FIXED_POINT)
960     result_type->set_is_unsigned (index_type->is_unsigned ());
961   /* Note that the signed-ness of a range type can't simply be copied
962      from the underlying type.  Consider a case where the underlying
963      type is 'int', but the range type can hold 0..65535, and where
964      the range is further specified to fit into 16 bits.  In this
965      case, if we copy the underlying type's sign, then reading some
966      range values will cause an unwanted sign extension.  So, we have
967      some heuristics here instead.  */
968   else if (low_bound->kind () == PROP_CONST && low_bound->const_val () >= 0)
969     result_type->set_is_unsigned (true);
970   /* Ada allows the declaration of range types whose upper bound is
971      less than the lower bound, so checking the lower bound is not
972      enough.  Make sure we do not mark a range type whose upper bound
973      is negative as unsigned.  */
974   if (high_bound->kind () == PROP_CONST && high_bound->const_val () < 0)
975     result_type->set_is_unsigned (false);
976
977   result_type->set_endianity_is_not_default
978     (index_type->endianity_is_not_default ());
979
980   return result_type;
981 }
982
983 /* See gdbtypes.h.  */
984
985 struct type *
986 create_range_type_with_stride (struct type *result_type,
987                                struct type *index_type,
988                                const struct dynamic_prop *low_bound,
989                                const struct dynamic_prop *high_bound,
990                                LONGEST bias,
991                                const struct dynamic_prop *stride,
992                                bool byte_stride_p)
993 {
994   result_type = create_range_type (result_type, index_type, low_bound,
995                                    high_bound, bias);
996
997   gdb_assert (stride != nullptr);
998   result_type->bounds ()->stride = *stride;
999   result_type->bounds ()->flag_is_byte_stride = byte_stride_p;
1000
1001   return result_type;
1002 }
1003
1004
1005
1006 /* Create a range type using either a blank type supplied in
1007    RESULT_TYPE, or creating a new type, inheriting the objfile from
1008    INDEX_TYPE.
1009
1010    Indices will be of type INDEX_TYPE, and will range from LOW_BOUND
1011    to HIGH_BOUND, inclusive.
1012
1013    FIXME: Maybe we should check the TYPE_CODE of RESULT_TYPE to make
1014    sure it is TYPE_CODE_UNDEF before we bash it into a range type?  */
1015
1016 struct type *
1017 create_static_range_type (struct type *result_type, struct type *index_type,
1018                           LONGEST low_bound, LONGEST high_bound)
1019 {
1020   struct dynamic_prop low, high;
1021
1022   low.set_const_val (low_bound);
1023   high.set_const_val (high_bound);
1024
1025   result_type = create_range_type (result_type, index_type, &low, &high, 0);
1026
1027   return result_type;
1028 }
1029
1030 /* Predicate tests whether BOUNDS are static.  Returns 1 if all bounds values
1031    are static, otherwise returns 0.  */
1032
1033 static bool
1034 has_static_range (const struct range_bounds *bounds)
1035 {
1036   /* If the range doesn't have a defined stride then its stride field will
1037      be initialized to the constant 0.  */
1038   return (bounds->low.kind () == PROP_CONST
1039           && bounds->high.kind () == PROP_CONST
1040           && bounds->stride.kind () == PROP_CONST);
1041 }
1042
1043 /* See gdbtypes.h.  */
1044
1045 gdb::optional<LONGEST>
1046 get_discrete_low_bound (struct type *type)
1047 {
1048   type = check_typedef (type);
1049   switch (type->code ())
1050     {
1051     case TYPE_CODE_RANGE:
1052       {
1053         /* This function only works for ranges with a constant low bound.  */
1054         if (type->bounds ()->low.kind () != PROP_CONST)
1055           return {};
1056
1057         LONGEST low = type->bounds ()->low.const_val ();
1058
1059         if (TYPE_TARGET_TYPE (type)->code () == TYPE_CODE_ENUM)
1060           {
1061             gdb::optional<LONGEST> low_pos
1062               = discrete_position (TYPE_TARGET_TYPE (type), low);
1063
1064             if (low_pos.has_value ())
1065               low = *low_pos;
1066           }
1067
1068         return low;
1069       }
1070
1071     case TYPE_CODE_ENUM:
1072       {
1073         if (type->num_fields () > 0)
1074           {
1075             /* The enums may not be sorted by value, so search all
1076                entries.  */
1077             LONGEST low = type->field (0).loc_enumval ();
1078
1079             for (int i = 0; i < type->num_fields (); i++)
1080               {
1081                 if (type->field (i).loc_enumval () < low)
1082                   low = type->field (i).loc_enumval ();
1083               }
1084
1085             /* Set unsigned indicator if warranted.  */
1086             if (low >= 0)
1087               type->set_is_unsigned (true);
1088
1089             return low;
1090           }
1091         else
1092           return 0;
1093       }
1094
1095     case TYPE_CODE_BOOL:
1096       return 0;
1097
1098     case TYPE_CODE_INT:
1099       if (TYPE_LENGTH (type) > sizeof (LONGEST))        /* Too big */
1100         return {};
1101
1102       if (!type->is_unsigned ())
1103         return -(1 << (TYPE_LENGTH (type) * TARGET_CHAR_BIT - 1));
1104
1105       /* fall through */
1106     case TYPE_CODE_CHAR:
1107       return 0;
1108
1109     default:
1110       return {};
1111     }
1112 }
1113
1114 /* See gdbtypes.h.  */
1115
1116 gdb::optional<LONGEST>
1117 get_discrete_high_bound (struct type *type)
1118 {
1119   type = check_typedef (type);
1120   switch (type->code ())
1121     {
1122     case TYPE_CODE_RANGE:
1123       {
1124         /* This function only works for ranges with a constant high bound.  */
1125         if (type->bounds ()->high.kind () != PROP_CONST)
1126           return {};
1127
1128         LONGEST high = type->bounds ()->high.const_val ();
1129
1130         if (TYPE_TARGET_TYPE (type)->code () == TYPE_CODE_ENUM)
1131           {
1132             gdb::optional<LONGEST> high_pos
1133               = discrete_position (TYPE_TARGET_TYPE (type), high);
1134
1135             if (high_pos.has_value ())
1136               high = *high_pos;
1137           }
1138
1139         return high;
1140       }
1141
1142     case TYPE_CODE_ENUM:
1143       {
1144         if (type->num_fields () > 0)
1145           {
1146             /* The enums may not be sorted by value, so search all
1147                entries.  */
1148             LONGEST high = type->field (0).loc_enumval ();
1149
1150             for (int i = 0; i < type->num_fields (); i++)
1151               {
1152                 if (type->field (i).loc_enumval () > high)
1153                   high = type->field (i).loc_enumval ();
1154               }
1155
1156             return high;
1157           }
1158         else
1159           return -1;
1160       }
1161
1162     case TYPE_CODE_BOOL:
1163       return 1;
1164
1165     case TYPE_CODE_INT:
1166       if (TYPE_LENGTH (type) > sizeof (LONGEST))        /* Too big */
1167         return {};
1168
1169       if (!type->is_unsigned ())
1170         {
1171           LONGEST low = -(1 << (TYPE_LENGTH (type) * TARGET_CHAR_BIT - 1));
1172           return -low - 1;
1173         }
1174
1175       /* fall through */
1176     case TYPE_CODE_CHAR:
1177       {
1178         /* This round-about calculation is to avoid shifting by
1179            TYPE_LENGTH (type) * TARGET_CHAR_BIT, which will not work
1180            if TYPE_LENGTH (type) == sizeof (LONGEST).  */
1181         LONGEST high = 1 << (TYPE_LENGTH (type) * TARGET_CHAR_BIT - 1);
1182         return (high - 1) | high;
1183       }
1184
1185     default:
1186       return {};
1187     }
1188 }
1189
1190 /* See gdbtypes.h.  */
1191
1192 bool
1193 get_discrete_bounds (struct type *type, LONGEST *lowp, LONGEST *highp)
1194 {
1195   gdb::optional<LONGEST> low = get_discrete_low_bound (type);
1196   if (!low.has_value ())
1197     return false;
1198
1199   gdb::optional<LONGEST> high = get_discrete_high_bound (type);
1200   if (!high.has_value ())
1201     return false;
1202
1203   *lowp = *low;
1204   *highp = *high;
1205
1206   return true;
1207 }
1208
1209 /* See gdbtypes.h  */
1210
1211 bool
1212 get_array_bounds (struct type *type, LONGEST *low_bound, LONGEST *high_bound)
1213 {
1214   struct type *index = type->index_type ();
1215   LONGEST low = 0;
1216   LONGEST high = 0;
1217
1218   if (index == NULL)
1219     return false;
1220
1221   if (!get_discrete_bounds (index, &low, &high))
1222     return false;
1223
1224   if (low_bound)
1225     *low_bound = low;
1226
1227   if (high_bound)
1228     *high_bound = high;
1229
1230   return true;
1231 }
1232
1233 /* Assuming that TYPE is a discrete type and VAL is a valid integer
1234    representation of a value of this type, save the corresponding
1235    position number in POS.
1236
1237    Its differs from VAL only in the case of enumeration types.  In
1238    this case, the position number of the value of the first listed
1239    enumeration literal is zero; the position number of the value of
1240    each subsequent enumeration literal is one more than that of its
1241    predecessor in the list.
1242
1243    Return 1 if the operation was successful.  Return zero otherwise,
1244    in which case the value of POS is unmodified.
1245 */
1246
1247 gdb::optional<LONGEST>
1248 discrete_position (struct type *type, LONGEST val)
1249 {
1250   if (type->code () == TYPE_CODE_RANGE)
1251     type = TYPE_TARGET_TYPE (type);
1252
1253   if (type->code () == TYPE_CODE_ENUM)
1254     {
1255       int i;
1256
1257       for (i = 0; i < type->num_fields (); i += 1)
1258         {
1259           if (val == type->field (i).loc_enumval ())
1260             return i;
1261         }
1262
1263       /* Invalid enumeration value.  */
1264       return {};
1265     }
1266   else
1267     return val;
1268 }
1269
1270 /* If the array TYPE has static bounds calculate and update its
1271    size, then return true.  Otherwise return false and leave TYPE
1272    unchanged.  */
1273
1274 static bool
1275 update_static_array_size (struct type *type)
1276 {
1277   gdb_assert (type->code () == TYPE_CODE_ARRAY);
1278
1279   struct type *range_type = type->index_type ();
1280
1281   if (type->dyn_prop (DYN_PROP_BYTE_STRIDE) == nullptr
1282       && has_static_range (range_type->bounds ())
1283       && (!type_not_associated (type)
1284           && !type_not_allocated (type)))
1285     {
1286       LONGEST low_bound, high_bound;
1287       int stride;
1288       struct type *element_type;
1289
1290       stride = type->bit_stride ();
1291
1292       if (!get_discrete_bounds (range_type, &low_bound, &high_bound))
1293         low_bound = high_bound = 0;
1294
1295       element_type = check_typedef (TYPE_TARGET_TYPE (type));
1296       /* Be careful when setting the array length.  Ada arrays can be
1297          empty arrays with the high_bound being smaller than the low_bound.
1298          In such cases, the array length should be zero.  */
1299       if (high_bound < low_bound)
1300         TYPE_LENGTH (type) = 0;
1301       else if (stride != 0)
1302         {
1303           /* Ensure that the type length is always positive, even in the
1304              case where (for example in Fortran) we have a negative
1305              stride.  It is possible to have a single element array with a
1306              negative stride in Fortran (this doesn't mean anything
1307              special, it's still just a single element array) so do
1308              consider that case when touching this code.  */
1309           LONGEST element_count = std::abs (high_bound - low_bound + 1);
1310           TYPE_LENGTH (type)
1311             = ((std::abs (stride) * element_count) + 7) / 8;
1312         }
1313       else
1314         TYPE_LENGTH (type) =
1315           TYPE_LENGTH (element_type) * (high_bound - low_bound + 1);
1316
1317       /* If this array's element is itself an array with a bit stride,
1318          then we want to update this array's bit stride to reflect the
1319          size of the sub-array.  Otherwise, we'll end up using the
1320          wrong size when trying to find elements of the outer
1321          array.  */
1322       if (element_type->code () == TYPE_CODE_ARRAY
1323           && TYPE_LENGTH (element_type) != 0
1324           && TYPE_FIELD_BITSIZE (element_type, 0) != 0
1325           && get_array_bounds (element_type, &low_bound, &high_bound)
1326           && high_bound >= low_bound)
1327         TYPE_FIELD_BITSIZE (type, 0)
1328           = ((high_bound - low_bound + 1)
1329              * TYPE_FIELD_BITSIZE (element_type, 0));
1330
1331       return true;
1332     }
1333
1334   return false;
1335 }
1336
1337 /* Create an array type using either a blank type supplied in
1338    RESULT_TYPE, or creating a new type, inheriting the objfile from
1339    RANGE_TYPE.
1340
1341    Elements will be of type ELEMENT_TYPE, the indices will be of type
1342    RANGE_TYPE.
1343
1344    BYTE_STRIDE_PROP, when not NULL, provides the array's byte stride.
1345    This byte stride property is added to the resulting array type
1346    as a DYN_PROP_BYTE_STRIDE.  As a consequence, the BYTE_STRIDE_PROP
1347    argument can only be used to create types that are objfile-owned
1348    (see add_dyn_prop), meaning that either this function must be called
1349    with an objfile-owned RESULT_TYPE, or an objfile-owned RANGE_TYPE.
1350
1351    BIT_STRIDE is taken into account only when BYTE_STRIDE_PROP is NULL.
1352    If BIT_STRIDE is not zero, build a packed array type whose element
1353    size is BIT_STRIDE.  Otherwise, ignore this parameter.
1354
1355    FIXME: Maybe we should check the TYPE_CODE of RESULT_TYPE to make
1356    sure it is TYPE_CODE_UNDEF before we bash it into an array
1357    type?  */
1358
1359 struct type *
1360 create_array_type_with_stride (struct type *result_type,
1361                                struct type *element_type,
1362                                struct type *range_type,
1363                                struct dynamic_prop *byte_stride_prop,
1364                                unsigned int bit_stride)
1365 {
1366   if (byte_stride_prop != NULL
1367       && byte_stride_prop->kind () == PROP_CONST)
1368     {
1369       /* The byte stride is actually not dynamic.  Pretend we were
1370          called with bit_stride set instead of byte_stride_prop.
1371          This will give us the same result type, while avoiding
1372          the need to handle this as a special case.  */
1373       bit_stride = byte_stride_prop->const_val () * 8;
1374       byte_stride_prop = NULL;
1375     }
1376
1377   if (result_type == NULL)
1378     result_type = alloc_type_copy (range_type);
1379
1380   result_type->set_code (TYPE_CODE_ARRAY);
1381   result_type->set_target_type (element_type);
1382
1383   result_type->set_num_fields (1);
1384   result_type->set_fields
1385     ((struct field *) TYPE_ZALLOC (result_type, sizeof (struct field)));
1386   result_type->set_index_type (range_type);
1387   if (byte_stride_prop != NULL)
1388     result_type->add_dyn_prop (DYN_PROP_BYTE_STRIDE, *byte_stride_prop);
1389   else if (bit_stride > 0)
1390     TYPE_FIELD_BITSIZE (result_type, 0) = bit_stride;
1391
1392   if (!update_static_array_size (result_type))
1393     {
1394       /* This type is dynamic and its length needs to be computed
1395          on demand.  In the meantime, avoid leaving the TYPE_LENGTH
1396          undefined by setting it to zero.  Although we are not expected
1397          to trust TYPE_LENGTH in this case, setting the size to zero
1398          allows us to avoid allocating objects of random sizes in case
1399          we accidently do.  */
1400       TYPE_LENGTH (result_type) = 0;
1401     }
1402
1403   /* TYPE_TARGET_STUB will take care of zero length arrays.  */
1404   if (TYPE_LENGTH (result_type) == 0)
1405     result_type->set_target_is_stub (true);
1406
1407   return result_type;
1408 }
1409
1410 /* Same as create_array_type_with_stride but with no bit_stride
1411    (BIT_STRIDE = 0), thus building an unpacked array.  */
1412
1413 struct type *
1414 create_array_type (struct type *result_type,
1415                    struct type *element_type,
1416                    struct type *range_type)
1417 {
1418   return create_array_type_with_stride (result_type, element_type,
1419                                         range_type, NULL, 0);
1420 }
1421
1422 struct type *
1423 lookup_array_range_type (struct type *element_type,
1424                          LONGEST low_bound, LONGEST high_bound)
1425 {
1426   struct type *index_type;
1427   struct type *range_type;
1428
1429   if (element_type->is_objfile_owned ())
1430     index_type = objfile_type (element_type->objfile_owner ())->builtin_int;
1431   else
1432     index_type = builtin_type (element_type->arch_owner ())->builtin_int;
1433
1434   range_type = create_static_range_type (NULL, index_type,
1435                                          low_bound, high_bound);
1436
1437   return create_array_type (NULL, element_type, range_type);
1438 }
1439
1440 /* Create a string type using either a blank type supplied in
1441    RESULT_TYPE, or creating a new type.  String types are similar
1442    enough to array of char types that we can use create_array_type to
1443    build the basic type and then bash it into a string type.
1444
1445    For fixed length strings, the range type contains 0 as the lower
1446    bound and the length of the string minus one as the upper bound.
1447
1448    FIXME: Maybe we should check the TYPE_CODE of RESULT_TYPE to make
1449    sure it is TYPE_CODE_UNDEF before we bash it into a string
1450    type?  */
1451
1452 struct type *
1453 create_string_type (struct type *result_type,
1454                     struct type *string_char_type,
1455                     struct type *range_type)
1456 {
1457   result_type = create_array_type (result_type,
1458                                    string_char_type,
1459                                    range_type);
1460   result_type->set_code (TYPE_CODE_STRING);
1461   return result_type;
1462 }
1463
1464 struct type *
1465 lookup_string_range_type (struct type *string_char_type,
1466                           LONGEST low_bound, LONGEST high_bound)
1467 {
1468   struct type *result_type;
1469
1470   result_type = lookup_array_range_type (string_char_type,
1471                                          low_bound, high_bound);
1472   result_type->set_code (TYPE_CODE_STRING);
1473   return result_type;
1474 }
1475
1476 struct type *
1477 create_set_type (struct type *result_type, struct type *domain_type)
1478 {
1479   if (result_type == NULL)
1480     result_type = alloc_type_copy (domain_type);
1481
1482   result_type->set_code (TYPE_CODE_SET);
1483   result_type->set_num_fields (1);
1484   result_type->set_fields
1485     ((struct field *) TYPE_ZALLOC (result_type, sizeof (struct field)));
1486
1487   if (!domain_type->is_stub ())
1488     {
1489       LONGEST low_bound, high_bound, bit_length;
1490
1491       if (!get_discrete_bounds (domain_type, &low_bound, &high_bound))
1492         low_bound = high_bound = 0;
1493
1494       bit_length = high_bound - low_bound + 1;
1495       TYPE_LENGTH (result_type)
1496         = (bit_length + TARGET_CHAR_BIT - 1) / TARGET_CHAR_BIT;
1497       if (low_bound >= 0)
1498         result_type->set_is_unsigned (true);
1499     }
1500   result_type->field (0).set_type (domain_type);
1501
1502   return result_type;
1503 }
1504
1505 /* Convert ARRAY_TYPE to a vector type.  This may modify ARRAY_TYPE
1506    and any array types nested inside it.  */
1507
1508 void
1509 make_vector_type (struct type *array_type)
1510 {
1511   struct type *inner_array, *elt_type;
1512
1513   /* Find the innermost array type, in case the array is
1514      multi-dimensional.  */
1515   inner_array = array_type;
1516   while (TYPE_TARGET_TYPE (inner_array)->code () == TYPE_CODE_ARRAY)
1517     inner_array = TYPE_TARGET_TYPE (inner_array);
1518
1519   elt_type = TYPE_TARGET_TYPE (inner_array);
1520   if (elt_type->code () == TYPE_CODE_INT)
1521     {
1522       type_instance_flags flags
1523         = elt_type->instance_flags () | TYPE_INSTANCE_FLAG_NOTTEXT;
1524       elt_type = make_qualified_type (elt_type, flags, NULL);
1525       inner_array->set_target_type (elt_type);
1526     }
1527
1528   array_type->set_is_vector (true);
1529 }
1530
1531 struct type *
1532 init_vector_type (struct type *elt_type, int n)
1533 {
1534   struct type *array_type;
1535
1536   array_type = lookup_array_range_type (elt_type, 0, n - 1);
1537   make_vector_type (array_type);
1538   return array_type;
1539 }
1540
1541 /* Internal routine called by TYPE_SELF_TYPE to return the type that TYPE
1542    belongs to.  In c++ this is the class of "this", but TYPE_THIS_TYPE is too
1543    confusing.  "self" is a common enough replacement for "this".
1544    TYPE must be one of TYPE_CODE_METHODPTR, TYPE_CODE_MEMBERPTR, or
1545    TYPE_CODE_METHOD.  */
1546
1547 struct type *
1548 internal_type_self_type (struct type *type)
1549 {
1550   switch (type->code ())
1551     {
1552     case TYPE_CODE_METHODPTR:
1553     case TYPE_CODE_MEMBERPTR:
1554       if (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_NONE)
1555         return NULL;
1556       gdb_assert (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_SELF_TYPE);
1557       return TYPE_MAIN_TYPE (type)->type_specific.self_type;
1558     case TYPE_CODE_METHOD:
1559       if (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_NONE)
1560         return NULL;
1561       gdb_assert (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_FUNC);
1562       return TYPE_MAIN_TYPE (type)->type_specific.func_stuff->self_type;
1563     default:
1564       gdb_assert_not_reached ("bad type");
1565     }
1566 }
1567
1568 /* Set the type of the class that TYPE belongs to.
1569    In c++ this is the class of "this".
1570    TYPE must be one of TYPE_CODE_METHODPTR, TYPE_CODE_MEMBERPTR, or
1571    TYPE_CODE_METHOD.  */
1572
1573 void
1574 set_type_self_type (struct type *type, struct type *self_type)
1575 {
1576   switch (type->code ())
1577     {
1578     case TYPE_CODE_METHODPTR:
1579     case TYPE_CODE_MEMBERPTR:
1580       if (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_NONE)
1581         TYPE_SPECIFIC_FIELD (type) = TYPE_SPECIFIC_SELF_TYPE;
1582       gdb_assert (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_SELF_TYPE);
1583       TYPE_MAIN_TYPE (type)->type_specific.self_type = self_type;
1584       break;
1585     case TYPE_CODE_METHOD:
1586       if (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_NONE)
1587         INIT_FUNC_SPECIFIC (type);
1588       gdb_assert (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_FUNC);
1589       TYPE_MAIN_TYPE (type)->type_specific.func_stuff->self_type = self_type;
1590       break;
1591     default:
1592       gdb_assert_not_reached ("bad type");
1593     }
1594 }
1595
1596 /* Smash TYPE to be a type of pointers to members of SELF_TYPE with type
1597    TO_TYPE.  A member pointer is a wierd thing -- it amounts to a
1598    typed offset into a struct, e.g. "an int at offset 8".  A MEMBER
1599    TYPE doesn't include the offset (that's the value of the MEMBER
1600    itself), but does include the structure type into which it points
1601    (for some reason).
1602
1603    When "smashing" the type, we preserve the objfile that the old type
1604    pointed to, since we aren't changing where the type is actually
1605    allocated.  */
1606
1607 void
1608 smash_to_memberptr_type (struct type *type, struct type *self_type,
1609                          struct type *to_type)
1610 {
1611   smash_type (type);
1612   type->set_code (TYPE_CODE_MEMBERPTR);
1613   type->set_target_type (to_type);
1614   set_type_self_type (type, self_type);
1615   /* Assume that a data member pointer is the same size as a normal
1616      pointer.  */
1617   TYPE_LENGTH (type) = gdbarch_ptr_bit (to_type->arch ()) / TARGET_CHAR_BIT;
1618 }
1619
1620 /* Smash TYPE to be a type of pointer to methods type TO_TYPE.
1621
1622    When "smashing" the type, we preserve the objfile that the old type
1623    pointed to, since we aren't changing where the type is actually
1624    allocated.  */
1625
1626 void
1627 smash_to_methodptr_type (struct type *type, struct type *to_type)
1628 {
1629   smash_type (type);
1630   type->set_code (TYPE_CODE_METHODPTR);
1631   type->set_target_type (to_type);
1632   set_type_self_type (type, TYPE_SELF_TYPE (to_type));
1633   TYPE_LENGTH (type) = cplus_method_ptr_size (to_type);
1634 }
1635
1636 /* Smash TYPE to be a type of method of SELF_TYPE with type TO_TYPE.
1637    METHOD just means `function that gets an extra "this" argument'.
1638
1639    When "smashing" the type, we preserve the objfile that the old type
1640    pointed to, since we aren't changing where the type is actually
1641    allocated.  */
1642
1643 void
1644 smash_to_method_type (struct type *type, struct type *self_type,
1645                       struct type *to_type, struct field *args,
1646                       int nargs, int varargs)
1647 {
1648   smash_type (type);
1649   type->set_code (TYPE_CODE_METHOD);
1650   type->set_target_type (to_type);
1651   set_type_self_type (type, self_type);
1652   type->set_fields (args);
1653   type->set_num_fields (nargs);
1654   if (varargs)
1655     type->set_has_varargs (true);
1656   TYPE_LENGTH (type) = 1;       /* In practice, this is never needed.  */
1657 }
1658
1659 /* A wrapper of TYPE_NAME which calls error if the type is anonymous.
1660    Since GCC PR debug/47510 DWARF provides associated information to detect the
1661    anonymous class linkage name from its typedef.
1662
1663    Parameter TYPE should not yet have CHECK_TYPEDEF applied, this function will
1664    apply it itself.  */
1665
1666 const char *
1667 type_name_or_error (struct type *type)
1668 {
1669   struct type *saved_type = type;
1670   const char *name;
1671   struct objfile *objfile;
1672
1673   type = check_typedef (type);
1674
1675   name = type->name ();
1676   if (name != NULL)
1677     return name;
1678
1679   name = saved_type->name ();
1680   objfile = saved_type->objfile_owner ();
1681   error (_("Invalid anonymous type %s [in module %s], GCC PR debug/47510 bug?"),
1682          name ? name : "<anonymous>",
1683          objfile ? objfile_name (objfile) : "<arch>");
1684 }
1685
1686 /* Lookup a typedef or primitive type named NAME, visible in lexical
1687    block BLOCK.  If NOERR is nonzero, return zero if NAME is not
1688    suitably defined.  */
1689
1690 struct type *
1691 lookup_typename (const struct language_defn *language,
1692                  const char *name,
1693                  const struct block *block, int noerr)
1694 {
1695   struct symbol *sym;
1696
1697   sym = lookup_symbol_in_language (name, block, VAR_DOMAIN,
1698                                    language->la_language, NULL).symbol;
1699   if (sym != NULL && sym->aclass () == LOC_TYPEDEF)
1700     return sym->type ();
1701
1702   if (noerr)
1703     return NULL;
1704   error (_("No type named %s."), name);
1705 }
1706
1707 struct type *
1708 lookup_unsigned_typename (const struct language_defn *language,
1709                           const char *name)
1710 {
1711   char *uns = (char *) alloca (strlen (name) + 10);
1712
1713   strcpy (uns, "unsigned ");
1714   strcpy (uns + 9, name);
1715   return lookup_typename (language, uns, NULL, 0);
1716 }
1717
1718 struct type *
1719 lookup_signed_typename (const struct language_defn *language, const char *name)
1720 {
1721   struct type *t;
1722   char *uns = (char *) alloca (strlen (name) + 8);
1723
1724   strcpy (uns, "signed ");
1725   strcpy (uns + 7, name);
1726   t = lookup_typename (language, uns, NULL, 1);
1727   /* If we don't find "signed FOO" just try again with plain "FOO".  */
1728   if (t != NULL)
1729     return t;
1730   return lookup_typename (language, name, NULL, 0);
1731 }
1732
1733 /* Lookup a structure type named "struct NAME",
1734    visible in lexical block BLOCK.  */
1735
1736 struct type *
1737 lookup_struct (const char *name, const struct block *block)
1738 {
1739   struct symbol *sym;
1740
1741   sym = lookup_symbol (name, block, STRUCT_DOMAIN, 0).symbol;
1742
1743   if (sym == NULL)
1744     {
1745       error (_("No struct type named %s."), name);
1746     }
1747   if (sym->type ()->code () != TYPE_CODE_STRUCT)
1748     {
1749       error (_("This context has class, union or enum %s, not a struct."),
1750              name);
1751     }
1752   return (sym->type ());
1753 }
1754
1755 /* Lookup a union type named "union NAME",
1756    visible in lexical block BLOCK.  */
1757
1758 struct type *
1759 lookup_union (const char *name, const struct block *block)
1760 {
1761   struct symbol *sym;
1762   struct type *t;
1763
1764   sym = lookup_symbol (name, block, STRUCT_DOMAIN, 0).symbol;
1765
1766   if (sym == NULL)
1767     error (_("No union type named %s."), name);
1768
1769   t = sym->type ();
1770
1771   if (t->code () == TYPE_CODE_UNION)
1772     return t;
1773
1774   /* If we get here, it's not a union.  */
1775   error (_("This context has class, struct or enum %s, not a union."), 
1776          name);
1777 }
1778
1779 /* Lookup an enum type named "enum NAME",
1780    visible in lexical block BLOCK.  */
1781
1782 struct type *
1783 lookup_enum (const char *name, const struct block *block)
1784 {
1785   struct symbol *sym;
1786
1787   sym = lookup_symbol (name, block, STRUCT_DOMAIN, 0).symbol;
1788   if (sym == NULL)
1789     {
1790       error (_("No enum type named %s."), name);
1791     }
1792   if (sym->type ()->code () != TYPE_CODE_ENUM)
1793     {
1794       error (_("This context has class, struct or union %s, not an enum."), 
1795              name);
1796     }
1797   return (sym->type ());
1798 }
1799
1800 /* Lookup a template type named "template NAME<TYPE>",
1801    visible in lexical block BLOCK.  */
1802
1803 struct type *
1804 lookup_template_type (const char *name, struct type *type, 
1805                       const struct block *block)
1806 {
1807   struct symbol *sym;
1808   char *nam = (char *) 
1809     alloca (strlen (name) + strlen (type->name ()) + 4);
1810
1811   strcpy (nam, name);
1812   strcat (nam, "<");
1813   strcat (nam, type->name ());
1814   strcat (nam, " >");   /* FIXME, extra space still introduced in gcc?  */
1815
1816   sym = lookup_symbol (nam, block, VAR_DOMAIN, 0).symbol;
1817
1818   if (sym == NULL)
1819     {
1820       error (_("No template type named %s."), name);
1821     }
1822   if (sym->type ()->code () != TYPE_CODE_STRUCT)
1823     {
1824       error (_("This context has class, union or enum %s, not a struct."),
1825              name);
1826     }
1827   return (sym->type ());
1828 }
1829
1830 /* See gdbtypes.h.  */
1831
1832 struct_elt
1833 lookup_struct_elt (struct type *type, const char *name, int noerr)
1834 {
1835   int i;
1836
1837   for (;;)
1838     {
1839       type = check_typedef (type);
1840       if (type->code () != TYPE_CODE_PTR
1841           && type->code () != TYPE_CODE_REF)
1842         break;
1843       type = TYPE_TARGET_TYPE (type);
1844     }
1845
1846   if (type->code () != TYPE_CODE_STRUCT
1847       && type->code () != TYPE_CODE_UNION)
1848     {
1849       std::string type_name = type_to_string (type);
1850       error (_("Type %s is not a structure or union type."),
1851              type_name.c_str ());
1852     }
1853
1854   for (i = type->num_fields () - 1; i >= TYPE_N_BASECLASSES (type); i--)
1855     {
1856       const char *t_field_name = type->field (i).name ();
1857
1858       if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
1859         {
1860           return {&type->field (i), type->field (i).loc_bitpos ()};
1861         }
1862       else if (!t_field_name || *t_field_name == '\0')
1863         {
1864           struct_elt elt
1865             = lookup_struct_elt (type->field (i).type (), name, 1);
1866           if (elt.field != NULL)
1867             {
1868               elt.offset += type->field (i).loc_bitpos ();
1869               return elt;
1870             }
1871         }
1872     }
1873
1874   /* OK, it's not in this class.  Recursively check the baseclasses.  */
1875   for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
1876     {
1877       struct_elt elt = lookup_struct_elt (TYPE_BASECLASS (type, i), name, 1);
1878       if (elt.field != NULL)
1879         return elt;
1880     }
1881
1882   if (noerr)
1883     return {nullptr, 0};
1884
1885   std::string type_name = type_to_string (type);
1886   error (_("Type %s has no component named %s."), type_name.c_str (), name);
1887 }
1888
1889 /* See gdbtypes.h.  */
1890
1891 struct type *
1892 lookup_struct_elt_type (struct type *type, const char *name, int noerr)
1893 {
1894   struct_elt elt = lookup_struct_elt (type, name, noerr);
1895   if (elt.field != NULL)
1896     return elt.field->type ();
1897   else
1898     return NULL;
1899 }
1900
1901 /* Return the largest number representable by unsigned integer type TYPE.  */
1902
1903 ULONGEST
1904 get_unsigned_type_max (struct type *type)
1905 {
1906   unsigned int n;
1907
1908   type = check_typedef (type);
1909   gdb_assert (type->code () == TYPE_CODE_INT && type->is_unsigned ());
1910   gdb_assert (TYPE_LENGTH (type) <= sizeof (ULONGEST));
1911
1912   /* Written this way to avoid overflow.  */
1913   n = TYPE_LENGTH (type) * TARGET_CHAR_BIT;
1914   return ((((ULONGEST) 1 << (n - 1)) - 1) << 1) | 1;
1915 }
1916
1917 /* Store in *MIN, *MAX the smallest and largest numbers representable by
1918    signed integer type TYPE.  */
1919
1920 void
1921 get_signed_type_minmax (struct type *type, LONGEST *min, LONGEST *max)
1922 {
1923   unsigned int n;
1924
1925   type = check_typedef (type);
1926   gdb_assert (type->code () == TYPE_CODE_INT && !type->is_unsigned ());
1927   gdb_assert (TYPE_LENGTH (type) <= sizeof (LONGEST));
1928
1929   n = TYPE_LENGTH (type) * TARGET_CHAR_BIT;
1930   *min = -((ULONGEST) 1 << (n - 1));
1931   *max = ((ULONGEST) 1 << (n - 1)) - 1;
1932 }
1933
1934 /* Return the largest value representable by pointer type TYPE. */
1935
1936 CORE_ADDR
1937 get_pointer_type_max (struct type *type)
1938 {
1939   unsigned int n;
1940
1941   type = check_typedef (type);
1942   gdb_assert (type->code () == TYPE_CODE_PTR);
1943   gdb_assert (TYPE_LENGTH (type) <= sizeof (CORE_ADDR));
1944
1945   n = TYPE_LENGTH (type) * TARGET_CHAR_BIT;
1946   return ((((CORE_ADDR) 1 << (n - 1)) - 1) << 1) | 1;
1947 }
1948
1949 /* Internal routine called by TYPE_VPTR_FIELDNO to return the value of
1950    cplus_stuff.vptr_fieldno.
1951
1952    cplus_stuff is initialized to cplus_struct_default which does not
1953    set vptr_fieldno to -1 for portability reasons (IWBN to use C99
1954    designated initializers).  We cope with that here.  */
1955
1956 int
1957 internal_type_vptr_fieldno (struct type *type)
1958 {
1959   type = check_typedef (type);
1960   gdb_assert (type->code () == TYPE_CODE_STRUCT
1961               || type->code () == TYPE_CODE_UNION);
1962   if (!HAVE_CPLUS_STRUCT (type))
1963     return -1;
1964   return TYPE_RAW_CPLUS_SPECIFIC (type)->vptr_fieldno;
1965 }
1966
1967 /* Set the value of cplus_stuff.vptr_fieldno.  */
1968
1969 void
1970 set_type_vptr_fieldno (struct type *type, int fieldno)
1971 {
1972   type = check_typedef (type);
1973   gdb_assert (type->code () == TYPE_CODE_STRUCT
1974               || type->code () == TYPE_CODE_UNION);
1975   if (!HAVE_CPLUS_STRUCT (type))
1976     ALLOCATE_CPLUS_STRUCT_TYPE (type);
1977   TYPE_RAW_CPLUS_SPECIFIC (type)->vptr_fieldno = fieldno;
1978 }
1979
1980 /* Internal routine called by TYPE_VPTR_BASETYPE to return the value of
1981    cplus_stuff.vptr_basetype.  */
1982
1983 struct type *
1984 internal_type_vptr_basetype (struct type *type)
1985 {
1986   type = check_typedef (type);
1987   gdb_assert (type->code () == TYPE_CODE_STRUCT
1988               || type->code () == TYPE_CODE_UNION);
1989   gdb_assert (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_CPLUS_STUFF);
1990   return TYPE_RAW_CPLUS_SPECIFIC (type)->vptr_basetype;
1991 }
1992
1993 /* Set the value of cplus_stuff.vptr_basetype.  */
1994
1995 void
1996 set_type_vptr_basetype (struct type *type, struct type *basetype)
1997 {
1998   type = check_typedef (type);
1999   gdb_assert (type->code () == TYPE_CODE_STRUCT
2000               || type->code () == TYPE_CODE_UNION);
2001   if (!HAVE_CPLUS_STRUCT (type))
2002     ALLOCATE_CPLUS_STRUCT_TYPE (type);
2003   TYPE_RAW_CPLUS_SPECIFIC (type)->vptr_basetype = basetype;
2004 }
2005
2006 /* Lookup the vptr basetype/fieldno values for TYPE.
2007    If found store vptr_basetype in *BASETYPEP if non-NULL, and return
2008    vptr_fieldno.  Also, if found and basetype is from the same objfile,
2009    cache the results.
2010    If not found, return -1 and ignore BASETYPEP.
2011    Callers should be aware that in some cases (for example,
2012    the type or one of its baseclasses is a stub type and we are
2013    debugging a .o file, or the compiler uses DWARF-2 and is not GCC),
2014    this function will not be able to find the
2015    virtual function table pointer, and vptr_fieldno will remain -1 and
2016    vptr_basetype will remain NULL or incomplete.  */
2017
2018 int
2019 get_vptr_fieldno (struct type *type, struct type **basetypep)
2020 {
2021   type = check_typedef (type);
2022
2023   if (TYPE_VPTR_FIELDNO (type) < 0)
2024     {
2025       int i;
2026
2027       /* We must start at zero in case the first (and only) baseclass
2028          is virtual (and hence we cannot share the table pointer).  */
2029       for (i = 0; i < TYPE_N_BASECLASSES (type); i++)
2030         {
2031           struct type *baseclass = check_typedef (TYPE_BASECLASS (type, i));
2032           int fieldno;
2033           struct type *basetype;
2034
2035           fieldno = get_vptr_fieldno (baseclass, &basetype);
2036           if (fieldno >= 0)
2037             {
2038               /* If the type comes from a different objfile we can't cache
2039                  it, it may have a different lifetime.  PR 2384 */
2040               if (type->objfile_owner () == basetype->objfile_owner ())
2041                 {
2042                   set_type_vptr_fieldno (type, fieldno);
2043                   set_type_vptr_basetype (type, basetype);
2044                 }
2045               if (basetypep)
2046                 *basetypep = basetype;
2047               return fieldno;
2048             }
2049         }
2050
2051       /* Not found.  */
2052       return -1;
2053     }
2054   else
2055     {
2056       if (basetypep)
2057         *basetypep = TYPE_VPTR_BASETYPE (type);
2058       return TYPE_VPTR_FIELDNO (type);
2059     }
2060 }
2061
2062 static void
2063 stub_noname_complaint (void)
2064 {
2065   complaint (_("stub type has NULL name"));
2066 }
2067
2068 /* Return nonzero if TYPE has a DYN_PROP_BYTE_STRIDE dynamic property
2069    attached to it, and that property has a non-constant value.  */
2070
2071 static int
2072 array_type_has_dynamic_stride (struct type *type)
2073 {
2074   struct dynamic_prop *prop = type->dyn_prop (DYN_PROP_BYTE_STRIDE);
2075
2076   return (prop != NULL && prop->kind () != PROP_CONST);
2077 }
2078
2079 /* Worker for is_dynamic_type.  */
2080
2081 static int
2082 is_dynamic_type_internal (struct type *type, int top_level)
2083 {
2084   type = check_typedef (type);
2085
2086   /* We only want to recognize references at the outermost level.  */
2087   if (top_level && type->code () == TYPE_CODE_REF)
2088     type = check_typedef (TYPE_TARGET_TYPE (type));
2089
2090   /* Types that have a dynamic TYPE_DATA_LOCATION are considered
2091      dynamic, even if the type itself is statically defined.
2092      From a user's point of view, this may appear counter-intuitive;
2093      but it makes sense in this context, because the point is to determine
2094      whether any part of the type needs to be resolved before it can
2095      be exploited.  */
2096   if (TYPE_DATA_LOCATION (type) != NULL
2097       && (TYPE_DATA_LOCATION_KIND (type) == PROP_LOCEXPR
2098           || TYPE_DATA_LOCATION_KIND (type) == PROP_LOCLIST))
2099     return 1;
2100
2101   if (TYPE_ASSOCIATED_PROP (type))
2102     return 1;
2103
2104   if (TYPE_ALLOCATED_PROP (type))
2105     return 1;
2106
2107   struct dynamic_prop *prop = type->dyn_prop (DYN_PROP_VARIANT_PARTS);
2108   if (prop != nullptr && prop->kind () != PROP_TYPE)
2109     return 1;
2110
2111   if (TYPE_HAS_DYNAMIC_LENGTH (type))
2112     return 1;
2113
2114   switch (type->code ())
2115     {
2116     case TYPE_CODE_RANGE:
2117       {
2118         /* A range type is obviously dynamic if it has at least one
2119            dynamic bound.  But also consider the range type to be
2120            dynamic when its subtype is dynamic, even if the bounds
2121            of the range type are static.  It allows us to assume that
2122            the subtype of a static range type is also static.  */
2123         return (!has_static_range (type->bounds ())
2124                 || is_dynamic_type_internal (TYPE_TARGET_TYPE (type), 0));
2125       }
2126
2127     case TYPE_CODE_STRING:
2128       /* Strings are very much like an array of characters, and can be
2129          treated as one here.  */
2130     case TYPE_CODE_ARRAY:
2131       {
2132         gdb_assert (type->num_fields () == 1);
2133
2134         /* The array is dynamic if either the bounds are dynamic...  */
2135         if (is_dynamic_type_internal (type->index_type (), 0))
2136           return 1;
2137         /* ... or the elements it contains have a dynamic contents...  */
2138         if (is_dynamic_type_internal (TYPE_TARGET_TYPE (type), 0))
2139           return 1;
2140         /* ... or if it has a dynamic stride...  */
2141         if (array_type_has_dynamic_stride (type))
2142           return 1;
2143         return 0;
2144       }
2145
2146     case TYPE_CODE_STRUCT:
2147     case TYPE_CODE_UNION:
2148       {
2149         int i;
2150
2151         bool is_cplus = HAVE_CPLUS_STRUCT (type);
2152
2153         for (i = 0; i < type->num_fields (); ++i)
2154           {
2155             /* Static fields can be ignored here.  */
2156             if (field_is_static (&type->field (i)))
2157               continue;
2158             /* If the field has dynamic type, then so does TYPE.  */
2159             if (is_dynamic_type_internal (type->field (i).type (), 0))
2160               return 1;
2161             /* If the field is at a fixed offset, then it is not
2162                dynamic.  */
2163             if (type->field (i).loc_kind () != FIELD_LOC_KIND_DWARF_BLOCK)
2164               continue;
2165             /* Do not consider C++ virtual base types to be dynamic
2166                due to the field's offset being dynamic; these are
2167                handled via other means.  */
2168             if (is_cplus && BASETYPE_VIA_VIRTUAL (type, i))
2169               continue;
2170             return 1;
2171           }
2172       }
2173       break;
2174     }
2175
2176   return 0;
2177 }
2178
2179 /* See gdbtypes.h.  */
2180
2181 int
2182 is_dynamic_type (struct type *type)
2183 {
2184   return is_dynamic_type_internal (type, 1);
2185 }
2186
2187 static struct type *resolve_dynamic_type_internal
2188   (struct type *type, struct property_addr_info *addr_stack, int top_level);
2189
2190 /* Given a dynamic range type (dyn_range_type) and a stack of
2191    struct property_addr_info elements, return a static version
2192    of that type.
2193
2194    When RESOLVE_P is true then the returned static range is created by
2195    actually evaluating any dynamic properties within the range type, while
2196    when RESOLVE_P is false the returned static range has all of the bounds
2197    and stride information set to undefined.  The RESOLVE_P set to false
2198    case will be used when evaluating a dynamic array that is not
2199    allocated, or not associated, i.e. the bounds information might not be
2200    initialized yet.
2201
2202    RANK is the array rank for which we are resolving this range, and is a
2203    zero based count.  The rank should never be negative.
2204 */
2205
2206 static struct type *
2207 resolve_dynamic_range (struct type *dyn_range_type,
2208                        struct property_addr_info *addr_stack,
2209                        int rank, bool resolve_p = true)
2210 {
2211   CORE_ADDR value;
2212   struct type *static_range_type, *static_target_type;
2213   struct dynamic_prop low_bound, high_bound, stride;
2214
2215   gdb_assert (dyn_range_type->code () == TYPE_CODE_RANGE);
2216   gdb_assert (rank >= 0);
2217
2218   const struct dynamic_prop *prop = &dyn_range_type->bounds ()->low;
2219   if (resolve_p && dwarf2_evaluate_property (prop, NULL, addr_stack, &value,
2220                                              { (CORE_ADDR) rank }))
2221     low_bound.set_const_val (value);
2222   else
2223     low_bound.set_undefined ();
2224
2225   prop = &dyn_range_type->bounds ()->high;
2226   if (resolve_p && dwarf2_evaluate_property (prop, NULL, addr_stack, &value,
2227                                              { (CORE_ADDR) rank }))
2228     {
2229       high_bound.set_const_val (value);
2230
2231       if (dyn_range_type->bounds ()->flag_upper_bound_is_count)
2232         high_bound.set_const_val
2233           (low_bound.const_val () + high_bound.const_val () - 1);
2234     }
2235   else
2236     high_bound.set_undefined ();
2237
2238   bool byte_stride_p = dyn_range_type->bounds ()->flag_is_byte_stride;
2239   prop = &dyn_range_type->bounds ()->stride;
2240   if (resolve_p && dwarf2_evaluate_property (prop, NULL, addr_stack, &value,
2241                                              { (CORE_ADDR) rank }))
2242     {
2243       stride.set_const_val (value);
2244
2245       /* If we have a bit stride that is not an exact number of bytes then
2246          I really don't think this is going to work with current GDB, the
2247          array indexing code in GDB seems to be pretty heavily tied to byte
2248          offsets right now.  Assuming 8 bits in a byte.  */
2249       struct gdbarch *gdbarch = dyn_range_type->arch ();
2250       int unit_size = gdbarch_addressable_memory_unit_size (gdbarch);
2251       if (!byte_stride_p && (value % (unit_size * 8)) != 0)
2252         error (_("bit strides that are not a multiple of the byte size "
2253                  "are currently not supported"));
2254     }
2255   else
2256     {
2257       stride.set_undefined ();
2258       byte_stride_p = true;
2259     }
2260
2261   static_target_type
2262     = resolve_dynamic_type_internal (TYPE_TARGET_TYPE (dyn_range_type),
2263                                      addr_stack, 0);
2264   LONGEST bias = dyn_range_type->bounds ()->bias;
2265   static_range_type = create_range_type_with_stride
2266     (copy_type (dyn_range_type), static_target_type,
2267      &low_bound, &high_bound, bias, &stride, byte_stride_p);
2268   static_range_type->bounds ()->flag_bound_evaluated = 1;
2269   return static_range_type;
2270 }
2271
2272 /* Helper function for resolve_dynamic_array_or_string.  This function
2273    resolves the properties for a single array at RANK within a nested array
2274    of arrays structure.  The RANK value is greater than or equal to 0, and
2275    starts at it's maximum value and goes down by 1 for each recursive call
2276    to this function.  So, for a 3-dimensional array, the first call to this
2277    function has RANK == 2, then we call ourselves recursively with RANK ==
2278    1, than again with RANK == 0, and at that point we should return.
2279
2280    TYPE is updated as the dynamic properties are resolved, and so, should
2281    be a copy of the dynamic type, rather than the original dynamic type
2282    itself.
2283
2284    ADDR_STACK is a stack of struct property_addr_info to be used if needed
2285    during the dynamic resolution.
2286
2287    When RESOLVE_P is true then the dynamic properties of TYPE are
2288    evaluated, otherwise the dynamic properties of TYPE are not evaluated,
2289    instead we assume the array is not allocated/associated yet.  */
2290
2291 static struct type *
2292 resolve_dynamic_array_or_string_1 (struct type *type,
2293                                    struct property_addr_info *addr_stack,
2294                                    int rank, bool resolve_p)
2295 {
2296   CORE_ADDR value;
2297   struct type *elt_type;
2298   struct type *range_type;
2299   struct type *ary_dim;
2300   struct dynamic_prop *prop;
2301   unsigned int bit_stride = 0;
2302
2303   /* For dynamic type resolution strings can be treated like arrays of
2304      characters.  */
2305   gdb_assert (type->code () == TYPE_CODE_ARRAY
2306               || type->code () == TYPE_CODE_STRING);
2307
2308   /* As the rank is a zero based count we expect this to never be
2309      negative.  */
2310   gdb_assert (rank >= 0);
2311
2312   /* Resolve the allocated and associated properties before doing anything
2313      else.  If an array is not allocated or not associated then (at least
2314      for Fortran) there is no guarantee that the data to define the upper
2315      bound, lower bound, or stride will be correct.  If RESOLVE_P is
2316      already false at this point then this is not the first dimension of
2317      the array and a more outer dimension has already marked this array as
2318      not allocated/associated, as such we just ignore this property.  This
2319      is fine as GDB only checks the allocated/associated on the outer most
2320      dimension of the array.  */
2321   prop = TYPE_ALLOCATED_PROP (type);
2322   if (prop != NULL && resolve_p
2323       && dwarf2_evaluate_property (prop, NULL, addr_stack, &value))
2324     {
2325       prop->set_const_val (value);
2326       if (value == 0)
2327         resolve_p = false;
2328     }
2329
2330   prop = TYPE_ASSOCIATED_PROP (type);
2331   if (prop != NULL && resolve_p
2332       && dwarf2_evaluate_property (prop, NULL, addr_stack, &value))
2333     {
2334       prop->set_const_val (value);
2335       if (value == 0)
2336         resolve_p = false;
2337     }
2338
2339   range_type = check_typedef (type->index_type ());
2340   range_type
2341     = resolve_dynamic_range (range_type, addr_stack, rank, resolve_p);
2342
2343   ary_dim = check_typedef (TYPE_TARGET_TYPE (type));
2344   if (ary_dim != NULL && ary_dim->code () == TYPE_CODE_ARRAY)
2345     {
2346       ary_dim = copy_type (ary_dim);
2347       elt_type = resolve_dynamic_array_or_string_1 (ary_dim, addr_stack,
2348                                                     rank - 1, resolve_p);
2349     }
2350   else
2351     elt_type = TYPE_TARGET_TYPE (type);
2352
2353   prop = type->dyn_prop (DYN_PROP_BYTE_STRIDE);
2354   if (prop != NULL && resolve_p)
2355     {
2356       if (dwarf2_evaluate_property (prop, NULL, addr_stack, &value))
2357         {
2358           type->remove_dyn_prop (DYN_PROP_BYTE_STRIDE);
2359           bit_stride = (unsigned int) (value * 8);
2360         }
2361       else
2362         {
2363           /* Could be a bug in our code, but it could also happen
2364              if the DWARF info is not correct.  Issue a warning,
2365              and assume no byte/bit stride (leave bit_stride = 0).  */
2366           warning (_("cannot determine array stride for type %s"),
2367                    type->name () ? type->name () : "<no name>");
2368         }
2369     }
2370   else
2371     bit_stride = TYPE_FIELD_BITSIZE (type, 0);
2372
2373   return create_array_type_with_stride (type, elt_type, range_type, NULL,
2374                                         bit_stride);
2375 }
2376
2377 /* Resolve an array or string type with dynamic properties, return a new
2378    type with the dynamic properties resolved to actual values.  The
2379    ADDR_STACK represents the location of the object being resolved.  */
2380
2381 static struct type *
2382 resolve_dynamic_array_or_string (struct type *type,
2383                                  struct property_addr_info *addr_stack)
2384 {
2385   CORE_ADDR value;
2386   int rank = 0;
2387
2388   /* For dynamic type resolution strings can be treated like arrays of
2389      characters.  */
2390   gdb_assert (type->code () == TYPE_CODE_ARRAY
2391               || type->code () == TYPE_CODE_STRING);
2392
2393   type = copy_type (type);
2394
2395   /* Resolve the rank property to get rank value.  */
2396   struct dynamic_prop *prop = TYPE_RANK_PROP (type);
2397   if (dwarf2_evaluate_property (prop, nullptr, addr_stack, &value))
2398     {
2399       prop->set_const_val (value);
2400       rank = value;
2401
2402       if (rank == 0)
2403         {
2404           /* Rank is zero, if a variable is passed as an argument to a
2405              function.  In this case the resolved type should not be an
2406              array, but should instead be that of an array element.  */
2407           struct type *dynamic_array_type = type;
2408           type = copy_type (TYPE_TARGET_TYPE (dynamic_array_type));
2409           struct dynamic_prop_list *prop_list
2410             = TYPE_MAIN_TYPE (dynamic_array_type)->dyn_prop_list;
2411           if (prop_list != nullptr)
2412             {
2413               struct obstack *obstack
2414                 = &type->objfile_owner ()->objfile_obstack;
2415               TYPE_MAIN_TYPE (type)->dyn_prop_list
2416                 = copy_dynamic_prop_list (obstack, prop_list);
2417             }
2418           return type;
2419         }
2420       else if (type->code () == TYPE_CODE_STRING && rank != 1)
2421         {
2422           /* What would this even mean?  A string with a dynamic rank
2423              greater than 1.  */
2424           error (_("unable to handle string with dynamic rank greater than 1"));
2425         }
2426       else if (rank > 1)
2427         {
2428           /* Arrays with dynamic rank are initially just an array type
2429              with a target type that is the array element.
2430
2431              However, now we know the rank of the array we need to build
2432              the array of arrays structure that GDB expects, that is we
2433              need an array type that has a target which is an array type,
2434              and so on, until eventually, we have the element type at the
2435              end of the chain.  Create all the additional array types here
2436              by copying the top level array type.  */
2437           struct type *element_type = TYPE_TARGET_TYPE (type);
2438           struct type *rank_type = type;
2439           for (int i = 1; i < rank; i++)
2440             {
2441               rank_type->set_target_type (copy_type (rank_type));
2442               rank_type = TYPE_TARGET_TYPE (rank_type);
2443             }
2444           rank_type->set_target_type (element_type);
2445         }
2446     }
2447   else
2448     {
2449       rank = 1;
2450
2451       for (struct type *tmp_type = check_typedef (TYPE_TARGET_TYPE (type));
2452            tmp_type->code () == TYPE_CODE_ARRAY;
2453            tmp_type = check_typedef (TYPE_TARGET_TYPE (tmp_type)))
2454         ++rank;
2455     }
2456
2457   /* The rank that we calculated above is actually a count of the number of
2458      ranks.  However, when we resolve the type of each individual array
2459      rank we should actually use a rank "offset", e.g. an array with a rank
2460      count of 1 (calculated above) will use the rank offset 0 in order to
2461      resolve the details of the first array dimension.  As a result, we
2462      reduce the rank by 1 here.  */
2463   --rank;
2464
2465   return resolve_dynamic_array_or_string_1 (type, addr_stack, rank, true);
2466 }
2467
2468 /* Resolve dynamic bounds of members of the union TYPE to static
2469    bounds.  ADDR_STACK is a stack of struct property_addr_info
2470    to be used if needed during the dynamic resolution.  */
2471
2472 static struct type *
2473 resolve_dynamic_union (struct type *type,
2474                        struct property_addr_info *addr_stack)
2475 {
2476   struct type *resolved_type;
2477   int i;
2478   unsigned int max_len = 0;
2479
2480   gdb_assert (type->code () == TYPE_CODE_UNION);
2481
2482   resolved_type = copy_type (type);
2483   resolved_type->set_fields
2484     ((struct field *)
2485      TYPE_ALLOC (resolved_type,
2486                  resolved_type->num_fields () * sizeof (struct field)));
2487   memcpy (resolved_type->fields (),
2488           type->fields (),
2489           resolved_type->num_fields () * sizeof (struct field));
2490   for (i = 0; i < resolved_type->num_fields (); ++i)
2491     {
2492       struct type *t;
2493
2494       if (field_is_static (&type->field (i)))
2495         continue;
2496
2497       t = resolve_dynamic_type_internal (resolved_type->field (i).type (),
2498                                          addr_stack, 0);
2499       resolved_type->field (i).set_type (t);
2500
2501       struct type *real_type = check_typedef (t);
2502       if (TYPE_LENGTH (real_type) > max_len)
2503         max_len = TYPE_LENGTH (real_type);
2504     }
2505
2506   TYPE_LENGTH (resolved_type) = max_len;
2507   return resolved_type;
2508 }
2509
2510 /* See gdbtypes.h.  */
2511
2512 bool
2513 variant::matches (ULONGEST value, bool is_unsigned) const
2514 {
2515   for (const discriminant_range &range : discriminants)
2516     if (range.contains (value, is_unsigned))
2517       return true;
2518   return false;
2519 }
2520
2521 static void
2522 compute_variant_fields_inner (struct type *type,
2523                               struct property_addr_info *addr_stack,
2524                               const variant_part &part,
2525                               std::vector<bool> &flags);
2526
2527 /* A helper function to determine which variant fields will be active.
2528    This handles both the variant's direct fields, and any variant
2529    parts embedded in this variant.  TYPE is the type we're examining.
2530    ADDR_STACK holds information about the concrete object.  VARIANT is
2531    the current variant to be handled.  FLAGS is where the results are
2532    stored -- this function sets the Nth element in FLAGS if the
2533    corresponding field is enabled.  ENABLED is whether this variant is
2534    enabled or not.  */
2535
2536 static void
2537 compute_variant_fields_recurse (struct type *type,
2538                                 struct property_addr_info *addr_stack,
2539                                 const variant &variant,
2540                                 std::vector<bool> &flags,
2541                                 bool enabled)
2542 {
2543   for (int field = variant.first_field; field < variant.last_field; ++field)
2544     flags[field] = enabled;
2545
2546   for (const variant_part &new_part : variant.parts)
2547     {
2548       if (enabled)
2549         compute_variant_fields_inner (type, addr_stack, new_part, flags);
2550       else
2551         {
2552           for (const auto &sub_variant : new_part.variants)
2553             compute_variant_fields_recurse (type, addr_stack, sub_variant,
2554                                             flags, enabled);
2555         }
2556     }
2557 }
2558
2559 /* A helper function to determine which variant fields will be active.
2560    This evaluates the discriminant, decides which variant (if any) is
2561    active, and then updates FLAGS to reflect which fields should be
2562    available.  TYPE is the type we're examining.  ADDR_STACK holds
2563    information about the concrete object.  VARIANT is the current
2564    variant to be handled.  FLAGS is where the results are stored --
2565    this function sets the Nth element in FLAGS if the corresponding
2566    field is enabled.  */
2567
2568 static void
2569 compute_variant_fields_inner (struct type *type,
2570                               struct property_addr_info *addr_stack,
2571                               const variant_part &part,
2572                               std::vector<bool> &flags)
2573 {
2574   /* Evaluate the discriminant.  */
2575   gdb::optional<ULONGEST> discr_value;
2576   if (part.discriminant_index != -1)
2577     {
2578       int idx = part.discriminant_index;
2579
2580       if (type->field (idx).loc_kind () != FIELD_LOC_KIND_BITPOS)
2581         error (_("Cannot determine struct field location"
2582                  " (invalid location kind)"));
2583
2584       if (addr_stack->valaddr.data () != NULL)
2585         discr_value = unpack_field_as_long (type, addr_stack->valaddr.data (),
2586                                             idx);
2587       else
2588         {
2589           CORE_ADDR addr = (addr_stack->addr
2590                             + (type->field (idx).loc_bitpos ()
2591                                / TARGET_CHAR_BIT));
2592
2593           LONGEST bitsize = TYPE_FIELD_BITSIZE (type, idx);
2594           LONGEST size = bitsize / 8;
2595           if (size == 0)
2596             size = TYPE_LENGTH (type->field (idx).type ());
2597
2598           gdb_byte bits[sizeof (ULONGEST)];
2599           read_memory (addr, bits, size);
2600
2601           LONGEST bitpos = (type->field (idx).loc_bitpos ()
2602                             % TARGET_CHAR_BIT);
2603
2604           discr_value = unpack_bits_as_long (type->field (idx).type (),
2605                                              bits, bitpos, bitsize);
2606         }
2607     }
2608
2609   /* Go through each variant and see which applies.  */
2610   const variant *default_variant = nullptr;
2611   const variant *applied_variant = nullptr;
2612   for (const auto &variant : part.variants)
2613     {
2614       if (variant.is_default ())
2615         default_variant = &variant;
2616       else if (discr_value.has_value ()
2617                && variant.matches (*discr_value, part.is_unsigned))
2618         {
2619           applied_variant = &variant;
2620           break;
2621         }
2622     }
2623   if (applied_variant == nullptr)
2624     applied_variant = default_variant;
2625
2626   for (const auto &variant : part.variants)
2627     compute_variant_fields_recurse (type, addr_stack, variant,
2628                                     flags, applied_variant == &variant);
2629 }  
2630
2631 /* Determine which variant fields are available in TYPE.  The enabled
2632    fields are stored in RESOLVED_TYPE.  ADDR_STACK holds information
2633    about the concrete object.  PARTS describes the top-level variant
2634    parts for this type.  */
2635
2636 static void
2637 compute_variant_fields (struct type *type,
2638                         struct type *resolved_type,
2639                         struct property_addr_info *addr_stack,
2640                         const gdb::array_view<variant_part> &parts)
2641 {
2642   /* Assume all fields are included by default.  */
2643   std::vector<bool> flags (resolved_type->num_fields (), true);
2644
2645   /* Now disable fields based on the variants that control them.  */
2646   for (const auto &part : parts)
2647     compute_variant_fields_inner (type, addr_stack, part, flags);
2648
2649   resolved_type->set_num_fields
2650     (std::count (flags.begin (), flags.end (), true));
2651   resolved_type->set_fields
2652     ((struct field *)
2653      TYPE_ALLOC (resolved_type,
2654                  resolved_type->num_fields () * sizeof (struct field)));
2655
2656   int out = 0;
2657   for (int i = 0; i < type->num_fields (); ++i)
2658     {
2659       if (!flags[i])
2660         continue;
2661
2662       resolved_type->field (out) = type->field (i);
2663       ++out;
2664     }
2665 }
2666
2667 /* Resolve dynamic bounds of members of the struct TYPE to static
2668    bounds.  ADDR_STACK is a stack of struct property_addr_info to
2669    be used if needed during the dynamic resolution.  */
2670
2671 static struct type *
2672 resolve_dynamic_struct (struct type *type,
2673                         struct property_addr_info *addr_stack)
2674 {
2675   struct type *resolved_type;
2676   int i;
2677   unsigned resolved_type_bit_length = 0;
2678
2679   gdb_assert (type->code () == TYPE_CODE_STRUCT);
2680
2681   resolved_type = copy_type (type);
2682
2683   dynamic_prop *variant_prop = resolved_type->dyn_prop (DYN_PROP_VARIANT_PARTS);
2684   if (variant_prop != nullptr && variant_prop->kind () == PROP_VARIANT_PARTS)
2685     {
2686       compute_variant_fields (type, resolved_type, addr_stack,
2687                               *variant_prop->variant_parts ());
2688       /* We want to leave the property attached, so that the Rust code
2689          can tell whether the type was originally an enum.  */
2690       variant_prop->set_original_type (type);
2691     }
2692   else
2693     {
2694       resolved_type->set_fields
2695         ((struct field *)
2696          TYPE_ALLOC (resolved_type,
2697                      resolved_type->num_fields () * sizeof (struct field)));
2698       if (type->num_fields () > 0)
2699         memcpy (resolved_type->fields (),
2700                 type->fields (),
2701                 resolved_type->num_fields () * sizeof (struct field));
2702     }
2703
2704   for (i = 0; i < resolved_type->num_fields (); ++i)
2705     {
2706       unsigned new_bit_length;
2707       struct property_addr_info pinfo;
2708
2709       if (field_is_static (&resolved_type->field (i)))
2710         continue;
2711
2712       if (resolved_type->field (i).loc_kind () == FIELD_LOC_KIND_DWARF_BLOCK)
2713         {
2714           struct dwarf2_property_baton baton;
2715           baton.property_type
2716             = lookup_pointer_type (resolved_type->field (i).type ());
2717           baton.locexpr = *resolved_type->field (i).loc_dwarf_block ();
2718
2719           struct dynamic_prop prop;
2720           prop.set_locexpr (&baton);
2721
2722           CORE_ADDR addr;
2723           if (dwarf2_evaluate_property (&prop, nullptr, addr_stack, &addr,
2724                                         {addr_stack->addr}))
2725             resolved_type->field (i).set_loc_bitpos
2726               (TARGET_CHAR_BIT * (addr - addr_stack->addr));
2727         }
2728
2729       /* As we know this field is not a static field, the field's
2730          field_loc_kind should be FIELD_LOC_KIND_BITPOS.  Verify
2731          this is the case, but only trigger a simple error rather
2732          than an internal error if that fails.  While failing
2733          that verification indicates a bug in our code, the error
2734          is not severe enough to suggest to the user he stops
2735          his debugging session because of it.  */
2736       if (resolved_type->field (i).loc_kind () != FIELD_LOC_KIND_BITPOS)
2737         error (_("Cannot determine struct field location"
2738                  " (invalid location kind)"));
2739
2740       pinfo.type = check_typedef (resolved_type->field (i).type ());
2741       size_t offset = resolved_type->field (i).loc_bitpos () / TARGET_CHAR_BIT;
2742       pinfo.valaddr = addr_stack->valaddr;
2743       if (!pinfo.valaddr.empty ())
2744         pinfo.valaddr = pinfo.valaddr.slice (offset);
2745       pinfo.addr = addr_stack->addr + offset;
2746       pinfo.next = addr_stack;
2747
2748       resolved_type->field (i).set_type
2749         (resolve_dynamic_type_internal (resolved_type->field (i).type (),
2750                                         &pinfo, 0));
2751       gdb_assert (resolved_type->field (i).loc_kind ()
2752                   == FIELD_LOC_KIND_BITPOS);
2753
2754       new_bit_length = resolved_type->field (i).loc_bitpos ();
2755       if (TYPE_FIELD_BITSIZE (resolved_type, i) != 0)
2756         new_bit_length += TYPE_FIELD_BITSIZE (resolved_type, i);
2757       else
2758         {
2759           struct type *real_type
2760             = check_typedef (resolved_type->field (i).type ());
2761
2762           new_bit_length += (TYPE_LENGTH (real_type) * TARGET_CHAR_BIT);
2763         }
2764
2765       /* Normally, we would use the position and size of the last field
2766          to determine the size of the enclosing structure.  But GCC seems
2767          to be encoding the position of some fields incorrectly when
2768          the struct contains a dynamic field that is not placed last.
2769          So we compute the struct size based on the field that has
2770          the highest position + size - probably the best we can do.  */
2771       if (new_bit_length > resolved_type_bit_length)
2772         resolved_type_bit_length = new_bit_length;
2773     }
2774
2775   /* The length of a type won't change for fortran, but it does for C and Ada.
2776      For fortran the size of dynamic fields might change over time but not the
2777      type length of the structure.  If we adapt it, we run into problems
2778      when calculating the element offset for arrays of structs.  */
2779   if (current_language->la_language != language_fortran)
2780     TYPE_LENGTH (resolved_type)
2781       = (resolved_type_bit_length + TARGET_CHAR_BIT - 1) / TARGET_CHAR_BIT;
2782
2783   /* The Ada language uses this field as a cache for static fixed types: reset
2784      it as RESOLVED_TYPE must have its own static fixed type.  */
2785   resolved_type->set_target_type (nullptr);
2786
2787   return resolved_type;
2788 }
2789
2790 /* Worker for resolved_dynamic_type.  */
2791
2792 static struct type *
2793 resolve_dynamic_type_internal (struct type *type,
2794                                struct property_addr_info *addr_stack,
2795                                int top_level)
2796 {
2797   struct type *real_type = check_typedef (type);
2798   struct type *resolved_type = nullptr;
2799   struct dynamic_prop *prop;
2800   CORE_ADDR value;
2801
2802   if (!is_dynamic_type_internal (real_type, top_level))
2803     return type;
2804
2805   gdb::optional<CORE_ADDR> type_length;
2806   prop = TYPE_DYNAMIC_LENGTH (type);
2807   if (prop != NULL
2808       && dwarf2_evaluate_property (prop, NULL, addr_stack, &value))
2809     type_length = value;
2810
2811   if (type->code () == TYPE_CODE_TYPEDEF)
2812     {
2813       resolved_type = copy_type (type);
2814       resolved_type->set_target_type
2815         (resolve_dynamic_type_internal (TYPE_TARGET_TYPE (type), addr_stack,
2816                                         top_level));
2817     }
2818   else
2819     {
2820       /* Before trying to resolve TYPE, make sure it is not a stub.  */
2821       type = real_type;
2822
2823       switch (type->code ())
2824         {
2825         case TYPE_CODE_REF:
2826           {
2827             struct property_addr_info pinfo;
2828
2829             pinfo.type = check_typedef (TYPE_TARGET_TYPE (type));
2830             pinfo.valaddr = {};
2831             if (addr_stack->valaddr.data () != NULL)
2832               pinfo.addr = extract_typed_address (addr_stack->valaddr.data (),
2833                                                   type);
2834             else
2835               pinfo.addr = read_memory_typed_address (addr_stack->addr, type);
2836             pinfo.next = addr_stack;
2837
2838             resolved_type = copy_type (type);
2839             resolved_type->set_target_type
2840               (resolve_dynamic_type_internal (TYPE_TARGET_TYPE (type),
2841                                               &pinfo, top_level));
2842             break;
2843           }
2844
2845         case TYPE_CODE_STRING:
2846           /* Strings are very much like an array of characters, and can be
2847              treated as one here.  */
2848         case TYPE_CODE_ARRAY:
2849           resolved_type = resolve_dynamic_array_or_string (type, addr_stack);
2850           break;
2851
2852         case TYPE_CODE_RANGE:
2853           /* Pass 0 for the rank value here, which indicates this is a
2854              range for the first rank of an array.  The assumption is that
2855              this rank value is not actually required for the resolution of
2856              the dynamic range, otherwise, we'd be resolving this range
2857              within the context of a dynamic array.  */
2858           resolved_type = resolve_dynamic_range (type, addr_stack, 0);
2859           break;
2860
2861         case TYPE_CODE_UNION:
2862           resolved_type = resolve_dynamic_union (type, addr_stack);
2863           break;
2864
2865         case TYPE_CODE_STRUCT:
2866           resolved_type = resolve_dynamic_struct (type, addr_stack);
2867           break;
2868         }
2869     }
2870
2871   if (resolved_type == nullptr)
2872     return type;
2873
2874   if (type_length.has_value ())
2875     {
2876       TYPE_LENGTH (resolved_type) = *type_length;
2877       resolved_type->remove_dyn_prop (DYN_PROP_BYTE_SIZE);
2878     }
2879
2880   /* Resolve data_location attribute.  */
2881   prop = TYPE_DATA_LOCATION (resolved_type);
2882   if (prop != NULL
2883       && dwarf2_evaluate_property (prop, NULL, addr_stack, &value))
2884     {
2885       /* Start of Fortran hack.  See comment in f-lang.h for what is going
2886          on here.*/
2887       if (current_language->la_language == language_fortran
2888           && resolved_type->code () == TYPE_CODE_ARRAY)
2889         value = fortran_adjust_dynamic_array_base_address_hack (resolved_type,
2890                                                                 value);
2891       /* End of Fortran hack.  */
2892       prop->set_const_val (value);
2893     }
2894
2895   return resolved_type;
2896 }
2897
2898 /* See gdbtypes.h  */
2899
2900 struct type *
2901 resolve_dynamic_type (struct type *type,
2902                       gdb::array_view<const gdb_byte> valaddr,
2903                       CORE_ADDR addr)
2904 {
2905   struct property_addr_info pinfo
2906     = {check_typedef (type), valaddr, addr, NULL};
2907
2908   return resolve_dynamic_type_internal (type, &pinfo, 1);
2909 }
2910
2911 /* See gdbtypes.h  */
2912
2913 dynamic_prop *
2914 type::dyn_prop (dynamic_prop_node_kind prop_kind) const
2915 {
2916   dynamic_prop_list *node = this->main_type->dyn_prop_list;
2917
2918   while (node != NULL)
2919     {
2920       if (node->prop_kind == prop_kind)
2921         return &node->prop;
2922       node = node->next;
2923     }
2924   return NULL;
2925 }
2926
2927 /* See gdbtypes.h  */
2928
2929 void
2930 type::add_dyn_prop (dynamic_prop_node_kind prop_kind, dynamic_prop prop)
2931 {
2932   struct dynamic_prop_list *temp;
2933
2934   gdb_assert (this->is_objfile_owned ());
2935
2936   temp = XOBNEW (&this->objfile_owner ()->objfile_obstack,
2937                  struct dynamic_prop_list);
2938   temp->prop_kind = prop_kind;
2939   temp->prop = prop;
2940   temp->next = this->main_type->dyn_prop_list;
2941
2942   this->main_type->dyn_prop_list = temp;
2943 }
2944
2945 /* See gdbtypes.h.  */
2946
2947 void
2948 type::remove_dyn_prop (dynamic_prop_node_kind kind)
2949 {
2950   struct dynamic_prop_list *prev_node, *curr_node;
2951
2952   curr_node = this->main_type->dyn_prop_list;
2953   prev_node = NULL;
2954
2955   while (NULL != curr_node)
2956     {
2957       if (curr_node->prop_kind == kind)
2958         {
2959           /* Update the linked list but don't free anything.
2960              The property was allocated on objstack and it is not known
2961              if we are on top of it.  Nevertheless, everything is released
2962              when the complete objstack is freed.  */
2963           if (NULL == prev_node)
2964             this->main_type->dyn_prop_list = curr_node->next;
2965           else
2966             prev_node->next = curr_node->next;
2967
2968           return;
2969         }
2970
2971       prev_node = curr_node;
2972       curr_node = curr_node->next;
2973     }
2974 }
2975
2976 /* Find the real type of TYPE.  This function returns the real type,
2977    after removing all layers of typedefs, and completing opaque or stub
2978    types.  Completion changes the TYPE argument, but stripping of
2979    typedefs does not.
2980
2981    Instance flags (e.g. const/volatile) are preserved as typedefs are
2982    stripped.  If necessary a new qualified form of the underlying type
2983    is created.
2984
2985    NOTE: This will return a typedef if TYPE_TARGET_TYPE for the typedef has
2986    not been computed and we're either in the middle of reading symbols, or
2987    there was no name for the typedef in the debug info.
2988
2989    NOTE: Lookup of opaque types can throw errors for invalid symbol files.
2990    QUITs in the symbol reading code can also throw.
2991    Thus this function can throw an exception.
2992
2993    If TYPE is a TYPE_CODE_TYPEDEF, its length is updated to the length of
2994    the target type.
2995
2996    If this is a stubbed struct (i.e. declared as struct foo *), see if
2997    we can find a full definition in some other file.  If so, copy this
2998    definition, so we can use it in future.  There used to be a comment
2999    (but not any code) that if we don't find a full definition, we'd
3000    set a flag so we don't spend time in the future checking the same
3001    type.  That would be a mistake, though--we might load in more
3002    symbols which contain a full definition for the type.  */
3003
3004 struct type *
3005 check_typedef (struct type *type)
3006 {
3007   struct type *orig_type = type;
3008
3009   gdb_assert (type);
3010
3011   /* While we're removing typedefs, we don't want to lose qualifiers.
3012      E.g., const/volatile.  */
3013   type_instance_flags instance_flags = type->instance_flags ();
3014
3015   while (type->code () == TYPE_CODE_TYPEDEF)
3016     {
3017       if (!TYPE_TARGET_TYPE (type))
3018         {
3019           const char *name;
3020           struct symbol *sym;
3021
3022           /* It is dangerous to call lookup_symbol if we are currently
3023              reading a symtab.  Infinite recursion is one danger.  */
3024           if (currently_reading_symtab)
3025             return make_qualified_type (type, instance_flags, NULL);
3026
3027           name = type->name ();
3028           /* FIXME: shouldn't we look in STRUCT_DOMAIN and/or
3029              VAR_DOMAIN as appropriate?  */
3030           if (name == NULL)
3031             {
3032               stub_noname_complaint ();
3033               return make_qualified_type (type, instance_flags, NULL);
3034             }
3035           sym = lookup_symbol (name, 0, STRUCT_DOMAIN, 0).symbol;
3036           if (sym)
3037             type->set_target_type (sym->type ());
3038           else                                  /* TYPE_CODE_UNDEF */
3039             type->set_target_type (alloc_type_arch (type->arch ()));
3040         }
3041       type = TYPE_TARGET_TYPE (type);
3042
3043       /* Preserve the instance flags as we traverse down the typedef chain.
3044
3045          Handling address spaces/classes is nasty, what do we do if there's a
3046          conflict?
3047          E.g., what if an outer typedef marks the type as class_1 and an inner
3048          typedef marks the type as class_2?
3049          This is the wrong place to do such error checking.  We leave it to
3050          the code that created the typedef in the first place to flag the
3051          error.  We just pick the outer address space (akin to letting the
3052          outer cast in a chain of casting win), instead of assuming
3053          "it can't happen".  */
3054       {
3055         const type_instance_flags ALL_SPACES
3056           = (TYPE_INSTANCE_FLAG_CODE_SPACE
3057              | TYPE_INSTANCE_FLAG_DATA_SPACE);
3058         const type_instance_flags ALL_CLASSES
3059           = TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL;
3060
3061         type_instance_flags new_instance_flags = type->instance_flags ();
3062
3063         /* Treat code vs data spaces and address classes separately.  */
3064         if ((instance_flags & ALL_SPACES) != 0)
3065           new_instance_flags &= ~ALL_SPACES;
3066         if ((instance_flags & ALL_CLASSES) != 0)
3067           new_instance_flags &= ~ALL_CLASSES;
3068
3069         instance_flags |= new_instance_flags;
3070       }
3071     }
3072
3073   /* If this is a struct/class/union with no fields, then check
3074      whether a full definition exists somewhere else.  This is for
3075      systems where a type definition with no fields is issued for such
3076      types, instead of identifying them as stub types in the first
3077      place.  */
3078
3079   if (TYPE_IS_OPAQUE (type) 
3080       && opaque_type_resolution 
3081       && !currently_reading_symtab)
3082     {
3083       const char *name = type->name ();
3084       struct type *newtype;
3085
3086       if (name == NULL)
3087         {
3088           stub_noname_complaint ();
3089           return make_qualified_type (type, instance_flags, NULL);
3090         }
3091       newtype = lookup_transparent_type (name);
3092
3093       if (newtype)
3094         {
3095           /* If the resolved type and the stub are in the same
3096              objfile, then replace the stub type with the real deal.
3097              But if they're in separate objfiles, leave the stub
3098              alone; we'll just look up the transparent type every time
3099              we call check_typedef.  We can't create pointers between
3100              types allocated to different objfiles, since they may
3101              have different lifetimes.  Trying to copy NEWTYPE over to
3102              TYPE's objfile is pointless, too, since you'll have to
3103              move over any other types NEWTYPE refers to, which could
3104              be an unbounded amount of stuff.  */
3105           if (newtype->objfile_owner () == type->objfile_owner ())
3106             type = make_qualified_type (newtype, type->instance_flags (), type);
3107           else
3108             type = newtype;
3109         }
3110     }
3111   /* Otherwise, rely on the stub flag being set for opaque/stubbed
3112      types.  */
3113   else if (type->is_stub () && !currently_reading_symtab)
3114     {
3115       const char *name = type->name ();
3116       /* FIXME: shouldn't we look in STRUCT_DOMAIN and/or VAR_DOMAIN
3117          as appropriate?  */
3118       struct symbol *sym;
3119
3120       if (name == NULL)
3121         {
3122           stub_noname_complaint ();
3123           return make_qualified_type (type, instance_flags, NULL);
3124         }
3125       sym = lookup_symbol (name, 0, STRUCT_DOMAIN, 0).symbol;
3126       if (sym)
3127         {
3128           /* Same as above for opaque types, we can replace the stub
3129              with the complete type only if they are in the same
3130              objfile.  */
3131           if (sym->type ()->objfile_owner () == type->objfile_owner ())
3132             type = make_qualified_type (sym->type (),
3133                                         type->instance_flags (), type);
3134           else
3135             type = sym->type ();
3136         }
3137     }
3138
3139   if (type->target_is_stub ())
3140     {
3141       struct type *target_type = check_typedef (TYPE_TARGET_TYPE (type));
3142
3143       if (target_type->is_stub () || target_type->target_is_stub ())
3144         {
3145           /* Nothing we can do.  */
3146         }
3147       else if (type->code () == TYPE_CODE_RANGE)
3148         {
3149           TYPE_LENGTH (type) = TYPE_LENGTH (target_type);
3150           type->set_target_is_stub (false);
3151         }
3152       else if (type->code () == TYPE_CODE_ARRAY
3153                && update_static_array_size (type))
3154         type->set_target_is_stub (false);
3155     }
3156
3157   type = make_qualified_type (type, instance_flags, NULL);
3158
3159   /* Cache TYPE_LENGTH for future use.  */
3160   TYPE_LENGTH (orig_type) = TYPE_LENGTH (type);
3161
3162   return type;
3163 }
3164
3165 /* Parse a type expression in the string [P..P+LENGTH).  If an error
3166    occurs, silently return a void type.  */
3167
3168 static struct type *
3169 safe_parse_type (struct gdbarch *gdbarch, const char *p, int length)
3170 {
3171   struct type *type = NULL; /* Initialize to keep gcc happy.  */
3172
3173   /* Suppress error messages.  */
3174   scoped_restore saved_gdb_stderr = make_scoped_restore (&gdb_stderr,
3175                                                          &null_stream);
3176
3177   /* Call parse_and_eval_type() without fear of longjmp()s.  */
3178   try
3179     {
3180       type = parse_and_eval_type (p, length);
3181     }
3182   catch (const gdb_exception_error &except)
3183     {
3184       type = builtin_type (gdbarch)->builtin_void;
3185     }
3186
3187   return type;
3188 }
3189
3190 /* Ugly hack to convert method stubs into method types.
3191
3192    He ain't kiddin'.  This demangles the name of the method into a
3193    string including argument types, parses out each argument type,
3194    generates a string casting a zero to that type, evaluates the
3195    string, and stuffs the resulting type into an argtype vector!!!
3196    Then it knows the type of the whole function (including argument
3197    types for overloading), which info used to be in the stab's but was
3198    removed to hack back the space required for them.  */
3199
3200 static void
3201 check_stub_method (struct type *type, int method_id, int signature_id)
3202 {
3203   struct gdbarch *gdbarch = type->arch ();
3204   struct fn_field *f;
3205   char *mangled_name = gdb_mangle_name (type, method_id, signature_id);
3206   gdb::unique_xmalloc_ptr<char> demangled_name
3207     = gdb_demangle (mangled_name, DMGL_PARAMS | DMGL_ANSI);
3208   char *argtypetext, *p;
3209   int depth = 0, argcount = 1;
3210   struct field *argtypes;
3211   struct type *mtype;
3212
3213   /* Make sure we got back a function string that we can use.  */
3214   if (demangled_name)
3215     p = strchr (demangled_name.get (), '(');
3216   else
3217     p = NULL;
3218
3219   if (demangled_name == NULL || p == NULL)
3220     error (_("Internal: Cannot demangle mangled name `%s'."), 
3221            mangled_name);
3222
3223   /* Now, read in the parameters that define this type.  */
3224   p += 1;
3225   argtypetext = p;
3226   while (*p)
3227     {
3228       if (*p == '(' || *p == '<')
3229         {
3230           depth += 1;
3231         }
3232       else if (*p == ')' || *p == '>')
3233         {
3234           depth -= 1;
3235         }
3236       else if (*p == ',' && depth == 0)
3237         {
3238           argcount += 1;
3239         }
3240
3241       p += 1;
3242     }
3243
3244   /* If we read one argument and it was ``void'', don't count it.  */
3245   if (startswith (argtypetext, "(void)"))
3246     argcount -= 1;
3247
3248   /* We need one extra slot, for the THIS pointer.  */
3249
3250   argtypes = (struct field *)
3251     TYPE_ALLOC (type, (argcount + 1) * sizeof (struct field));
3252   p = argtypetext;
3253
3254   /* Add THIS pointer for non-static methods.  */
3255   f = TYPE_FN_FIELDLIST1 (type, method_id);
3256   if (TYPE_FN_FIELD_STATIC_P (f, signature_id))
3257     argcount = 0;
3258   else
3259     {
3260       argtypes[0].set_type (lookup_pointer_type (type));
3261       argcount = 1;
3262     }
3263
3264   if (*p != ')')                /* () means no args, skip while.  */
3265     {
3266       depth = 0;
3267       while (*p)
3268         {
3269           if (depth <= 0 && (*p == ',' || *p == ')'))
3270             {
3271               /* Avoid parsing of ellipsis, they will be handled below.
3272                  Also avoid ``void'' as above.  */
3273               if (strncmp (argtypetext, "...", p - argtypetext) != 0
3274                   && strncmp (argtypetext, "void", p - argtypetext) != 0)
3275                 {
3276                   argtypes[argcount].set_type
3277                     (safe_parse_type (gdbarch, argtypetext, p - argtypetext));
3278                   argcount += 1;
3279                 }
3280               argtypetext = p + 1;
3281             }
3282
3283           if (*p == '(' || *p == '<')
3284             {
3285               depth += 1;
3286             }
3287           else if (*p == ')' || *p == '>')
3288             {
3289               depth -= 1;
3290             }
3291
3292           p += 1;
3293         }
3294     }
3295
3296   TYPE_FN_FIELD_PHYSNAME (f, signature_id) = mangled_name;
3297
3298   /* Now update the old "stub" type into a real type.  */
3299   mtype = TYPE_FN_FIELD_TYPE (f, signature_id);
3300   /* MTYPE may currently be a function (TYPE_CODE_FUNC).
3301      We want a method (TYPE_CODE_METHOD).  */
3302   smash_to_method_type (mtype, type, TYPE_TARGET_TYPE (mtype),
3303                         argtypes, argcount, p[-2] == '.');
3304   mtype->set_is_stub (false);
3305   TYPE_FN_FIELD_STUB (f, signature_id) = 0;
3306 }
3307
3308 /* This is the external interface to check_stub_method, above.  This
3309    function unstubs all of the signatures for TYPE's METHOD_ID method
3310    name.  After calling this function TYPE_FN_FIELD_STUB will be
3311    cleared for each signature and TYPE_FN_FIELDLIST_NAME will be
3312    correct.
3313
3314    This function unfortunately can not die until stabs do.  */
3315
3316 void
3317 check_stub_method_group (struct type *type, int method_id)
3318 {
3319   int len = TYPE_FN_FIELDLIST_LENGTH (type, method_id);
3320   struct fn_field *f = TYPE_FN_FIELDLIST1 (type, method_id);
3321
3322   for (int j = 0; j < len; j++)
3323     {
3324       if (TYPE_FN_FIELD_STUB (f, j))
3325         check_stub_method (type, method_id, j);
3326     }
3327 }
3328
3329 /* Ensure it is in .rodata (if available) by working around GCC PR 44690.  */
3330 const struct cplus_struct_type cplus_struct_default = { };
3331
3332 void
3333 allocate_cplus_struct_type (struct type *type)
3334 {
3335   if (HAVE_CPLUS_STRUCT (type))
3336     /* Structure was already allocated.  Nothing more to do.  */
3337     return;
3338
3339   TYPE_SPECIFIC_FIELD (type) = TYPE_SPECIFIC_CPLUS_STUFF;
3340   TYPE_RAW_CPLUS_SPECIFIC (type) = (struct cplus_struct_type *)
3341     TYPE_ALLOC (type, sizeof (struct cplus_struct_type));
3342   *(TYPE_RAW_CPLUS_SPECIFIC (type)) = cplus_struct_default;
3343   set_type_vptr_fieldno (type, -1);
3344 }
3345
3346 const struct gnat_aux_type gnat_aux_default =
3347   { NULL };
3348
3349 /* Set the TYPE's type-specific kind to TYPE_SPECIFIC_GNAT_STUFF,
3350    and allocate the associated gnat-specific data.  The gnat-specific
3351    data is also initialized to gnat_aux_default.  */
3352
3353 void
3354 allocate_gnat_aux_type (struct type *type)
3355 {
3356   TYPE_SPECIFIC_FIELD (type) = TYPE_SPECIFIC_GNAT_STUFF;
3357   TYPE_GNAT_SPECIFIC (type) = (struct gnat_aux_type *)
3358     TYPE_ALLOC (type, sizeof (struct gnat_aux_type));
3359   *(TYPE_GNAT_SPECIFIC (type)) = gnat_aux_default;
3360 }
3361
3362 /* Helper function to initialize a newly allocated type.  Set type code
3363    to CODE and initialize the type-specific fields accordingly.  */
3364
3365 static void
3366 set_type_code (struct type *type, enum type_code code)
3367 {
3368   type->set_code (code);
3369
3370   switch (code)
3371     {
3372       case TYPE_CODE_STRUCT:
3373       case TYPE_CODE_UNION:
3374       case TYPE_CODE_NAMESPACE:
3375         INIT_CPLUS_SPECIFIC (type);
3376         break;
3377       case TYPE_CODE_FLT:
3378         TYPE_SPECIFIC_FIELD (type) = TYPE_SPECIFIC_FLOATFORMAT;
3379         break;
3380       case TYPE_CODE_FUNC:
3381         INIT_FUNC_SPECIFIC (type);
3382         break;
3383       case TYPE_CODE_FIXED_POINT:
3384         INIT_FIXED_POINT_SPECIFIC (type);
3385         break;
3386     }
3387 }
3388
3389 /* Helper function to verify floating-point format and size.
3390    BIT is the type size in bits; if BIT equals -1, the size is
3391    determined by the floatformat.  Returns size to be used.  */
3392
3393 static int
3394 verify_floatformat (int bit, const struct floatformat *floatformat)
3395 {
3396   gdb_assert (floatformat != NULL);
3397
3398   if (bit == -1)
3399     bit = floatformat->totalsize;
3400
3401   gdb_assert (bit >= 0);
3402   gdb_assert (bit >= floatformat->totalsize);
3403
3404   return bit;
3405 }
3406
3407 /* Return the floating-point format for a floating-point variable of
3408    type TYPE.  */
3409
3410 const struct floatformat *
3411 floatformat_from_type (const struct type *type)
3412 {
3413   gdb_assert (type->code () == TYPE_CODE_FLT);
3414   gdb_assert (TYPE_FLOATFORMAT (type));
3415   return TYPE_FLOATFORMAT (type);
3416 }
3417
3418 /* Helper function to initialize the standard scalar types.
3419
3420    If NAME is non-NULL, then it is used to initialize the type name.
3421    Note that NAME is not copied; it is required to have a lifetime at
3422    least as long as OBJFILE.  */
3423
3424 struct type *
3425 init_type (struct objfile *objfile, enum type_code code, int bit,
3426            const char *name)
3427 {
3428   struct type *type;
3429
3430   type = alloc_type (objfile);
3431   set_type_code (type, code);
3432   gdb_assert ((bit % TARGET_CHAR_BIT) == 0);
3433   TYPE_LENGTH (type) = bit / TARGET_CHAR_BIT;
3434   type->set_name (name);
3435
3436   return type;
3437 }
3438
3439 /* Allocate a TYPE_CODE_ERROR type structure associated with OBJFILE,
3440    to use with variables that have no debug info.  NAME is the type
3441    name.  */
3442
3443 static struct type *
3444 init_nodebug_var_type (struct objfile *objfile, const char *name)
3445 {
3446   return init_type (objfile, TYPE_CODE_ERROR, 0, name);
3447 }
3448
3449 /* Allocate a TYPE_CODE_INT type structure associated with OBJFILE.
3450    BIT is the type size in bits.  If UNSIGNED_P is non-zero, set
3451    the type's TYPE_UNSIGNED flag.  NAME is the type name.  */
3452
3453 struct type *
3454 init_integer_type (struct objfile *objfile,
3455                    int bit, int unsigned_p, const char *name)
3456 {
3457   struct type *t;
3458
3459   t = init_type (objfile, TYPE_CODE_INT, bit, name);
3460   if (unsigned_p)
3461     t->set_is_unsigned (true);
3462
3463   TYPE_SPECIFIC_FIELD (t) = TYPE_SPECIFIC_INT;
3464   TYPE_MAIN_TYPE (t)->type_specific.int_stuff.bit_size = bit;
3465   TYPE_MAIN_TYPE (t)->type_specific.int_stuff.bit_offset = 0;
3466
3467   return t;
3468 }
3469
3470 /* Allocate a TYPE_CODE_CHAR type structure associated with OBJFILE.
3471    BIT is the type size in bits.  If UNSIGNED_P is non-zero, set
3472    the type's TYPE_UNSIGNED flag.  NAME is the type name.  */
3473
3474 struct type *
3475 init_character_type (struct objfile *objfile,
3476                      int bit, int unsigned_p, const char *name)
3477 {
3478   struct type *t;
3479
3480   t = init_type (objfile, TYPE_CODE_CHAR, bit, name);
3481   if (unsigned_p)
3482     t->set_is_unsigned (true);
3483
3484   return t;
3485 }
3486
3487 /* Allocate a TYPE_CODE_BOOL type structure associated with OBJFILE.
3488    BIT is the type size in bits.  If UNSIGNED_P is non-zero, set
3489    the type's TYPE_UNSIGNED flag.  NAME is the type name.  */
3490
3491 struct type *
3492 init_boolean_type (struct objfile *objfile,
3493                    int bit, int unsigned_p, const char *name)
3494 {
3495   struct type *t;
3496
3497   t = init_type (objfile, TYPE_CODE_BOOL, bit, name);
3498   if (unsigned_p)
3499     t->set_is_unsigned (true);
3500
3501   TYPE_SPECIFIC_FIELD (t) = TYPE_SPECIFIC_INT;
3502   TYPE_MAIN_TYPE (t)->type_specific.int_stuff.bit_size = bit;
3503   TYPE_MAIN_TYPE (t)->type_specific.int_stuff.bit_offset = 0;
3504
3505   return t;
3506 }
3507
3508 /* Allocate a TYPE_CODE_FLT type structure associated with OBJFILE.
3509    BIT is the type size in bits; if BIT equals -1, the size is
3510    determined by the floatformat.  NAME is the type name.  Set the
3511    TYPE_FLOATFORMAT from FLOATFORMATS.  BYTE_ORDER is the byte order
3512    to use.  If it is BFD_ENDIAN_UNKNOWN (the default), then the byte
3513    order of the objfile's architecture is used.  */
3514
3515 struct type *
3516 init_float_type (struct objfile *objfile,
3517                  int bit, const char *name,
3518                  const struct floatformat **floatformats,
3519                  enum bfd_endian byte_order)
3520 {
3521   if (byte_order == BFD_ENDIAN_UNKNOWN)
3522     {
3523       struct gdbarch *gdbarch = objfile->arch ();
3524       byte_order = gdbarch_byte_order (gdbarch);
3525     }
3526   const struct floatformat *fmt = floatformats[byte_order];
3527   struct type *t;
3528
3529   bit = verify_floatformat (bit, fmt);
3530   t = init_type (objfile, TYPE_CODE_FLT, bit, name);
3531   TYPE_FLOATFORMAT (t) = fmt;
3532
3533   return t;
3534 }
3535
3536 /* Allocate a TYPE_CODE_DECFLOAT type structure associated with OBJFILE.
3537    BIT is the type size in bits.  NAME is the type name.  */
3538
3539 struct type *
3540 init_decfloat_type (struct objfile *objfile, int bit, const char *name)
3541 {
3542   struct type *t;
3543
3544   t = init_type (objfile, TYPE_CODE_DECFLOAT, bit, name);
3545   return t;
3546 }
3547
3548 /* Return true if init_complex_type can be called with TARGET_TYPE.  */
3549
3550 bool
3551 can_create_complex_type (struct type *target_type)
3552 {
3553   return (target_type->code () == TYPE_CODE_INT
3554           || target_type->code () == TYPE_CODE_FLT);
3555 }
3556
3557 /* Allocate a TYPE_CODE_COMPLEX type structure.  NAME is the type
3558    name.  TARGET_TYPE is the component type.  */
3559
3560 struct type *
3561 init_complex_type (const char *name, struct type *target_type)
3562 {
3563   struct type *t;
3564
3565   gdb_assert (can_create_complex_type (target_type));
3566
3567   if (TYPE_MAIN_TYPE (target_type)->flds_bnds.complex_type == nullptr)
3568     {
3569       if (name == nullptr && target_type->name () != nullptr)
3570         {
3571           char *new_name
3572             = (char *) TYPE_ALLOC (target_type,
3573                                    strlen (target_type->name ())
3574                                    + strlen ("_Complex ") + 1);
3575           strcpy (new_name, "_Complex ");
3576           strcat (new_name, target_type->name ());
3577           name = new_name;
3578         }
3579
3580       t = alloc_type_copy (target_type);
3581       set_type_code (t, TYPE_CODE_COMPLEX);
3582       TYPE_LENGTH (t) = 2 * TYPE_LENGTH (target_type);
3583       t->set_name (name);
3584
3585       t->set_target_type (target_type);
3586       TYPE_MAIN_TYPE (target_type)->flds_bnds.complex_type = t;
3587     }
3588
3589   return TYPE_MAIN_TYPE (target_type)->flds_bnds.complex_type;
3590 }
3591
3592 /* Allocate a TYPE_CODE_PTR type structure associated with OBJFILE.
3593    BIT is the pointer type size in bits.  NAME is the type name.
3594    TARGET_TYPE is the pointer target type.  Always sets the pointer type's
3595    TYPE_UNSIGNED flag.  */
3596
3597 struct type *
3598 init_pointer_type (struct objfile *objfile,
3599                    int bit, const char *name, struct type *target_type)
3600 {
3601   struct type *t;
3602
3603   t = init_type (objfile, TYPE_CODE_PTR, bit, name);
3604   t->set_target_type (target_type);
3605   t->set_is_unsigned (true);
3606   return t;
3607 }
3608
3609 /* Allocate a TYPE_CODE_FIXED_POINT type structure associated with OBJFILE.
3610    BIT is the pointer type size in bits.
3611    UNSIGNED_P should be nonzero if the type is unsigned.
3612    NAME is the type name.  */
3613
3614 struct type *
3615 init_fixed_point_type (struct objfile *objfile,
3616                        int bit, int unsigned_p, const char *name)
3617 {
3618   struct type *t;
3619
3620   t = init_type (objfile, TYPE_CODE_FIXED_POINT, bit, name);
3621   if (unsigned_p)
3622     t->set_is_unsigned (true);
3623
3624   return t;
3625 }
3626
3627 /* See gdbtypes.h.  */
3628
3629 unsigned
3630 type_raw_align (struct type *type)
3631 {
3632   if (type->align_log2 != 0)
3633     return 1 << (type->align_log2 - 1);
3634   return 0;
3635 }
3636
3637 /* See gdbtypes.h.  */
3638
3639 unsigned
3640 type_align (struct type *type)
3641 {
3642   /* Check alignment provided in the debug information.  */
3643   unsigned raw_align = type_raw_align (type);
3644   if (raw_align != 0)
3645     return raw_align;
3646
3647   /* Allow the architecture to provide an alignment.  */
3648   ULONGEST align = gdbarch_type_align (type->arch (), type);
3649   if (align != 0)
3650     return align;
3651
3652   switch (type->code ())
3653     {
3654     case TYPE_CODE_PTR:
3655     case TYPE_CODE_FUNC:
3656     case TYPE_CODE_FLAGS:
3657     case TYPE_CODE_INT:
3658     case TYPE_CODE_RANGE:
3659     case TYPE_CODE_FLT:
3660     case TYPE_CODE_ENUM:
3661     case TYPE_CODE_REF:
3662     case TYPE_CODE_RVALUE_REF:
3663     case TYPE_CODE_CHAR:
3664     case TYPE_CODE_BOOL:
3665     case TYPE_CODE_DECFLOAT:
3666     case TYPE_CODE_METHODPTR:
3667     case TYPE_CODE_MEMBERPTR:
3668       align = type_length_units (check_typedef (type));
3669       break;
3670
3671     case TYPE_CODE_ARRAY:
3672     case TYPE_CODE_COMPLEX:
3673     case TYPE_CODE_TYPEDEF:
3674       align = type_align (TYPE_TARGET_TYPE (type));
3675       break;
3676
3677     case TYPE_CODE_STRUCT:
3678     case TYPE_CODE_UNION:
3679       {
3680         int number_of_non_static_fields = 0;
3681         for (unsigned i = 0; i < type->num_fields (); ++i)
3682           {
3683             if (!field_is_static (&type->field (i)))
3684               {
3685                 number_of_non_static_fields++;
3686                 ULONGEST f_align = type_align (type->field (i).type ());
3687                 if (f_align == 0)
3688                   {
3689                     /* Don't pretend we know something we don't.  */
3690                     align = 0;
3691                     break;
3692                   }
3693                 if (f_align > align)
3694                   align = f_align;
3695               }
3696           }
3697         /* A struct with no fields, or with only static fields has an
3698            alignment of 1.  */
3699         if (number_of_non_static_fields == 0)
3700           align = 1;
3701       }
3702       break;
3703
3704     case TYPE_CODE_SET:
3705     case TYPE_CODE_STRING:
3706       /* Not sure what to do here, and these can't appear in C or C++
3707          anyway.  */
3708       break;
3709
3710     case TYPE_CODE_VOID:
3711       align = 1;
3712       break;
3713
3714     case TYPE_CODE_ERROR:
3715     case TYPE_CODE_METHOD:
3716     default:
3717       break;
3718     }
3719
3720   if ((align & (align - 1)) != 0)
3721     {
3722       /* Not a power of 2, so pass.  */
3723       align = 0;
3724     }
3725
3726   return align;
3727 }
3728
3729 /* See gdbtypes.h.  */
3730
3731 bool
3732 set_type_align (struct type *type, ULONGEST align)
3733 {
3734   /* Must be a power of 2.  Zero is ok.  */
3735   gdb_assert ((align & (align - 1)) == 0);
3736
3737   unsigned result = 0;
3738   while (align != 0)
3739     {
3740       ++result;
3741       align >>= 1;
3742     }
3743
3744   if (result >= (1 << TYPE_ALIGN_BITS))
3745     return false;
3746
3747   type->align_log2 = result;
3748   return true;
3749 }
3750
3751 \f
3752 /* Queries on types.  */
3753
3754 int
3755 can_dereference (struct type *t)
3756 {
3757   /* FIXME: Should we return true for references as well as
3758      pointers?  */
3759   t = check_typedef (t);
3760   return
3761     (t != NULL
3762      && t->code () == TYPE_CODE_PTR
3763      && TYPE_TARGET_TYPE (t)->code () != TYPE_CODE_VOID);
3764 }
3765
3766 int
3767 is_integral_type (struct type *t)
3768 {
3769   t = check_typedef (t);
3770   return
3771     ((t != NULL)
3772      && !is_fixed_point_type (t)
3773      && ((t->code () == TYPE_CODE_INT)
3774          || (t->code () == TYPE_CODE_ENUM)
3775          || (t->code () == TYPE_CODE_FLAGS)
3776          || (t->code () == TYPE_CODE_CHAR)
3777          || (t->code () == TYPE_CODE_RANGE)
3778          || (t->code () == TYPE_CODE_BOOL)));
3779 }
3780
3781 int
3782 is_floating_type (struct type *t)
3783 {
3784   t = check_typedef (t);
3785   return
3786     ((t != NULL)
3787      && ((t->code () == TYPE_CODE_FLT)
3788          || (t->code () == TYPE_CODE_DECFLOAT)));
3789 }
3790
3791 /* Return true if TYPE is scalar.  */
3792
3793 int
3794 is_scalar_type (struct type *type)
3795 {
3796   type = check_typedef (type);
3797
3798   if (is_fixed_point_type (type))
3799     return 0; /* Implemented as a scalar, but more like a floating point.  */
3800
3801   switch (type->code ())
3802     {
3803     case TYPE_CODE_ARRAY:
3804     case TYPE_CODE_STRUCT:
3805     case TYPE_CODE_UNION:
3806     case TYPE_CODE_SET:
3807     case TYPE_CODE_STRING:
3808       return 0;
3809     default:
3810       return 1;
3811     }
3812 }
3813
3814 /* Return true if T is scalar, or a composite type which in practice has
3815    the memory layout of a scalar type.  E.g., an array or struct with only
3816    one scalar element inside it, or a union with only scalar elements.  */
3817
3818 int
3819 is_scalar_type_recursive (struct type *t)
3820 {
3821   t = check_typedef (t);
3822
3823   if (is_scalar_type (t))
3824     return 1;
3825   /* Are we dealing with an array or string of known dimensions?  */
3826   else if ((t->code () == TYPE_CODE_ARRAY
3827             || t->code () == TYPE_CODE_STRING) && t->num_fields () == 1
3828            && t->index_type ()->code () == TYPE_CODE_RANGE)
3829     {
3830       LONGEST low_bound, high_bound;
3831       struct type *elt_type = check_typedef (TYPE_TARGET_TYPE (t));
3832
3833       if (get_discrete_bounds (t->index_type (), &low_bound, &high_bound))
3834         return (high_bound == low_bound
3835                 && is_scalar_type_recursive (elt_type));
3836       else
3837         return 0;
3838     }
3839   /* Are we dealing with a struct with one element?  */
3840   else if (t->code () == TYPE_CODE_STRUCT && t->num_fields () == 1)
3841     return is_scalar_type_recursive (t->field (0).type ());
3842   else if (t->code () == TYPE_CODE_UNION)
3843     {
3844       int i, n = t->num_fields ();
3845
3846       /* If all elements of the union are scalar, then the union is scalar.  */
3847       for (i = 0; i < n; i++)
3848         if (!is_scalar_type_recursive (t->field (i).type ()))
3849           return 0;
3850
3851       return 1;
3852     }
3853
3854   return 0;
3855 }
3856
3857 /* Return true is T is a class or a union.  False otherwise.  */
3858
3859 int
3860 class_or_union_p (const struct type *t)
3861 {
3862   return (t->code () == TYPE_CODE_STRUCT
3863           || t->code () == TYPE_CODE_UNION);
3864 }
3865
3866 /* A helper function which returns true if types A and B represent the
3867    "same" class type.  This is true if the types have the same main
3868    type, or the same name.  */
3869
3870 int
3871 class_types_same_p (const struct type *a, const struct type *b)
3872 {
3873   return (TYPE_MAIN_TYPE (a) == TYPE_MAIN_TYPE (b)
3874           || (a->name () && b->name ()
3875               && !strcmp (a->name (), b->name ())));
3876 }
3877
3878 /* If BASE is an ancestor of DCLASS return the distance between them.
3879    otherwise return -1;
3880    eg:
3881
3882    class A {};
3883    class B: public A {};
3884    class C: public B {};
3885    class D: C {};
3886
3887    distance_to_ancestor (A, A, 0) = 0
3888    distance_to_ancestor (A, B, 0) = 1
3889    distance_to_ancestor (A, C, 0) = 2
3890    distance_to_ancestor (A, D, 0) = 3
3891
3892    If PUBLIC is 1 then only public ancestors are considered,
3893    and the function returns the distance only if BASE is a public ancestor
3894    of DCLASS.
3895    Eg:
3896
3897    distance_to_ancestor (A, D, 1) = -1.  */
3898
3899 static int
3900 distance_to_ancestor (struct type *base, struct type *dclass, int is_public)
3901 {
3902   int i;
3903   int d;
3904
3905   base = check_typedef (base);
3906   dclass = check_typedef (dclass);
3907
3908   if (class_types_same_p (base, dclass))
3909     return 0;
3910
3911   for (i = 0; i < TYPE_N_BASECLASSES (dclass); i++)
3912     {
3913       if (is_public && ! BASETYPE_VIA_PUBLIC (dclass, i))
3914         continue;
3915
3916       d = distance_to_ancestor (base, TYPE_BASECLASS (dclass, i), is_public);
3917       if (d >= 0)
3918         return 1 + d;
3919     }
3920
3921   return -1;
3922 }
3923
3924 /* Check whether BASE is an ancestor or base class or DCLASS
3925    Return 1 if so, and 0 if not.
3926    Note: If BASE and DCLASS are of the same type, this function
3927    will return 1. So for some class A, is_ancestor (A, A) will
3928    return 1.  */
3929
3930 int
3931 is_ancestor (struct type *base, struct type *dclass)
3932 {
3933   return distance_to_ancestor (base, dclass, 0) >= 0;
3934 }
3935
3936 /* Like is_ancestor, but only returns true when BASE is a public
3937    ancestor of DCLASS.  */
3938
3939 int
3940 is_public_ancestor (struct type *base, struct type *dclass)
3941 {
3942   return distance_to_ancestor (base, dclass, 1) >= 0;
3943 }
3944
3945 /* A helper function for is_unique_ancestor.  */
3946
3947 static int
3948 is_unique_ancestor_worker (struct type *base, struct type *dclass,
3949                            int *offset,
3950                            const gdb_byte *valaddr, int embedded_offset,
3951                            CORE_ADDR address, struct value *val)
3952 {
3953   int i, count = 0;
3954
3955   base = check_typedef (base);
3956   dclass = check_typedef (dclass);
3957
3958   for (i = 0; i < TYPE_N_BASECLASSES (dclass) && count < 2; ++i)
3959     {
3960       struct type *iter;
3961       int this_offset;
3962
3963       iter = check_typedef (TYPE_BASECLASS (dclass, i));
3964
3965       this_offset = baseclass_offset (dclass, i, valaddr, embedded_offset,
3966                                       address, val);
3967
3968       if (class_types_same_p (base, iter))
3969         {
3970           /* If this is the first subclass, set *OFFSET and set count
3971              to 1.  Otherwise, if this is at the same offset as
3972              previous instances, do nothing.  Otherwise, increment
3973              count.  */
3974           if (*offset == -1)
3975             {
3976               *offset = this_offset;
3977               count = 1;
3978             }
3979           else if (this_offset == *offset)
3980             {
3981               /* Nothing.  */
3982             }
3983           else
3984             ++count;
3985         }
3986       else
3987         count += is_unique_ancestor_worker (base, iter, offset,
3988                                             valaddr,
3989                                             embedded_offset + this_offset,
3990                                             address, val);
3991     }
3992
3993   return count;
3994 }
3995
3996 /* Like is_ancestor, but only returns true if BASE is a unique base
3997    class of the type of VAL.  */
3998
3999 int
4000 is_unique_ancestor (struct type *base, struct value *val)
4001 {
4002   int offset = -1;
4003
4004   return is_unique_ancestor_worker (base, value_type (val), &offset,
4005                                     value_contents_for_printing (val).data (),
4006                                     value_embedded_offset (val),
4007                                     value_address (val), val) == 1;
4008 }
4009
4010 /* See gdbtypes.h.  */
4011
4012 enum bfd_endian
4013 type_byte_order (const struct type *type)
4014 {
4015   bfd_endian byteorder = gdbarch_byte_order (type->arch ());
4016   if (type->endianity_is_not_default ())
4017     {
4018       if (byteorder == BFD_ENDIAN_BIG)
4019         return BFD_ENDIAN_LITTLE;
4020       else
4021         {
4022           gdb_assert (byteorder == BFD_ENDIAN_LITTLE);
4023           return BFD_ENDIAN_BIG;
4024         }
4025     }
4026
4027   return byteorder;
4028 }
4029
4030 /* See gdbtypes.h.  */
4031
4032 bool
4033 is_nocall_function (const struct type *type)
4034 {
4035   gdb_assert (type->code () == TYPE_CODE_FUNC
4036               || type->code () == TYPE_CODE_METHOD);
4037
4038   return TYPE_CALLING_CONVENTION (type) == DW_CC_nocall;
4039 }
4040
4041 \f
4042 /* Overload resolution.  */
4043
4044 /* Return the sum of the rank of A with the rank of B.  */
4045
4046 struct rank
4047 sum_ranks (struct rank a, struct rank b)
4048 {
4049   struct rank c;
4050   c.rank = a.rank + b.rank;
4051   c.subrank = a.subrank + b.subrank;
4052   return c;
4053 }
4054
4055 /* Compare rank A and B and return:
4056    0 if a = b
4057    1 if a is better than b
4058   -1 if b is better than a.  */
4059
4060 int
4061 compare_ranks (struct rank a, struct rank b)
4062 {
4063   if (a.rank == b.rank)
4064     {
4065       if (a.subrank == b.subrank)
4066         return 0;
4067       if (a.subrank < b.subrank)
4068         return 1;
4069       if (a.subrank > b.subrank)
4070         return -1;
4071     }
4072
4073   if (a.rank < b.rank)
4074     return 1;
4075
4076   /* a.rank > b.rank */
4077   return -1;
4078 }
4079
4080 /* Functions for overload resolution begin here.  */
4081
4082 /* Compare two badness vectors A and B and return the result.
4083    0 => A and B are identical
4084    1 => A and B are incomparable
4085    2 => A is better than B
4086    3 => A is worse than B  */
4087
4088 int
4089 compare_badness (const badness_vector &a, const badness_vector &b)
4090 {
4091   int i;
4092   int tmp;
4093   /* Any positives in comparison? */
4094   bool found_pos = false;
4095   /* Any negatives in comparison? */
4096   bool found_neg = false;
4097   /* Did A have any INVALID_CONVERSION entries.  */
4098   bool a_invalid = false;
4099   /* Did B have any INVALID_CONVERSION entries.  */
4100   bool b_invalid = false;
4101
4102   /* differing sizes => incomparable */
4103   if (a.size () != b.size ())
4104     return 1;
4105
4106   /* Subtract b from a */
4107   for (i = 0; i < a.size (); i++)
4108     {
4109       tmp = compare_ranks (b[i], a[i]);
4110       if (tmp > 0)
4111         found_pos = true;
4112       else if (tmp < 0)
4113         found_neg = true;
4114       if (a[i].rank >= INVALID_CONVERSION)
4115         a_invalid = true;
4116       if (b[i].rank >= INVALID_CONVERSION)
4117         b_invalid = true;
4118     }
4119
4120   /* B will only be considered better than or incomparable to A if
4121      they both have invalid entries, or if neither does.  That is, if
4122      A has only valid entries, and B has an invalid entry, then A will
4123      be considered better than B, even if B happens to be better for
4124      some parameter.  */
4125   if (a_invalid != b_invalid)
4126     {
4127       if (a_invalid)
4128         return 3;               /* A > B */
4129       return 2;                 /* A < B */
4130     }
4131   else if (found_pos)
4132     {
4133       if (found_neg)
4134         return 1;               /* incomparable */
4135       else
4136         return 3;               /* A > B */
4137     }
4138   else
4139     /* no positives */
4140     {
4141       if (found_neg)
4142         return 2;               /* A < B */
4143       else
4144         return 0;               /* A == B */
4145     }
4146 }
4147
4148 /* Rank a function by comparing its parameter types (PARMS), to the
4149    types of an argument list (ARGS).  Return the badness vector.  This
4150    has ARGS.size() + 1 entries.  */
4151
4152 badness_vector
4153 rank_function (gdb::array_view<type *> parms,
4154                gdb::array_view<value *> args)
4155 {
4156   /* add 1 for the length-match rank.  */
4157   badness_vector bv;
4158   bv.reserve (1 + args.size ());
4159
4160   /* First compare the lengths of the supplied lists.
4161      If there is a mismatch, set it to a high value.  */
4162
4163   /* pai/1997-06-03 FIXME: when we have debug info about default
4164      arguments and ellipsis parameter lists, we should consider those
4165      and rank the length-match more finely.  */
4166
4167   bv.push_back ((args.size () != parms.size ())
4168                 ? LENGTH_MISMATCH_BADNESS
4169                 : EXACT_MATCH_BADNESS);
4170
4171   /* Now rank all the parameters of the candidate function.  */
4172   size_t min_len = std::min (parms.size (), args.size ());
4173
4174   for (size_t i = 0; i < min_len; i++)
4175     bv.push_back (rank_one_type (parms[i], value_type (args[i]),
4176                                  args[i]));
4177
4178   /* If more arguments than parameters, add dummy entries.  */
4179   for (size_t i = min_len; i < args.size (); i++)
4180     bv.push_back (TOO_FEW_PARAMS_BADNESS);
4181
4182   return bv;
4183 }
4184
4185 /* Compare the names of two integer types, assuming that any sign
4186    qualifiers have been checked already.  We do it this way because
4187    there may be an "int" in the name of one of the types.  */
4188
4189 static int
4190 integer_types_same_name_p (const char *first, const char *second)
4191 {
4192   int first_p, second_p;
4193
4194   /* If both are shorts, return 1; if neither is a short, keep
4195      checking.  */
4196   first_p = (strstr (first, "short") != NULL);
4197   second_p = (strstr (second, "short") != NULL);
4198   if (first_p && second_p)
4199     return 1;
4200   if (first_p || second_p)
4201     return 0;
4202
4203   /* Likewise for long.  */
4204   first_p = (strstr (first, "long") != NULL);
4205   second_p = (strstr (second, "long") != NULL);
4206   if (first_p && second_p)
4207     return 1;
4208   if (first_p || second_p)
4209     return 0;
4210
4211   /* Likewise for char.  */
4212   first_p = (strstr (first, "char") != NULL);
4213   second_p = (strstr (second, "char") != NULL);
4214   if (first_p && second_p)
4215     return 1;
4216   if (first_p || second_p)
4217     return 0;
4218
4219   /* They must both be ints.  */
4220   return 1;
4221 }
4222
4223 /* Compares type A to type B.  Returns true if they represent the same
4224    type, false otherwise.  */
4225
4226 bool
4227 types_equal (struct type *a, struct type *b)
4228 {
4229   /* Identical type pointers.  */
4230   /* However, this still doesn't catch all cases of same type for b
4231      and a.  The reason is that builtin types are different from
4232      the same ones constructed from the object.  */
4233   if (a == b)
4234     return true;
4235
4236   /* Resolve typedefs */
4237   if (a->code () == TYPE_CODE_TYPEDEF)
4238     a = check_typedef (a);
4239   if (b->code () == TYPE_CODE_TYPEDEF)
4240     b = check_typedef (b);
4241
4242   /* Check if identical after resolving typedefs.  */
4243   if (a == b)
4244     return true;
4245
4246   /* If after resolving typedefs a and b are not of the same type
4247      code then they are not equal.  */
4248   if (a->code () != b->code ())
4249     return false;
4250
4251   /* If a and b are both pointers types or both reference types then
4252      they are equal of the same type iff the objects they refer to are
4253      of the same type.  */
4254   if (a->code () == TYPE_CODE_PTR
4255       || a->code () == TYPE_CODE_REF)
4256     return types_equal (TYPE_TARGET_TYPE (a),
4257                         TYPE_TARGET_TYPE (b));
4258
4259   /* Well, damnit, if the names are exactly the same, I'll say they
4260      are exactly the same.  This happens when we generate method
4261      stubs.  The types won't point to the same address, but they
4262      really are the same.  */
4263
4264   if (a->name () && b->name ()
4265       && strcmp (a->name (), b->name ()) == 0)
4266     return true;
4267
4268   /* Two function types are equal if their argument and return types
4269      are equal.  */
4270   if (a->code () == TYPE_CODE_FUNC)
4271     {
4272       int i;
4273
4274       if (a->num_fields () != b->num_fields ())
4275         return false;
4276       
4277       if (!types_equal (TYPE_TARGET_TYPE (a), TYPE_TARGET_TYPE (b)))
4278         return false;
4279
4280       for (i = 0; i < a->num_fields (); ++i)
4281         if (!types_equal (a->field (i).type (), b->field (i).type ()))
4282           return false;
4283
4284       return true;
4285     }
4286
4287   return false;
4288 }
4289 \f
4290 /* Deep comparison of types.  */
4291
4292 /* An entry in the type-equality bcache.  */
4293
4294 struct type_equality_entry
4295 {
4296   type_equality_entry (struct type *t1, struct type *t2)
4297     : type1 (t1),
4298       type2 (t2)
4299   {
4300   }
4301
4302   struct type *type1, *type2;
4303 };
4304
4305 /* A helper function to compare two strings.  Returns true if they are
4306    the same, false otherwise.  Handles NULLs properly.  */
4307
4308 static bool
4309 compare_maybe_null_strings (const char *s, const char *t)
4310 {
4311   if (s == NULL || t == NULL)
4312     return s == t;
4313   return strcmp (s, t) == 0;
4314 }
4315
4316 /* A helper function for check_types_worklist that checks two types for
4317    "deep" equality.  Returns true if the types are considered the
4318    same, false otherwise.  */
4319
4320 static bool
4321 check_types_equal (struct type *type1, struct type *type2,
4322                    std::vector<type_equality_entry> *worklist)
4323 {
4324   type1 = check_typedef (type1);
4325   type2 = check_typedef (type2);
4326
4327   if (type1 == type2)
4328     return true;
4329
4330   if (type1->code () != type2->code ()
4331       || TYPE_LENGTH (type1) != TYPE_LENGTH (type2)
4332       || type1->is_unsigned () != type2->is_unsigned ()
4333       || type1->has_no_signedness () != type2->has_no_signedness ()
4334       || type1->endianity_is_not_default () != type2->endianity_is_not_default ()
4335       || type1->has_varargs () != type2->has_varargs ()
4336       || type1->is_vector () != type2->is_vector ()
4337       || TYPE_NOTTEXT (type1) != TYPE_NOTTEXT (type2)
4338       || type1->instance_flags () != type2->instance_flags ()
4339       || type1->num_fields () != type2->num_fields ())
4340     return false;
4341
4342   if (!compare_maybe_null_strings (type1->name (), type2->name ()))
4343     return false;
4344   if (!compare_maybe_null_strings (type1->name (), type2->name ()))
4345     return false;
4346
4347   if (type1->code () == TYPE_CODE_RANGE)
4348     {
4349       if (*type1->bounds () != *type2->bounds ())
4350         return false;
4351     }
4352   else
4353     {
4354       int i;
4355
4356       for (i = 0; i < type1->num_fields (); ++i)
4357         {
4358           const struct field *field1 = &type1->field (i);
4359           const struct field *field2 = &type2->field (i);
4360
4361           if (FIELD_ARTIFICIAL (*field1) != FIELD_ARTIFICIAL (*field2)
4362               || FIELD_BITSIZE (*field1) != FIELD_BITSIZE (*field2)
4363               || field1->loc_kind () != field2->loc_kind ())
4364             return false;
4365           if (!compare_maybe_null_strings (field1->name (), field2->name ()))
4366             return false;
4367           switch (field1->loc_kind ())
4368             {
4369             case FIELD_LOC_KIND_BITPOS:
4370               if (field1->loc_bitpos () != field2->loc_bitpos ())
4371                 return false;
4372               break;
4373             case FIELD_LOC_KIND_ENUMVAL:
4374               if (field1->loc_enumval () != field2->loc_enumval ())
4375                 return false;
4376               /* Don't compare types of enum fields, because they don't
4377                  have a type.  */
4378               continue;
4379             case FIELD_LOC_KIND_PHYSADDR:
4380               if (field1->loc_physaddr () != field2->loc_physaddr ())
4381                 return false;
4382               break;
4383             case FIELD_LOC_KIND_PHYSNAME:
4384               if (!compare_maybe_null_strings (field1->loc_physname (),
4385                                                field2->loc_physname ()))
4386                 return false;
4387               break;
4388             case FIELD_LOC_KIND_DWARF_BLOCK:
4389               {
4390                 struct dwarf2_locexpr_baton *block1, *block2;
4391
4392                 block1 = field1->loc_dwarf_block ();
4393                 block2 = field2->loc_dwarf_block ();
4394                 if (block1->per_cu != block2->per_cu
4395                     || block1->size != block2->size
4396                     || memcmp (block1->data, block2->data, block1->size) != 0)
4397                   return false;
4398               }
4399               break;
4400             default:
4401               internal_error (__FILE__, __LINE__, _("Unsupported field kind "
4402                                                     "%d by check_types_equal"),
4403                               field1->loc_kind ());
4404             }
4405
4406           worklist->emplace_back (field1->type (), field2->type ());
4407         }
4408     }
4409
4410   if (TYPE_TARGET_TYPE (type1) != NULL)
4411     {
4412       if (TYPE_TARGET_TYPE (type2) == NULL)
4413         return false;
4414
4415       worklist->emplace_back (TYPE_TARGET_TYPE (type1),
4416                               TYPE_TARGET_TYPE (type2));
4417     }
4418   else if (TYPE_TARGET_TYPE (type2) != NULL)
4419     return false;
4420
4421   return true;
4422 }
4423
4424 /* Check types on a worklist for equality.  Returns false if any pair
4425    is not equal, true if they are all considered equal.  */
4426
4427 static bool
4428 check_types_worklist (std::vector<type_equality_entry> *worklist,
4429                       gdb::bcache *cache)
4430 {
4431   while (!worklist->empty ())
4432     {
4433       bool added;
4434
4435       struct type_equality_entry entry = std::move (worklist->back ());
4436       worklist->pop_back ();
4437
4438       /* If the type pair has already been visited, we know it is
4439          ok.  */
4440       cache->insert (&entry, sizeof (entry), &added);
4441       if (!added)
4442         continue;
4443
4444       if (!check_types_equal (entry.type1, entry.type2, worklist))
4445         return false;
4446     }
4447
4448   return true;
4449 }
4450
4451 /* Return true if types TYPE1 and TYPE2 are equal, as determined by a
4452    "deep comparison".  Otherwise return false.  */
4453
4454 bool
4455 types_deeply_equal (struct type *type1, struct type *type2)
4456 {
4457   std::vector<type_equality_entry> worklist;
4458
4459   gdb_assert (type1 != NULL && type2 != NULL);
4460
4461   /* Early exit for the simple case.  */
4462   if (type1 == type2)
4463     return true;
4464
4465   gdb::bcache cache;
4466   worklist.emplace_back (type1, type2);
4467   return check_types_worklist (&worklist, &cache);
4468 }
4469
4470 /* Allocated status of type TYPE.  Return zero if type TYPE is allocated.
4471    Otherwise return one.  */
4472
4473 int
4474 type_not_allocated (const struct type *type)
4475 {
4476   struct dynamic_prop *prop = TYPE_ALLOCATED_PROP (type);
4477
4478   return (prop != nullptr && prop->kind () == PROP_CONST
4479           && prop->const_val () == 0);
4480 }
4481
4482 /* Associated status of type TYPE.  Return zero if type TYPE is associated.
4483    Otherwise return one.  */
4484
4485 int
4486 type_not_associated (const struct type *type)
4487 {
4488   struct dynamic_prop *prop = TYPE_ASSOCIATED_PROP (type);
4489
4490   return (prop != nullptr && prop->kind () == PROP_CONST
4491           && prop->const_val () == 0);
4492 }
4493
4494 /* rank_one_type helper for when PARM's type code is TYPE_CODE_PTR.  */
4495
4496 static struct rank
4497 rank_one_type_parm_ptr (struct type *parm, struct type *arg, struct value *value)
4498 {
4499   struct rank rank = {0,0};
4500
4501   switch (arg->code ())
4502     {
4503     case TYPE_CODE_PTR:
4504
4505       /* Allowed pointer conversions are:
4506          (a) pointer to void-pointer conversion.  */
4507       if (TYPE_TARGET_TYPE (parm)->code () == TYPE_CODE_VOID)
4508         return VOID_PTR_CONVERSION_BADNESS;
4509
4510       /* (b) pointer to ancestor-pointer conversion.  */
4511       rank.subrank = distance_to_ancestor (TYPE_TARGET_TYPE (parm),
4512                                            TYPE_TARGET_TYPE (arg),
4513                                            0);
4514       if (rank.subrank >= 0)
4515         return sum_ranks (BASE_PTR_CONVERSION_BADNESS, rank);
4516
4517       return INCOMPATIBLE_TYPE_BADNESS;
4518     case TYPE_CODE_ARRAY:
4519       {
4520         struct type *t1 = TYPE_TARGET_TYPE (parm);
4521         struct type *t2 = TYPE_TARGET_TYPE (arg);
4522
4523         if (types_equal (t1, t2))
4524           {
4525             /* Make sure they are CV equal.  */
4526             if (TYPE_CONST (t1) != TYPE_CONST (t2))
4527               rank.subrank |= CV_CONVERSION_CONST;
4528             if (TYPE_VOLATILE (t1) != TYPE_VOLATILE (t2))
4529               rank.subrank |= CV_CONVERSION_VOLATILE;
4530             if (rank.subrank != 0)
4531               return sum_ranks (CV_CONVERSION_BADNESS, rank);
4532             return EXACT_MATCH_BADNESS;
4533           }
4534         return INCOMPATIBLE_TYPE_BADNESS;
4535       }
4536     case TYPE_CODE_FUNC:
4537       return rank_one_type (TYPE_TARGET_TYPE (parm), arg, NULL);
4538     case TYPE_CODE_INT:
4539       if (value != NULL && value_type (value)->code () == TYPE_CODE_INT)
4540         {
4541           if (value_as_long (value) == 0)
4542             {
4543               /* Null pointer conversion: allow it to be cast to a pointer.
4544                  [4.10.1 of C++ standard draft n3290]  */
4545               return NULL_POINTER_CONVERSION_BADNESS;
4546             }
4547           else
4548             {
4549               /* If type checking is disabled, allow the conversion.  */
4550               if (!strict_type_checking)
4551                 return NS_INTEGER_POINTER_CONVERSION_BADNESS;
4552             }
4553         }
4554       /* fall through  */
4555     case TYPE_CODE_ENUM:
4556     case TYPE_CODE_FLAGS:
4557     case TYPE_CODE_CHAR:
4558     case TYPE_CODE_RANGE:
4559     case TYPE_CODE_BOOL:
4560     default:
4561       return INCOMPATIBLE_TYPE_BADNESS;
4562     }
4563 }
4564
4565 /* rank_one_type helper for when PARM's type code is TYPE_CODE_ARRAY.  */
4566
4567 static struct rank
4568 rank_one_type_parm_array (struct type *parm, struct type *arg, struct value *value)
4569 {
4570   switch (arg->code ())
4571     {
4572     case TYPE_CODE_PTR:
4573     case TYPE_CODE_ARRAY:
4574       return rank_one_type (TYPE_TARGET_TYPE (parm),
4575                             TYPE_TARGET_TYPE (arg), NULL);
4576     default:
4577       return INCOMPATIBLE_TYPE_BADNESS;
4578     }
4579 }
4580
4581 /* rank_one_type helper for when PARM's type code is TYPE_CODE_FUNC.  */
4582
4583 static struct rank
4584 rank_one_type_parm_func (struct type *parm, struct type *arg, struct value *value)
4585 {
4586   switch (arg->code ())
4587     {
4588     case TYPE_CODE_PTR: /* funcptr -> func */
4589       return rank_one_type (parm, TYPE_TARGET_TYPE (arg), NULL);
4590     default:
4591       return INCOMPATIBLE_TYPE_BADNESS;
4592     }
4593 }
4594
4595 /* rank_one_type helper for when PARM's type code is TYPE_CODE_INT.  */
4596
4597 static struct rank
4598 rank_one_type_parm_int (struct type *parm, struct type *arg, struct value *value)
4599 {
4600   switch (arg->code ())
4601     {
4602     case TYPE_CODE_INT:
4603       if (TYPE_LENGTH (arg) == TYPE_LENGTH (parm))
4604         {
4605           /* Deal with signed, unsigned, and plain chars and
4606              signed and unsigned ints.  */
4607           if (parm->has_no_signedness ())
4608             {
4609               /* This case only for character types.  */
4610               if (arg->has_no_signedness ())
4611                 return EXACT_MATCH_BADNESS;     /* plain char -> plain char */
4612               else              /* signed/unsigned char -> plain char */
4613                 return INTEGER_CONVERSION_BADNESS;
4614             }
4615           else if (parm->is_unsigned ())
4616             {
4617               if (arg->is_unsigned ())
4618                 {
4619                   /* unsigned int -> unsigned int, or
4620                      unsigned long -> unsigned long */
4621                   if (integer_types_same_name_p (parm->name (),
4622                                                  arg->name ()))
4623                     return EXACT_MATCH_BADNESS;
4624                   else if (integer_types_same_name_p (arg->name (),
4625                                                       "int")
4626                            && integer_types_same_name_p (parm->name (),
4627                                                          "long"))
4628                     /* unsigned int -> unsigned long */
4629                     return INTEGER_PROMOTION_BADNESS;
4630                   else
4631                     /* unsigned long -> unsigned int */
4632                     return INTEGER_CONVERSION_BADNESS;
4633                 }
4634               else
4635                 {
4636                   if (integer_types_same_name_p (arg->name (),
4637                                                  "long")
4638                       && integer_types_same_name_p (parm->name (),
4639                                                     "int"))
4640                     /* signed long -> unsigned int */
4641                     return INTEGER_CONVERSION_BADNESS;
4642                   else
4643                     /* signed int/long -> unsigned int/long */
4644                     return INTEGER_CONVERSION_BADNESS;
4645                 }
4646             }
4647           else if (!arg->has_no_signedness () && !arg->is_unsigned ())
4648             {
4649               if (integer_types_same_name_p (parm->name (),
4650                                              arg->name ()))
4651                 return EXACT_MATCH_BADNESS;
4652               else if (integer_types_same_name_p (arg->name (),
4653                                                   "int")
4654                        && integer_types_same_name_p (parm->name (),
4655                                                      "long"))
4656                 return INTEGER_PROMOTION_BADNESS;
4657               else
4658                 return INTEGER_CONVERSION_BADNESS;
4659             }
4660           else
4661             return INTEGER_CONVERSION_BADNESS;
4662         }
4663       else if (TYPE_LENGTH (arg) < TYPE_LENGTH (parm))
4664         return INTEGER_PROMOTION_BADNESS;
4665       else
4666         return INTEGER_CONVERSION_BADNESS;
4667     case TYPE_CODE_ENUM:
4668     case TYPE_CODE_FLAGS:
4669     case TYPE_CODE_CHAR:
4670     case TYPE_CODE_RANGE:
4671     case TYPE_CODE_BOOL:
4672       if (arg->is_declared_class ())
4673         return INCOMPATIBLE_TYPE_BADNESS;
4674       return INTEGER_PROMOTION_BADNESS;
4675     case TYPE_CODE_FLT:
4676       return INT_FLOAT_CONVERSION_BADNESS;
4677     case TYPE_CODE_PTR:
4678       return NS_POINTER_CONVERSION_BADNESS;
4679     default:
4680       return INCOMPATIBLE_TYPE_BADNESS;
4681     }
4682 }
4683
4684 /* rank_one_type helper for when PARM's type code is TYPE_CODE_ENUM.  */
4685
4686 static struct rank
4687 rank_one_type_parm_enum (struct type *parm, struct type *arg, struct value *value)
4688 {
4689   switch (arg->code ())
4690     {
4691     case TYPE_CODE_INT:
4692     case TYPE_CODE_CHAR:
4693     case TYPE_CODE_RANGE:
4694     case TYPE_CODE_BOOL:
4695     case TYPE_CODE_ENUM:
4696       if (parm->is_declared_class () || arg->is_declared_class ())
4697         return INCOMPATIBLE_TYPE_BADNESS;
4698       return INTEGER_CONVERSION_BADNESS;
4699     case TYPE_CODE_FLT:
4700       return INT_FLOAT_CONVERSION_BADNESS;
4701     default:
4702       return INCOMPATIBLE_TYPE_BADNESS;
4703     }
4704 }
4705
4706 /* rank_one_type helper for when PARM's type code is TYPE_CODE_CHAR.  */
4707
4708 static struct rank
4709 rank_one_type_parm_char (struct type *parm, struct type *arg, struct value *value)
4710 {
4711   switch (arg->code ())
4712     {
4713     case TYPE_CODE_RANGE:
4714     case TYPE_CODE_BOOL:
4715     case TYPE_CODE_ENUM:
4716       if (arg->is_declared_class ())
4717         return INCOMPATIBLE_TYPE_BADNESS;
4718       return INTEGER_CONVERSION_BADNESS;
4719     case TYPE_CODE_FLT:
4720       return INT_FLOAT_CONVERSION_BADNESS;
4721     case TYPE_CODE_INT:
4722       if (TYPE_LENGTH (arg) > TYPE_LENGTH (parm))
4723         return INTEGER_CONVERSION_BADNESS;
4724       else if (TYPE_LENGTH (arg) < TYPE_LENGTH (parm))
4725         return INTEGER_PROMOTION_BADNESS;
4726       /* fall through */
4727     case TYPE_CODE_CHAR:
4728       /* Deal with signed, unsigned, and plain chars for C++ and
4729          with int cases falling through from previous case.  */
4730       if (parm->has_no_signedness ())
4731         {
4732           if (arg->has_no_signedness ())
4733             return EXACT_MATCH_BADNESS;
4734           else
4735             return INTEGER_CONVERSION_BADNESS;
4736         }
4737       else if (parm->is_unsigned ())
4738         {
4739           if (arg->is_unsigned ())
4740             return EXACT_MATCH_BADNESS;
4741           else
4742             return INTEGER_PROMOTION_BADNESS;
4743         }
4744       else if (!arg->has_no_signedness () && !arg->is_unsigned ())
4745         return EXACT_MATCH_BADNESS;
4746       else
4747         return INTEGER_CONVERSION_BADNESS;
4748     default:
4749       return INCOMPATIBLE_TYPE_BADNESS;
4750     }
4751 }
4752
4753 /* rank_one_type helper for when PARM's type code is TYPE_CODE_RANGE.  */
4754
4755 static struct rank
4756 rank_one_type_parm_range (struct type *parm, struct type *arg, struct value *value)
4757 {
4758   switch (arg->code ())
4759     {
4760     case TYPE_CODE_INT:
4761     case TYPE_CODE_CHAR:
4762     case TYPE_CODE_RANGE:
4763     case TYPE_CODE_BOOL:
4764     case TYPE_CODE_ENUM:
4765       return INTEGER_CONVERSION_BADNESS;
4766     case TYPE_CODE_FLT:
4767       return INT_FLOAT_CONVERSION_BADNESS;
4768     default:
4769       return INCOMPATIBLE_TYPE_BADNESS;
4770     }
4771 }
4772
4773 /* rank_one_type helper for when PARM's type code is TYPE_CODE_BOOL.  */
4774
4775 static struct rank
4776 rank_one_type_parm_bool (struct type *parm, struct type *arg, struct value *value)
4777 {
4778   switch (arg->code ())
4779     {
4780       /* n3290 draft, section 4.12.1 (conv.bool):
4781
4782          "A prvalue of arithmetic, unscoped enumeration, pointer, or
4783          pointer to member type can be converted to a prvalue of type
4784          bool.  A zero value, null pointer value, or null member pointer
4785          value is converted to false; any other value is converted to
4786          true.  A prvalue of type std::nullptr_t can be converted to a
4787          prvalue of type bool; the resulting value is false."  */
4788     case TYPE_CODE_INT:
4789     case TYPE_CODE_CHAR:
4790     case TYPE_CODE_ENUM:
4791     case TYPE_CODE_FLT:
4792     case TYPE_CODE_MEMBERPTR:
4793     case TYPE_CODE_PTR:
4794       return BOOL_CONVERSION_BADNESS;
4795     case TYPE_CODE_RANGE:
4796       return INCOMPATIBLE_TYPE_BADNESS;
4797     case TYPE_CODE_BOOL:
4798       return EXACT_MATCH_BADNESS;
4799     default:
4800       return INCOMPATIBLE_TYPE_BADNESS;
4801     }
4802 }
4803
4804 /* rank_one_type helper for when PARM's type code is TYPE_CODE_FLOAT.  */
4805
4806 static struct rank
4807 rank_one_type_parm_float (struct type *parm, struct type *arg, struct value *value)
4808 {
4809   switch (arg->code ())
4810     {
4811     case TYPE_CODE_FLT:
4812       if (TYPE_LENGTH (arg) < TYPE_LENGTH (parm))
4813         return FLOAT_PROMOTION_BADNESS;
4814       else if (TYPE_LENGTH (arg) == TYPE_LENGTH (parm))
4815         return EXACT_MATCH_BADNESS;
4816       else
4817         return FLOAT_CONVERSION_BADNESS;
4818     case TYPE_CODE_INT:
4819     case TYPE_CODE_BOOL:
4820     case TYPE_CODE_ENUM:
4821     case TYPE_CODE_RANGE:
4822     case TYPE_CODE_CHAR:
4823       return INT_FLOAT_CONVERSION_BADNESS;
4824     default:
4825       return INCOMPATIBLE_TYPE_BADNESS;
4826     }
4827 }
4828
4829 /* rank_one_type helper for when PARM's type code is TYPE_CODE_COMPLEX.  */
4830
4831 static struct rank
4832 rank_one_type_parm_complex (struct type *parm, struct type *arg, struct value *value)
4833 {
4834   switch (arg->code ())
4835     {           /* Strictly not needed for C++, but...  */
4836     case TYPE_CODE_FLT:
4837       return FLOAT_PROMOTION_BADNESS;
4838     case TYPE_CODE_COMPLEX:
4839       return EXACT_MATCH_BADNESS;
4840     default:
4841       return INCOMPATIBLE_TYPE_BADNESS;
4842     }
4843 }
4844
4845 /* rank_one_type helper for when PARM's type code is TYPE_CODE_STRUCT.  */
4846
4847 static struct rank
4848 rank_one_type_parm_struct (struct type *parm, struct type *arg, struct value *value)
4849 {
4850   struct rank rank = {0, 0};
4851
4852   switch (arg->code ())
4853     {
4854     case TYPE_CODE_STRUCT:
4855       /* Check for derivation */
4856       rank.subrank = distance_to_ancestor (parm, arg, 0);
4857       if (rank.subrank >= 0)
4858         return sum_ranks (BASE_CONVERSION_BADNESS, rank);
4859       /* fall through */
4860     default:
4861       return INCOMPATIBLE_TYPE_BADNESS;
4862     }
4863 }
4864
4865 /* rank_one_type helper for when PARM's type code is TYPE_CODE_SET.  */
4866
4867 static struct rank
4868 rank_one_type_parm_set (struct type *parm, struct type *arg, struct value *value)
4869 {
4870   switch (arg->code ())
4871     {
4872       /* Not in C++ */
4873     case TYPE_CODE_SET:
4874       return rank_one_type (parm->field (0).type (),
4875                             arg->field (0).type (), NULL);
4876     default:
4877       return INCOMPATIBLE_TYPE_BADNESS;
4878     }
4879 }
4880
4881 /* Compare one type (PARM) for compatibility with another (ARG).
4882  * PARM is intended to be the parameter type of a function; and
4883  * ARG is the supplied argument's type.  This function tests if
4884  * the latter can be converted to the former.
4885  * VALUE is the argument's value or NULL if none (or called recursively)
4886  *
4887  * Return 0 if they are identical types;
4888  * Otherwise, return an integer which corresponds to how compatible
4889  * PARM is to ARG.  The higher the return value, the worse the match.
4890  * Generally the "bad" conversions are all uniformly assigned
4891  * INVALID_CONVERSION.  */
4892
4893 struct rank
4894 rank_one_type (struct type *parm, struct type *arg, struct value *value)
4895 {
4896   struct rank rank = {0,0};
4897
4898   /* Resolve typedefs */
4899   if (parm->code () == TYPE_CODE_TYPEDEF)
4900     parm = check_typedef (parm);
4901   if (arg->code () == TYPE_CODE_TYPEDEF)
4902     arg = check_typedef (arg);
4903
4904   if (TYPE_IS_REFERENCE (parm) && value != NULL)
4905     {
4906       if (VALUE_LVAL (value) == not_lval)
4907         {
4908           /* Rvalues should preferably bind to rvalue references or const
4909              lvalue references.  */
4910           if (parm->code () == TYPE_CODE_RVALUE_REF)
4911             rank.subrank = REFERENCE_CONVERSION_RVALUE;
4912           else if (TYPE_CONST (TYPE_TARGET_TYPE (parm)))
4913             rank.subrank = REFERENCE_CONVERSION_CONST_LVALUE;
4914           else
4915             return INCOMPATIBLE_TYPE_BADNESS;
4916           return sum_ranks (rank, REFERENCE_CONVERSION_BADNESS);
4917         }
4918       else
4919         {
4920           /* It's illegal to pass an lvalue as an rvalue.  */
4921           if (parm->code () == TYPE_CODE_RVALUE_REF)
4922             return INCOMPATIBLE_TYPE_BADNESS;
4923         }
4924     }
4925
4926   if (types_equal (parm, arg))
4927     {
4928       struct type *t1 = parm;
4929       struct type *t2 = arg;
4930
4931       /* For pointers and references, compare target type.  */
4932       if (parm->is_pointer_or_reference ())
4933         {
4934           t1 = TYPE_TARGET_TYPE (parm);
4935           t2 = TYPE_TARGET_TYPE (arg);
4936         }
4937
4938       /* Make sure they are CV equal, too.  */
4939       if (TYPE_CONST (t1) != TYPE_CONST (t2))
4940         rank.subrank |= CV_CONVERSION_CONST;
4941       if (TYPE_VOLATILE (t1) != TYPE_VOLATILE (t2))
4942         rank.subrank |= CV_CONVERSION_VOLATILE;
4943       if (rank.subrank != 0)
4944         return sum_ranks (CV_CONVERSION_BADNESS, rank);
4945       return EXACT_MATCH_BADNESS;
4946     }
4947
4948   /* See through references, since we can almost make non-references
4949      references.  */
4950
4951   if (TYPE_IS_REFERENCE (arg))
4952     return (sum_ranks (rank_one_type (parm, TYPE_TARGET_TYPE (arg), NULL),
4953                        REFERENCE_SEE_THROUGH_BADNESS));
4954   if (TYPE_IS_REFERENCE (parm))
4955     return (sum_ranks (rank_one_type (TYPE_TARGET_TYPE (parm), arg, NULL),
4956                        REFERENCE_SEE_THROUGH_BADNESS));
4957   if (overload_debug)
4958     {
4959       /* Debugging only.  */
4960       gdb_printf (gdb_stderr,
4961                   "------ Arg is %s [%d], parm is %s [%d]\n",
4962                   arg->name (), arg->code (),
4963                   parm->name (), parm->code ());
4964     }
4965
4966   /* x -> y means arg of type x being supplied for parameter of type y.  */
4967
4968   switch (parm->code ())
4969     {
4970     case TYPE_CODE_PTR:
4971       return rank_one_type_parm_ptr (parm, arg, value);
4972     case TYPE_CODE_ARRAY:
4973       return rank_one_type_parm_array (parm, arg, value);
4974     case TYPE_CODE_FUNC:
4975       return rank_one_type_parm_func (parm, arg, value);
4976     case TYPE_CODE_INT:
4977       return rank_one_type_parm_int (parm, arg, value);
4978     case TYPE_CODE_ENUM:
4979       return rank_one_type_parm_enum (parm, arg, value);
4980     case TYPE_CODE_CHAR:
4981       return rank_one_type_parm_char (parm, arg, value);
4982     case TYPE_CODE_RANGE:
4983       return rank_one_type_parm_range (parm, arg, value);
4984     case TYPE_CODE_BOOL:
4985       return rank_one_type_parm_bool (parm, arg, value);
4986     case TYPE_CODE_FLT:
4987       return rank_one_type_parm_float (parm, arg, value);
4988     case TYPE_CODE_COMPLEX:
4989       return rank_one_type_parm_complex (parm, arg, value);
4990     case TYPE_CODE_STRUCT:
4991       return rank_one_type_parm_struct (parm, arg, value);
4992     case TYPE_CODE_SET:
4993       return rank_one_type_parm_set (parm, arg, value);
4994     default:
4995       return INCOMPATIBLE_TYPE_BADNESS;
4996     }                           /* switch (arg->code ()) */
4997 }
4998
4999 /* End of functions for overload resolution.  */
5000 \f
5001 /* Routines to pretty-print types.  */
5002
5003 static void
5004 print_bit_vector (B_TYPE *bits, int nbits)
5005 {
5006   int bitno;
5007
5008   for (bitno = 0; bitno < nbits; bitno++)
5009     {
5010       if ((bitno % 8) == 0)
5011         {
5012           gdb_puts (" ");
5013         }
5014       if (B_TST (bits, bitno))
5015         gdb_printf (("1"));
5016       else
5017         gdb_printf (("0"));
5018     }
5019 }
5020
5021 /* Note the first arg should be the "this" pointer, we may not want to
5022    include it since we may get into a infinitely recursive
5023    situation.  */
5024
5025 static void
5026 print_args (struct field *args, int nargs, int spaces)
5027 {
5028   if (args != NULL)
5029     {
5030       int i;
5031
5032       for (i = 0; i < nargs; i++)
5033         {
5034           gdb_printf
5035             ("%*s[%d] name '%s'\n", spaces, "", i,
5036              args[i].name () != NULL ? args[i].name () : "<NULL>");
5037           recursive_dump_type (args[i].type (), spaces + 2);
5038         }
5039     }
5040 }
5041
5042 int
5043 field_is_static (struct field *f)
5044 {
5045   /* "static" fields are the fields whose location is not relative
5046      to the address of the enclosing struct.  It would be nice to
5047      have a dedicated flag that would be set for static fields when
5048      the type is being created.  But in practice, checking the field
5049      loc_kind should give us an accurate answer.  */
5050   return (f->loc_kind () == FIELD_LOC_KIND_PHYSNAME
5051           || f->loc_kind () == FIELD_LOC_KIND_PHYSADDR);
5052 }
5053
5054 static void
5055 dump_fn_fieldlists (struct type *type, int spaces)
5056 {
5057   int method_idx;
5058   int overload_idx;
5059   struct fn_field *f;
5060
5061   gdb_printf ("%*sfn_fieldlists %s\n", spaces, "",
5062               host_address_to_string (TYPE_FN_FIELDLISTS (type)));
5063   for (method_idx = 0; method_idx < TYPE_NFN_FIELDS (type); method_idx++)
5064     {
5065       f = TYPE_FN_FIELDLIST1 (type, method_idx);
5066       gdb_printf
5067         ("%*s[%d] name '%s' (%s) length %d\n", spaces + 2, "",
5068          method_idx,
5069          TYPE_FN_FIELDLIST_NAME (type, method_idx),
5070          host_address_to_string (TYPE_FN_FIELDLIST_NAME (type, method_idx)),
5071          TYPE_FN_FIELDLIST_LENGTH (type, method_idx));
5072       for (overload_idx = 0;
5073            overload_idx < TYPE_FN_FIELDLIST_LENGTH (type, method_idx);
5074            overload_idx++)
5075         {
5076           gdb_printf
5077             ("%*s[%d] physname '%s' (%s)\n",
5078              spaces + 4, "", overload_idx,
5079              TYPE_FN_FIELD_PHYSNAME (f, overload_idx),
5080              host_address_to_string (TYPE_FN_FIELD_PHYSNAME (f,
5081                                                              overload_idx)));
5082           gdb_printf
5083             ("%*stype %s\n", spaces + 8, "",
5084              host_address_to_string (TYPE_FN_FIELD_TYPE (f, overload_idx)));
5085
5086           recursive_dump_type (TYPE_FN_FIELD_TYPE (f, overload_idx),
5087                                spaces + 8 + 2);
5088
5089           gdb_printf
5090             ("%*sargs %s\n", spaces + 8, "",
5091              host_address_to_string (TYPE_FN_FIELD_ARGS (f, overload_idx)));
5092           print_args (TYPE_FN_FIELD_ARGS (f, overload_idx),
5093                       TYPE_FN_FIELD_TYPE (f, overload_idx)->num_fields (),
5094                       spaces + 8 + 2);
5095           gdb_printf
5096             ("%*sfcontext %s\n", spaces + 8, "",
5097              host_address_to_string (TYPE_FN_FIELD_FCONTEXT (f,
5098                                                              overload_idx)));
5099
5100           gdb_printf ("%*sis_const %d\n", spaces + 8, "",
5101                       TYPE_FN_FIELD_CONST (f, overload_idx));
5102           gdb_printf ("%*sis_volatile %d\n", spaces + 8, "",
5103                       TYPE_FN_FIELD_VOLATILE (f, overload_idx));
5104           gdb_printf ("%*sis_private %d\n", spaces + 8, "",
5105                       TYPE_FN_FIELD_PRIVATE (f, overload_idx));
5106           gdb_printf ("%*sis_protected %d\n", spaces + 8, "",
5107                       TYPE_FN_FIELD_PROTECTED (f, overload_idx));
5108           gdb_printf ("%*sis_stub %d\n", spaces + 8, "",
5109                       TYPE_FN_FIELD_STUB (f, overload_idx));
5110           gdb_printf ("%*sdefaulted %d\n", spaces + 8, "",
5111                       TYPE_FN_FIELD_DEFAULTED (f, overload_idx));
5112           gdb_printf ("%*sis_deleted %d\n", spaces + 8, "",
5113                       TYPE_FN_FIELD_DELETED (f, overload_idx));
5114           gdb_printf ("%*svoffset %u\n", spaces + 8, "",
5115                       TYPE_FN_FIELD_VOFFSET (f, overload_idx));
5116         }
5117     }
5118 }
5119
5120 static void
5121 print_cplus_stuff (struct type *type, int spaces)
5122 {
5123   gdb_printf ("%*svptr_fieldno %d\n", spaces, "",
5124               TYPE_VPTR_FIELDNO (type));
5125   gdb_printf ("%*svptr_basetype %s\n", spaces, "",
5126               host_address_to_string (TYPE_VPTR_BASETYPE (type)));
5127   if (TYPE_VPTR_BASETYPE (type) != NULL)
5128     recursive_dump_type (TYPE_VPTR_BASETYPE (type), spaces + 2);
5129
5130   gdb_printf ("%*sn_baseclasses %d\n", spaces, "",
5131               TYPE_N_BASECLASSES (type));
5132   gdb_printf ("%*snfn_fields %d\n", spaces, "",
5133               TYPE_NFN_FIELDS (type));
5134   if (TYPE_N_BASECLASSES (type) > 0)
5135     {
5136       gdb_printf
5137         ("%*svirtual_field_bits (%d bits at *%s)",
5138          spaces, "", TYPE_N_BASECLASSES (type),
5139          host_address_to_string (TYPE_FIELD_VIRTUAL_BITS (type)));
5140
5141       print_bit_vector (TYPE_FIELD_VIRTUAL_BITS (type),
5142                         TYPE_N_BASECLASSES (type));
5143       gdb_puts ("\n");
5144     }
5145   if (type->num_fields () > 0)
5146     {
5147       if (TYPE_FIELD_PRIVATE_BITS (type) != NULL)
5148         {
5149           gdb_printf
5150             ("%*sprivate_field_bits (%d bits at *%s)",
5151              spaces, "", type->num_fields (),
5152              host_address_to_string (TYPE_FIELD_PRIVATE_BITS (type)));
5153           print_bit_vector (TYPE_FIELD_PRIVATE_BITS (type),
5154                             type->num_fields ());
5155           gdb_puts ("\n");
5156         }
5157       if (TYPE_FIELD_PROTECTED_BITS (type) != NULL)
5158         {
5159           gdb_printf
5160             ("%*sprotected_field_bits (%d bits at *%s",
5161              spaces, "", type->num_fields (),
5162              host_address_to_string (TYPE_FIELD_PROTECTED_BITS (type)));
5163           print_bit_vector (TYPE_FIELD_PROTECTED_BITS (type),
5164                             type->num_fields ());
5165           gdb_puts ("\n");
5166         }
5167     }
5168   if (TYPE_NFN_FIELDS (type) > 0)
5169     {
5170       dump_fn_fieldlists (type, spaces);
5171     }
5172
5173   gdb_printf ("%*scalling_convention %d\n", spaces, "",
5174               TYPE_CPLUS_CALLING_CONVENTION (type));
5175 }
5176
5177 /* Print the contents of the TYPE's type_specific union, assuming that
5178    its type-specific kind is TYPE_SPECIFIC_GNAT_STUFF.  */
5179
5180 static void
5181 print_gnat_stuff (struct type *type, int spaces)
5182 {
5183   struct type *descriptive_type = TYPE_DESCRIPTIVE_TYPE (type);
5184
5185   if (descriptive_type == NULL)
5186     gdb_printf ("%*sno descriptive type\n", spaces + 2, "");
5187   else
5188     {
5189       gdb_printf ("%*sdescriptive type\n", spaces + 2, "");
5190       recursive_dump_type (descriptive_type, spaces + 4);
5191     }
5192 }
5193
5194 /* Print the contents of the TYPE's type_specific union, assuming that
5195    its type-specific kind is TYPE_SPECIFIC_FIXED_POINT.  */
5196
5197 static void
5198 print_fixed_point_type_info (struct type *type, int spaces)
5199 {
5200   gdb_printf ("%*sscaling factor: %s\n", spaces + 2, "",
5201               type->fixed_point_scaling_factor ().str ().c_str ());
5202 }
5203
5204 static struct obstack dont_print_type_obstack;
5205
5206 /* Print the dynamic_prop PROP.  */
5207
5208 static void
5209 dump_dynamic_prop (dynamic_prop const& prop)
5210 {
5211   switch (prop.kind ())
5212     {
5213     case PROP_CONST:
5214       gdb_printf ("%s", plongest (prop.const_val ()));
5215       break;
5216     case PROP_UNDEFINED:
5217       gdb_printf ("(undefined)");
5218       break;
5219     case PROP_LOCEXPR:
5220     case PROP_LOCLIST:
5221       gdb_printf ("(dynamic)");
5222       break;
5223     default:
5224       gdb_assert_not_reached ("unhandled prop kind");
5225       break;
5226     }
5227 }
5228
5229 void
5230 recursive_dump_type (struct type *type, int spaces)
5231 {
5232   int idx;
5233
5234   if (spaces == 0)
5235     obstack_begin (&dont_print_type_obstack, 0);
5236
5237   if (type->num_fields () > 0
5238       || (HAVE_CPLUS_STRUCT (type) && TYPE_NFN_FIELDS (type) > 0))
5239     {
5240       struct type **first_dont_print
5241         = (struct type **) obstack_base (&dont_print_type_obstack);
5242
5243       int i = (struct type **) 
5244         obstack_next_free (&dont_print_type_obstack) - first_dont_print;
5245
5246       while (--i >= 0)
5247         {
5248           if (type == first_dont_print[i])
5249             {
5250               gdb_printf ("%*stype node %s", spaces, "",
5251                           host_address_to_string (type));
5252               gdb_printf (_(" <same as already seen type>\n"));
5253               return;
5254             }
5255         }
5256
5257       obstack_ptr_grow (&dont_print_type_obstack, type);
5258     }
5259
5260   gdb_printf ("%*stype node %s\n", spaces, "",
5261               host_address_to_string (type));
5262   gdb_printf ("%*sname '%s' (%s)\n", spaces, "",
5263               type->name () ? type->name () : "<NULL>",
5264               host_address_to_string (type->name ()));
5265   gdb_printf ("%*scode 0x%x ", spaces, "", type->code ());
5266   switch (type->code ())
5267     {
5268     case TYPE_CODE_UNDEF:
5269       gdb_printf ("(TYPE_CODE_UNDEF)");
5270       break;
5271     case TYPE_CODE_PTR:
5272       gdb_printf ("(TYPE_CODE_PTR)");
5273       break;
5274     case TYPE_CODE_ARRAY:
5275       gdb_printf ("(TYPE_CODE_ARRAY)");
5276       break;
5277     case TYPE_CODE_STRUCT:
5278       gdb_printf ("(TYPE_CODE_STRUCT)");
5279       break;
5280     case TYPE_CODE_UNION:
5281       gdb_printf ("(TYPE_CODE_UNION)");
5282       break;
5283     case TYPE_CODE_ENUM:
5284       gdb_printf ("(TYPE_CODE_ENUM)");
5285       break;
5286     case TYPE_CODE_FLAGS:
5287       gdb_printf ("(TYPE_CODE_FLAGS)");
5288       break;
5289     case TYPE_CODE_FUNC:
5290       gdb_printf ("(TYPE_CODE_FUNC)");
5291       break;
5292     case TYPE_CODE_INT:
5293       gdb_printf ("(TYPE_CODE_INT)");
5294       break;
5295     case TYPE_CODE_FLT:
5296       gdb_printf ("(TYPE_CODE_FLT)");
5297       break;
5298     case TYPE_CODE_VOID:
5299       gdb_printf ("(TYPE_CODE_VOID)");
5300       break;
5301     case TYPE_CODE_SET:
5302       gdb_printf ("(TYPE_CODE_SET)");
5303       break;
5304     case TYPE_CODE_RANGE:
5305       gdb_printf ("(TYPE_CODE_RANGE)");
5306       break;
5307     case TYPE_CODE_STRING:
5308       gdb_printf ("(TYPE_CODE_STRING)");
5309       break;
5310     case TYPE_CODE_ERROR:
5311       gdb_printf ("(TYPE_CODE_ERROR)");
5312       break;
5313     case TYPE_CODE_MEMBERPTR:
5314       gdb_printf ("(TYPE_CODE_MEMBERPTR)");
5315       break;
5316     case TYPE_CODE_METHODPTR:
5317       gdb_printf ("(TYPE_CODE_METHODPTR)");
5318       break;
5319     case TYPE_CODE_METHOD:
5320       gdb_printf ("(TYPE_CODE_METHOD)");
5321       break;
5322     case TYPE_CODE_REF:
5323       gdb_printf ("(TYPE_CODE_REF)");
5324       break;
5325     case TYPE_CODE_CHAR:
5326       gdb_printf ("(TYPE_CODE_CHAR)");
5327       break;
5328     case TYPE_CODE_BOOL:
5329       gdb_printf ("(TYPE_CODE_BOOL)");
5330       break;
5331     case TYPE_CODE_COMPLEX:
5332       gdb_printf ("(TYPE_CODE_COMPLEX)");
5333       break;
5334     case TYPE_CODE_TYPEDEF:
5335       gdb_printf ("(TYPE_CODE_TYPEDEF)");
5336       break;
5337     case TYPE_CODE_NAMESPACE:
5338       gdb_printf ("(TYPE_CODE_NAMESPACE)");
5339       break;
5340     case TYPE_CODE_FIXED_POINT:
5341       gdb_printf ("(TYPE_CODE_FIXED_POINT)");
5342       break;
5343     default:
5344       gdb_printf ("(UNKNOWN TYPE CODE)");
5345       break;
5346     }
5347   gdb_puts ("\n");
5348   gdb_printf ("%*slength %s\n", spaces, "",
5349               pulongest (TYPE_LENGTH (type)));
5350   if (type->is_objfile_owned ())
5351     gdb_printf ("%*sobjfile %s\n", spaces, "",
5352                 host_address_to_string (type->objfile_owner ()));
5353   else
5354     gdb_printf ("%*sgdbarch %s\n", spaces, "",
5355                 host_address_to_string (type->arch_owner ()));
5356   gdb_printf ("%*starget_type %s\n", spaces, "",
5357               host_address_to_string (TYPE_TARGET_TYPE (type)));
5358   if (TYPE_TARGET_TYPE (type) != NULL)
5359     {
5360       recursive_dump_type (TYPE_TARGET_TYPE (type), spaces + 2);
5361     }
5362   gdb_printf ("%*spointer_type %s\n", spaces, "",
5363               host_address_to_string (TYPE_POINTER_TYPE (type)));
5364   gdb_printf ("%*sreference_type %s\n", spaces, "",
5365               host_address_to_string (TYPE_REFERENCE_TYPE (type)));
5366   gdb_printf ("%*stype_chain %s\n", spaces, "",
5367               host_address_to_string (TYPE_CHAIN (type)));
5368   gdb_printf ("%*sinstance_flags 0x%x", spaces, "", 
5369               (unsigned) type->instance_flags ());
5370   if (TYPE_CONST (type))
5371     {
5372       gdb_puts (" TYPE_CONST");
5373     }
5374   if (TYPE_VOLATILE (type))
5375     {
5376       gdb_puts (" TYPE_VOLATILE");
5377     }
5378   if (TYPE_CODE_SPACE (type))
5379     {
5380       gdb_puts (" TYPE_CODE_SPACE");
5381     }
5382   if (TYPE_DATA_SPACE (type))
5383     {
5384       gdb_puts (" TYPE_DATA_SPACE");
5385     }
5386   if (TYPE_ADDRESS_CLASS_1 (type))
5387     {
5388       gdb_puts (" TYPE_ADDRESS_CLASS_1");
5389     }
5390   if (TYPE_ADDRESS_CLASS_2 (type))
5391     {
5392       gdb_puts (" TYPE_ADDRESS_CLASS_2");
5393     }
5394   if (TYPE_RESTRICT (type))
5395     {
5396       gdb_puts (" TYPE_RESTRICT");
5397     }
5398   if (TYPE_ATOMIC (type))
5399     {
5400       gdb_puts (" TYPE_ATOMIC");
5401     }
5402   gdb_puts ("\n");
5403
5404   gdb_printf ("%*sflags", spaces, "");
5405   if (type->is_unsigned ())
5406     {
5407       gdb_puts (" TYPE_UNSIGNED");
5408     }
5409   if (type->has_no_signedness ())
5410     {
5411       gdb_puts (" TYPE_NOSIGN");
5412     }
5413   if (type->endianity_is_not_default ())
5414     {
5415       gdb_puts (" TYPE_ENDIANITY_NOT_DEFAULT");
5416     }
5417   if (type->is_stub ())
5418     {
5419       gdb_puts (" TYPE_STUB");
5420     }
5421   if (type->target_is_stub ())
5422     {
5423       gdb_puts (" TYPE_TARGET_STUB");
5424     }
5425   if (type->is_prototyped ())
5426     {
5427       gdb_puts (" TYPE_PROTOTYPED");
5428     }
5429   if (type->has_varargs ())
5430     {
5431       gdb_puts (" TYPE_VARARGS");
5432     }
5433   /* This is used for things like AltiVec registers on ppc.  Gcc emits
5434      an attribute for the array type, which tells whether or not we
5435      have a vector, instead of a regular array.  */
5436   if (type->is_vector ())
5437     {
5438       gdb_puts (" TYPE_VECTOR");
5439     }
5440   if (type->is_fixed_instance ())
5441     {
5442       gdb_puts (" TYPE_FIXED_INSTANCE");
5443     }
5444   if (type->stub_is_supported ())
5445     {
5446       gdb_puts (" TYPE_STUB_SUPPORTED");
5447     }
5448   if (TYPE_NOTTEXT (type))
5449     {
5450       gdb_puts (" TYPE_NOTTEXT");
5451     }
5452   gdb_puts ("\n");
5453   gdb_printf ("%*snfields %d ", spaces, "", type->num_fields ());
5454   if (TYPE_ASSOCIATED_PROP (type) != nullptr
5455       || TYPE_ALLOCATED_PROP (type) != nullptr)
5456     {
5457       gdb_printf ("%*s", spaces, "");
5458       if (TYPE_ASSOCIATED_PROP (type) != nullptr)
5459         {
5460           gdb_printf ("associated ");
5461           dump_dynamic_prop (*TYPE_ASSOCIATED_PROP (type));
5462         }
5463       if (TYPE_ALLOCATED_PROP (type) != nullptr)
5464         {
5465           if (TYPE_ASSOCIATED_PROP (type) != nullptr)
5466             gdb_printf ("  ");
5467           gdb_printf ("allocated ");
5468           dump_dynamic_prop (*TYPE_ALLOCATED_PROP (type));
5469         }
5470       gdb_printf ("\n");
5471     }
5472   gdb_printf ("%s\n", host_address_to_string (type->fields ()));
5473   for (idx = 0; idx < type->num_fields (); idx++)
5474     {
5475       if (type->code () == TYPE_CODE_ENUM)
5476         gdb_printf ("%*s[%d] enumval %s type ", spaces + 2, "",
5477                     idx, plongest (type->field (idx).loc_enumval ()));
5478       else
5479         gdb_printf ("%*s[%d] bitpos %s bitsize %d type ", spaces + 2, "",
5480                     idx, plongest (type->field (idx).loc_bitpos ()),
5481                     TYPE_FIELD_BITSIZE (type, idx));
5482       gdb_printf ("%s name '%s' (%s)\n",
5483                   host_address_to_string (type->field (idx).type ()),
5484                   type->field (idx).name () != NULL
5485                   ? type->field (idx).name ()
5486                   : "<NULL>",
5487                   host_address_to_string (type->field (idx).name ()));
5488       if (type->field (idx).type () != NULL)
5489         {
5490           recursive_dump_type (type->field (idx).type (), spaces + 4);
5491         }
5492     }
5493   if (type->code () == TYPE_CODE_RANGE)
5494     {
5495       gdb_printf ("%*slow ", spaces, "");
5496       dump_dynamic_prop (type->bounds ()->low);
5497       gdb_printf ("  high ");
5498       dump_dynamic_prop (type->bounds ()->high);
5499       gdb_printf ("\n");
5500     }
5501
5502   switch (TYPE_SPECIFIC_FIELD (type))
5503     {
5504       case TYPE_SPECIFIC_CPLUS_STUFF:
5505         gdb_printf ("%*scplus_stuff %s\n", spaces, "",
5506                     host_address_to_string (TYPE_CPLUS_SPECIFIC (type)));
5507         print_cplus_stuff (type, spaces);
5508         break;
5509
5510       case TYPE_SPECIFIC_GNAT_STUFF:
5511         gdb_printf ("%*sgnat_stuff %s\n", spaces, "",
5512                     host_address_to_string (TYPE_GNAT_SPECIFIC (type)));
5513         print_gnat_stuff (type, spaces);
5514         break;
5515
5516       case TYPE_SPECIFIC_FLOATFORMAT:
5517         gdb_printf ("%*sfloatformat ", spaces, "");
5518         if (TYPE_FLOATFORMAT (type) == NULL
5519             || TYPE_FLOATFORMAT (type)->name == NULL)
5520           gdb_puts ("(null)");
5521         else
5522           gdb_puts (TYPE_FLOATFORMAT (type)->name);
5523         gdb_puts ("\n");
5524         break;
5525
5526       case TYPE_SPECIFIC_FUNC:
5527         gdb_printf ("%*scalling_convention %d\n", spaces, "",
5528                     TYPE_CALLING_CONVENTION (type));
5529         /* tail_call_list is not printed.  */
5530         break;
5531
5532       case TYPE_SPECIFIC_SELF_TYPE:
5533         gdb_printf ("%*sself_type %s\n", spaces, "",
5534                     host_address_to_string (TYPE_SELF_TYPE (type)));
5535         break;
5536
5537       case TYPE_SPECIFIC_FIXED_POINT:
5538         gdb_printf ("%*sfixed_point_info ", spaces, "");
5539         print_fixed_point_type_info (type, spaces);
5540         gdb_puts ("\n");
5541         break;
5542
5543     case TYPE_SPECIFIC_INT:
5544       if (type->bit_size_differs_p ())
5545         {
5546           unsigned bit_size = type->bit_size ();
5547           unsigned bit_off = type->bit_offset ();
5548           gdb_printf ("%*s bit size = %u, bit offset = %u\n", spaces, "",
5549                       bit_size, bit_off);
5550         }
5551       break;
5552     }
5553
5554   if (spaces == 0)
5555     obstack_free (&dont_print_type_obstack, NULL);
5556 }
5557 \f
5558 /* Trivial helpers for the libiberty hash table, for mapping one
5559    type to another.  */
5560
5561 struct type_pair
5562 {
5563   type_pair (struct type *old_, struct type *newobj_)
5564     : old (old_), newobj (newobj_)
5565   {}
5566
5567   struct type * const old, * const newobj;
5568 };
5569
5570 static hashval_t
5571 type_pair_hash (const void *item)
5572 {
5573   const struct type_pair *pair = (const struct type_pair *) item;
5574
5575   return htab_hash_pointer (pair->old);
5576 }
5577
5578 static int
5579 type_pair_eq (const void *item_lhs, const void *item_rhs)
5580 {
5581   const struct type_pair *lhs = (const struct type_pair *) item_lhs;
5582   const struct type_pair *rhs = (const struct type_pair *) item_rhs;
5583
5584   return lhs->old == rhs->old;
5585 }
5586
5587 /* Allocate the hash table used by copy_type_recursive to walk
5588    types without duplicates.  */
5589
5590 htab_up
5591 create_copied_types_hash ()
5592 {
5593   return htab_up (htab_create_alloc (1, type_pair_hash, type_pair_eq,
5594                                      htab_delete_entry<type_pair>,
5595                                      xcalloc, xfree));
5596 }
5597
5598 /* Recursively copy (deep copy) a dynamic attribute list of a type.  */
5599
5600 static struct dynamic_prop_list *
5601 copy_dynamic_prop_list (struct obstack *storage,
5602                         struct dynamic_prop_list *list)
5603 {
5604   struct dynamic_prop_list *copy = list;
5605   struct dynamic_prop_list **node_ptr = &copy;
5606
5607   while (*node_ptr != NULL)
5608     {
5609       struct dynamic_prop_list *node_copy;
5610
5611       node_copy = ((struct dynamic_prop_list *)
5612                    obstack_copy (storage, *node_ptr,
5613                                  sizeof (struct dynamic_prop_list)));
5614       node_copy->prop = (*node_ptr)->prop;
5615       *node_ptr = node_copy;
5616
5617       node_ptr = &node_copy->next;
5618     }
5619
5620   return copy;
5621 }
5622
5623 /* Recursively copy (deep copy) TYPE, if it is associated with
5624    OBJFILE.  Return a new type owned by the gdbarch associated with the type, a
5625    saved type if we have already visited TYPE (using COPIED_TYPES), or TYPE if
5626    it is not associated with OBJFILE.  */
5627
5628 struct type *
5629 copy_type_recursive (struct type *type, htab_t copied_types)
5630 {
5631   void **slot;
5632   struct type *new_type;
5633
5634   if (!type->is_objfile_owned ())
5635     return type;
5636
5637   struct type_pair pair (type, nullptr);
5638
5639   slot = htab_find_slot (copied_types, &pair, INSERT);
5640   if (*slot != NULL)
5641     return ((struct type_pair *) *slot)->newobj;
5642
5643   new_type = alloc_type_arch (type->arch ());
5644
5645   /* We must add the new type to the hash table immediately, in case
5646      we encounter this type again during a recursive call below.  */
5647   struct type_pair *stored = new type_pair (type, new_type);
5648
5649   *slot = stored;
5650
5651   /* Copy the common fields of types.  For the main type, we simply
5652      copy the entire thing and then update specific fields as needed.  */
5653   *TYPE_MAIN_TYPE (new_type) = *TYPE_MAIN_TYPE (type);
5654
5655   new_type->set_owner (type->arch ());
5656
5657   if (type->name ())
5658     new_type->set_name (xstrdup (type->name ()));
5659
5660   new_type->set_instance_flags (type->instance_flags ());
5661   TYPE_LENGTH (new_type) = TYPE_LENGTH (type);
5662
5663   /* Copy the fields.  */
5664   if (type->num_fields ())
5665     {
5666       int i, nfields;
5667
5668       nfields = type->num_fields ();
5669       new_type->set_fields
5670         ((struct field *)
5671          TYPE_ZALLOC (new_type, nfields * sizeof (struct field)));
5672
5673       for (i = 0; i < nfields; i++)
5674         {
5675           TYPE_FIELD_ARTIFICIAL (new_type, i) = 
5676             TYPE_FIELD_ARTIFICIAL (type, i);
5677           TYPE_FIELD_BITSIZE (new_type, i) = TYPE_FIELD_BITSIZE (type, i);
5678           if (type->field (i).type ())
5679             new_type->field (i).set_type
5680               (copy_type_recursive (type->field (i).type (), copied_types));
5681           if (type->field (i).name ())
5682             new_type->field (i).set_name (xstrdup (type->field (i).name ()));
5683
5684           switch (type->field (i).loc_kind ())
5685             {
5686             case FIELD_LOC_KIND_BITPOS:
5687               new_type->field (i).set_loc_bitpos (type->field (i).loc_bitpos ());
5688               break;
5689             case FIELD_LOC_KIND_ENUMVAL:
5690               new_type->field (i).set_loc_enumval (type->field (i).loc_enumval ());
5691               break;
5692             case FIELD_LOC_KIND_PHYSADDR:
5693               new_type->field (i).set_loc_physaddr
5694                 (type->field (i).loc_physaddr ());
5695               break;
5696             case FIELD_LOC_KIND_PHYSNAME:
5697               new_type->field (i).set_loc_physname
5698                 (xstrdup (type->field (i).loc_physname ()));
5699               break;
5700             case FIELD_LOC_KIND_DWARF_BLOCK:
5701               new_type->field (i).set_loc_dwarf_block
5702                 (type->field (i).loc_dwarf_block ());
5703               break;
5704             default:
5705               internal_error (__FILE__, __LINE__,
5706                               _("Unexpected type field location kind: %d"),
5707                               type->field (i).loc_kind ());
5708             }
5709         }
5710     }
5711
5712   /* For range types, copy the bounds information.  */
5713   if (type->code () == TYPE_CODE_RANGE)
5714     {
5715       range_bounds *bounds
5716         = ((struct range_bounds *) TYPE_ALLOC
5717            (new_type, sizeof (struct range_bounds)));
5718
5719       *bounds = *type->bounds ();
5720       new_type->set_bounds (bounds);
5721     }
5722
5723   if (type->main_type->dyn_prop_list != NULL)
5724     new_type->main_type->dyn_prop_list
5725       = copy_dynamic_prop_list (gdbarch_obstack (new_type->arch_owner ()),
5726                                 type->main_type->dyn_prop_list);
5727
5728
5729   /* Copy pointers to other types.  */
5730   if (TYPE_TARGET_TYPE (type))
5731     new_type->set_target_type
5732       (copy_type_recursive (TYPE_TARGET_TYPE (type), copied_types));
5733
5734   /* Maybe copy the type_specific bits.
5735
5736      NOTE drow/2005-12-09: We do not copy the C++-specific bits like
5737      base classes and methods.  There's no fundamental reason why we
5738      can't, but at the moment it is not needed.  */
5739
5740   switch (TYPE_SPECIFIC_FIELD (type))
5741     {
5742     case TYPE_SPECIFIC_NONE:
5743       break;
5744     case TYPE_SPECIFIC_FUNC:
5745       INIT_FUNC_SPECIFIC (new_type);
5746       TYPE_CALLING_CONVENTION (new_type) = TYPE_CALLING_CONVENTION (type);
5747       TYPE_NO_RETURN (new_type) = TYPE_NO_RETURN (type);
5748       TYPE_TAIL_CALL_LIST (new_type) = NULL;
5749       break;
5750     case TYPE_SPECIFIC_FLOATFORMAT:
5751       TYPE_FLOATFORMAT (new_type) = TYPE_FLOATFORMAT (type);
5752       break;
5753     case TYPE_SPECIFIC_CPLUS_STUFF:
5754       INIT_CPLUS_SPECIFIC (new_type);
5755       break;
5756     case TYPE_SPECIFIC_GNAT_STUFF:
5757       INIT_GNAT_SPECIFIC (new_type);
5758       break;
5759     case TYPE_SPECIFIC_SELF_TYPE:
5760       set_type_self_type (new_type,
5761                           copy_type_recursive (TYPE_SELF_TYPE (type),
5762                                                copied_types));
5763       break;
5764     case TYPE_SPECIFIC_FIXED_POINT:
5765       INIT_FIXED_POINT_SPECIFIC (new_type);
5766       new_type->fixed_point_info ().scaling_factor
5767         = type->fixed_point_info ().scaling_factor;
5768       break;
5769     case TYPE_SPECIFIC_INT:
5770       TYPE_SPECIFIC_FIELD (new_type) = TYPE_SPECIFIC_INT;
5771       TYPE_MAIN_TYPE (new_type)->type_specific.int_stuff
5772         = TYPE_MAIN_TYPE (type)->type_specific.int_stuff;
5773       break;
5774
5775     default:
5776       gdb_assert_not_reached ("bad type_specific_kind");
5777     }
5778
5779   return new_type;
5780 }
5781
5782 /* Make a copy of the given TYPE, except that the pointer & reference
5783    types are not preserved.  */
5784
5785 struct type *
5786 copy_type (const struct type *type)
5787 {
5788   struct type *new_type = alloc_type_copy (type);
5789   new_type->set_instance_flags (type->instance_flags ());
5790   TYPE_LENGTH (new_type) = TYPE_LENGTH (type);
5791   memcpy (TYPE_MAIN_TYPE (new_type), TYPE_MAIN_TYPE (type),
5792           sizeof (struct main_type));
5793   if (type->main_type->dyn_prop_list != NULL)
5794     {
5795       struct obstack *storage = (type->is_objfile_owned ()
5796                                  ? &type->objfile_owner ()->objfile_obstack
5797                                  : gdbarch_obstack (type->arch_owner ()));
5798       new_type->main_type->dyn_prop_list
5799         = copy_dynamic_prop_list (storage, type->main_type->dyn_prop_list);
5800     }
5801
5802   return new_type;
5803 }
5804 \f
5805 /* Helper functions to initialize architecture-specific types.  */
5806
5807 /* Allocate a type structure associated with GDBARCH and set its
5808    CODE, LENGTH, and NAME fields.  */
5809
5810 struct type *
5811 arch_type (struct gdbarch *gdbarch,
5812            enum type_code code, int bit, const char *name)
5813 {
5814   struct type *type;
5815
5816   type = alloc_type_arch (gdbarch);
5817   set_type_code (type, code);
5818   gdb_assert ((bit % TARGET_CHAR_BIT) == 0);
5819   TYPE_LENGTH (type) = bit / TARGET_CHAR_BIT;
5820
5821   if (name)
5822     type->set_name (gdbarch_obstack_strdup (gdbarch, name));
5823
5824   return type;
5825 }
5826
5827 /* Allocate a TYPE_CODE_INT type structure associated with GDBARCH.
5828    BIT is the type size in bits.  If UNSIGNED_P is non-zero, set
5829    the type's TYPE_UNSIGNED flag.  NAME is the type name.  */
5830
5831 struct type *
5832 arch_integer_type (struct gdbarch *gdbarch,
5833                    int bit, int unsigned_p, const char *name)
5834 {
5835   struct type *t;
5836
5837   t = arch_type (gdbarch, TYPE_CODE_INT, bit, name);
5838   if (unsigned_p)
5839     t->set_is_unsigned (true);
5840
5841   return t;
5842 }
5843
5844 /* Allocate a TYPE_CODE_CHAR type structure associated with GDBARCH.
5845    BIT is the type size in bits.  If UNSIGNED_P is non-zero, set
5846    the type's TYPE_UNSIGNED flag.  NAME is the type name.  */
5847
5848 struct type *
5849 arch_character_type (struct gdbarch *gdbarch,
5850                      int bit, int unsigned_p, const char *name)
5851 {
5852   struct type *t;
5853
5854   t = arch_type (gdbarch, TYPE_CODE_CHAR, bit, name);
5855   if (unsigned_p)
5856     t->set_is_unsigned (true);
5857
5858   return t;
5859 }
5860
5861 /* Allocate a TYPE_CODE_BOOL type structure associated with GDBARCH.
5862    BIT is the type size in bits.  If UNSIGNED_P is non-zero, set
5863    the type's TYPE_UNSIGNED flag.  NAME is the type name.  */
5864
5865 struct type *
5866 arch_boolean_type (struct gdbarch *gdbarch,
5867                    int bit, int unsigned_p, const char *name)
5868 {
5869   struct type *t;
5870
5871   t = arch_type (gdbarch, TYPE_CODE_BOOL, bit, name);
5872   if (unsigned_p)
5873     t->set_is_unsigned (true);
5874
5875   return t;
5876 }
5877
5878 /* Allocate a TYPE_CODE_FLT type structure associated with GDBARCH.
5879    BIT is the type size in bits; if BIT equals -1, the size is
5880    determined by the floatformat.  NAME is the type name.  Set the
5881    TYPE_FLOATFORMAT from FLOATFORMATS.  */
5882
5883 struct type *
5884 arch_float_type (struct gdbarch *gdbarch,
5885                  int bit, const char *name,
5886                  const struct floatformat **floatformats)
5887 {
5888   const struct floatformat *fmt = floatformats[gdbarch_byte_order (gdbarch)];
5889   struct type *t;
5890
5891   bit = verify_floatformat (bit, fmt);
5892   t = arch_type (gdbarch, TYPE_CODE_FLT, bit, name);
5893   TYPE_FLOATFORMAT (t) = fmt;
5894
5895   return t;
5896 }
5897
5898 /* Allocate a TYPE_CODE_DECFLOAT type structure associated with GDBARCH.
5899    BIT is the type size in bits.  NAME is the type name.  */
5900
5901 struct type *
5902 arch_decfloat_type (struct gdbarch *gdbarch, int bit, const char *name)
5903 {
5904   struct type *t;
5905
5906   t = arch_type (gdbarch, TYPE_CODE_DECFLOAT, bit, name);
5907   return t;
5908 }
5909
5910 /* Allocate a TYPE_CODE_PTR type structure associated with GDBARCH.
5911    BIT is the pointer type size in bits.  NAME is the type name.
5912    TARGET_TYPE is the pointer target type.  Always sets the pointer type's
5913    TYPE_UNSIGNED flag.  */
5914
5915 struct type *
5916 arch_pointer_type (struct gdbarch *gdbarch,
5917                    int bit, const char *name, struct type *target_type)
5918 {
5919   struct type *t;
5920
5921   t = arch_type (gdbarch, TYPE_CODE_PTR, bit, name);
5922   t->set_target_type (target_type);
5923   t->set_is_unsigned (true);
5924   return t;
5925 }
5926
5927 /* Allocate a TYPE_CODE_FLAGS type structure associated with GDBARCH.
5928    NAME is the type name.  BIT is the size of the flag word in bits.  */
5929
5930 struct type *
5931 arch_flags_type (struct gdbarch *gdbarch, const char *name, int bit)
5932 {
5933   struct type *type;
5934
5935   type = arch_type (gdbarch, TYPE_CODE_FLAGS, bit, name);
5936   type->set_is_unsigned (true);
5937   type->set_num_fields (0);
5938   /* Pre-allocate enough space assuming every field is one bit.  */
5939   type->set_fields
5940     ((struct field *) TYPE_ZALLOC (type, bit * sizeof (struct field)));
5941
5942   return type;
5943 }
5944
5945 /* Add field to TYPE_CODE_FLAGS type TYPE to indicate the bit at
5946    position BITPOS is called NAME.  Pass NAME as "" for fields that
5947    should not be printed.  */
5948
5949 void
5950 append_flags_type_field (struct type *type, int start_bitpos, int nr_bits,
5951                          struct type *field_type, const char *name)
5952 {
5953   int type_bitsize = TYPE_LENGTH (type) * TARGET_CHAR_BIT;
5954   int field_nr = type->num_fields ();
5955
5956   gdb_assert (type->code () == TYPE_CODE_FLAGS);
5957   gdb_assert (type->num_fields () + 1 <= type_bitsize);
5958   gdb_assert (start_bitpos >= 0 && start_bitpos < type_bitsize);
5959   gdb_assert (nr_bits >= 1 && (start_bitpos + nr_bits) <= type_bitsize);
5960   gdb_assert (name != NULL);
5961
5962   type->set_num_fields (type->num_fields () + 1);
5963   type->field (field_nr).set_name (xstrdup (name));
5964   type->field (field_nr).set_type (field_type);
5965   type->field (field_nr).set_loc_bitpos (start_bitpos);
5966   TYPE_FIELD_BITSIZE (type, field_nr) = nr_bits;
5967 }
5968
5969 /* Special version of append_flags_type_field to add a flag field.
5970    Add field to TYPE_CODE_FLAGS type TYPE to indicate the bit at
5971    position BITPOS is called NAME.  */
5972
5973 void
5974 append_flags_type_flag (struct type *type, int bitpos, const char *name)
5975 {
5976   append_flags_type_field (type, bitpos, 1,
5977                            builtin_type (type->arch ())->builtin_bool,
5978                            name);
5979 }
5980
5981 /* Allocate a TYPE_CODE_STRUCT or TYPE_CODE_UNION type structure (as
5982    specified by CODE) associated with GDBARCH.  NAME is the type name.  */
5983
5984 struct type *
5985 arch_composite_type (struct gdbarch *gdbarch, const char *name,
5986                      enum type_code code)
5987 {
5988   struct type *t;
5989
5990   gdb_assert (code == TYPE_CODE_STRUCT || code == TYPE_CODE_UNION);
5991   t = arch_type (gdbarch, code, 0, NULL);
5992   t->set_name (name);
5993   INIT_CPLUS_SPECIFIC (t);
5994   return t;
5995 }
5996
5997 /* Add new field with name NAME and type FIELD to composite type T.
5998    Do not set the field's position or adjust the type's length;
5999    the caller should do so.  Return the new field.  */
6000
6001 struct field *
6002 append_composite_type_field_raw (struct type *t, const char *name,
6003                                  struct type *field)
6004 {
6005   struct field *f;
6006
6007   t->set_num_fields (t->num_fields () + 1);
6008   t->set_fields (XRESIZEVEC (struct field, t->fields (),
6009                              t->num_fields ()));
6010   f = &t->field (t->num_fields () - 1);
6011   memset (f, 0, sizeof f[0]);
6012   f[0].set_type (field);
6013   f[0].set_name (name);
6014   return f;
6015 }
6016
6017 /* Add new field with name NAME and type FIELD to composite type T.
6018    ALIGNMENT (if non-zero) specifies the minimum field alignment.  */
6019
6020 void
6021 append_composite_type_field_aligned (struct type *t, const char *name,
6022                                      struct type *field, int alignment)
6023 {
6024   struct field *f = append_composite_type_field_raw (t, name, field);
6025
6026   if (t->code () == TYPE_CODE_UNION)
6027     {
6028       if (TYPE_LENGTH (t) < TYPE_LENGTH (field))
6029         TYPE_LENGTH (t) = TYPE_LENGTH (field);
6030     }
6031   else if (t->code () == TYPE_CODE_STRUCT)
6032     {
6033       TYPE_LENGTH (t) = TYPE_LENGTH (t) + TYPE_LENGTH (field);
6034       if (t->num_fields () > 1)
6035         {
6036           f->set_loc_bitpos
6037             (f[-1].loc_bitpos () + (TYPE_LENGTH (f[-1].type ()) * TARGET_CHAR_BIT));
6038
6039           if (alignment)
6040             {
6041               int left;
6042
6043               alignment *= TARGET_CHAR_BIT;
6044               left = f[0].loc_bitpos () % alignment;
6045
6046               if (left)
6047                 {
6048                   f->set_loc_bitpos (f[0].loc_bitpos () + (alignment - left));
6049                   TYPE_LENGTH (t) += (alignment - left) / TARGET_CHAR_BIT;
6050                 }
6051             }
6052         }
6053     }
6054 }
6055
6056 /* Add new field with name NAME and type FIELD to composite type T.  */
6057
6058 void
6059 append_composite_type_field (struct type *t, const char *name,
6060                              struct type *field)
6061 {
6062   append_composite_type_field_aligned (t, name, field, 0);
6063 }
6064
6065 \f
6066
6067 /* We manage the lifetimes of fixed_point_type_info objects by
6068    attaching them to the objfile.  Currently, these objects are
6069    modified during construction, and GMP does not provide a way to
6070    hash the contents of an mpq_t; so it's a bit of a pain to hash-cons
6071    them.  If we did do this, they could be moved to the per-BFD and
6072    shared across objfiles.  */
6073 typedef std::vector<std::unique_ptr<fixed_point_type_info>>
6074     fixed_point_type_storage;
6075
6076 /* Key used for managing the storage of fixed-point type info.  */
6077 static const struct registry<objfile>::key<fixed_point_type_storage>
6078     fixed_point_objfile_key;
6079
6080 /* See gdbtypes.h.  */
6081
6082 void
6083 allocate_fixed_point_type_info (struct type *type)
6084 {
6085   std::unique_ptr<fixed_point_type_info> up (new fixed_point_type_info);
6086   fixed_point_type_info *info;
6087
6088   if (type->is_objfile_owned ())
6089     {
6090       fixed_point_type_storage *storage
6091         = fixed_point_objfile_key.get (type->objfile_owner ());
6092       if (storage == nullptr)
6093         storage = fixed_point_objfile_key.emplace (type->objfile_owner ());
6094       info = up.get ();
6095       storage->push_back (std::move (up));
6096     }
6097   else
6098     {
6099       /* We just leak the memory, because that's what we do generally
6100          for non-objfile-attached types.  */
6101       info = up.release ();
6102     }
6103
6104   type->set_fixed_point_info (info);
6105 }
6106
6107 /* See gdbtypes.h.  */
6108
6109 bool
6110 is_fixed_point_type (struct type *type)
6111 {
6112   while (check_typedef (type)->code () == TYPE_CODE_RANGE)
6113     type = TYPE_TARGET_TYPE (check_typedef (type));
6114   type = check_typedef (type);
6115
6116   return type->code () == TYPE_CODE_FIXED_POINT;
6117 }
6118
6119 /* See gdbtypes.h.  */
6120
6121 struct type *
6122 type::fixed_point_type_base_type ()
6123 {
6124   struct type *type = this;
6125
6126   while (check_typedef (type)->code () == TYPE_CODE_RANGE)
6127     type = TYPE_TARGET_TYPE (check_typedef (type));
6128   type = check_typedef (type);
6129
6130   gdb_assert (type->code () == TYPE_CODE_FIXED_POINT);
6131   return type;
6132 }
6133
6134 /* See gdbtypes.h.  */
6135
6136 const gdb_mpq &
6137 type::fixed_point_scaling_factor ()
6138 {
6139   struct type *type = this->fixed_point_type_base_type ();
6140
6141   return type->fixed_point_info ().scaling_factor;
6142 }
6143
6144 \f
6145
6146 static const registry<gdbarch>::key<struct builtin_type> gdbtypes_data;
6147
6148 static struct builtin_type *
6149 create_gdbtypes_data (struct gdbarch *gdbarch)
6150 {
6151   struct builtin_type *builtin_type = new struct builtin_type;
6152
6153   /* Basic types.  */
6154   builtin_type->builtin_void
6155     = arch_type (gdbarch, TYPE_CODE_VOID, TARGET_CHAR_BIT, "void");
6156   builtin_type->builtin_char
6157     = arch_integer_type (gdbarch, TARGET_CHAR_BIT,
6158                          !gdbarch_char_signed (gdbarch), "char");
6159   builtin_type->builtin_char->set_has_no_signedness (true);
6160   builtin_type->builtin_signed_char
6161     = arch_integer_type (gdbarch, TARGET_CHAR_BIT,
6162                          0, "signed char");
6163   builtin_type->builtin_unsigned_char
6164     = arch_integer_type (gdbarch, TARGET_CHAR_BIT,
6165                          1, "unsigned char");
6166   builtin_type->builtin_short
6167     = arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
6168                          0, "short");
6169   builtin_type->builtin_unsigned_short
6170     = arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
6171                          1, "unsigned short");
6172   builtin_type->builtin_int
6173     = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
6174                          0, "int");
6175   builtin_type->builtin_unsigned_int
6176     = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
6177                          1, "unsigned int");
6178   builtin_type->builtin_long
6179     = arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
6180                          0, "long");
6181   builtin_type->builtin_unsigned_long
6182     = arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
6183                          1, "unsigned long");
6184   builtin_type->builtin_long_long
6185     = arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
6186                          0, "long long");
6187   builtin_type->builtin_unsigned_long_long
6188     = arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
6189                          1, "unsigned long long");
6190   builtin_type->builtin_half
6191     = arch_float_type (gdbarch, gdbarch_half_bit (gdbarch),
6192                        "half", gdbarch_half_format (gdbarch));
6193   builtin_type->builtin_float
6194     = arch_float_type (gdbarch, gdbarch_float_bit (gdbarch),
6195                        "float", gdbarch_float_format (gdbarch));
6196   builtin_type->builtin_bfloat16
6197     = arch_float_type (gdbarch, gdbarch_bfloat16_bit (gdbarch),
6198                        "bfloat16", gdbarch_bfloat16_format (gdbarch));
6199   builtin_type->builtin_double
6200     = arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
6201                        "double", gdbarch_double_format (gdbarch));
6202   builtin_type->builtin_long_double
6203     = arch_float_type (gdbarch, gdbarch_long_double_bit (gdbarch),
6204                        "long double", gdbarch_long_double_format (gdbarch));
6205   builtin_type->builtin_complex
6206     = init_complex_type ("complex", builtin_type->builtin_float);
6207   builtin_type->builtin_double_complex
6208     = init_complex_type ("double complex", builtin_type->builtin_double);
6209   builtin_type->builtin_string
6210     = arch_type (gdbarch, TYPE_CODE_STRING, TARGET_CHAR_BIT, "string");
6211   builtin_type->builtin_bool
6212     = arch_boolean_type (gdbarch, TARGET_CHAR_BIT, 1, "bool");
6213
6214   /* The following three are about decimal floating point types, which
6215      are 32-bits, 64-bits and 128-bits respectively.  */
6216   builtin_type->builtin_decfloat
6217     = arch_decfloat_type (gdbarch, 32, "_Decimal32");
6218   builtin_type->builtin_decdouble
6219     = arch_decfloat_type (gdbarch, 64, "_Decimal64");
6220   builtin_type->builtin_declong
6221     = arch_decfloat_type (gdbarch, 128, "_Decimal128");
6222
6223   /* "True" character types.  */
6224   builtin_type->builtin_true_char
6225     = arch_character_type (gdbarch, TARGET_CHAR_BIT, 0, "true character");
6226   builtin_type->builtin_true_unsigned_char
6227     = arch_character_type (gdbarch, TARGET_CHAR_BIT, 1, "true character");
6228
6229   /* Fixed-size integer types.  */
6230   builtin_type->builtin_int0
6231     = arch_integer_type (gdbarch, 0, 0, "int0_t");
6232   builtin_type->builtin_int8
6233     = arch_integer_type (gdbarch, 8, 0, "int8_t");
6234   builtin_type->builtin_uint8
6235     = arch_integer_type (gdbarch, 8, 1, "uint8_t");
6236   builtin_type->builtin_int16
6237     = arch_integer_type (gdbarch, 16, 0, "int16_t");
6238   builtin_type->builtin_uint16
6239     = arch_integer_type (gdbarch, 16, 1, "uint16_t");
6240   builtin_type->builtin_int24
6241     = arch_integer_type (gdbarch, 24, 0, "int24_t");
6242   builtin_type->builtin_uint24
6243     = arch_integer_type (gdbarch, 24, 1, "uint24_t");
6244   builtin_type->builtin_int32
6245     = arch_integer_type (gdbarch, 32, 0, "int32_t");
6246   builtin_type->builtin_uint32
6247     = arch_integer_type (gdbarch, 32, 1, "uint32_t");
6248   builtin_type->builtin_int64
6249     = arch_integer_type (gdbarch, 64, 0, "int64_t");
6250   builtin_type->builtin_uint64
6251     = arch_integer_type (gdbarch, 64, 1, "uint64_t");
6252   builtin_type->builtin_int128
6253     = arch_integer_type (gdbarch, 128, 0, "int128_t");
6254   builtin_type->builtin_uint128
6255     = arch_integer_type (gdbarch, 128, 1, "uint128_t");
6256
6257   builtin_type->builtin_int8->set_instance_flags
6258     (builtin_type->builtin_int8->instance_flags ()
6259      | TYPE_INSTANCE_FLAG_NOTTEXT);
6260
6261   builtin_type->builtin_uint8->set_instance_flags
6262     (builtin_type->builtin_uint8->instance_flags ()
6263      | TYPE_INSTANCE_FLAG_NOTTEXT);
6264
6265   /* Wide character types.  */
6266   builtin_type->builtin_char16
6267     = arch_integer_type (gdbarch, 16, 1, "char16_t");
6268   builtin_type->builtin_char32
6269     = arch_integer_type (gdbarch, 32, 1, "char32_t");
6270   builtin_type->builtin_wchar
6271     = arch_integer_type (gdbarch, gdbarch_wchar_bit (gdbarch),
6272                          !gdbarch_wchar_signed (gdbarch), "wchar_t");
6273
6274   /* Default data/code pointer types.  */
6275   builtin_type->builtin_data_ptr
6276     = lookup_pointer_type (builtin_type->builtin_void);
6277   builtin_type->builtin_func_ptr
6278     = lookup_pointer_type (lookup_function_type (builtin_type->builtin_void));
6279   builtin_type->builtin_func_func
6280     = lookup_function_type (builtin_type->builtin_func_ptr);
6281
6282   /* This type represents a GDB internal function.  */
6283   builtin_type->internal_fn
6284     = arch_type (gdbarch, TYPE_CODE_INTERNAL_FUNCTION, 0,
6285                  "<internal function>");
6286
6287   /* This type represents an xmethod.  */
6288   builtin_type->xmethod
6289     = arch_type (gdbarch, TYPE_CODE_XMETHOD, 0, "<xmethod>");
6290
6291   return builtin_type;
6292 }
6293
6294 const struct builtin_type *
6295 builtin_type (struct gdbarch *gdbarch)
6296 {
6297   struct builtin_type *result = gdbtypes_data.get (gdbarch);
6298   if (result == nullptr)
6299     {
6300       result = create_gdbtypes_data (gdbarch);
6301       gdbtypes_data.set (gdbarch, result);
6302     }
6303   return result;
6304 }
6305
6306 /* This set of objfile-based types is intended to be used by symbol
6307    readers as basic types.  */
6308
6309 static const registry<objfile>::key<struct objfile_type,
6310                                     gdb::noop_deleter<struct objfile_type>>
6311   objfile_type_data;
6312
6313 const struct objfile_type *
6314 objfile_type (struct objfile *objfile)
6315 {
6316   struct gdbarch *gdbarch;
6317   struct objfile_type *objfile_type = objfile_type_data.get (objfile);
6318
6319   if (objfile_type)
6320     return objfile_type;
6321
6322   objfile_type = OBSTACK_CALLOC (&objfile->objfile_obstack,
6323                                  1, struct objfile_type);
6324
6325   /* Use the objfile architecture to determine basic type properties.  */
6326   gdbarch = objfile->arch ();
6327
6328   /* Basic types.  */
6329   objfile_type->builtin_void
6330     = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, "void");
6331   objfile_type->builtin_char
6332     = init_integer_type (objfile, TARGET_CHAR_BIT,
6333                          !gdbarch_char_signed (gdbarch), "char");
6334   objfile_type->builtin_char->set_has_no_signedness (true);
6335   objfile_type->builtin_signed_char
6336     = init_integer_type (objfile, TARGET_CHAR_BIT,
6337                          0, "signed char");
6338   objfile_type->builtin_unsigned_char
6339     = init_integer_type (objfile, TARGET_CHAR_BIT,
6340                          1, "unsigned char");
6341   objfile_type->builtin_short
6342     = init_integer_type (objfile, gdbarch_short_bit (gdbarch),
6343                          0, "short");
6344   objfile_type->builtin_unsigned_short
6345     = init_integer_type (objfile, gdbarch_short_bit (gdbarch),
6346                          1, "unsigned short");
6347   objfile_type->builtin_int
6348     = init_integer_type (objfile, gdbarch_int_bit (gdbarch),
6349                          0, "int");
6350   objfile_type->builtin_unsigned_int
6351     = init_integer_type (objfile, gdbarch_int_bit (gdbarch),
6352                          1, "unsigned int");
6353   objfile_type->builtin_long
6354     = init_integer_type (objfile, gdbarch_long_bit (gdbarch),
6355                          0, "long");
6356   objfile_type->builtin_unsigned_long
6357     = init_integer_type (objfile, gdbarch_long_bit (gdbarch),
6358                          1, "unsigned long");
6359   objfile_type->builtin_long_long
6360     = init_integer_type (objfile, gdbarch_long_long_bit (gdbarch),
6361                          0, "long long");
6362   objfile_type->builtin_unsigned_long_long
6363     = init_integer_type (objfile, gdbarch_long_long_bit (gdbarch),
6364                          1, "unsigned long long");
6365   objfile_type->builtin_float
6366     = init_float_type (objfile, gdbarch_float_bit (gdbarch),
6367                        "float", gdbarch_float_format (gdbarch));
6368   objfile_type->builtin_double
6369     = init_float_type (objfile, gdbarch_double_bit (gdbarch),
6370                        "double", gdbarch_double_format (gdbarch));
6371   objfile_type->builtin_long_double
6372     = init_float_type (objfile, gdbarch_long_double_bit (gdbarch),
6373                        "long double", gdbarch_long_double_format (gdbarch));
6374
6375   /* This type represents a type that was unrecognized in symbol read-in.  */
6376   objfile_type->builtin_error
6377     = init_type (objfile, TYPE_CODE_ERROR, 0, "<unknown type>");
6378
6379   /* The following set of types is used for symbols with no
6380      debug information.  */
6381   objfile_type->nodebug_text_symbol
6382     = init_type (objfile, TYPE_CODE_FUNC, TARGET_CHAR_BIT,
6383                  "<text variable, no debug info>");
6384
6385   objfile_type->nodebug_text_gnu_ifunc_symbol
6386     = init_type (objfile, TYPE_CODE_FUNC, TARGET_CHAR_BIT,
6387                  "<text gnu-indirect-function variable, no debug info>");
6388   objfile_type->nodebug_text_gnu_ifunc_symbol->set_is_gnu_ifunc (true);
6389
6390   objfile_type->nodebug_got_plt_symbol
6391     = init_pointer_type (objfile, gdbarch_addr_bit (gdbarch),
6392                          "<text from jump slot in .got.plt, no debug info>",
6393                          objfile_type->nodebug_text_symbol);
6394   objfile_type->nodebug_data_symbol
6395     = init_nodebug_var_type (objfile, "<data variable, no debug info>");
6396   objfile_type->nodebug_unknown_symbol
6397     = init_nodebug_var_type (objfile, "<variable (not text or data), no debug info>");
6398   objfile_type->nodebug_tls_symbol
6399     = init_nodebug_var_type (objfile, "<thread local variable, no debug info>");
6400
6401   /* NOTE: on some targets, addresses and pointers are not necessarily
6402      the same.
6403
6404      The upshot is:
6405      - gdb's `struct type' always describes the target's
6406        representation.
6407      - gdb's `struct value' objects should always hold values in
6408        target form.
6409      - gdb's CORE_ADDR values are addresses in the unified virtual
6410        address space that the assembler and linker work with.  Thus,
6411        since target_read_memory takes a CORE_ADDR as an argument, it
6412        can access any memory on the target, even if the processor has
6413        separate code and data address spaces.
6414
6415      In this context, objfile_type->builtin_core_addr is a bit odd:
6416      it's a target type for a value the target will never see.  It's
6417      only used to hold the values of (typeless) linker symbols, which
6418      are indeed in the unified virtual address space.  */
6419
6420   objfile_type->builtin_core_addr
6421     = init_integer_type (objfile, gdbarch_addr_bit (gdbarch), 1,
6422                          "__CORE_ADDR");
6423
6424   objfile_type_data.set (objfile, objfile_type);
6425   return objfile_type;
6426 }
6427
6428 /* See gdbtypes.h.  */
6429
6430 CORE_ADDR
6431 call_site::pc () const
6432 {
6433   compunit_symtab *cust = this->per_objfile->get_symtab (this->per_cu);
6434   CORE_ADDR delta
6435         = this->per_objfile->objfile->section_offsets[cust->block_line_section ()];
6436   return m_unrelocated_pc + delta;
6437 }
6438
6439 void _initialize_gdbtypes ();
6440 void
6441 _initialize_gdbtypes ()
6442 {
6443   add_setshow_zuinteger_cmd ("overload", no_class, &overload_debug,
6444                              _("Set debugging of C++ overloading."),
6445                              _("Show debugging of C++ overloading."),
6446                              _("When enabled, ranking of the "
6447                                "functions is displayed."),
6448                              NULL,
6449                              show_overload_debug,
6450                              &setdebuglist, &showdebuglist);
6451
6452   /* Add user knob for controlling resolution of opaque types.  */
6453   add_setshow_boolean_cmd ("opaque-type-resolution", class_support,
6454                            &opaque_type_resolution,
6455                            _("Set resolution of opaque struct/class/union"
6456                              " types (if set before loading symbols)."),
6457                            _("Show resolution of opaque struct/class/union"
6458                              " types (if set before loading symbols)."),
6459                            NULL, NULL,
6460                            show_opaque_type_resolution,
6461                            &setlist, &showlist);
6462
6463   /* Add an option to permit non-strict type checking.  */
6464   add_setshow_boolean_cmd ("type", class_support,
6465                            &strict_type_checking,
6466                            _("Set strict type checking."),
6467                            _("Show strict type checking."),
6468                            NULL, NULL,
6469                            show_strict_type_checking,
6470                            &setchecklist, &showchecklist);
6471 }
This page took 0.378648 seconds and 4 git commands to generate.