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