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