9eee22c44acec4e0ab71ce64b300b20cc533cdb1
[platform/upstream/binutils.git] / gdb / ada-lang.c
1 /* Ada language support routines for GDB, the GNU debugger.  Copyright
2    1992, 1993, 1994, 1997, 1998, 1999, 2000, 2003, 2004.
3    Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21
22 /* Sections of code marked 
23
24      #ifdef GNAT_GDB 
25      ...
26      #endif
27
28    indicate sections that are used in sources distributed by 
29    ACT, Inc., but not yet integrated into the public tree (where
30    GNAT_GDB is not defined).  They are retained here nevertheless 
31    to minimize the problems of maintaining different versions 
32    of the source and to make the full source available. */
33
34 #include "defs.h"
35 #include <stdio.h>
36 #include "gdb_string.h"
37 #include <ctype.h>
38 #include <stdarg.h>
39 #include "demangle.h"
40 #include "gdb_regex.h"
41 #include "frame.h"
42 #include "symtab.h"
43 #include "gdbtypes.h"
44 #include "gdbcmd.h"
45 #include "expression.h"
46 #include "parser-defs.h"
47 #include "language.h"
48 #include "c-lang.h"
49 #include "inferior.h"
50 #include "symfile.h"
51 #include "objfiles.h"
52 #include "breakpoint.h"
53 #include "gdbcore.h"
54 #include "hashtab.h"
55 #include "gdb_obstack.h"
56 #include "ada-lang.h"
57 #include "completer.h"
58 #include "gdb_stat.h"
59 #ifdef UI_OUT
60 #include "ui-out.h"
61 #endif
62 #include "block.h"
63 #include "infcall.h"
64 #include "dictionary.h"
65
66 #ifndef ADA_RETAIN_DOTS
67 #define ADA_RETAIN_DOTS 0
68 #endif
69
70 /* Define whether or not the C operator '/' truncates towards zero for
71    differently signed operands (truncation direction is undefined in C). 
72    Copied from valarith.c.  */
73
74 #ifndef TRUNCATION_TOWARDS_ZERO
75 #define TRUNCATION_TOWARDS_ZERO ((-5 / 2) == -2)
76 #endif
77
78 #ifdef GNAT_GDB
79 /* A structure that contains a vector of strings.
80    The main purpose of this type is to group the vector and its
81    associated parameters in one structure.  This makes it easier
82    to handle and pass around.  */
83
84 struct string_vector
85 {
86   char **array; /* The vector itself.  */
87   int index;    /* Index of the next available element in the array.  */
88   size_t size;  /* The number of entries allocated in the array.  */
89 };
90
91 static struct string_vector xnew_string_vector (int initial_size);
92 static void string_vector_append (struct string_vector *sv, char *str);
93 #endif /* GNAT_GDB */
94
95 static const char *ada_unqualified_name (const char *decoded_name);
96 static char *add_angle_brackets (const char *str);
97 static void extract_string (CORE_ADDR addr, char *buf);
98 static char *function_name_from_pc (CORE_ADDR pc);
99
100 static struct type *ada_create_fundamental_type (struct objfile *, int);
101
102 static void modify_general_field (char *, LONGEST, int, int);
103
104 static struct type *desc_base_type (struct type *);
105
106 static struct type *desc_bounds_type (struct type *);
107
108 static struct value *desc_bounds (struct value *);
109
110 static int fat_pntr_bounds_bitpos (struct type *);
111
112 static int fat_pntr_bounds_bitsize (struct type *);
113
114 static struct type *desc_data_type (struct type *);
115
116 static struct value *desc_data (struct value *);
117
118 static int fat_pntr_data_bitpos (struct type *);
119
120 static int fat_pntr_data_bitsize (struct type *);
121
122 static struct value *desc_one_bound (struct value *, int, int);
123
124 static int desc_bound_bitpos (struct type *, int, int);
125
126 static int desc_bound_bitsize (struct type *, int, int);
127
128 static struct type *desc_index_type (struct type *, int);
129
130 static int desc_arity (struct type *);
131
132 static int ada_type_match (struct type *, struct type *, int);
133
134 static int ada_args_match (struct symbol *, struct value **, int);
135
136 static struct value *ensure_lval (struct value *, CORE_ADDR *);
137
138 static struct value *convert_actual (struct value *, struct type *,
139                                      CORE_ADDR *);
140
141 static struct value *make_array_descriptor (struct type *, struct value *,
142                                             CORE_ADDR *);
143
144 static void ada_add_block_symbols (struct obstack *,
145                                    struct block *, const char *,
146                                    domain_enum, struct objfile *,
147                                    struct symtab *, int);
148
149 static int is_nonfunction (struct ada_symbol_info *, int);
150
151 static void add_defn_to_vec (struct obstack *, struct symbol *,
152                              struct block *, struct symtab *);
153
154 static int num_defns_collected (struct obstack *);
155
156 static struct ada_symbol_info *defns_collected (struct obstack *, int);
157
158 static struct partial_symbol *ada_lookup_partial_symbol (struct partial_symtab
159                                                          *, const char *, int,
160                                                          domain_enum, int);
161
162 static struct symtab *symtab_for_sym (struct symbol *);
163
164 static struct value *resolve_subexp (struct expression **, int *, int,
165                                      struct type *);
166
167 static void replace_operator_with_call (struct expression **, int, int, int,
168                                         struct symbol *, struct block *);
169
170 static int possible_user_operator_p (enum exp_opcode, struct value **);
171
172 static char *ada_op_name (enum exp_opcode);
173
174 static const char *ada_decoded_op_name (enum exp_opcode);
175
176 static int numeric_type_p (struct type *);
177
178 static int integer_type_p (struct type *);
179
180 static int scalar_type_p (struct type *);
181
182 static int discrete_type_p (struct type *);
183
184 static struct type *ada_lookup_struct_elt_type (struct type *, char *,
185                                                 int, int, int *);
186
187 static char *extended_canonical_line_spec (struct symtab_and_line,
188                                            const char *);
189
190 static struct value *evaluate_subexp (struct type *, struct expression *,
191                                       int *, enum noside);
192
193 static struct value *evaluate_subexp_type (struct expression *, int *);
194
195 static struct type *ada_create_fundamental_type (struct objfile *, int);
196
197 static int is_dynamic_field (struct type *, int);
198
199 static struct type *to_fixed_variant_branch_type (struct type *, char *,
200                                                   CORE_ADDR, struct value *);
201
202 static struct type *to_fixed_array_type (struct type *, struct value *, int);
203
204 static struct type *to_fixed_range_type (char *, struct value *,
205                                          struct objfile *);
206
207 static struct type *to_static_fixed_type (struct type *);
208
209 static struct value *unwrap_value (struct value *);
210
211 static struct type *packed_array_type (struct type *, long *);
212
213 static struct type *decode_packed_array_type (struct type *);
214
215 static struct value *decode_packed_array (struct value *);
216
217 static struct value *value_subscript_packed (struct value *, int,
218                                              struct value **);
219
220 static struct value *coerce_unspec_val_to_type (struct value *,
221                                                 struct type *);
222
223 static struct value *get_var_value (char *, char *);
224
225 static int lesseq_defined_than (struct symbol *, struct symbol *);
226
227 static int equiv_types (struct type *, struct type *);
228
229 static int is_name_suffix (const char *);
230
231 static int wild_match (const char *, int, const char *);
232
233 static struct symtabs_and_lines
234 find_sal_from_funcs_and_line (const char *, int,
235                               struct ada_symbol_info *, int);
236
237 static int find_line_in_linetable (struct linetable *, int,
238                                    struct ada_symbol_info *, int, int *);
239
240 static int find_next_line_in_linetable (struct linetable *, int, int, int);
241
242 static void read_all_symtabs (const char *);
243
244 static int is_plausible_func_for_line (struct symbol *, int);
245
246 static struct value *ada_coerce_ref (struct value *);
247
248 static LONGEST pos_atr (struct value *);
249
250 static struct value *value_pos_atr (struct value *);
251
252 static struct value *value_val_atr (struct type *, struct value *);
253
254 static struct symbol *standard_lookup (const char *, const struct block *,
255                                        domain_enum);
256
257 static struct value *ada_search_struct_field (char *, struct value *, int,
258                                               struct type *);
259
260 static struct value *ada_value_primitive_field (struct value *, int, int,
261                                                 struct type *);
262
263 static int find_struct_field (char *, struct type *, int,
264                               struct type **, int *, int *, int *);
265
266 static struct value *ada_to_fixed_value_create (struct type *, CORE_ADDR,
267                                                 struct value *);
268
269 static struct value *ada_to_fixed_value (struct value *);
270
271 static void adjust_pc_past_prologue (CORE_ADDR *);
272
273 static int ada_resolve_function (struct ada_symbol_info *, int,
274                                  struct value **, int, const char *,
275                                  struct type *);
276
277 static struct value *ada_coerce_to_simple_array (struct value *);
278
279 static int ada_is_direct_array_type (struct type *);
280
281 static void error_breakpoint_runtime_sym_not_found (const char *err_desc);
282
283 static int is_runtime_sym_defined (const char *name, int allow_tramp);
284 \f
285
286
287 /* Maximum-sized dynamic type.  */
288 static unsigned int varsize_limit;
289
290 /* FIXME: brobecker/2003-09-17: No longer a const because it is
291    returned by a function that does not return a const char *.  */
292 static char *ada_completer_word_break_characters =
293 #ifdef VMS
294   " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
295 #else
296   " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
297 #endif
298
299 /* The name of the symbol to use to get the name of the main subprogram.  */
300 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
301   = "__gnat_ada_main_program_name";
302
303 /* The name of the runtime function called when an exception is raised.  */
304 static const char raise_sym_name[] = "__gnat_raise_nodefer_with_msg";
305
306 /* The name of the runtime function called when an unhandled exception
307    is raised.  */
308 static const char raise_unhandled_sym_name[] = "__gnat_unhandled_exception";
309
310 /* The name of the runtime function called when an assert failure is
311    raised.  */
312 static const char raise_assert_sym_name[] =
313   "system__assertions__raise_assert_failure";
314
315 /* When GDB stops on an unhandled exception, GDB will go up the stack until
316    if finds a frame corresponding to this function, in order to extract the
317    name of the exception that has been raised from one of the parameters.  */
318 static const char process_raise_exception_name[] =
319   "ada__exceptions__process_raise_exception";
320
321 /* A string that reflects the longest exception expression rewrite,
322    aside from the exception name.  */
323 static const char longest_exception_template[] =
324   "'__gnat_raise_nodefer_with_msg' if long_integer(e) = long_integer(&)";
325
326 /* Limit on the number of warnings to raise per expression evaluation.  */
327 static int warning_limit = 2;
328
329 /* Number of warning messages issued; reset to 0 by cleanups after
330    expression evaluation.  */
331 static int warnings_issued = 0;
332
333 static const char *known_runtime_file_name_patterns[] = {
334   ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
335 };
336
337 static const char *known_auxiliary_function_name_patterns[] = {
338   ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
339 };
340
341 /* Space for allocating results of ada_lookup_symbol_list.  */
342 static struct obstack symbol_list_obstack;
343
344                         /* Utilities */
345
346 #ifdef GNAT_GDB
347
348 /* Create a new empty string_vector struct with an initial size of
349    INITIAL_SIZE.  */
350
351 static struct string_vector
352 xnew_string_vector (int initial_size)
353 {
354   struct string_vector result;
355
356   result.array = (char **) xmalloc ((initial_size + 1) * sizeof (char *));
357   result.index = 0;
358   result.size = initial_size;
359
360   return result;
361 }
362
363 /* Add STR at the end of the given string vector SV.  If SV is already
364    full, its size is automatically increased (doubled).  */
365
366 static void
367 string_vector_append (struct string_vector *sv, char *str)
368 {
369   if (sv->index >= sv->size)
370     GROW_VECT (sv->array, sv->size, sv->size * 2);
371
372   sv->array[sv->index] = str;
373   sv->index++;
374 }
375
376 /* Given DECODED_NAME a string holding a symbol name in its
377    decoded form (ie using the Ada dotted notation), returns
378    its unqualified name.  */
379
380 static const char *
381 ada_unqualified_name (const char *decoded_name)
382 {
383   const char *result = strrchr (decoded_name, '.');
384
385   if (result != NULL)
386     result++;                   /* Skip the dot...  */
387   else
388     result = decoded_name;
389
390   return result;
391 }
392
393 /* Return a string starting with '<', followed by STR, and '>'.
394    The result is good until the next call.  */
395
396 static char *
397 add_angle_brackets (const char *str)
398 {
399   static char *result = NULL;
400
401   xfree (result);
402   result = (char *) xmalloc ((strlen (str) + 3) * sizeof (char));
403
404   sprintf (result, "<%s>", str);
405   return result;
406 }
407
408 #endif /* GNAT_GDB */
409
410 static char *
411 ada_get_gdb_completer_word_break_characters (void)
412 {
413   return ada_completer_word_break_characters;
414 }
415
416 /* Read the string located at ADDR from the inferior and store the
417    result into BUF.  */
418
419 static void
420 extract_string (CORE_ADDR addr, char *buf)
421 {
422   int char_index = 0;
423
424   /* Loop, reading one byte at a time, until we reach the '\000'
425      end-of-string marker.  */
426   do
427     {
428       target_read_memory (addr + char_index * sizeof (char),
429                           buf + char_index * sizeof (char), sizeof (char));
430       char_index++;
431     }
432   while (buf[char_index - 1] != '\000');
433 }
434
435 /* Return the name of the function owning the instruction located at PC.
436    Return NULL if no such function could be found.  */
437
438 static char *
439 function_name_from_pc (CORE_ADDR pc)
440 {
441   char *func_name;
442
443   if (!find_pc_partial_function (pc, &func_name, NULL, NULL))
444     return NULL;
445
446   return func_name;
447 }
448
449 /* Assuming *OLD_VECT points to an array of *SIZE objects of size
450    ELEMENT_SIZE, grow it to contain at least MIN_SIZE objects,
451    updating *OLD_VECT and *SIZE as necessary.  */
452
453 void
454 grow_vect (void **old_vect, size_t * size, size_t min_size, int element_size)
455 {
456   if (*size < min_size)
457     {
458       *size *= 2;
459       if (*size < min_size)
460         *size = min_size;
461       *old_vect = xrealloc (*old_vect, *size * element_size);
462     }
463 }
464
465 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
466    suffix of FIELD_NAME beginning "___".  */
467
468 static int
469 field_name_match (const char *field_name, const char *target)
470 {
471   int len = strlen (target);
472   return
473     (strncmp (field_name, target, len) == 0
474      && (field_name[len] == '\0'
475          || (strncmp (field_name + len, "___", 3) == 0
476              && strcmp (field_name + strlen (field_name) - 6,
477                         "___XVN") != 0)));
478 }
479
480
481 /* Assuming TYPE is a TYPE_CODE_STRUCT, find the field whose name matches
482    FIELD_NAME, and return its index.  This function also handles fields
483    whose name have ___ suffixes because the compiler sometimes alters
484    their name by adding such a suffix to represent fields with certain
485    constraints.  If the field could not be found, return a negative
486    number if MAYBE_MISSING is set.  Otherwise raise an error.  */
487
488 int
489 ada_get_field_index (const struct type *type, const char *field_name,
490                      int maybe_missing)
491 {
492   int fieldno;
493   for (fieldno = 0; fieldno < TYPE_NFIELDS (type); fieldno++)
494     if (field_name_match (TYPE_FIELD_NAME (type, fieldno), field_name))
495       return fieldno;
496
497   if (!maybe_missing)
498     error ("Unable to find field %s in struct %s.  Aborting",
499            field_name, TYPE_NAME (type));
500
501   return -1;
502 }
503
504 /* The length of the prefix of NAME prior to any "___" suffix.  */
505
506 int
507 ada_name_prefix_len (const char *name)
508 {
509   if (name == NULL)
510     return 0;
511   else
512     {
513       const char *p = strstr (name, "___");
514       if (p == NULL)
515         return strlen (name);
516       else
517         return p - name;
518     }
519 }
520
521 /* Return non-zero if SUFFIX is a suffix of STR.
522    Return zero if STR is null.  */
523
524 static int
525 is_suffix (const char *str, const char *suffix)
526 {
527   int len1, len2;
528   if (str == NULL)
529     return 0;
530   len1 = strlen (str);
531   len2 = strlen (suffix);
532   return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
533 }
534
535 /* Create a value of type TYPE whose contents come from VALADDR, if it
536    is non-null, and whose memory address (in the inferior) is
537    ADDRESS.  */
538
539 struct value *
540 value_from_contents_and_address (struct type *type, char *valaddr,
541                                  CORE_ADDR address)
542 {
543   struct value *v = allocate_value (type);
544   if (valaddr == NULL)
545     VALUE_LAZY (v) = 1;
546   else
547     memcpy (VALUE_CONTENTS_RAW (v), valaddr, TYPE_LENGTH (type));
548   VALUE_ADDRESS (v) = address;
549   if (address != 0)
550     VALUE_LVAL (v) = lval_memory;
551   return v;
552 }
553
554 /* The contents of value VAL, treated as a value of type TYPE.  The
555    result is an lval in memory if VAL is.  */
556
557 static struct value *
558 coerce_unspec_val_to_type (struct value *val, struct type *type)
559 {
560   CHECK_TYPEDEF (type);
561   if (VALUE_TYPE (val) == type)
562     return val;
563   else
564     {
565       struct value *result;
566
567       /* Make sure that the object size is not unreasonable before
568          trying to allocate some memory for it.  */
569       if (TYPE_LENGTH (type) > varsize_limit)
570         error ("object size is larger than varsize-limit");
571
572       result = allocate_value (type);
573       VALUE_LVAL (result) = VALUE_LVAL (val);
574       VALUE_BITSIZE (result) = VALUE_BITSIZE (val);
575       VALUE_BITPOS (result) = VALUE_BITPOS (val);
576       VALUE_ADDRESS (result) = VALUE_ADDRESS (val) + VALUE_OFFSET (val);
577       if (VALUE_LAZY (val)
578           || TYPE_LENGTH (type) > TYPE_LENGTH (VALUE_TYPE (val)))
579         VALUE_LAZY (result) = 1;
580       else
581         memcpy (VALUE_CONTENTS_RAW (result), VALUE_CONTENTS (val),
582                 TYPE_LENGTH (type));
583       return result;
584     }
585 }
586
587 static char *
588 cond_offset_host (char *valaddr, long offset)
589 {
590   if (valaddr == NULL)
591     return NULL;
592   else
593     return valaddr + offset;
594 }
595
596 static CORE_ADDR
597 cond_offset_target (CORE_ADDR address, long offset)
598 {
599   if (address == 0)
600     return 0;
601   else
602     return address + offset;
603 }
604
605 /* Issue a warning (as for the definition of warning in utils.c, but
606    with exactly one argument rather than ...), unless the limit on the
607    number of warnings has passed during the evaluation of the current
608    expression.  */
609 static void
610 lim_warning (const char *format, long arg)
611 {
612   warnings_issued += 1;
613   if (warnings_issued <= warning_limit)
614     warning (format, arg);
615 }
616
617 static const char *
618 ada_translate_error_message (const char *string)
619 {
620   if (strcmp (string, "Invalid cast.") == 0)
621     return "Invalid type conversion.";
622   else
623     return string;
624 }
625
626 /* Note: would have used MAX_OF_TYPE and MIN_OF_TYPE macros from
627    gdbtypes.h, but some of the necessary definitions in that file
628    seem to have gone missing. */
629
630 /* Maximum value of a SIZE-byte signed integer type. */
631 static LONGEST
632 max_of_size (int size)
633 {
634   LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
635   return top_bit | (top_bit - 1);
636 }
637
638 /* Minimum value of a SIZE-byte signed integer type. */
639 static LONGEST
640 min_of_size (int size)
641 {
642   return -max_of_size (size) - 1;
643 }
644
645 /* Maximum value of a SIZE-byte unsigned integer type. */
646 static ULONGEST
647 umax_of_size (int size)
648 {
649   ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
650   return top_bit | (top_bit - 1);
651 }
652
653 /* Maximum value of integral type T, as a signed quantity. */
654 static LONGEST
655 max_of_type (struct type *t)
656 {
657   if (TYPE_UNSIGNED (t))
658     return (LONGEST) umax_of_size (TYPE_LENGTH (t));
659   else
660     return max_of_size (TYPE_LENGTH (t));
661 }
662
663 /* Minimum value of integral type T, as a signed quantity. */
664 static LONGEST
665 min_of_type (struct type *t)
666 {
667   if (TYPE_UNSIGNED (t)) 
668     return 0;
669   else
670     return min_of_size (TYPE_LENGTH (t));
671 }
672
673 /* The largest value in the domain of TYPE, a discrete type, as an integer.  */
674 static struct value *
675 discrete_type_high_bound (struct type *type)
676 {
677   switch (TYPE_CODE (type))
678     {
679     case TYPE_CODE_RANGE:
680       return value_from_longest (TYPE_TARGET_TYPE (type),
681                                  TYPE_HIGH_BOUND (type));
682     case TYPE_CODE_ENUM:
683       return
684         value_from_longest (type,
685                             TYPE_FIELD_BITPOS (type,
686                                                TYPE_NFIELDS (type) - 1));
687     case TYPE_CODE_INT:
688       return value_from_longest (type, max_of_type (type));
689     default:
690       error ("Unexpected type in discrete_type_high_bound.");
691     }
692 }
693
694 /* The largest value in the domain of TYPE, a discrete type, as an integer.  */
695 static struct value *
696 discrete_type_low_bound (struct type *type)
697 {
698   switch (TYPE_CODE (type))
699     {
700     case TYPE_CODE_RANGE:
701       return value_from_longest (TYPE_TARGET_TYPE (type),
702                                  TYPE_LOW_BOUND (type));
703     case TYPE_CODE_ENUM:
704       return value_from_longest (type, TYPE_FIELD_BITPOS (type, 0));
705     case TYPE_CODE_INT:
706       return value_from_longest (type, min_of_type (type));
707     default:
708       error ("Unexpected type in discrete_type_low_bound.");
709     }
710 }
711
712 /* The identity on non-range types.  For range types, the underlying
713    non-range scalar type.  */
714
715 static struct type *
716 base_type (struct type *type)
717 {
718   while (type != NULL && TYPE_CODE (type) == TYPE_CODE_RANGE)
719     {
720       if (type == TYPE_TARGET_TYPE (type) || TYPE_TARGET_TYPE (type) == NULL)
721         return type;
722       type = TYPE_TARGET_TYPE (type);
723     }
724   return type;
725 }
726 \f
727
728                                 /* Language Selection */
729
730 /* If the main program is in Ada, return language_ada, otherwise return LANG
731    (the main program is in Ada iif the adainit symbol is found).
732
733    MAIN_PST is not used.  */
734
735 enum language
736 ada_update_initial_language (enum language lang,
737                              struct partial_symtab *main_pst)
738 {
739   if (lookup_minimal_symbol ("adainit", (const char *) NULL,
740                              (struct objfile *) NULL) != NULL)
741     return language_ada;
742
743   return lang;
744 }
745
746 /* If the main procedure is written in Ada, then return its name.
747    The result is good until the next call.  Return NULL if the main
748    procedure doesn't appear to be in Ada.  */
749
750 char *
751 ada_main_name (void)
752 {
753   struct minimal_symbol *msym;
754   CORE_ADDR main_program_name_addr;
755   static char main_program_name[1024];
756
757   /* For Ada, the name of the main procedure is stored in a specific
758      string constant, generated by the binder.  Look for that symbol,
759      extract its address, and then read that string.  If we didn't find
760      that string, then most probably the main procedure is not written
761      in Ada.  */
762   msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
763
764   if (msym != NULL)
765     {
766       main_program_name_addr = SYMBOL_VALUE_ADDRESS (msym);
767       if (main_program_name_addr == 0)
768         error ("Invalid address for Ada main program name.");
769
770       extract_string (main_program_name_addr, main_program_name);
771       return main_program_name;
772     }
773
774   /* The main procedure doesn't seem to be in Ada.  */
775   return NULL;
776 }
777 \f
778                                 /* Symbols */
779
780 /* Table of Ada operators and their GNAT-encoded names.  Last entry is pair
781    of NULLs.  */
782
783 const struct ada_opname_map ada_opname_table[] = {
784   {"Oadd", "\"+\"", BINOP_ADD},
785   {"Osubtract", "\"-\"", BINOP_SUB},
786   {"Omultiply", "\"*\"", BINOP_MUL},
787   {"Odivide", "\"/\"", BINOP_DIV},
788   {"Omod", "\"mod\"", BINOP_MOD},
789   {"Orem", "\"rem\"", BINOP_REM},
790   {"Oexpon", "\"**\"", BINOP_EXP},
791   {"Olt", "\"<\"", BINOP_LESS},
792   {"Ole", "\"<=\"", BINOP_LEQ},
793   {"Ogt", "\">\"", BINOP_GTR},
794   {"Oge", "\">=\"", BINOP_GEQ},
795   {"Oeq", "\"=\"", BINOP_EQUAL},
796   {"One", "\"/=\"", BINOP_NOTEQUAL},
797   {"Oand", "\"and\"", BINOP_BITWISE_AND},
798   {"Oor", "\"or\"", BINOP_BITWISE_IOR},
799   {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
800   {"Oconcat", "\"&\"", BINOP_CONCAT},
801   {"Oabs", "\"abs\"", UNOP_ABS},
802   {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
803   {"Oadd", "\"+\"", UNOP_PLUS},
804   {"Osubtract", "\"-\"", UNOP_NEG},
805   {NULL, NULL}
806 };
807
808 /* Return non-zero if STR should be suppressed in info listings.  */
809
810 static int
811 is_suppressed_name (const char *str)
812 {
813   if (strncmp (str, "_ada_", 5) == 0)
814     str += 5;
815   if (str[0] == '_' || str[0] == '\000')
816     return 1;
817   else
818     {
819       const char *p;
820       const char *suffix = strstr (str, "___");
821       if (suffix != NULL && suffix[3] != 'X')
822         return 1;
823       if (suffix == NULL)
824         suffix = str + strlen (str);
825       for (p = suffix - 1; p != str; p -= 1)
826         if (isupper (*p))
827           {
828             int i;
829             if (p[0] == 'X' && p[-1] != '_')
830               goto OK;
831             if (*p != 'O')
832               return 1;
833             for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
834               if (strncmp (ada_opname_table[i].encoded, p,
835                            strlen (ada_opname_table[i].encoded)) == 0)
836                 goto OK;
837             return 1;
838           OK:;
839           }
840       return 0;
841     }
842 }
843
844 /* The "encoded" form of DECODED, according to GNAT conventions.
845    The result is valid until the next call to ada_encode.  */
846
847 char *
848 ada_encode (const char *decoded)
849 {
850   static char *encoding_buffer = NULL;
851   static size_t encoding_buffer_size = 0;
852   const char *p;
853   int k;
854
855   if (decoded == NULL)
856     return NULL;
857
858   GROW_VECT (encoding_buffer, encoding_buffer_size,
859              2 * strlen (decoded) + 10);
860
861   k = 0;
862   for (p = decoded; *p != '\0'; p += 1)
863     {
864       if (!ADA_RETAIN_DOTS && *p == '.')
865         {
866           encoding_buffer[k] = encoding_buffer[k + 1] = '_';
867           k += 2;
868         }
869       else if (*p == '"')
870         {
871           const struct ada_opname_map *mapping;
872
873           for (mapping = ada_opname_table;
874                mapping->encoded != NULL
875                && strncmp (mapping->decoded, p,
876                            strlen (mapping->decoded)) != 0; mapping += 1)
877             ;
878           if (mapping->encoded == NULL)
879             error ("invalid Ada operator name: %s", p);
880           strcpy (encoding_buffer + k, mapping->encoded);
881           k += strlen (mapping->encoded);
882           break;
883         }
884       else
885         {
886           encoding_buffer[k] = *p;
887           k += 1;
888         }
889     }
890
891   encoding_buffer[k] = '\0';
892   return encoding_buffer;
893 }
894
895 /* Return NAME folded to lower case, or, if surrounded by single
896    quotes, unfolded, but with the quotes stripped away.  Result good
897    to next call.  */
898
899 char *
900 ada_fold_name (const char *name)
901 {
902   static char *fold_buffer = NULL;
903   static size_t fold_buffer_size = 0;
904
905   int len = strlen (name);
906   GROW_VECT (fold_buffer, fold_buffer_size, len + 1);
907
908   if (name[0] == '\'')
909     {
910       strncpy (fold_buffer, name + 1, len - 2);
911       fold_buffer[len - 2] = '\000';
912     }
913   else
914     {
915       int i;
916       for (i = 0; i <= len; i += 1)
917         fold_buffer[i] = tolower (name[i]);
918     }
919
920   return fold_buffer;
921 }
922
923 /* decode:
924      0. Discard trailing .{DIGIT}+ or trailing ___{DIGIT}+
925         These are suffixes introduced by GNAT5 to nested subprogram
926         names, and do not serve any purpose for the debugger.
927      1. Discard final __{DIGIT}+ or $({DIGIT}+(__{DIGIT}+)*)
928      2. Convert other instances of embedded "__" to `.'.
929      3. Discard leading _ada_.
930      4. Convert operator names to the appropriate quoted symbols.
931      5. Remove everything after first ___ if it is followed by
932         'X'.
933      6. Replace TK__ with __, and a trailing B or TKB with nothing.
934      7. Put symbols that should be suppressed in <...> brackets.
935      8. Remove trailing X[bn]* suffix (indicating names in package bodies).
936
937    The resulting string is valid until the next call of ada_decode.
938    If the string is unchanged by demangling, the original string pointer
939    is returned.  */
940
941 const char *
942 ada_decode (const char *encoded)
943 {
944   int i, j;
945   int len0;
946   const char *p;
947   char *decoded;
948   int at_start_name;
949   static char *decoding_buffer = NULL;
950   static size_t decoding_buffer_size = 0;
951
952   if (strncmp (encoded, "_ada_", 5) == 0)
953     encoded += 5;
954
955   if (encoded[0] == '_' || encoded[0] == '<')
956     goto Suppress;
957
958   /* Remove trailing .{DIGIT}+ or ___{DIGIT}+.  */
959   len0 = strlen (encoded);
960   if (len0 > 1 && isdigit (encoded[len0 - 1]))
961     {
962       i = len0 - 2;
963       while (i > 0 && isdigit (encoded[i]))
964         i--;
965       if (i >= 0 && encoded[i] == '.')
966         len0 = i;
967       else if (i >= 2 && strncmp (encoded + i - 2, "___", 3) == 0)
968         len0 = i - 2;
969     }
970
971   /* Remove the ___X.* suffix if present.  Do not forget to verify that
972      the suffix is located before the current "end" of ENCODED.  We want
973      to avoid re-matching parts of ENCODED that have previously been
974      marked as discarded (by decrementing LEN0).  */
975   p = strstr (encoded, "___");
976   if (p != NULL && p - encoded < len0 - 3)
977     {
978       if (p[3] == 'X')
979         len0 = p - encoded;
980       else
981         goto Suppress;
982     }
983
984   if (len0 > 3 && strncmp (encoded + len0 - 3, "TKB", 3) == 0)
985     len0 -= 3;
986
987   if (len0 > 1 && strncmp (encoded + len0 - 1, "B", 1) == 0)
988     len0 -= 1;
989
990   /* Make decoded big enough for possible expansion by operator name.  */
991   GROW_VECT (decoding_buffer, decoding_buffer_size, 2 * len0 + 1);
992   decoded = decoding_buffer;
993
994   if (len0 > 1 && isdigit (encoded[len0 - 1]))
995     {
996       i = len0 - 2;
997       while ((i >= 0 && isdigit (encoded[i]))
998              || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
999         i -= 1;
1000       if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1001         len0 = i - 1;
1002       else if (encoded[i] == '$')
1003         len0 = i;
1004     }
1005
1006   for (i = 0, j = 0; i < len0 && !isalpha (encoded[i]); i += 1, j += 1)
1007     decoded[j] = encoded[i];
1008
1009   at_start_name = 1;
1010   while (i < len0)
1011     {
1012       if (at_start_name && encoded[i] == 'O')
1013         {
1014           int k;
1015           for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1016             {
1017               int op_len = strlen (ada_opname_table[k].encoded);
1018               if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1019                             op_len - 1) == 0)
1020                   && !isalnum (encoded[i + op_len]))
1021                 {
1022                   strcpy (decoded + j, ada_opname_table[k].decoded);
1023                   at_start_name = 0;
1024                   i += op_len;
1025                   j += strlen (ada_opname_table[k].decoded);
1026                   break;
1027                 }
1028             }
1029           if (ada_opname_table[k].encoded != NULL)
1030             continue;
1031         }
1032       at_start_name = 0;
1033
1034       if (i < len0 - 4 && strncmp (encoded + i, "TK__", 4) == 0)
1035         i += 2;
1036       if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1037         {
1038           do
1039             i += 1;
1040           while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1041           if (i < len0)
1042             goto Suppress;
1043         }
1044       else if (!ADA_RETAIN_DOTS
1045                && i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1046         {
1047           decoded[j] = '.';
1048           at_start_name = 1;
1049           i += 2;
1050           j += 1;
1051         }
1052       else
1053         {
1054           decoded[j] = encoded[i];
1055           i += 1;
1056           j += 1;
1057         }
1058     }
1059   decoded[j] = '\000';
1060
1061   for (i = 0; decoded[i] != '\0'; i += 1)
1062     if (isupper (decoded[i]) || decoded[i] == ' ')
1063       goto Suppress;
1064
1065   if (strcmp (decoded, encoded) == 0)
1066     return encoded;
1067   else
1068     return decoded;
1069
1070 Suppress:
1071   GROW_VECT (decoding_buffer, decoding_buffer_size, strlen (encoded) + 3);
1072   decoded = decoding_buffer;
1073   if (encoded[0] == '<')
1074     strcpy (decoded, encoded);
1075   else
1076     sprintf (decoded, "<%s>", encoded);
1077   return decoded;
1078
1079 }
1080
1081 /* Table for keeping permanent unique copies of decoded names.  Once
1082    allocated, names in this table are never released.  While this is a
1083    storage leak, it should not be significant unless there are massive
1084    changes in the set of decoded names in successive versions of a 
1085    symbol table loaded during a single session.  */
1086 static struct htab *decoded_names_store;
1087
1088 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1089    in the language-specific part of GSYMBOL, if it has not been
1090    previously computed.  Tries to save the decoded name in the same
1091    obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1092    in any case, the decoded symbol has a lifetime at least that of
1093    GSYMBOL).  
1094    The GSYMBOL parameter is "mutable" in the C++ sense: logically
1095    const, but nevertheless modified to a semantically equivalent form
1096    when a decoded name is cached in it.
1097 */
1098
1099 char *
1100 ada_decode_symbol (const struct general_symbol_info *gsymbol)
1101 {
1102   char **resultp =
1103     (char **) &gsymbol->language_specific.cplus_specific.demangled_name;
1104   if (*resultp == NULL)
1105     {
1106       const char *decoded = ada_decode (gsymbol->name);
1107       if (gsymbol->bfd_section != NULL)
1108         {
1109           bfd *obfd = gsymbol->bfd_section->owner;
1110           if (obfd != NULL)
1111             {
1112               struct objfile *objf;
1113               ALL_OBJFILES (objf)
1114               {
1115                 if (obfd == objf->obfd)
1116                   {
1117                     *resultp = obsavestring (decoded, strlen (decoded),
1118                                              &objf->objfile_obstack);
1119                     break;
1120                   }
1121               }
1122             }
1123         }
1124       /* Sometimes, we can't find a corresponding objfile, in which
1125          case, we put the result on the heap.  Since we only decode
1126          when needed, we hope this usually does not cause a
1127          significant memory leak (FIXME).  */
1128       if (*resultp == NULL)
1129         {
1130           char **slot = (char **) htab_find_slot (decoded_names_store,
1131                                                   decoded, INSERT);
1132           if (*slot == NULL)
1133             *slot = xstrdup (decoded);
1134           *resultp = *slot;
1135         }
1136     }
1137
1138   return *resultp;
1139 }
1140
1141 char *
1142 ada_la_decode (const char *encoded, int options)
1143 {
1144   return xstrdup (ada_decode (encoded));
1145 }
1146
1147 /* Returns non-zero iff SYM_NAME matches NAME, ignoring any trailing
1148    suffixes that encode debugging information or leading _ada_ on
1149    SYM_NAME (see is_name_suffix commentary for the debugging
1150    information that is ignored).  If WILD, then NAME need only match a
1151    suffix of SYM_NAME minus the same suffixes.  Also returns 0 if
1152    either argument is NULL.  */
1153
1154 int
1155 ada_match_name (const char *sym_name, const char *name, int wild)
1156 {
1157   if (sym_name == NULL || name == NULL)
1158     return 0;
1159   else if (wild)
1160     return wild_match (name, strlen (name), sym_name);
1161   else
1162     {
1163       int len_name = strlen (name);
1164       return (strncmp (sym_name, name, len_name) == 0
1165               && is_name_suffix (sym_name + len_name))
1166         || (strncmp (sym_name, "_ada_", 5) == 0
1167             && strncmp (sym_name + 5, name, len_name) == 0
1168             && is_name_suffix (sym_name + len_name + 5));
1169     }
1170 }
1171
1172 /* True (non-zero) iff, in Ada mode, the symbol SYM should be
1173    suppressed in info listings.  */
1174
1175 int
1176 ada_suppress_symbol_printing (struct symbol *sym)
1177 {
1178   if (SYMBOL_DOMAIN (sym) == STRUCT_DOMAIN)
1179     return 1;
1180   else
1181     return is_suppressed_name (SYMBOL_LINKAGE_NAME (sym));
1182 }
1183 \f
1184
1185                                 /* Arrays */
1186
1187 /* Names of MAX_ADA_DIMENS bounds in P_BOUNDS fields of array descriptors.  */
1188
1189 static char *bound_name[] = {
1190   "LB0", "UB0", "LB1", "UB1", "LB2", "UB2", "LB3", "UB3",
1191   "LB4", "UB4", "LB5", "UB5", "LB6", "UB6", "LB7", "UB7"
1192 };
1193
1194 /* Maximum number of array dimensions we are prepared to handle.  */
1195
1196 #define MAX_ADA_DIMENS (sizeof(bound_name) / (2*sizeof(char *)))
1197
1198 /* Like modify_field, but allows bitpos > wordlength.  */
1199
1200 static void
1201 modify_general_field (char *addr, LONGEST fieldval, int bitpos, int bitsize)
1202 {
1203   modify_field (addr + bitpos / 8, fieldval, bitpos % 8, bitsize);
1204 }
1205
1206
1207 /* The desc_* routines return primitive portions of array descriptors
1208    (fat pointers).  */
1209
1210 /* The descriptor or array type, if any, indicated by TYPE; removes
1211    level of indirection, if needed.  */
1212
1213 static struct type *
1214 desc_base_type (struct type *type)
1215 {
1216   if (type == NULL)
1217     return NULL;
1218   CHECK_TYPEDEF (type);
1219   if (type != NULL
1220       && (TYPE_CODE (type) == TYPE_CODE_PTR
1221           || TYPE_CODE (type) == TYPE_CODE_REF))
1222     return check_typedef (TYPE_TARGET_TYPE (type));
1223   else
1224     return type;
1225 }
1226
1227 /* True iff TYPE indicates a "thin" array pointer type.  */
1228
1229 static int
1230 is_thin_pntr (struct type *type)
1231 {
1232   return
1233     is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1234     || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1235 }
1236
1237 /* The descriptor type for thin pointer type TYPE.  */
1238
1239 static struct type *
1240 thin_descriptor_type (struct type *type)
1241 {
1242   struct type *base_type = desc_base_type (type);
1243   if (base_type == NULL)
1244     return NULL;
1245   if (is_suffix (ada_type_name (base_type), "___XVE"))
1246     return base_type;
1247   else
1248     {
1249       struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1250       if (alt_type == NULL)
1251         return base_type;
1252       else
1253         return alt_type;
1254     }
1255 }
1256
1257 /* A pointer to the array data for thin-pointer value VAL.  */
1258
1259 static struct value *
1260 thin_data_pntr (struct value *val)
1261 {
1262   struct type *type = VALUE_TYPE (val);
1263   if (TYPE_CODE (type) == TYPE_CODE_PTR)
1264     return value_cast (desc_data_type (thin_descriptor_type (type)),
1265                        value_copy (val));
1266   else
1267     return value_from_longest (desc_data_type (thin_descriptor_type (type)),
1268                                VALUE_ADDRESS (val) + VALUE_OFFSET (val));
1269 }
1270
1271 /* True iff TYPE indicates a "thick" array pointer type.  */
1272
1273 static int
1274 is_thick_pntr (struct type *type)
1275 {
1276   type = desc_base_type (type);
1277   return (type != NULL && TYPE_CODE (type) == TYPE_CODE_STRUCT
1278           && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1279 }
1280
1281 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1282    pointer to one, the type of its bounds data; otherwise, NULL.  */
1283
1284 static struct type *
1285 desc_bounds_type (struct type *type)
1286 {
1287   struct type *r;
1288
1289   type = desc_base_type (type);
1290
1291   if (type == NULL)
1292     return NULL;
1293   else if (is_thin_pntr (type))
1294     {
1295       type = thin_descriptor_type (type);
1296       if (type == NULL)
1297         return NULL;
1298       r = lookup_struct_elt_type (type, "BOUNDS", 1);
1299       if (r != NULL)
1300         return check_typedef (r);
1301     }
1302   else if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
1303     {
1304       r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1305       if (r != NULL)
1306         return check_typedef (TYPE_TARGET_TYPE (check_typedef (r)));
1307     }
1308   return NULL;
1309 }
1310
1311 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1312    one, a pointer to its bounds data.   Otherwise NULL.  */
1313
1314 static struct value *
1315 desc_bounds (struct value *arr)
1316 {
1317   struct type *type = check_typedef (VALUE_TYPE (arr));
1318   if (is_thin_pntr (type))
1319     {
1320       struct type *bounds_type =
1321         desc_bounds_type (thin_descriptor_type (type));
1322       LONGEST addr;
1323
1324       if (desc_bounds_type == NULL)
1325         error ("Bad GNAT array descriptor");
1326
1327       /* NOTE: The following calculation is not really kosher, but
1328          since desc_type is an XVE-encoded type (and shouldn't be),
1329          the correct calculation is a real pain.  FIXME (and fix GCC).  */
1330       if (TYPE_CODE (type) == TYPE_CODE_PTR)
1331         addr = value_as_long (arr);
1332       else
1333         addr = VALUE_ADDRESS (arr) + VALUE_OFFSET (arr);
1334
1335       return
1336         value_from_longest (lookup_pointer_type (bounds_type),
1337                             addr - TYPE_LENGTH (bounds_type));
1338     }
1339
1340   else if (is_thick_pntr (type))
1341     return value_struct_elt (&arr, NULL, "P_BOUNDS", NULL,
1342                              "Bad GNAT array descriptor");
1343   else
1344     return NULL;
1345 }
1346
1347 /* If TYPE is the type of an array-descriptor (fat pointer),  the bit
1348    position of the field containing the address of the bounds data.  */
1349
1350 static int
1351 fat_pntr_bounds_bitpos (struct type *type)
1352 {
1353   return TYPE_FIELD_BITPOS (desc_base_type (type), 1);
1354 }
1355
1356 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1357    size of the field containing the address of the bounds data.  */
1358
1359 static int
1360 fat_pntr_bounds_bitsize (struct type *type)
1361 {
1362   type = desc_base_type (type);
1363
1364   if (TYPE_FIELD_BITSIZE (type, 1) > 0)
1365     return TYPE_FIELD_BITSIZE (type, 1);
1366   else
1367     return 8 * TYPE_LENGTH (check_typedef (TYPE_FIELD_TYPE (type, 1)));
1368 }
1369
1370 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1371    pointer to one, the type of its array data (a
1372    pointer-to-array-with-no-bounds type); otherwise, NULL.  Use
1373    ada_type_of_array to get an array type with bounds data.  */
1374
1375 static struct type *
1376 desc_data_type (struct type *type)
1377 {
1378   type = desc_base_type (type);
1379
1380   /* NOTE: The following is bogus; see comment in desc_bounds.  */
1381   if (is_thin_pntr (type))
1382     return lookup_pointer_type
1383       (desc_base_type (TYPE_FIELD_TYPE (thin_descriptor_type (type), 1)));
1384   else if (is_thick_pntr (type))
1385     return lookup_struct_elt_type (type, "P_ARRAY", 1);
1386   else
1387     return NULL;
1388 }
1389
1390 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1391    its array data.  */
1392
1393 static struct value *
1394 desc_data (struct value *arr)
1395 {
1396   struct type *type = VALUE_TYPE (arr);
1397   if (is_thin_pntr (type))
1398     return thin_data_pntr (arr);
1399   else if (is_thick_pntr (type))
1400     return value_struct_elt (&arr, NULL, "P_ARRAY", NULL,
1401                              "Bad GNAT array descriptor");
1402   else
1403     return NULL;
1404 }
1405
1406
1407 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1408    position of the field containing the address of the data.  */
1409
1410 static int
1411 fat_pntr_data_bitpos (struct type *type)
1412 {
1413   return TYPE_FIELD_BITPOS (desc_base_type (type), 0);
1414 }
1415
1416 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1417    size of the field containing the address of the data.  */
1418
1419 static int
1420 fat_pntr_data_bitsize (struct type *type)
1421 {
1422   type = desc_base_type (type);
1423
1424   if (TYPE_FIELD_BITSIZE (type, 0) > 0)
1425     return TYPE_FIELD_BITSIZE (type, 0);
1426   else
1427     return TARGET_CHAR_BIT * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 0));
1428 }
1429
1430 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1431    the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1432    bound, if WHICH is 1.  The first bound is I=1.  */
1433
1434 static struct value *
1435 desc_one_bound (struct value *bounds, int i, int which)
1436 {
1437   return value_struct_elt (&bounds, NULL, bound_name[2 * i + which - 2], NULL,
1438                            "Bad GNAT array descriptor bounds");
1439 }
1440
1441 /* If BOUNDS is an array-bounds structure type, return the bit position
1442    of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1443    bound, if WHICH is 1.  The first bound is I=1.  */
1444
1445 static int
1446 desc_bound_bitpos (struct type *type, int i, int which)
1447 {
1448   return TYPE_FIELD_BITPOS (desc_base_type (type), 2 * i + which - 2);
1449 }
1450
1451 /* If BOUNDS is an array-bounds structure type, return the bit field size
1452    of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1453    bound, if WHICH is 1.  The first bound is I=1.  */
1454
1455 static int
1456 desc_bound_bitsize (struct type *type, int i, int which)
1457 {
1458   type = desc_base_type (type);
1459
1460   if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
1461     return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
1462   else
1463     return 8 * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 2 * i + which - 2));
1464 }
1465
1466 /* If TYPE is the type of an array-bounds structure, the type of its
1467    Ith bound (numbering from 1).  Otherwise, NULL.  */
1468
1469 static struct type *
1470 desc_index_type (struct type *type, int i)
1471 {
1472   type = desc_base_type (type);
1473
1474   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
1475     return lookup_struct_elt_type (type, bound_name[2 * i - 2], 1);
1476   else
1477     return NULL;
1478 }
1479
1480 /* The number of index positions in the array-bounds type TYPE.
1481    Return 0 if TYPE is NULL.  */
1482
1483 static int
1484 desc_arity (struct type *type)
1485 {
1486   type = desc_base_type (type);
1487
1488   if (type != NULL)
1489     return TYPE_NFIELDS (type) / 2;
1490   return 0;
1491 }
1492
1493 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or 
1494    an array descriptor type (representing an unconstrained array
1495    type).  */
1496
1497 static int
1498 ada_is_direct_array_type (struct type *type)
1499 {
1500   if (type == NULL)
1501     return 0;
1502   CHECK_TYPEDEF (type);
1503   return (TYPE_CODE (type) == TYPE_CODE_ARRAY
1504           || ada_is_array_descriptor_type (type));
1505 }
1506
1507 /* Non-zero iff TYPE is a simple array type or pointer to one.  */
1508
1509 int
1510 ada_is_simple_array_type (struct type *type)
1511 {
1512   if (type == NULL)
1513     return 0;
1514   CHECK_TYPEDEF (type);
1515   return (TYPE_CODE (type) == TYPE_CODE_ARRAY
1516           || (TYPE_CODE (type) == TYPE_CODE_PTR
1517               && TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_ARRAY));
1518 }
1519
1520 /* Non-zero iff TYPE belongs to a GNAT array descriptor.  */
1521
1522 int
1523 ada_is_array_descriptor_type (struct type *type)
1524 {
1525   struct type *data_type = desc_data_type (type);
1526
1527   if (type == NULL)
1528     return 0;
1529   CHECK_TYPEDEF (type);
1530   return
1531     data_type != NULL
1532     && ((TYPE_CODE (data_type) == TYPE_CODE_PTR
1533          && TYPE_TARGET_TYPE (data_type) != NULL
1534          && TYPE_CODE (TYPE_TARGET_TYPE (data_type)) == TYPE_CODE_ARRAY)
1535         || TYPE_CODE (data_type) == TYPE_CODE_ARRAY)
1536     && desc_arity (desc_bounds_type (type)) > 0;
1537 }
1538
1539 /* Non-zero iff type is a partially mal-formed GNAT array
1540    descriptor.  FIXME: This is to compensate for some problems with
1541    debugging output from GNAT.  Re-examine periodically to see if it
1542    is still needed.  */
1543
1544 int
1545 ada_is_bogus_array_descriptor (struct type *type)
1546 {
1547   return
1548     type != NULL
1549     && TYPE_CODE (type) == TYPE_CODE_STRUCT
1550     && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
1551         || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
1552     && !ada_is_array_descriptor_type (type);
1553 }
1554
1555
1556 /* If ARR has a record type in the form of a standard GNAT array descriptor,
1557    (fat pointer) returns the type of the array data described---specifically,
1558    a pointer-to-array type.  If BOUNDS is non-zero, the bounds data are filled
1559    in from the descriptor; otherwise, they are left unspecified.  If
1560    the ARR denotes a null array descriptor and BOUNDS is non-zero,
1561    returns NULL.  The result is simply the type of ARR if ARR is not
1562    a descriptor.  */
1563 struct type *
1564 ada_type_of_array (struct value *arr, int bounds)
1565 {
1566   if (ada_is_packed_array_type (VALUE_TYPE (arr)))
1567     return decode_packed_array_type (VALUE_TYPE (arr));
1568
1569   if (!ada_is_array_descriptor_type (VALUE_TYPE (arr)))
1570     return VALUE_TYPE (arr);
1571
1572   if (!bounds)
1573     return
1574       check_typedef (TYPE_TARGET_TYPE (desc_data_type (VALUE_TYPE (arr))));
1575   else
1576     {
1577       struct type *elt_type;
1578       int arity;
1579       struct value *descriptor;
1580       struct objfile *objf = TYPE_OBJFILE (VALUE_TYPE (arr));
1581
1582       elt_type = ada_array_element_type (VALUE_TYPE (arr), -1);
1583       arity = ada_array_arity (VALUE_TYPE (arr));
1584
1585       if (elt_type == NULL || arity == 0)
1586         return check_typedef (VALUE_TYPE (arr));
1587
1588       descriptor = desc_bounds (arr);
1589       if (value_as_long (descriptor) == 0)
1590         return NULL;
1591       while (arity > 0)
1592         {
1593           struct type *range_type = alloc_type (objf);
1594           struct type *array_type = alloc_type (objf);
1595           struct value *low = desc_one_bound (descriptor, arity, 0);
1596           struct value *high = desc_one_bound (descriptor, arity, 1);
1597           arity -= 1;
1598
1599           create_range_type (range_type, VALUE_TYPE (low),
1600                              (int) value_as_long (low),
1601                              (int) value_as_long (high));
1602           elt_type = create_array_type (array_type, elt_type, range_type);
1603         }
1604
1605       return lookup_pointer_type (elt_type);
1606     }
1607 }
1608
1609 /* If ARR does not represent an array, returns ARR unchanged.
1610    Otherwise, returns either a standard GDB array with bounds set
1611    appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
1612    GDB array.  Returns NULL if ARR is a null fat pointer.  */
1613
1614 struct value *
1615 ada_coerce_to_simple_array_ptr (struct value *arr)
1616 {
1617   if (ada_is_array_descriptor_type (VALUE_TYPE (arr)))
1618     {
1619       struct type *arrType = ada_type_of_array (arr, 1);
1620       if (arrType == NULL)
1621         return NULL;
1622       return value_cast (arrType, value_copy (desc_data (arr)));
1623     }
1624   else if (ada_is_packed_array_type (VALUE_TYPE (arr)))
1625     return decode_packed_array (arr);
1626   else
1627     return arr;
1628 }
1629
1630 /* If ARR does not represent an array, returns ARR unchanged.
1631    Otherwise, returns a standard GDB array describing ARR (which may
1632    be ARR itself if it already is in the proper form).  */
1633
1634 static struct value *
1635 ada_coerce_to_simple_array (struct value *arr)
1636 {
1637   if (ada_is_array_descriptor_type (VALUE_TYPE (arr)))
1638     {
1639       struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
1640       if (arrVal == NULL)
1641         error ("Bounds unavailable for null array pointer.");
1642       return value_ind (arrVal);
1643     }
1644   else if (ada_is_packed_array_type (VALUE_TYPE (arr)))
1645     return decode_packed_array (arr);
1646   else
1647     return arr;
1648 }
1649
1650 /* If TYPE represents a GNAT array type, return it translated to an
1651    ordinary GDB array type (possibly with BITSIZE fields indicating
1652    packing).  For other types, is the identity.  */
1653
1654 struct type *
1655 ada_coerce_to_simple_array_type (struct type *type)
1656 {
1657   struct value *mark = value_mark ();
1658   struct value *dummy = value_from_longest (builtin_type_long, 0);
1659   struct type *result;
1660   VALUE_TYPE (dummy) = type;
1661   result = ada_type_of_array (dummy, 0);
1662   value_free_to_mark (mark);
1663   return result;
1664 }
1665
1666 /* Non-zero iff TYPE represents a standard GNAT packed-array type.  */
1667
1668 int
1669 ada_is_packed_array_type (struct type *type)
1670 {
1671   if (type == NULL)
1672     return 0;
1673   type = desc_base_type (type);
1674   CHECK_TYPEDEF (type);
1675   return
1676     ada_type_name (type) != NULL
1677     && strstr (ada_type_name (type), "___XP") != NULL;
1678 }
1679
1680 /* Given that TYPE is a standard GDB array type with all bounds filled
1681    in, and that the element size of its ultimate scalar constituents
1682    (that is, either its elements, or, if it is an array of arrays, its
1683    elements' elements, etc.) is *ELT_BITS, return an identical type,
1684    but with the bit sizes of its elements (and those of any
1685    constituent arrays) recorded in the BITSIZE components of its
1686    TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
1687    in bits.  */
1688
1689 static struct type *
1690 packed_array_type (struct type *type, long *elt_bits)
1691 {
1692   struct type *new_elt_type;
1693   struct type *new_type;
1694   LONGEST low_bound, high_bound;
1695
1696   CHECK_TYPEDEF (type);
1697   if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
1698     return type;
1699
1700   new_type = alloc_type (TYPE_OBJFILE (type));
1701   new_elt_type = packed_array_type (check_typedef (TYPE_TARGET_TYPE (type)),
1702                                     elt_bits);
1703   create_array_type (new_type, new_elt_type, TYPE_FIELD_TYPE (type, 0));
1704   TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
1705   TYPE_NAME (new_type) = ada_type_name (type);
1706
1707   if (get_discrete_bounds (TYPE_FIELD_TYPE (type, 0),
1708                            &low_bound, &high_bound) < 0)
1709     low_bound = high_bound = 0;
1710   if (high_bound < low_bound)
1711     *elt_bits = TYPE_LENGTH (new_type) = 0;
1712   else
1713     {
1714       *elt_bits *= (high_bound - low_bound + 1);
1715       TYPE_LENGTH (new_type) =
1716         (*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
1717     }
1718
1719   TYPE_FLAGS (new_type) |= TYPE_FLAG_FIXED_INSTANCE;
1720   return new_type;
1721 }
1722
1723 /* The array type encoded by TYPE, where ada_is_packed_array_type (TYPE).  */
1724
1725 static struct type *
1726 decode_packed_array_type (struct type *type)
1727 {
1728   struct symbol *sym;
1729   struct block **blocks;
1730   const char *raw_name = ada_type_name (check_typedef (type));
1731   char *name = (char *) alloca (strlen (raw_name) + 1);
1732   char *tail = strstr (raw_name, "___XP");
1733   struct type *shadow_type;
1734   long bits;
1735   int i, n;
1736
1737   type = desc_base_type (type);
1738
1739   memcpy (name, raw_name, tail - raw_name);
1740   name[tail - raw_name] = '\000';
1741
1742   sym = standard_lookup (name, get_selected_block (0), VAR_DOMAIN);
1743   if (sym == NULL || SYMBOL_TYPE (sym) == NULL)
1744     {
1745       lim_warning ("could not find bounds information on packed array", 0);
1746       return NULL;
1747     }
1748   shadow_type = SYMBOL_TYPE (sym);
1749
1750   if (TYPE_CODE (shadow_type) != TYPE_CODE_ARRAY)
1751     {
1752       lim_warning ("could not understand bounds information on packed array",
1753                    0);
1754       return NULL;
1755     }
1756
1757   if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
1758     {
1759       lim_warning
1760         ("could not understand bit size information on packed array", 0);
1761       return NULL;
1762     }
1763
1764   return packed_array_type (shadow_type, &bits);
1765 }
1766
1767 /* Given that ARR is a struct value *indicating a GNAT packed array,
1768    returns a simple array that denotes that array.  Its type is a
1769    standard GDB array type except that the BITSIZEs of the array
1770    target types are set to the number of bits in each element, and the
1771    type length is set appropriately.  */
1772
1773 static struct value *
1774 decode_packed_array (struct value *arr)
1775 {
1776   struct type *type;
1777
1778   arr = ada_coerce_ref (arr);
1779   if (TYPE_CODE (VALUE_TYPE (arr)) == TYPE_CODE_PTR)
1780     arr = ada_value_ind (arr);
1781
1782   type = decode_packed_array_type (VALUE_TYPE (arr));
1783   if (type == NULL)
1784     {
1785       error ("can't unpack array");
1786       return NULL;
1787     }
1788   return coerce_unspec_val_to_type (arr, type);
1789 }
1790
1791
1792 /* The value of the element of packed array ARR at the ARITY indices
1793    given in IND.   ARR must be a simple array.  */
1794
1795 static struct value *
1796 value_subscript_packed (struct value *arr, int arity, struct value **ind)
1797 {
1798   int i;
1799   int bits, elt_off, bit_off;
1800   long elt_total_bit_offset;
1801   struct type *elt_type;
1802   struct value *v;
1803
1804   bits = 0;
1805   elt_total_bit_offset = 0;
1806   elt_type = check_typedef (VALUE_TYPE (arr));
1807   for (i = 0; i < arity; i += 1)
1808     {
1809       if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY
1810           || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
1811         error
1812           ("attempt to do packed indexing of something other than a packed array");
1813       else
1814         {
1815           struct type *range_type = TYPE_INDEX_TYPE (elt_type);
1816           LONGEST lowerbound, upperbound;
1817           LONGEST idx;
1818
1819           if (get_discrete_bounds (range_type, &lowerbound, &upperbound) < 0)
1820             {
1821               lim_warning ("don't know bounds of array", 0);
1822               lowerbound = upperbound = 0;
1823             }
1824
1825           idx = value_as_long (value_pos_atr (ind[i]));
1826           if (idx < lowerbound || idx > upperbound)
1827             lim_warning ("packed array index %ld out of bounds", (long) idx);
1828           bits = TYPE_FIELD_BITSIZE (elt_type, 0);
1829           elt_total_bit_offset += (idx - lowerbound) * bits;
1830           elt_type = check_typedef (TYPE_TARGET_TYPE (elt_type));
1831         }
1832     }
1833   elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
1834   bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
1835
1836   v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
1837                                       bits, elt_type);
1838   if (VALUE_LVAL (arr) == lval_internalvar)
1839     VALUE_LVAL (v) = lval_internalvar_component;
1840   else
1841     VALUE_LVAL (v) = VALUE_LVAL (arr);
1842   return v;
1843 }
1844
1845 /* Non-zero iff TYPE includes negative integer values.  */
1846
1847 static int
1848 has_negatives (struct type *type)
1849 {
1850   switch (TYPE_CODE (type))
1851     {
1852     default:
1853       return 0;
1854     case TYPE_CODE_INT:
1855       return !TYPE_UNSIGNED (type);
1856     case TYPE_CODE_RANGE:
1857       return TYPE_LOW_BOUND (type) < 0;
1858     }
1859 }
1860
1861
1862 /* Create a new value of type TYPE from the contents of OBJ starting
1863    at byte OFFSET, and bit offset BIT_OFFSET within that byte,
1864    proceeding for BIT_SIZE bits.  If OBJ is an lval in memory, then
1865    assigning through the result will set the field fetched from.  
1866    VALADDR is ignored unless OBJ is NULL, in which case,
1867    VALADDR+OFFSET must address the start of storage containing the 
1868    packed value.  The value returned  in this case is never an lval.
1869    Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT.  */
1870
1871 struct value *
1872 ada_value_primitive_packed_val (struct value *obj, char *valaddr, long offset,
1873                                 int bit_offset, int bit_size,
1874                                 struct type *type)
1875 {
1876   struct value *v;
1877   int src,                      /* Index into the source area */
1878     targ,                       /* Index into the target area */
1879     srcBitsLeft,                /* Number of source bits left to move */
1880     nsrc, ntarg,                /* Number of source and target bytes */
1881     unusedLS,                   /* Number of bits in next significant
1882                                    byte of source that are unused */
1883     accumSize;                  /* Number of meaningful bits in accum */
1884   unsigned char *bytes;         /* First byte containing data to unpack */
1885   unsigned char *unpacked;
1886   unsigned long accum;          /* Staging area for bits being transferred */
1887   unsigned char sign;
1888   int len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
1889   /* Transmit bytes from least to most significant; delta is the direction
1890      the indices move.  */
1891   int delta = BITS_BIG_ENDIAN ? -1 : 1;
1892
1893   CHECK_TYPEDEF (type);
1894
1895   if (obj == NULL)
1896     {
1897       v = allocate_value (type);
1898       bytes = (unsigned char *) (valaddr + offset);
1899     }
1900   else if (VALUE_LAZY (obj))
1901     {
1902       v = value_at (type,
1903                     VALUE_ADDRESS (obj) + VALUE_OFFSET (obj) + offset, NULL);
1904       bytes = (unsigned char *) alloca (len);
1905       read_memory (VALUE_ADDRESS (v), bytes, len);
1906     }
1907   else
1908     {
1909       v = allocate_value (type);
1910       bytes = (unsigned char *) VALUE_CONTENTS (obj) + offset;
1911     }
1912
1913   if (obj != NULL)
1914     {
1915       VALUE_LVAL (v) = VALUE_LVAL (obj);
1916       if (VALUE_LVAL (obj) == lval_internalvar)
1917         VALUE_LVAL (v) = lval_internalvar_component;
1918       VALUE_ADDRESS (v) = VALUE_ADDRESS (obj) + VALUE_OFFSET (obj) + offset;
1919       VALUE_BITPOS (v) = bit_offset + VALUE_BITPOS (obj);
1920       VALUE_BITSIZE (v) = bit_size;
1921       if (VALUE_BITPOS (v) >= HOST_CHAR_BIT)
1922         {
1923           VALUE_ADDRESS (v) += 1;
1924           VALUE_BITPOS (v) -= HOST_CHAR_BIT;
1925         }
1926     }
1927   else
1928     VALUE_BITSIZE (v) = bit_size;
1929   unpacked = (unsigned char *) VALUE_CONTENTS (v);
1930
1931   srcBitsLeft = bit_size;
1932   nsrc = len;
1933   ntarg = TYPE_LENGTH (type);
1934   sign = 0;
1935   if (bit_size == 0)
1936     {
1937       memset (unpacked, 0, TYPE_LENGTH (type));
1938       return v;
1939     }
1940   else if (BITS_BIG_ENDIAN)
1941     {
1942       src = len - 1;
1943       if (has_negatives (type)
1944           && ((bytes[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
1945         sign = ~0;
1946
1947       unusedLS =
1948         (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
1949         % HOST_CHAR_BIT;
1950
1951       switch (TYPE_CODE (type))
1952         {
1953         case TYPE_CODE_ARRAY:
1954         case TYPE_CODE_UNION:
1955         case TYPE_CODE_STRUCT:
1956           /* Non-scalar values must be aligned at a byte boundary...  */
1957           accumSize =
1958             (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
1959           /* ... And are placed at the beginning (most-significant) bytes
1960              of the target.  */
1961           targ = src;
1962           break;
1963         default:
1964           accumSize = 0;
1965           targ = TYPE_LENGTH (type) - 1;
1966           break;
1967         }
1968     }
1969   else
1970     {
1971       int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
1972
1973       src = targ = 0;
1974       unusedLS = bit_offset;
1975       accumSize = 0;
1976
1977       if (has_negatives (type) && (bytes[len - 1] & (1 << sign_bit_offset)))
1978         sign = ~0;
1979     }
1980
1981   accum = 0;
1982   while (nsrc > 0)
1983     {
1984       /* Mask for removing bits of the next source byte that are not
1985          part of the value.  */
1986       unsigned int unusedMSMask =
1987         (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
1988         1;
1989       /* Sign-extend bits for this byte.  */
1990       unsigned int signMask = sign & ~unusedMSMask;
1991       accum |=
1992         (((bytes[src] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
1993       accumSize += HOST_CHAR_BIT - unusedLS;
1994       if (accumSize >= HOST_CHAR_BIT)
1995         {
1996           unpacked[targ] = accum & ~(~0L << HOST_CHAR_BIT);
1997           accumSize -= HOST_CHAR_BIT;
1998           accum >>= HOST_CHAR_BIT;
1999           ntarg -= 1;
2000           targ += delta;
2001         }
2002       srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2003       unusedLS = 0;
2004       nsrc -= 1;
2005       src += delta;
2006     }
2007   while (ntarg > 0)
2008     {
2009       accum |= sign << accumSize;
2010       unpacked[targ] = accum & ~(~0L << HOST_CHAR_BIT);
2011       accumSize -= HOST_CHAR_BIT;
2012       accum >>= HOST_CHAR_BIT;
2013       ntarg -= 1;
2014       targ += delta;
2015     }
2016
2017   return v;
2018 }
2019
2020 /* Move N bits from SOURCE, starting at bit offset SRC_OFFSET to
2021    TARGET, starting at bit offset TARG_OFFSET.  SOURCE and TARGET must
2022    not overlap.  */
2023 static void
2024 move_bits (char *target, int targ_offset, char *source, int src_offset, int n)
2025 {
2026   unsigned int accum, mask;
2027   int accum_bits, chunk_size;
2028
2029   target += targ_offset / HOST_CHAR_BIT;
2030   targ_offset %= HOST_CHAR_BIT;
2031   source += src_offset / HOST_CHAR_BIT;
2032   src_offset %= HOST_CHAR_BIT;
2033   if (BITS_BIG_ENDIAN)
2034     {
2035       accum = (unsigned char) *source;
2036       source += 1;
2037       accum_bits = HOST_CHAR_BIT - src_offset;
2038
2039       while (n > 0)
2040         {
2041           int unused_right;
2042           accum = (accum << HOST_CHAR_BIT) + (unsigned char) *source;
2043           accum_bits += HOST_CHAR_BIT;
2044           source += 1;
2045           chunk_size = HOST_CHAR_BIT - targ_offset;
2046           if (chunk_size > n)
2047             chunk_size = n;
2048           unused_right = HOST_CHAR_BIT - (chunk_size + targ_offset);
2049           mask = ((1 << chunk_size) - 1) << unused_right;
2050           *target =
2051             (*target & ~mask)
2052             | ((accum >> (accum_bits - chunk_size - unused_right)) & mask);
2053           n -= chunk_size;
2054           accum_bits -= chunk_size;
2055           target += 1;
2056           targ_offset = 0;
2057         }
2058     }
2059   else
2060     {
2061       accum = (unsigned char) *source >> src_offset;
2062       source += 1;
2063       accum_bits = HOST_CHAR_BIT - src_offset;
2064
2065       while (n > 0)
2066         {
2067           accum = accum + ((unsigned char) *source << accum_bits);
2068           accum_bits += HOST_CHAR_BIT;
2069           source += 1;
2070           chunk_size = HOST_CHAR_BIT - targ_offset;
2071           if (chunk_size > n)
2072             chunk_size = n;
2073           mask = ((1 << chunk_size) - 1) << targ_offset;
2074           *target = (*target & ~mask) | ((accum << targ_offset) & mask);
2075           n -= chunk_size;
2076           accum_bits -= chunk_size;
2077           accum >>= chunk_size;
2078           target += 1;
2079           targ_offset = 0;
2080         }
2081     }
2082 }
2083
2084
2085 /* Store the contents of FROMVAL into the location of TOVAL.
2086    Return a new value with the location of TOVAL and contents of
2087    FROMVAL.   Handles assignment into packed fields that have
2088    floating-point or non-scalar types.  */
2089
2090 static struct value *
2091 ada_value_assign (struct value *toval, struct value *fromval)
2092 {
2093   struct type *type = VALUE_TYPE (toval);
2094   int bits = VALUE_BITSIZE (toval);
2095
2096   if (!toval->modifiable)
2097     error ("Left operand of assignment is not a modifiable lvalue.");
2098
2099   COERCE_REF (toval);
2100
2101   if (VALUE_LVAL (toval) == lval_memory
2102       && bits > 0
2103       && (TYPE_CODE (type) == TYPE_CODE_FLT
2104           || TYPE_CODE (type) == TYPE_CODE_STRUCT))
2105     {
2106       int len =
2107         (VALUE_BITPOS (toval) + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2108       char *buffer = (char *) alloca (len);
2109       struct value *val;
2110
2111       if (TYPE_CODE (type) == TYPE_CODE_FLT)
2112         fromval = value_cast (type, fromval);
2113
2114       read_memory (VALUE_ADDRESS (toval) + VALUE_OFFSET (toval), buffer, len);
2115       if (BITS_BIG_ENDIAN)
2116         move_bits (buffer, VALUE_BITPOS (toval),
2117                    VALUE_CONTENTS (fromval),
2118                    TYPE_LENGTH (VALUE_TYPE (fromval)) * TARGET_CHAR_BIT -
2119                    bits, bits);
2120       else
2121         move_bits (buffer, VALUE_BITPOS (toval), VALUE_CONTENTS (fromval),
2122                    0, bits);
2123       write_memory (VALUE_ADDRESS (toval) + VALUE_OFFSET (toval), buffer,
2124                     len);
2125
2126       val = value_copy (toval);
2127       memcpy (VALUE_CONTENTS_RAW (val), VALUE_CONTENTS (fromval),
2128               TYPE_LENGTH (type));
2129       VALUE_TYPE (val) = type;
2130
2131       return val;
2132     }
2133
2134   return value_assign (toval, fromval);
2135 }
2136
2137
2138 /* The value of the element of array ARR at the ARITY indices given in IND.
2139    ARR may be either a simple array, GNAT array descriptor, or pointer
2140    thereto.  */
2141
2142 struct value *
2143 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2144 {
2145   int k;
2146   struct value *elt;
2147   struct type *elt_type;
2148
2149   elt = ada_coerce_to_simple_array (arr);
2150
2151   elt_type = check_typedef (VALUE_TYPE (elt));
2152   if (TYPE_CODE (elt_type) == TYPE_CODE_ARRAY
2153       && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
2154     return value_subscript_packed (elt, arity, ind);
2155
2156   for (k = 0; k < arity; k += 1)
2157     {
2158       if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY)
2159         error ("too many subscripts (%d expected)", k);
2160       elt = value_subscript (elt, value_pos_atr (ind[k]));
2161     }
2162   return elt;
2163 }
2164
2165 /* Assuming ARR is a pointer to a standard GDB array of type TYPE, the
2166    value of the element of *ARR at the ARITY indices given in
2167    IND.  Does not read the entire array into memory.  */
2168
2169 struct value *
2170 ada_value_ptr_subscript (struct value *arr, struct type *type, int arity,
2171                          struct value **ind)
2172 {
2173   int k;
2174
2175   for (k = 0; k < arity; k += 1)
2176     {
2177       LONGEST lwb, upb;
2178       struct value *idx;
2179
2180       if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
2181         error ("too many subscripts (%d expected)", k);
2182       arr = value_cast (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
2183                         value_copy (arr));
2184       get_discrete_bounds (TYPE_INDEX_TYPE (type), &lwb, &upb);
2185       idx = value_pos_atr (ind[k]);
2186       if (lwb != 0)
2187         idx = value_sub (idx, value_from_longest (builtin_type_int, lwb));
2188       arr = value_add (arr, idx);
2189       type = TYPE_TARGET_TYPE (type);
2190     }
2191
2192   return value_ind (arr);
2193 }
2194
2195 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
2196    actual type of ARRAY_PTR is ignored), returns a reference to
2197    the Ada slice of HIGH-LOW+1 elements starting at index LOW.  The lower
2198    bound of this array is LOW, as per Ada rules. */
2199 static struct value *
2200 ada_value_slice_ptr (struct value *array_ptr, struct type *type,
2201                      int low, int high)
2202 {
2203   CORE_ADDR base = value_as_address (array_ptr)
2204     + ((low - TYPE_LOW_BOUND (TYPE_INDEX_TYPE (type)))
2205        * TYPE_LENGTH (TYPE_TARGET_TYPE (type)));
2206   struct type *index_type =
2207     create_range_type (NULL, TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (type)),
2208                        low, high);
2209   struct type *slice_type =
2210     create_array_type (NULL, TYPE_TARGET_TYPE (type), index_type);
2211   return value_from_pointer (lookup_reference_type (slice_type), base);
2212 }
2213
2214
2215 static struct value *
2216 ada_value_slice (struct value *array, int low, int high)
2217 {
2218   struct type *type = VALUE_TYPE (array);
2219   struct type *index_type =
2220     create_range_type (NULL, TYPE_INDEX_TYPE (type), low, high);
2221   struct type *slice_type =
2222     create_array_type (NULL, TYPE_TARGET_TYPE (type), index_type);
2223   return value_cast (slice_type, value_slice (array, low, high - low + 1));
2224 }
2225
2226 /* If type is a record type in the form of a standard GNAT array
2227    descriptor, returns the number of dimensions for type.  If arr is a
2228    simple array, returns the number of "array of"s that prefix its
2229    type designation.  Otherwise, returns 0.  */
2230
2231 int
2232 ada_array_arity (struct type *type)
2233 {
2234   int arity;
2235
2236   if (type == NULL)
2237     return 0;
2238
2239   type = desc_base_type (type);
2240
2241   arity = 0;
2242   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
2243     return desc_arity (desc_bounds_type (type));
2244   else
2245     while (TYPE_CODE (type) == TYPE_CODE_ARRAY)
2246       {
2247         arity += 1;
2248         type = check_typedef (TYPE_TARGET_TYPE (type));
2249       }
2250
2251   return arity;
2252 }
2253
2254 /* If TYPE is a record type in the form of a standard GNAT array
2255    descriptor or a simple array type, returns the element type for
2256    TYPE after indexing by NINDICES indices, or by all indices if
2257    NINDICES is -1.  Otherwise, returns NULL.  */
2258
2259 struct type *
2260 ada_array_element_type (struct type *type, int nindices)
2261 {
2262   type = desc_base_type (type);
2263
2264   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
2265     {
2266       int k;
2267       struct type *p_array_type;
2268
2269       p_array_type = desc_data_type (type);
2270
2271       k = ada_array_arity (type);
2272       if (k == 0)
2273         return NULL;
2274
2275       /* Initially p_array_type = elt_type(*)[]...(k times)...[].  */
2276       if (nindices >= 0 && k > nindices)
2277         k = nindices;
2278       p_array_type = TYPE_TARGET_TYPE (p_array_type);
2279       while (k > 0 && p_array_type != NULL)
2280         {
2281           p_array_type = check_typedef (TYPE_TARGET_TYPE (p_array_type));
2282           k -= 1;
2283         }
2284       return p_array_type;
2285     }
2286   else if (TYPE_CODE (type) == TYPE_CODE_ARRAY)
2287     {
2288       while (nindices != 0 && TYPE_CODE (type) == TYPE_CODE_ARRAY)
2289         {
2290           type = TYPE_TARGET_TYPE (type);
2291           nindices -= 1;
2292         }
2293       return type;
2294     }
2295
2296   return NULL;
2297 }
2298
2299 /* The type of nth index in arrays of given type (n numbering from 1).
2300    Does not examine memory.  */
2301
2302 struct type *
2303 ada_index_type (struct type *type, int n)
2304 {
2305   struct type *result_type;
2306
2307   type = desc_base_type (type);
2308
2309   if (n > ada_array_arity (type))
2310     return NULL;
2311
2312   if (ada_is_simple_array_type (type))
2313     {
2314       int i;
2315
2316       for (i = 1; i < n; i += 1)
2317         type = TYPE_TARGET_TYPE (type);
2318       result_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type, 0));
2319       /* FIXME: The stabs type r(0,0);bound;bound in an array type
2320          has a target type of TYPE_CODE_UNDEF.  We compensate here, but
2321          perhaps stabsread.c would make more sense.  */
2322       if (result_type == NULL || TYPE_CODE (result_type) == TYPE_CODE_UNDEF)
2323         result_type = builtin_type_int;
2324
2325       return result_type;
2326     }
2327   else
2328     return desc_index_type (desc_bounds_type (type), n);
2329 }
2330
2331 /* Given that arr is an array type, returns the lower bound of the
2332    Nth index (numbering from 1) if WHICH is 0, and the upper bound if
2333    WHICH is 1.  This returns bounds 0 .. -1 if ARR_TYPE is an
2334    array-descriptor type.  If TYPEP is non-null, *TYPEP is set to the
2335    bounds type.  It works for other arrays with bounds supplied by
2336    run-time quantities other than discriminants.  */
2337
2338 LONGEST
2339 ada_array_bound_from_type (struct type * arr_type, int n, int which,
2340                            struct type ** typep)
2341 {
2342   struct type *type;
2343   struct type *index_type_desc;
2344
2345   if (ada_is_packed_array_type (arr_type))
2346     arr_type = decode_packed_array_type (arr_type);
2347
2348   if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
2349     {
2350       if (typep != NULL)
2351         *typep = builtin_type_int;
2352       return (LONGEST) - which;
2353     }
2354
2355   if (TYPE_CODE (arr_type) == TYPE_CODE_PTR)
2356     type = TYPE_TARGET_TYPE (arr_type);
2357   else
2358     type = arr_type;
2359
2360   index_type_desc = ada_find_parallel_type (type, "___XA");
2361   if (index_type_desc == NULL)
2362     {
2363       struct type *range_type;
2364       struct type *index_type;
2365
2366       while (n > 1)
2367         {
2368           type = TYPE_TARGET_TYPE (type);
2369           n -= 1;
2370         }
2371
2372       range_type = TYPE_INDEX_TYPE (type);
2373       index_type = TYPE_TARGET_TYPE (range_type);
2374       if (TYPE_CODE (index_type) == TYPE_CODE_UNDEF)
2375         index_type = builtin_type_long;
2376       if (typep != NULL)
2377         *typep = index_type;
2378       return
2379         (LONGEST) (which == 0
2380                    ? TYPE_LOW_BOUND (range_type)
2381                    : TYPE_HIGH_BOUND (range_type));
2382     }
2383   else
2384     {
2385       struct type *index_type =
2386         to_fixed_range_type (TYPE_FIELD_NAME (index_type_desc, n - 1),
2387                              NULL, TYPE_OBJFILE (arr_type));
2388       if (typep != NULL)
2389         *typep = TYPE_TARGET_TYPE (index_type);
2390       return
2391         (LONGEST) (which == 0
2392                    ? TYPE_LOW_BOUND (index_type)
2393                    : TYPE_HIGH_BOUND (index_type));
2394     }
2395 }
2396
2397 /* Given that arr is an array value, returns the lower bound of the
2398    nth index (numbering from 1) if which is 0, and the upper bound if
2399    which is 1.  This routine will also work for arrays with bounds
2400    supplied by run-time quantities other than discriminants.  */
2401
2402 struct value *
2403 ada_array_bound (struct value *arr, int n, int which)
2404 {
2405   struct type *arr_type = VALUE_TYPE (arr);
2406
2407   if (ada_is_packed_array_type (arr_type))
2408     return ada_array_bound (decode_packed_array (arr), n, which);
2409   else if (ada_is_simple_array_type (arr_type))
2410     {
2411       struct type *type;
2412       LONGEST v = ada_array_bound_from_type (arr_type, n, which, &type);
2413       return value_from_longest (type, v);
2414     }
2415   else
2416     return desc_one_bound (desc_bounds (arr), n, which);
2417 }
2418
2419 /* Given that arr is an array value, returns the length of the
2420    nth index.  This routine will also work for arrays with bounds
2421    supplied by run-time quantities other than discriminants.
2422    Does not work for arrays indexed by enumeration types with representation
2423    clauses at the moment.  */
2424
2425 struct value *
2426 ada_array_length (struct value *arr, int n)
2427 {
2428   struct type *arr_type = check_typedef (VALUE_TYPE (arr));
2429
2430   if (ada_is_packed_array_type (arr_type))
2431     return ada_array_length (decode_packed_array (arr), n);
2432
2433   if (ada_is_simple_array_type (arr_type))
2434     {
2435       struct type *type;
2436       LONGEST v =
2437         ada_array_bound_from_type (arr_type, n, 1, &type) -
2438         ada_array_bound_from_type (arr_type, n, 0, NULL) + 1;
2439       return value_from_longest (type, v);
2440     }
2441   else
2442     return
2443       value_from_longest (builtin_type_ada_int,
2444                           value_as_long (desc_one_bound (desc_bounds (arr),
2445                                                          n, 1))
2446                           - value_as_long (desc_one_bound (desc_bounds (arr),
2447                                                            n, 0)) + 1);
2448 }
2449
2450 /* An empty array whose type is that of ARR_TYPE (an array type),
2451    with bounds LOW to LOW-1.  */
2452
2453 static struct value *
2454 empty_array (struct type *arr_type, int low)
2455 {
2456   struct type *index_type =
2457     create_range_type (NULL, TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (arr_type)),
2458                        low, low - 1);
2459   struct type *elt_type = ada_array_element_type (arr_type, 1);
2460   return allocate_value (create_array_type (NULL, elt_type, index_type));
2461 }
2462 \f
2463
2464                                 /* Name resolution */
2465
2466 /* The "decoded" name for the user-definable Ada operator corresponding
2467    to OP.  */
2468
2469 static const char *
2470 ada_decoded_op_name (enum exp_opcode op)
2471 {
2472   int i;
2473
2474   for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
2475     {
2476       if (ada_opname_table[i].op == op)
2477         return ada_opname_table[i].decoded;
2478     }
2479   error ("Could not find operator name for opcode");
2480 }
2481
2482
2483 /* Same as evaluate_type (*EXP), but resolves ambiguous symbol
2484    references (marked by OP_VAR_VALUE nodes in which the symbol has an
2485    undefined namespace) and converts operators that are
2486    user-defined into appropriate function calls.  If CONTEXT_TYPE is
2487    non-null, it provides a preferred result type [at the moment, only
2488    type void has any effect---causing procedures to be preferred over
2489    functions in calls].  A null CONTEXT_TYPE indicates that a non-void
2490    return type is preferred.  May change (expand) *EXP.  */
2491
2492 static void
2493 resolve (struct expression **expp, int void_context_p)
2494 {
2495   int pc;
2496   pc = 0;
2497   resolve_subexp (expp, &pc, 1, void_context_p ? builtin_type_void : NULL);
2498 }
2499
2500 /* Resolve the operator of the subexpression beginning at
2501    position *POS of *EXPP.  "Resolving" consists of replacing
2502    the symbols that have undefined namespaces in OP_VAR_VALUE nodes
2503    with their resolutions, replacing built-in operators with
2504    function calls to user-defined operators, where appropriate, and,
2505    when DEPROCEDURE_P is non-zero, converting function-valued variables
2506    into parameterless calls.  May expand *EXPP.  The CONTEXT_TYPE functions
2507    are as in ada_resolve, above.  */
2508
2509 static struct value *
2510 resolve_subexp (struct expression **expp, int *pos, int deprocedure_p,
2511                 struct type *context_type)
2512 {
2513   int pc = *pos;
2514   int i;
2515   struct expression *exp;       /* Convenience: == *expp.  */
2516   enum exp_opcode op = (*expp)->elts[pc].opcode;
2517   struct value **argvec;        /* Vector of operand types (alloca'ed).  */
2518   int nargs;                    /* Number of operands.  */
2519
2520   argvec = NULL;
2521   nargs = 0;
2522   exp = *expp;
2523
2524   /* Pass one: resolve operands, saving their types and updating *pos.  */
2525   switch (op)
2526     {
2527     case OP_FUNCALL:
2528       if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
2529           && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
2530         *pos += 7;
2531       else
2532         {
2533           *pos += 3;
2534           resolve_subexp (expp, pos, 0, NULL);
2535         }
2536       nargs = longest_to_int (exp->elts[pc + 1].longconst);
2537       break;
2538
2539     case UNOP_QUAL:
2540       *pos += 3;
2541       resolve_subexp (expp, pos, 1, exp->elts[pc + 1].type);
2542       break;
2543
2544     case UNOP_ADDR:
2545       *pos += 1;
2546       resolve_subexp (expp, pos, 0, NULL);
2547       break;
2548
2549     case OP_ATR_MODULUS:
2550       *pos += 4;
2551       break;
2552
2553     case OP_ATR_SIZE:
2554     case OP_ATR_TAG:
2555       *pos += 1;
2556       nargs = 1;
2557       break;
2558
2559     case OP_ATR_FIRST:
2560     case OP_ATR_LAST:
2561     case OP_ATR_LENGTH:
2562     case OP_ATR_POS:
2563     case OP_ATR_VAL:
2564       *pos += 1;
2565       nargs = 2;
2566       break;
2567
2568     case OP_ATR_MIN:
2569     case OP_ATR_MAX:
2570       *pos += 1;
2571       nargs = 3;
2572       break;
2573
2574     case BINOP_ASSIGN:
2575       {
2576         struct value *arg1;
2577
2578         *pos += 1;
2579         arg1 = resolve_subexp (expp, pos, 0, NULL);
2580         if (arg1 == NULL)
2581           resolve_subexp (expp, pos, 1, NULL);
2582         else
2583           resolve_subexp (expp, pos, 1, VALUE_TYPE (arg1));
2584         break;
2585       }
2586
2587     case UNOP_CAST:
2588     case UNOP_IN_RANGE:
2589       *pos += 3;
2590       nargs = 1;
2591       break;
2592
2593     case BINOP_ADD:
2594     case BINOP_SUB:
2595     case BINOP_MUL:
2596     case BINOP_DIV:
2597     case BINOP_REM:
2598     case BINOP_MOD:
2599     case BINOP_EXP:
2600     case BINOP_CONCAT:
2601     case BINOP_LOGICAL_AND:
2602     case BINOP_LOGICAL_OR:
2603     case BINOP_BITWISE_AND:
2604     case BINOP_BITWISE_IOR:
2605     case BINOP_BITWISE_XOR:
2606
2607     case BINOP_EQUAL:
2608     case BINOP_NOTEQUAL:
2609     case BINOP_LESS:
2610     case BINOP_GTR:
2611     case BINOP_LEQ:
2612     case BINOP_GEQ:
2613
2614     case BINOP_REPEAT:
2615     case BINOP_SUBSCRIPT:
2616     case BINOP_COMMA:
2617       *pos += 1;
2618       nargs = 2;
2619       break;
2620
2621     case UNOP_NEG:
2622     case UNOP_PLUS:
2623     case UNOP_LOGICAL_NOT:
2624     case UNOP_ABS:
2625     case UNOP_IND:
2626       *pos += 1;
2627       nargs = 1;
2628       break;
2629
2630     case OP_LONG:
2631     case OP_DOUBLE:
2632     case OP_VAR_VALUE:
2633       *pos += 4;
2634       break;
2635
2636     case OP_TYPE:
2637     case OP_BOOL:
2638     case OP_LAST:
2639     case OP_REGISTER:
2640     case OP_INTERNALVAR:
2641       *pos += 3;
2642       break;
2643
2644     case UNOP_MEMVAL:
2645       *pos += 3;
2646       nargs = 1;
2647       break;
2648
2649     case STRUCTOP_STRUCT:
2650       *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
2651       nargs = 1;
2652       break;
2653
2654     case OP_STRING:
2655       (*pos) += 3 
2656         + BYTES_TO_EXP_ELEM (longest_to_int (exp->elts[pc + 1].longconst) 
2657                              + 1);
2658       break;
2659
2660     case TERNOP_SLICE:
2661     case TERNOP_IN_RANGE:
2662       *pos += 1;
2663       nargs = 3;
2664       break;
2665
2666     case BINOP_IN_BOUNDS:
2667       *pos += 3;
2668       nargs = 2;
2669       break;
2670
2671     default:
2672       error ("Unexpected operator during name resolution");
2673     }
2674
2675   argvec = (struct value * *) alloca (sizeof (struct value *) * (nargs + 1));
2676   for (i = 0; i < nargs; i += 1)
2677     argvec[i] = resolve_subexp (expp, pos, 1, NULL);
2678   argvec[i] = NULL;
2679   exp = *expp;
2680
2681   /* Pass two: perform any resolution on principal operator.  */
2682   switch (op)
2683     {
2684     default:
2685       break;
2686
2687     case OP_VAR_VALUE:
2688       if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
2689         {
2690           struct ada_symbol_info *candidates;
2691           int n_candidates;
2692
2693           n_candidates =
2694             ada_lookup_symbol_list (SYMBOL_LINKAGE_NAME
2695                                     (exp->elts[pc + 2].symbol),
2696                                     exp->elts[pc + 1].block, VAR_DOMAIN,
2697                                     &candidates);
2698
2699           if (n_candidates > 1)
2700             {
2701               /* Types tend to get re-introduced locally, so if there
2702                  are any local symbols that are not types, first filter
2703                  out all types.  */
2704               int j;
2705               for (j = 0; j < n_candidates; j += 1)
2706                 switch (SYMBOL_CLASS (candidates[j].sym))
2707                   {
2708                   case LOC_REGISTER:
2709                   case LOC_ARG:
2710                   case LOC_REF_ARG:
2711                   case LOC_REGPARM:
2712                   case LOC_REGPARM_ADDR:
2713                   case LOC_LOCAL:
2714                   case LOC_LOCAL_ARG:
2715                   case LOC_BASEREG:
2716                   case LOC_BASEREG_ARG:
2717                   case LOC_COMPUTED:
2718                   case LOC_COMPUTED_ARG:
2719                     goto FoundNonType;
2720                   default:
2721                     break;
2722                   }
2723             FoundNonType:
2724               if (j < n_candidates)
2725                 {
2726                   j = 0;
2727                   while (j < n_candidates)
2728                     {
2729                       if (SYMBOL_CLASS (candidates[j].sym) == LOC_TYPEDEF)
2730                         {
2731                           candidates[j] = candidates[n_candidates - 1];
2732                           n_candidates -= 1;
2733                         }
2734                       else
2735                         j += 1;
2736                     }
2737                 }
2738             }
2739
2740           if (n_candidates == 0)
2741             error ("No definition found for %s",
2742                    SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
2743           else if (n_candidates == 1)
2744             i = 0;
2745           else if (deprocedure_p
2746                    && !is_nonfunction (candidates, n_candidates))
2747             {
2748               i = ada_resolve_function
2749                 (candidates, n_candidates, NULL, 0,
2750                  SYMBOL_LINKAGE_NAME (exp->elts[pc + 2].symbol),
2751                  context_type);
2752               if (i < 0)
2753                 error ("Could not find a match for %s",
2754                        SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
2755             }
2756           else
2757             {
2758               printf_filtered ("Multiple matches for %s\n",
2759                                SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
2760               user_select_syms (candidates, n_candidates, 1);
2761               i = 0;
2762             }
2763
2764           exp->elts[pc + 1].block = candidates[i].block;
2765           exp->elts[pc + 2].symbol = candidates[i].sym;
2766           if (innermost_block == NULL
2767               || contained_in (candidates[i].block, innermost_block))
2768             innermost_block = candidates[i].block;
2769         }
2770
2771       if (deprocedure_p
2772           && (TYPE_CODE (SYMBOL_TYPE (exp->elts[pc + 2].symbol))
2773               == TYPE_CODE_FUNC))
2774         {
2775           replace_operator_with_call (expp, pc, 0, 0,
2776                                       exp->elts[pc + 2].symbol,
2777                                       exp->elts[pc + 1].block);
2778           exp = *expp;
2779         }
2780       break;
2781
2782     case OP_FUNCALL:
2783       {
2784         if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
2785             && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
2786           {
2787             struct ada_symbol_info *candidates;
2788             int n_candidates;
2789
2790             n_candidates =
2791               ada_lookup_symbol_list (SYMBOL_LINKAGE_NAME
2792                                       (exp->elts[pc + 5].symbol),
2793                                       exp->elts[pc + 4].block, VAR_DOMAIN,
2794                                       &candidates);
2795             if (n_candidates == 1)
2796               i = 0;
2797             else
2798               {
2799                 i = ada_resolve_function
2800                   (candidates, n_candidates,
2801                    argvec, nargs,
2802                    SYMBOL_LINKAGE_NAME (exp->elts[pc + 5].symbol),
2803                    context_type);
2804                 if (i < 0)
2805                   error ("Could not find a match for %s",
2806                          SYMBOL_PRINT_NAME (exp->elts[pc + 5].symbol));
2807               }
2808
2809             exp->elts[pc + 4].block = candidates[i].block;
2810             exp->elts[pc + 5].symbol = candidates[i].sym;
2811             if (innermost_block == NULL
2812                 || contained_in (candidates[i].block, innermost_block))
2813               innermost_block = candidates[i].block;
2814           }
2815       }
2816       break;
2817     case BINOP_ADD:
2818     case BINOP_SUB:
2819     case BINOP_MUL:
2820     case BINOP_DIV:
2821     case BINOP_REM:
2822     case BINOP_MOD:
2823     case BINOP_CONCAT:
2824     case BINOP_BITWISE_AND:
2825     case BINOP_BITWISE_IOR:
2826     case BINOP_BITWISE_XOR:
2827     case BINOP_EQUAL:
2828     case BINOP_NOTEQUAL:
2829     case BINOP_LESS:
2830     case BINOP_GTR:
2831     case BINOP_LEQ:
2832     case BINOP_GEQ:
2833     case BINOP_EXP:
2834     case UNOP_NEG:
2835     case UNOP_PLUS:
2836     case UNOP_LOGICAL_NOT:
2837     case UNOP_ABS:
2838       if (possible_user_operator_p (op, argvec))
2839         {
2840           struct ada_symbol_info *candidates;
2841           int n_candidates;
2842
2843           n_candidates =
2844             ada_lookup_symbol_list (ada_encode (ada_decoded_op_name (op)),
2845                                     (struct block *) NULL, VAR_DOMAIN,
2846                                     &candidates);
2847           i = ada_resolve_function (candidates, n_candidates, argvec, nargs,
2848                                     ada_decoded_op_name (op), NULL);
2849           if (i < 0)
2850             break;
2851
2852           replace_operator_with_call (expp, pc, nargs, 1,
2853                                       candidates[i].sym, candidates[i].block);
2854           exp = *expp;
2855         }
2856       break;
2857
2858     case OP_TYPE:
2859       return NULL;
2860     }
2861
2862   *pos = pc;
2863   return evaluate_subexp_type (exp, pos);
2864 }
2865
2866 /* Return non-zero if formal type FTYPE matches actual type ATYPE.  If
2867    MAY_DEREF is non-zero, the formal may be a pointer and the actual
2868    a non-pointer.   A type of 'void' (which is never a valid expression type)
2869    by convention matches anything. */
2870 /* The term "match" here is rather loose.  The match is heuristic and
2871    liberal.  FIXME: TOO liberal, in fact.  */
2872
2873 static int
2874 ada_type_match (struct type *ftype, struct type *atype, int may_deref)
2875 {
2876   CHECK_TYPEDEF (ftype);
2877   CHECK_TYPEDEF (atype);
2878
2879   if (TYPE_CODE (ftype) == TYPE_CODE_REF)
2880     ftype = TYPE_TARGET_TYPE (ftype);
2881   if (TYPE_CODE (atype) == TYPE_CODE_REF)
2882     atype = TYPE_TARGET_TYPE (atype);
2883
2884   if (TYPE_CODE (ftype) == TYPE_CODE_VOID
2885       || TYPE_CODE (atype) == TYPE_CODE_VOID)
2886     return 1;
2887
2888   switch (TYPE_CODE (ftype))
2889     {
2890     default:
2891       return 1;
2892     case TYPE_CODE_PTR:
2893       if (TYPE_CODE (atype) == TYPE_CODE_PTR)
2894         return ada_type_match (TYPE_TARGET_TYPE (ftype),
2895                                TYPE_TARGET_TYPE (atype), 0);
2896       else
2897         return (may_deref
2898                 && ada_type_match (TYPE_TARGET_TYPE (ftype), atype, 0));
2899     case TYPE_CODE_INT:
2900     case TYPE_CODE_ENUM:
2901     case TYPE_CODE_RANGE:
2902       switch (TYPE_CODE (atype))
2903         {
2904         case TYPE_CODE_INT:
2905         case TYPE_CODE_ENUM:
2906         case TYPE_CODE_RANGE:
2907           return 1;
2908         default:
2909           return 0;
2910         }
2911
2912     case TYPE_CODE_ARRAY:
2913       return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
2914               || ada_is_array_descriptor_type (atype));
2915
2916     case TYPE_CODE_STRUCT:
2917       if (ada_is_array_descriptor_type (ftype))
2918         return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
2919                 || ada_is_array_descriptor_type (atype));
2920       else
2921         return (TYPE_CODE (atype) == TYPE_CODE_STRUCT
2922                 && !ada_is_array_descriptor_type (atype));
2923
2924     case TYPE_CODE_UNION:
2925     case TYPE_CODE_FLT:
2926       return (TYPE_CODE (atype) == TYPE_CODE (ftype));
2927     }
2928 }
2929
2930 /* Return non-zero if the formals of FUNC "sufficiently match" the
2931    vector of actual argument types ACTUALS of size N_ACTUALS.  FUNC
2932    may also be an enumeral, in which case it is treated as a 0-
2933    argument function.  */
2934
2935 static int
2936 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
2937 {
2938   int i;
2939   struct type *func_type = SYMBOL_TYPE (func);
2940
2941   if (SYMBOL_CLASS (func) == LOC_CONST
2942       && TYPE_CODE (func_type) == TYPE_CODE_ENUM)
2943     return (n_actuals == 0);
2944   else if (func_type == NULL || TYPE_CODE (func_type) != TYPE_CODE_FUNC)
2945     return 0;
2946
2947   if (TYPE_NFIELDS (func_type) != n_actuals)
2948     return 0;
2949
2950   for (i = 0; i < n_actuals; i += 1)
2951     {
2952       if (actuals[i] == NULL)
2953         return 0;
2954       else
2955         {
2956           struct type *ftype = check_typedef (TYPE_FIELD_TYPE (func_type, i));
2957           struct type *atype = check_typedef (VALUE_TYPE (actuals[i]));
2958
2959           if (!ada_type_match (ftype, atype, 1))
2960             return 0;
2961         }
2962     }
2963   return 1;
2964 }
2965
2966 /* False iff function type FUNC_TYPE definitely does not produce a value
2967    compatible with type CONTEXT_TYPE.  Conservatively returns 1 if
2968    FUNC_TYPE is not a valid function type with a non-null return type
2969    or an enumerated type.  A null CONTEXT_TYPE indicates any non-void type.  */
2970
2971 static int
2972 return_match (struct type *func_type, struct type *context_type)
2973 {
2974   struct type *return_type;
2975
2976   if (func_type == NULL)
2977     return 1;
2978
2979   if (TYPE_CODE (func_type) == TYPE_CODE_FUNC)
2980     return_type = base_type (TYPE_TARGET_TYPE (func_type));
2981   else
2982     return_type = base_type (func_type);
2983   if (return_type == NULL)
2984     return 1;
2985
2986   context_type = base_type (context_type);
2987
2988   if (TYPE_CODE (return_type) == TYPE_CODE_ENUM)
2989     return context_type == NULL || return_type == context_type;
2990   else if (context_type == NULL)
2991     return TYPE_CODE (return_type) != TYPE_CODE_VOID;
2992   else
2993     return TYPE_CODE (return_type) == TYPE_CODE (context_type);
2994 }
2995
2996
2997 /* Returns the index in SYMS[0..NSYMS-1] that contains  the symbol for the
2998    function (if any) that matches the types of the NARGS arguments in
2999    ARGS.  If CONTEXT_TYPE is non-null and there is at least one match
3000    that returns that type, then eliminate matches that don't.  If
3001    CONTEXT_TYPE is void and there is at least one match that does not
3002    return void, eliminate all matches that do.
3003
3004    Asks the user if there is more than one match remaining.  Returns -1
3005    if there is no such symbol or none is selected.  NAME is used
3006    solely for messages.  May re-arrange and modify SYMS in
3007    the process; the index returned is for the modified vector.  */
3008
3009 static int
3010 ada_resolve_function (struct ada_symbol_info syms[],
3011                       int nsyms, struct value **args, int nargs,
3012                       const char *name, struct type *context_type)
3013 {
3014   int k;
3015   int m;                        /* Number of hits */
3016   struct type *fallback;
3017   struct type *return_type;
3018
3019   return_type = context_type;
3020   if (context_type == NULL)
3021     fallback = builtin_type_void;
3022   else
3023     fallback = NULL;
3024
3025   m = 0;
3026   while (1)
3027     {
3028       for (k = 0; k < nsyms; k += 1)
3029         {
3030           struct type *type = check_typedef (SYMBOL_TYPE (syms[k].sym));
3031
3032           if (ada_args_match (syms[k].sym, args, nargs)
3033               && return_match (type, return_type))
3034             {
3035               syms[m] = syms[k];
3036               m += 1;
3037             }
3038         }
3039       if (m > 0 || return_type == fallback)
3040         break;
3041       else
3042         return_type = fallback;
3043     }
3044
3045   if (m == 0)
3046     return -1;
3047   else if (m > 1)
3048     {
3049       printf_filtered ("Multiple matches for %s\n", name);
3050       user_select_syms (syms, m, 1);
3051       return 0;
3052     }
3053   return 0;
3054 }
3055
3056 /* Returns true (non-zero) iff decoded name N0 should appear before N1
3057    in a listing of choices during disambiguation (see sort_choices, below).
3058    The idea is that overloadings of a subprogram name from the
3059    same package should sort in their source order.  We settle for ordering
3060    such symbols by their trailing number (__N  or $N).  */
3061
3062 static int
3063 encoded_ordered_before (char *N0, char *N1)
3064 {
3065   if (N1 == NULL)
3066     return 0;
3067   else if (N0 == NULL)
3068     return 1;
3069   else
3070     {
3071       int k0, k1;
3072       for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
3073         ;
3074       for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
3075         ;
3076       if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
3077           && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3078         {
3079           int n0, n1;
3080           n0 = k0;
3081           while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3082             n0 -= 1;
3083           n1 = k1;
3084           while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3085             n1 -= 1;
3086           if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3087             return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3088         }
3089       return (strcmp (N0, N1) < 0);
3090     }
3091 }
3092
3093 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3094    encoded names.  */
3095
3096 static void
3097 sort_choices (struct ada_symbol_info syms[], int nsyms)
3098 {
3099   int i;
3100   for (i = 1; i < nsyms; i += 1)
3101     {
3102       struct ada_symbol_info sym = syms[i];
3103       int j;
3104
3105       for (j = i - 1; j >= 0; j -= 1)
3106         {
3107           if (encoded_ordered_before (SYMBOL_LINKAGE_NAME (syms[j].sym),
3108                                       SYMBOL_LINKAGE_NAME (sym.sym)))
3109             break;
3110           syms[j + 1] = syms[j];
3111         }
3112       syms[j + 1] = sym;
3113     }
3114 }
3115
3116 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0 
3117    by asking the user (if necessary), returning the number selected, 
3118    and setting the first elements of SYMS items.  Error if no symbols
3119    selected.  */
3120
3121 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3122    to be re-integrated one of these days.  */
3123
3124 int
3125 user_select_syms (struct ada_symbol_info *syms, int nsyms, int max_results)
3126 {
3127   int i;
3128   int *chosen = (int *) alloca (sizeof (int) * nsyms);
3129   int n_chosen;
3130   int first_choice = (max_results == 1) ? 1 : 2;
3131
3132   if (max_results < 1)
3133     error ("Request to select 0 symbols!");
3134   if (nsyms <= 1)
3135     return nsyms;
3136
3137   printf_unfiltered ("[0] cancel\n");
3138   if (max_results > 1)
3139     printf_unfiltered ("[1] all\n");
3140
3141   sort_choices (syms, nsyms);
3142
3143   for (i = 0; i < nsyms; i += 1)
3144     {
3145       if (syms[i].sym == NULL)
3146         continue;
3147
3148       if (SYMBOL_CLASS (syms[i].sym) == LOC_BLOCK)
3149         {
3150           struct symtab_and_line sal =
3151             find_function_start_sal (syms[i].sym, 1);
3152           printf_unfiltered ("[%d] %s at %s:%d\n", i + first_choice,
3153                              SYMBOL_PRINT_NAME (syms[i].sym),
3154                              (sal.symtab == NULL
3155                               ? "<no source file available>"
3156                               : sal.symtab->filename), sal.line);
3157           continue;
3158         }
3159       else
3160         {
3161           int is_enumeral =
3162             (SYMBOL_CLASS (syms[i].sym) == LOC_CONST
3163              && SYMBOL_TYPE (syms[i].sym) != NULL
3164              && TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) == TYPE_CODE_ENUM);
3165           struct symtab *symtab = symtab_for_sym (syms[i].sym);
3166
3167           if (SYMBOL_LINE (syms[i].sym) != 0 && symtab != NULL)
3168             printf_unfiltered ("[%d] %s at %s:%d\n",
3169                                i + first_choice,
3170                                SYMBOL_PRINT_NAME (syms[i].sym),
3171                                symtab->filename, SYMBOL_LINE (syms[i].sym));
3172           else if (is_enumeral
3173                    && TYPE_NAME (SYMBOL_TYPE (syms[i].sym)) != NULL)
3174             {
3175               printf_unfiltered ("[%d] ", i + first_choice);
3176               ada_print_type (SYMBOL_TYPE (syms[i].sym), NULL,
3177                               gdb_stdout, -1, 0);
3178               printf_unfiltered ("'(%s) (enumeral)\n",
3179                                  SYMBOL_PRINT_NAME (syms[i].sym));
3180             }
3181           else if (symtab != NULL)
3182             printf_unfiltered (is_enumeral
3183                                ? "[%d] %s in %s (enumeral)\n"
3184                                : "[%d] %s at %s:?\n",
3185                                i + first_choice,
3186                                SYMBOL_PRINT_NAME (syms[i].sym),
3187                                symtab->filename);
3188           else
3189             printf_unfiltered (is_enumeral
3190                                ? "[%d] %s (enumeral)\n"
3191                                : "[%d] %s at ?\n",
3192                                i + first_choice,
3193                                SYMBOL_PRINT_NAME (syms[i].sym));
3194         }
3195     }
3196
3197   n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
3198                              "overload-choice");
3199
3200   for (i = 0; i < n_chosen; i += 1)
3201     syms[i] = syms[chosen[i]];
3202
3203   return n_chosen;
3204 }
3205
3206 /* Read and validate a set of numeric choices from the user in the
3207    range 0 .. N_CHOICES-1.  Place the results in increasing
3208    order in CHOICES[0 .. N-1], and return N.
3209
3210    The user types choices as a sequence of numbers on one line
3211    separated by blanks, encoding them as follows:
3212
3213      + A choice of 0 means to cancel the selection, throwing an error.
3214      + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3215      + The user chooses k by typing k+IS_ALL_CHOICE+1.
3216
3217    The user is not allowed to choose more than MAX_RESULTS values.
3218
3219    ANNOTATION_SUFFIX, if present, is used to annotate the input
3220    prompts (for use with the -f switch).  */
3221
3222 int
3223 get_selections (int *choices, int n_choices, int max_results,
3224                 int is_all_choice, char *annotation_suffix)
3225 {
3226   char *args;
3227   const char *prompt;
3228   int n_chosen;
3229   int first_choice = is_all_choice ? 2 : 1;
3230
3231   prompt = getenv ("PS2");
3232   if (prompt == NULL)
3233     prompt = ">";
3234
3235   printf_unfiltered ("%s ", prompt);
3236   gdb_flush (gdb_stdout);
3237
3238   args = command_line_input ((char *) NULL, 0, annotation_suffix);
3239
3240   if (args == NULL)
3241     error_no_arg ("one or more choice numbers");
3242
3243   n_chosen = 0;
3244
3245   /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3246      order, as given in args.  Choices are validated.  */
3247   while (1)
3248     {
3249       char *args2;
3250       int choice, j;
3251
3252       while (isspace (*args))
3253         args += 1;
3254       if (*args == '\0' && n_chosen == 0)
3255         error_no_arg ("one or more choice numbers");
3256       else if (*args == '\0')
3257         break;
3258
3259       choice = strtol (args, &args2, 10);
3260       if (args == args2 || choice < 0
3261           || choice > n_choices + first_choice - 1)
3262         error ("Argument must be choice number");
3263       args = args2;
3264
3265       if (choice == 0)
3266         error ("cancelled");
3267
3268       if (choice < first_choice)
3269         {
3270           n_chosen = n_choices;
3271           for (j = 0; j < n_choices; j += 1)
3272             choices[j] = j;
3273           break;
3274         }
3275       choice -= first_choice;
3276
3277       for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3278         {
3279         }
3280
3281       if (j < 0 || choice != choices[j])
3282         {
3283           int k;
3284           for (k = n_chosen - 1; k > j; k -= 1)
3285             choices[k + 1] = choices[k];
3286           choices[j + 1] = choice;
3287           n_chosen += 1;
3288         }
3289     }
3290
3291   if (n_chosen > max_results)
3292     error ("Select no more than %d of the above", max_results);
3293
3294   return n_chosen;
3295 }
3296
3297 /* Replace the operator of length OPLEN at position PC in *EXPP with a call
3298    on the function identified by SYM and BLOCK, and taking NARGS
3299    arguments.  Update *EXPP as needed to hold more space.  */
3300
3301 static void
3302 replace_operator_with_call (struct expression **expp, int pc, int nargs,
3303                             int oplen, struct symbol *sym,
3304                             struct block *block)
3305 {
3306   /* A new expression, with 6 more elements (3 for funcall, 4 for function
3307      symbol, -oplen for operator being replaced).  */
3308   struct expression *newexp = (struct expression *)
3309     xmalloc (sizeof (struct expression)
3310              + EXP_ELEM_TO_BYTES ((*expp)->nelts + 7 - oplen));
3311   struct expression *exp = *expp;
3312
3313   newexp->nelts = exp->nelts + 7 - oplen;
3314   newexp->language_defn = exp->language_defn;
3315   memcpy (newexp->elts, exp->elts, EXP_ELEM_TO_BYTES (pc));
3316   memcpy (newexp->elts + pc + 7, exp->elts + pc + oplen,
3317           EXP_ELEM_TO_BYTES (exp->nelts - pc - oplen));
3318
3319   newexp->elts[pc].opcode = newexp->elts[pc + 2].opcode = OP_FUNCALL;
3320   newexp->elts[pc + 1].longconst = (LONGEST) nargs;
3321
3322   newexp->elts[pc + 3].opcode = newexp->elts[pc + 6].opcode = OP_VAR_VALUE;
3323   newexp->elts[pc + 4].block = block;
3324   newexp->elts[pc + 5].symbol = sym;
3325
3326   *expp = newexp;
3327   xfree (exp);
3328 }
3329
3330 /* Type-class predicates */
3331
3332 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
3333    or FLOAT).  */
3334
3335 static int
3336 numeric_type_p (struct type *type)
3337 {
3338   if (type == NULL)
3339     return 0;
3340   else
3341     {
3342       switch (TYPE_CODE (type))
3343         {
3344         case TYPE_CODE_INT:
3345         case TYPE_CODE_FLT:
3346           return 1;
3347         case TYPE_CODE_RANGE:
3348           return (type == TYPE_TARGET_TYPE (type)
3349                   || numeric_type_p (TYPE_TARGET_TYPE (type)));
3350         default:
3351           return 0;
3352         }
3353     }
3354 }
3355
3356 /* True iff TYPE is integral (an INT or RANGE of INTs).  */
3357
3358 static int
3359 integer_type_p (struct type *type)
3360 {
3361   if (type == NULL)
3362     return 0;
3363   else
3364     {
3365       switch (TYPE_CODE (type))
3366         {
3367         case TYPE_CODE_INT:
3368           return 1;
3369         case TYPE_CODE_RANGE:
3370           return (type == TYPE_TARGET_TYPE (type)
3371                   || integer_type_p (TYPE_TARGET_TYPE (type)));
3372         default:
3373           return 0;
3374         }
3375     }
3376 }
3377
3378 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM).  */
3379
3380 static int
3381 scalar_type_p (struct type *type)
3382 {
3383   if (type == NULL)
3384     return 0;
3385   else
3386     {
3387       switch (TYPE_CODE (type))
3388         {
3389         case TYPE_CODE_INT:
3390         case TYPE_CODE_RANGE:
3391         case TYPE_CODE_ENUM:
3392         case TYPE_CODE_FLT:
3393           return 1;
3394         default:
3395           return 0;
3396         }
3397     }
3398 }
3399
3400 /* True iff TYPE is discrete (INT, RANGE, ENUM).  */
3401
3402 static int
3403 discrete_type_p (struct type *type)
3404 {
3405   if (type == NULL)
3406     return 0;
3407   else
3408     {
3409       switch (TYPE_CODE (type))
3410         {
3411         case TYPE_CODE_INT:
3412         case TYPE_CODE_RANGE:
3413         case TYPE_CODE_ENUM:
3414           return 1;
3415         default:
3416           return 0;
3417         }
3418     }
3419 }
3420
3421 /* Returns non-zero if OP with operands in the vector ARGS could be
3422    a user-defined function.  Errs on the side of pre-defined operators
3423    (i.e., result 0).  */
3424
3425 static int
3426 possible_user_operator_p (enum exp_opcode op, struct value *args[])
3427 {
3428   struct type *type0 =
3429     (args[0] == NULL) ? NULL : check_typedef (VALUE_TYPE (args[0]));
3430   struct type *type1 =
3431     (args[1] == NULL) ? NULL : check_typedef (VALUE_TYPE (args[1]));
3432
3433   if (type0 == NULL)
3434     return 0;
3435
3436   switch (op)
3437     {
3438     default:
3439       return 0;
3440
3441     case BINOP_ADD:
3442     case BINOP_SUB:
3443     case BINOP_MUL:
3444     case BINOP_DIV:
3445       return (!(numeric_type_p (type0) && numeric_type_p (type1)));
3446
3447     case BINOP_REM:
3448     case BINOP_MOD:
3449     case BINOP_BITWISE_AND:
3450     case BINOP_BITWISE_IOR:
3451     case BINOP_BITWISE_XOR:
3452       return (!(integer_type_p (type0) && integer_type_p (type1)));
3453
3454     case BINOP_EQUAL:
3455     case BINOP_NOTEQUAL:
3456     case BINOP_LESS:
3457     case BINOP_GTR:
3458     case BINOP_LEQ:
3459     case BINOP_GEQ:
3460       return (!(scalar_type_p (type0) && scalar_type_p (type1)));
3461
3462     case BINOP_CONCAT:
3463       return
3464         ((TYPE_CODE (type0) != TYPE_CODE_ARRAY
3465           && (TYPE_CODE (type0) != TYPE_CODE_PTR
3466               || TYPE_CODE (TYPE_TARGET_TYPE (type0)) != TYPE_CODE_ARRAY))
3467          || (TYPE_CODE (type1) != TYPE_CODE_ARRAY
3468              && (TYPE_CODE (type1) != TYPE_CODE_PTR
3469                  || (TYPE_CODE (TYPE_TARGET_TYPE (type1)) 
3470                      != TYPE_CODE_ARRAY))));
3471
3472     case BINOP_EXP:
3473       return (!(numeric_type_p (type0) && integer_type_p (type1)));
3474
3475     case UNOP_NEG:
3476     case UNOP_PLUS:
3477     case UNOP_LOGICAL_NOT:
3478     case UNOP_ABS:
3479       return (!numeric_type_p (type0));
3480
3481     }
3482 }
3483 \f
3484                                 /* Renaming */
3485
3486 /* NOTE: In the following, we assume that a renaming type's name may
3487    have an ___XD suffix.  It would be nice if this went away at some
3488    point.  */
3489
3490 /* If TYPE encodes a renaming, returns the renaming suffix, which
3491    is XR for an object renaming, XRP for a procedure renaming, XRE for
3492    an exception renaming, and XRS for a subprogram renaming.  Returns
3493    NULL if NAME encodes none of these.  */
3494
3495 const char *
3496 ada_renaming_type (struct type *type)
3497 {
3498   if (type != NULL && TYPE_CODE (type) == TYPE_CODE_ENUM)
3499     {
3500       const char *name = type_name_no_tag (type);
3501       const char *suffix = (name == NULL) ? NULL : strstr (name, "___XR");
3502       if (suffix == NULL
3503           || (suffix[5] != '\000' && strchr ("PES_", suffix[5]) == NULL))
3504         return NULL;
3505       else
3506         return suffix + 3;
3507     }
3508   else
3509     return NULL;
3510 }
3511
3512 /* Return non-zero iff SYM encodes an object renaming.  */
3513
3514 int
3515 ada_is_object_renaming (struct symbol *sym)
3516 {
3517   const char *renaming_type = ada_renaming_type (SYMBOL_TYPE (sym));
3518   return renaming_type != NULL
3519     && (renaming_type[2] == '\0' || renaming_type[2] == '_');
3520 }
3521
3522 /* Assuming that SYM encodes a non-object renaming, returns the original
3523    name of the renamed entity.  The name is good until the end of
3524    parsing.  */
3525
3526 char *
3527 ada_simple_renamed_entity (struct symbol *sym)
3528 {
3529   struct type *type;
3530   const char *raw_name;
3531   int len;
3532   char *result;
3533
3534   type = SYMBOL_TYPE (sym);
3535   if (type == NULL || TYPE_NFIELDS (type) < 1)
3536     error ("Improperly encoded renaming.");
3537
3538   raw_name = TYPE_FIELD_NAME (type, 0);
3539   len = (raw_name == NULL ? 0 : strlen (raw_name)) - 5;
3540   if (len <= 0)
3541     error ("Improperly encoded renaming.");
3542
3543   result = xmalloc (len + 1);
3544   strncpy (result, raw_name, len);
3545   result[len] = '\000';
3546   return result;
3547 }
3548 \f
3549
3550                                 /* Evaluation: Function Calls */
3551
3552 /* Return an lvalue containing the value VAL.  This is the identity on
3553    lvalues, and otherwise has the side-effect of pushing a copy of VAL 
3554    on the stack, using and updating *SP as the stack pointer, and 
3555    returning an lvalue whose VALUE_ADDRESS points to the copy.  */
3556
3557 static struct value *
3558 ensure_lval (struct value *val, CORE_ADDR *sp)
3559 {
3560   if (! VALUE_LVAL (val))
3561     {
3562       int len = TYPE_LENGTH (check_typedef (VALUE_TYPE (val)));
3563
3564       /* The following is taken from the structure-return code in
3565          call_function_by_hand. FIXME: Therefore, some refactoring seems 
3566          indicated. */
3567       if (INNER_THAN (1, 2))
3568         {
3569           /* Stack grows downward.  Align SP and VALUE_ADDRESS (val) after
3570              reserving sufficient space. */
3571           *sp -= len;
3572           if (gdbarch_frame_align_p (current_gdbarch))
3573             *sp = gdbarch_frame_align (current_gdbarch, *sp);
3574           VALUE_ADDRESS (val) = *sp;
3575         }
3576       else
3577         {
3578           /* Stack grows upward.  Align the frame, allocate space, and
3579              then again, re-align the frame. */
3580           if (gdbarch_frame_align_p (current_gdbarch))
3581             *sp = gdbarch_frame_align (current_gdbarch, *sp);
3582           VALUE_ADDRESS (val) = *sp;
3583           *sp += len;
3584           if (gdbarch_frame_align_p (current_gdbarch))
3585             *sp = gdbarch_frame_align (current_gdbarch, *sp);
3586         }
3587
3588       write_memory (VALUE_ADDRESS (val), VALUE_CONTENTS_RAW (val), len);
3589     }
3590
3591   return val;
3592 }
3593
3594 /* Return the value ACTUAL, converted to be an appropriate value for a
3595    formal of type FORMAL_TYPE.  Use *SP as a stack pointer for
3596    allocating any necessary descriptors (fat pointers), or copies of
3597    values not residing in memory, updating it as needed.  */
3598
3599 static struct value *
3600 convert_actual (struct value *actual, struct type *formal_type0,
3601                 CORE_ADDR *sp)
3602 {
3603   struct type *actual_type = check_typedef (VALUE_TYPE (actual));
3604   struct type *formal_type = check_typedef (formal_type0);
3605   struct type *formal_target =
3606     TYPE_CODE (formal_type) == TYPE_CODE_PTR
3607     ? check_typedef (TYPE_TARGET_TYPE (formal_type)) : formal_type;
3608   struct type *actual_target =
3609     TYPE_CODE (actual_type) == TYPE_CODE_PTR
3610     ? check_typedef (TYPE_TARGET_TYPE (actual_type)) : actual_type;
3611
3612   if (ada_is_array_descriptor_type (formal_target)
3613       && TYPE_CODE (actual_target) == TYPE_CODE_ARRAY)
3614     return make_array_descriptor (formal_type, actual, sp);
3615   else if (TYPE_CODE (formal_type) == TYPE_CODE_PTR)
3616     {
3617       if (TYPE_CODE (formal_target) == TYPE_CODE_ARRAY
3618           && ada_is_array_descriptor_type (actual_target))
3619         return desc_data (actual);
3620       else if (TYPE_CODE (actual_type) != TYPE_CODE_PTR)
3621         {
3622           if (VALUE_LVAL (actual) != lval_memory)
3623             {
3624               struct value *val;
3625               actual_type = check_typedef (VALUE_TYPE (actual));
3626               val = allocate_value (actual_type);
3627               memcpy ((char *) VALUE_CONTENTS_RAW (val),
3628                       (char *) VALUE_CONTENTS (actual),
3629                       TYPE_LENGTH (actual_type));
3630               actual = ensure_lval (val, sp);
3631             }
3632           return value_addr (actual);
3633         }
3634     }
3635   else if (TYPE_CODE (actual_type) == TYPE_CODE_PTR)
3636     return ada_value_ind (actual);
3637
3638   return actual;
3639 }
3640
3641
3642 /* Push a descriptor of type TYPE for array value ARR on the stack at
3643    *SP, updating *SP to reflect the new descriptor.  Return either
3644    an lvalue representing the new descriptor, or (if TYPE is a pointer-
3645    to-descriptor type rather than a descriptor type), a struct value *
3646    representing a pointer to this descriptor.  */
3647
3648 static struct value *
3649 make_array_descriptor (struct type *type, struct value *arr, CORE_ADDR *sp)
3650 {
3651   struct type *bounds_type = desc_bounds_type (type);
3652   struct type *desc_type = desc_base_type (type);
3653   struct value *descriptor = allocate_value (desc_type);
3654   struct value *bounds = allocate_value (bounds_type);
3655   int i;
3656
3657   for (i = ada_array_arity (check_typedef (VALUE_TYPE (arr))); i > 0; i -= 1)
3658     {
3659       modify_general_field (VALUE_CONTENTS (bounds),
3660                             value_as_long (ada_array_bound (arr, i, 0)),
3661                             desc_bound_bitpos (bounds_type, i, 0),
3662                             desc_bound_bitsize (bounds_type, i, 0));
3663       modify_general_field (VALUE_CONTENTS (bounds),
3664                             value_as_long (ada_array_bound (arr, i, 1)),
3665                             desc_bound_bitpos (bounds_type, i, 1),
3666                             desc_bound_bitsize (bounds_type, i, 1));
3667     }
3668
3669   bounds = ensure_lval (bounds, sp);
3670
3671   modify_general_field (VALUE_CONTENTS (descriptor),
3672                         VALUE_ADDRESS (ensure_lval (arr, sp)),
3673                         fat_pntr_data_bitpos (desc_type),
3674                         fat_pntr_data_bitsize (desc_type));
3675
3676   modify_general_field (VALUE_CONTENTS (descriptor),
3677                         VALUE_ADDRESS (bounds),
3678                         fat_pntr_bounds_bitpos (desc_type),
3679                         fat_pntr_bounds_bitsize (desc_type));
3680
3681   descriptor = ensure_lval (descriptor, sp);
3682
3683   if (TYPE_CODE (type) == TYPE_CODE_PTR)
3684     return value_addr (descriptor);
3685   else
3686     return descriptor;
3687 }
3688
3689
3690 /* Assuming a dummy frame has been established on the target, perform any
3691    conversions needed for calling function FUNC on the NARGS actual
3692    parameters in ARGS, other than standard C conversions.  Does
3693    nothing if FUNC does not have Ada-style prototype data, or if NARGS
3694    does not match the number of arguments expected.  Use *SP as a
3695    stack pointer for additional data that must be pushed, updating its
3696    value as needed.  */
3697
3698 void
3699 ada_convert_actuals (struct value *func, int nargs, struct value *args[],
3700                      CORE_ADDR *sp)
3701 {
3702   int i;
3703
3704   if (TYPE_NFIELDS (VALUE_TYPE (func)) == 0
3705       || nargs != TYPE_NFIELDS (VALUE_TYPE (func)))
3706     return;
3707
3708   for (i = 0; i < nargs; i += 1)
3709     args[i] =
3710       convert_actual (args[i], TYPE_FIELD_TYPE (VALUE_TYPE (func), i), sp);
3711 }
3712 \f
3713                                 /* Experimental Symbol Cache Module */
3714
3715 /* This module may well have been OBE, due to improvements in the 
3716    symbol-table module.  So until proven otherwise, it is disabled in
3717    the submitted public code, and may be removed from all sources
3718    in the future. */
3719
3720 #ifdef GNAT_GDB
3721
3722 /* This section implements a simple, fixed-sized hash table for those
3723    Ada-mode symbols that get looked up in the course of executing the user's
3724    commands.  The size is fixed on the grounds that there are not
3725    likely to be all that many symbols looked up during any given
3726    session, regardless of the size of the symbol table.  If we decide
3727    to go to a resizable table, let's just use the stuff from libiberty
3728    instead.  */
3729
3730 #define HASH_SIZE 1009
3731
3732 struct cache_entry
3733 {
3734   const char *name;
3735   domain_enum namespace;
3736   struct symbol *sym;
3737   struct symtab *symtab;
3738   struct block *block;
3739   struct cache_entry *next;
3740 };
3741
3742 static struct obstack cache_space;
3743
3744 static struct cache_entry *cache[HASH_SIZE];
3745
3746 /* Clear all entries from the symbol cache.  */
3747
3748 void
3749 clear_ada_sym_cache (void)
3750 {
3751   obstack_free (&cache_space, NULL);
3752   obstack_init (&cache_space);
3753   memset (cache, '\000', sizeof (cache));
3754 }
3755
3756 static struct cache_entry **
3757 find_entry (const char *name, domain_enum namespace)
3758 {
3759   int h = msymbol_hash (name) % HASH_SIZE;
3760   struct cache_entry **e;
3761   for (e = &cache[h]; *e != NULL; e = &(*e)->next)
3762     {
3763       if (namespace == (*e)->namespace && strcmp (name, (*e)->name) == 0)
3764         return e;
3765     }
3766   return NULL;
3767 }
3768
3769 /* Return (in SYM) the last cached definition for global or static symbol NAME
3770    in namespace DOMAIN.  Returns 1 if entry found, 0 otherwise.
3771    If SYMTAB is non-NULL, store the symbol
3772    table in which the symbol was found there, or NULL if not found.
3773    *BLOCK is set to the block in which NAME is found.  */
3774
3775 static int
3776 lookup_cached_symbol (const char *name, domain_enum namespace,
3777                       struct symbol **sym, struct block **block,
3778                       struct symtab **symtab)
3779 {
3780   struct cache_entry **e = find_entry (name, namespace);
3781   if (e == NULL)
3782     return 0;
3783   if (sym != NULL)
3784     *sym = (*e)->sym;
3785   if (block != NULL)
3786     *block = (*e)->block;
3787   if (symtab != NULL)
3788     *symtab = (*e)->symtab;
3789   return 1;
3790 }
3791
3792 /* Set the cached definition of NAME in DOMAIN to SYM in block
3793    BLOCK and symbol table SYMTAB.  */
3794
3795 static void
3796 cache_symbol (const char *name, domain_enum namespace, struct symbol *sym,
3797               struct block *block, struct symtab *symtab)
3798 {
3799   int h = msymbol_hash (name) % HASH_SIZE;
3800   char *copy;
3801   struct cache_entry *e =
3802     (struct cache_entry *) obstack_alloc (&cache_space, sizeof (*e));
3803   e->next = cache[h];
3804   cache[h] = e;
3805   e->name = copy = obstack_alloc (&cache_space, strlen (name) + 1);
3806   strcpy (copy, name);
3807   e->sym = sym;
3808   e->namespace = namespace;
3809   e->symtab = symtab;
3810   e->block = block;
3811 }
3812
3813 #else
3814 static int
3815 lookup_cached_symbol (const char *name, domain_enum namespace,
3816                       struct symbol **sym, struct block **block,
3817                       struct symtab **symtab)
3818 {
3819   return 0;
3820 }
3821
3822 static void
3823 cache_symbol (const char *name, domain_enum namespace, struct symbol *sym,
3824               struct block *block, struct symtab *symtab)
3825 {
3826 }
3827 #endif /* GNAT_GDB */
3828 \f
3829                                 /* Symbol Lookup */
3830
3831 /* Return the result of a standard (literal, C-like) lookup of NAME in
3832    given DOMAIN, visible from lexical block BLOCK.  */
3833
3834 static struct symbol *
3835 standard_lookup (const char *name, const struct block *block,
3836                  domain_enum domain)
3837 {
3838   struct symbol *sym;
3839   struct symtab *symtab;
3840
3841   if (lookup_cached_symbol (name, domain, &sym, NULL, NULL))
3842     return sym;
3843   sym =
3844     lookup_symbol_in_language (name, block, domain, language_c, 0, &symtab);
3845   cache_symbol (name, domain, sym, block_found, symtab);
3846   return sym;
3847 }
3848
3849
3850 /* Non-zero iff there is at least one non-function/non-enumeral symbol
3851    in the symbol fields of SYMS[0..N-1].  We treat enumerals as functions, 
3852    since they contend in overloading in the same way.  */
3853 static int
3854 is_nonfunction (struct ada_symbol_info syms[], int n)
3855 {
3856   int i;
3857
3858   for (i = 0; i < n; i += 1)
3859     if (TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) != TYPE_CODE_FUNC
3860         && (TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) != TYPE_CODE_ENUM
3861             || SYMBOL_CLASS (syms[i].sym) != LOC_CONST))
3862       return 1;
3863
3864   return 0;
3865 }
3866
3867 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
3868    struct types.  Otherwise, they may not.  */
3869
3870 static int
3871 equiv_types (struct type *type0, struct type *type1)
3872 {
3873   if (type0 == type1)
3874     return 1;
3875   if (type0 == NULL || type1 == NULL
3876       || TYPE_CODE (type0) != TYPE_CODE (type1))
3877     return 0;
3878   if ((TYPE_CODE (type0) == TYPE_CODE_STRUCT
3879        || TYPE_CODE (type0) == TYPE_CODE_ENUM)
3880       && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
3881       && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
3882     return 1;
3883
3884   return 0;
3885 }
3886
3887 /* True iff SYM0 represents the same entity as SYM1, or one that is
3888    no more defined than that of SYM1.  */
3889
3890 static int
3891 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
3892 {
3893   if (sym0 == sym1)
3894     return 1;
3895   if (SYMBOL_DOMAIN (sym0) != SYMBOL_DOMAIN (sym1)
3896       || SYMBOL_CLASS (sym0) != SYMBOL_CLASS (sym1))
3897     return 0;
3898
3899   switch (SYMBOL_CLASS (sym0))
3900     {
3901     case LOC_UNDEF:
3902       return 1;
3903     case LOC_TYPEDEF:
3904       {
3905         struct type *type0 = SYMBOL_TYPE (sym0);
3906         struct type *type1 = SYMBOL_TYPE (sym1);
3907         char *name0 = SYMBOL_LINKAGE_NAME (sym0);
3908         char *name1 = SYMBOL_LINKAGE_NAME (sym1);
3909         int len0 = strlen (name0);
3910         return
3911           TYPE_CODE (type0) == TYPE_CODE (type1)
3912           && (equiv_types (type0, type1)
3913               || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
3914                   && strncmp (name1 + len0, "___XV", 5) == 0));
3915       }
3916     case LOC_CONST:
3917       return SYMBOL_VALUE (sym0) == SYMBOL_VALUE (sym1)
3918         && equiv_types (SYMBOL_TYPE (sym0), SYMBOL_TYPE (sym1));
3919     default:
3920       return 0;
3921     }
3922 }
3923
3924 /* Append (SYM,BLOCK,SYMTAB) to the end of the array of struct ada_symbol_info
3925    records in OBSTACKP.  Do nothing if SYM is a duplicate.  */
3926
3927 static void
3928 add_defn_to_vec (struct obstack *obstackp,
3929                  struct symbol *sym,
3930                  struct block *block, struct symtab *symtab)
3931 {
3932   int i;
3933   size_t tmp;
3934   struct ada_symbol_info *prevDefns = defns_collected (obstackp, 0);
3935
3936   if (SYMBOL_TYPE (sym) != NULL)
3937     CHECK_TYPEDEF (SYMBOL_TYPE (sym));
3938   for (i = num_defns_collected (obstackp) - 1; i >= 0; i -= 1)
3939     {
3940       if (lesseq_defined_than (sym, prevDefns[i].sym))
3941         return;
3942       else if (lesseq_defined_than (prevDefns[i].sym, sym))
3943         {
3944           prevDefns[i].sym = sym;
3945           prevDefns[i].block = block;
3946           prevDefns[i].symtab = symtab;
3947           return;
3948         }
3949     }
3950
3951   {
3952     struct ada_symbol_info info;
3953
3954     info.sym = sym;
3955     info.block = block;
3956     info.symtab = symtab;
3957     obstack_grow (obstackp, &info, sizeof (struct ada_symbol_info));
3958   }
3959 }
3960
3961 /* Number of ada_symbol_info structures currently collected in 
3962    current vector in *OBSTACKP.  */
3963
3964 static int
3965 num_defns_collected (struct obstack *obstackp)
3966 {
3967   return obstack_object_size (obstackp) / sizeof (struct ada_symbol_info);
3968 }
3969
3970 /* Vector of ada_symbol_info structures currently collected in current 
3971    vector in *OBSTACKP.  If FINISH, close off the vector and return
3972    its final address.  */
3973
3974 static struct ada_symbol_info *
3975 defns_collected (struct obstack *obstackp, int finish)
3976 {
3977   if (finish)
3978     return obstack_finish (obstackp);
3979   else
3980     return (struct ada_symbol_info *) obstack_base (obstackp);
3981 }
3982
3983 /* Look, in partial_symtab PST, for symbol NAME in given namespace.
3984    Check the global symbols if GLOBAL, the static symbols if not.
3985    Do wild-card match if WILD.  */
3986
3987 static struct partial_symbol *
3988 ada_lookup_partial_symbol (struct partial_symtab *pst, const char *name,
3989                            int global, domain_enum namespace, int wild)
3990 {
3991   struct partial_symbol **start;
3992   int name_len = strlen (name);
3993   int length = (global ? pst->n_global_syms : pst->n_static_syms);
3994   int i;
3995
3996   if (length == 0)
3997     {
3998       return (NULL);
3999     }
4000
4001   start = (global ?
4002            pst->objfile->global_psymbols.list + pst->globals_offset :
4003            pst->objfile->static_psymbols.list + pst->statics_offset);
4004
4005   if (wild)
4006     {
4007       for (i = 0; i < length; i += 1)
4008         {
4009           struct partial_symbol *psym = start[i];
4010
4011           if (SYMBOL_DOMAIN (psym) == namespace
4012               && wild_match (name, name_len, SYMBOL_LINKAGE_NAME (psym)))
4013             return psym;
4014         }
4015       return NULL;
4016     }
4017   else
4018     {
4019       if (global)
4020         {
4021           int U;
4022           i = 0;
4023           U = length - 1;
4024           while (U - i > 4)
4025             {
4026               int M = (U + i) >> 1;
4027               struct partial_symbol *psym = start[M];
4028               if (SYMBOL_LINKAGE_NAME (psym)[0] < name[0])
4029                 i = M + 1;
4030               else if (SYMBOL_LINKAGE_NAME (psym)[0] > name[0])
4031                 U = M - 1;
4032               else if (strcmp (SYMBOL_LINKAGE_NAME (psym), name) < 0)
4033                 i = M + 1;
4034               else
4035                 U = M;
4036             }
4037         }
4038       else
4039         i = 0;
4040
4041       while (i < length)
4042         {
4043           struct partial_symbol *psym = start[i];
4044
4045           if (SYMBOL_DOMAIN (psym) == namespace)
4046             {
4047               int cmp = strncmp (name, SYMBOL_LINKAGE_NAME (psym), name_len);
4048
4049               if (cmp < 0)
4050                 {
4051                   if (global)
4052                     break;
4053                 }
4054               else if (cmp == 0
4055                        && is_name_suffix (SYMBOL_LINKAGE_NAME (psym)
4056                                           + name_len))
4057                 return psym;
4058             }
4059           i += 1;
4060         }
4061
4062       if (global)
4063         {
4064           int U;
4065           i = 0;
4066           U = length - 1;
4067           while (U - i > 4)
4068             {
4069               int M = (U + i) >> 1;
4070               struct partial_symbol *psym = start[M];
4071               if (SYMBOL_LINKAGE_NAME (psym)[0] < '_')
4072                 i = M + 1;
4073               else if (SYMBOL_LINKAGE_NAME (psym)[0] > '_')
4074                 U = M - 1;
4075               else if (strcmp (SYMBOL_LINKAGE_NAME (psym), "_ada_") < 0)
4076                 i = M + 1;
4077               else
4078                 U = M;
4079             }
4080         }
4081       else
4082         i = 0;
4083
4084       while (i < length)
4085         {
4086           struct partial_symbol *psym = start[i];
4087
4088           if (SYMBOL_DOMAIN (psym) == namespace)
4089             {
4090               int cmp;
4091
4092               cmp = (int) '_' - (int) SYMBOL_LINKAGE_NAME (psym)[0];
4093               if (cmp == 0)
4094                 {
4095                   cmp = strncmp ("_ada_", SYMBOL_LINKAGE_NAME (psym), 5);
4096                   if (cmp == 0)
4097                     cmp = strncmp (name, SYMBOL_LINKAGE_NAME (psym) + 5,
4098                                    name_len);
4099                 }
4100
4101               if (cmp < 0)
4102                 {
4103                   if (global)
4104                     break;
4105                 }
4106               else if (cmp == 0
4107                        && is_name_suffix (SYMBOL_LINKAGE_NAME (psym)
4108                                           + name_len + 5))
4109                 return psym;
4110             }
4111           i += 1;
4112         }
4113     }
4114   return NULL;
4115 }
4116
4117 /* Find a symbol table containing symbol SYM or NULL if none.  */
4118
4119 static struct symtab *
4120 symtab_for_sym (struct symbol *sym)
4121 {
4122   struct symtab *s;
4123   struct objfile *objfile;
4124   struct block *b;
4125   struct symbol *tmp_sym;
4126   struct dict_iterator iter;
4127   int j;
4128
4129   ALL_SYMTABS (objfile, s)
4130   {
4131     switch (SYMBOL_CLASS (sym))
4132       {
4133       case LOC_CONST:
4134       case LOC_STATIC:
4135       case LOC_TYPEDEF:
4136       case LOC_REGISTER:
4137       case LOC_LABEL:
4138       case LOC_BLOCK:
4139       case LOC_CONST_BYTES:
4140         b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), GLOBAL_BLOCK);
4141         ALL_BLOCK_SYMBOLS (b, iter, tmp_sym) if (sym == tmp_sym)
4142           return s;
4143         b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), STATIC_BLOCK);
4144         ALL_BLOCK_SYMBOLS (b, iter, tmp_sym) if (sym == tmp_sym)
4145           return s;
4146         break;
4147       default:
4148         break;
4149       }
4150     switch (SYMBOL_CLASS (sym))
4151       {
4152       case LOC_REGISTER:
4153       case LOC_ARG:
4154       case LOC_REF_ARG:
4155       case LOC_REGPARM:
4156       case LOC_REGPARM_ADDR:
4157       case LOC_LOCAL:
4158       case LOC_TYPEDEF:
4159       case LOC_LOCAL_ARG:
4160       case LOC_BASEREG:
4161       case LOC_BASEREG_ARG:
4162       case LOC_COMPUTED:
4163       case LOC_COMPUTED_ARG:
4164         for (j = FIRST_LOCAL_BLOCK;
4165              j < BLOCKVECTOR_NBLOCKS (BLOCKVECTOR (s)); j += 1)
4166           {
4167             b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), j);
4168             ALL_BLOCK_SYMBOLS (b, iter, tmp_sym) if (sym == tmp_sym)
4169               return s;
4170           }
4171         break;
4172       default:
4173         break;
4174       }
4175   }
4176   return NULL;
4177 }
4178
4179 /* Return a minimal symbol matching NAME according to Ada decoding
4180    rules.  Returns NULL if there is no such minimal symbol.  Names 
4181    prefixed with "standard__" are handled specially: "standard__" is 
4182    first stripped off, and only static and global symbols are searched.  */
4183
4184 struct minimal_symbol *
4185 ada_lookup_simple_minsym (const char *name)
4186 {
4187   struct objfile *objfile;
4188   struct minimal_symbol *msymbol;
4189   int wild_match;
4190
4191   if (strncmp (name, "standard__", sizeof ("standard__") - 1) == 0)
4192     {
4193       name += sizeof ("standard__") - 1;
4194       wild_match = 0;
4195     }
4196   else
4197     wild_match = (strstr (name, "__") == NULL);
4198
4199   ALL_MSYMBOLS (objfile, msymbol)
4200   {
4201     if (ada_match_name (SYMBOL_LINKAGE_NAME (msymbol), name, wild_match)
4202         && MSYMBOL_TYPE (msymbol) != mst_solib_trampoline)
4203       return msymbol;
4204   }
4205
4206   return NULL;
4207 }
4208
4209 /* Return up minimal symbol for NAME, folded and encoded according to 
4210    Ada conventions, or NULL if none.  The last two arguments are ignored.  */
4211
4212 static struct minimal_symbol *
4213 ada_lookup_minimal_symbol (const char *name, const char *sfile,
4214                            struct objfile *objf)
4215 {
4216   return ada_lookup_simple_minsym (ada_encode (name));
4217 }
4218
4219 /* For all subprograms that statically enclose the subprogram of the
4220    selected frame, add symbols matching identifier NAME in DOMAIN
4221    and their blocks to the list of data in OBSTACKP, as for
4222    ada_add_block_symbols (q.v.).   If WILD, treat as NAME with a
4223    wildcard prefix.  */
4224
4225 static void
4226 add_symbols_from_enclosing_procs (struct obstack *obstackp,
4227                                   const char *name, domain_enum namespace,
4228                                   int wild_match)
4229 {
4230 #ifdef HAVE_ADD_SYMBOLS_FROM_ENCLOSING_PROCS
4231   /* Use a heuristic to find the frames of enclosing subprograms: treat the
4232      pointer-sized value at location 0 from the local-variable base of a
4233      frame as a static link, and then search up the call stack for a
4234      frame with that same local-variable base.  */
4235   static struct symbol static_link_sym;
4236   static struct symbol *static_link;
4237   struct value *target_link_val;
4238
4239   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
4240   struct frame_info *frame;
4241
4242   if (!target_has_stack)
4243     return;
4244
4245   if (static_link == NULL)
4246     {
4247       /* Initialize the local variable symbol that stands for the
4248          static link (when there is one).  */
4249       static_link = &static_link_sym;
4250       SYMBOL_LINKAGE_NAME (static_link) = "";
4251       SYMBOL_LANGUAGE (static_link) = language_unknown;
4252       SYMBOL_CLASS (static_link) = LOC_LOCAL;
4253       SYMBOL_DOMAIN (static_link) = VAR_DOMAIN;
4254       SYMBOL_TYPE (static_link) = lookup_pointer_type (builtin_type_void);
4255       SYMBOL_VALUE (static_link) =
4256         -(long) TYPE_LENGTH (SYMBOL_TYPE (static_link));
4257     }
4258
4259   frame = get_selected_frame ();
4260   if (frame == NULL || inside_main_func (get_frame_address_in_block (frame)))
4261     return;
4262
4263   target_link_val = read_var_value (static_link, frame);
4264   while (target_link_val != NULL
4265          && num_defns_collected (obstackp) == 0
4266          && frame_relative_level (frame) <= MAX_ENCLOSING_FRAME_LEVELS)
4267     {
4268       CORE_ADDR target_link = value_as_address (target_link_val);
4269
4270       frame = get_prev_frame (frame);
4271       if (frame == NULL)
4272         break;
4273
4274       if (get_frame_locals_address (frame) == target_link)
4275         {
4276           struct block *block;
4277
4278           QUIT;
4279
4280           block = get_frame_block (frame, 0);
4281           while (block != NULL && block_function (block) != NULL
4282                  && num_defns_collected (obstackp) == 0)
4283             {
4284               QUIT;
4285
4286               ada_add_block_symbols (obstackp, block, name, namespace,
4287                                      NULL, NULL, wild_match);
4288
4289               block = BLOCK_SUPERBLOCK (block);
4290             }
4291         }
4292     }
4293
4294   do_cleanups (old_chain);
4295 #endif
4296 }
4297
4298 /* FIXME: The next two routines belong in symtab.c */
4299
4300 static void
4301 restore_language (void *lang)
4302 {
4303   set_language ((enum language) lang);
4304 }
4305
4306 /* As for lookup_symbol, but performed as if the current language 
4307    were LANG. */
4308
4309 struct symbol *
4310 lookup_symbol_in_language (const char *name, const struct block *block,
4311                            domain_enum domain, enum language lang,
4312                            int *is_a_field_of_this, struct symtab **symtab)
4313 {
4314   struct cleanup *old_chain
4315     = make_cleanup (restore_language, (void *) current_language->la_language);
4316   struct symbol *result;
4317   set_language (lang);
4318   result = lookup_symbol (name, block, domain, is_a_field_of_this, symtab);
4319   do_cleanups (old_chain);
4320   return result;
4321 }
4322
4323 /* True if TYPE is definitely an artificial type supplied to a symbol
4324    for which no debugging information was given in the symbol file.  */
4325
4326 static int
4327 is_nondebugging_type (struct type *type)
4328 {
4329   char *name = ada_type_name (type);
4330   return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4331 }
4332
4333 /* Remove any non-debugging symbols in SYMS[0 .. NSYMS-1] that definitely
4334    duplicate other symbols in the list (The only case I know of where
4335    this happens is when object files containing stabs-in-ecoff are
4336    linked with files containing ordinary ecoff debugging symbols (or no
4337    debugging symbols)).  Modifies SYMS to squeeze out deleted entries.
4338    Returns the number of items in the modified list.  */
4339
4340 static int
4341 remove_extra_symbols (struct ada_symbol_info *syms, int nsyms)
4342 {
4343   int i, j;
4344
4345   i = 0;
4346   while (i < nsyms)
4347     {
4348       if (SYMBOL_LINKAGE_NAME (syms[i].sym) != NULL
4349           && SYMBOL_CLASS (syms[i].sym) == LOC_STATIC
4350           && is_nondebugging_type (SYMBOL_TYPE (syms[i].sym)))
4351         {
4352           for (j = 0; j < nsyms; j += 1)
4353             {
4354               if (i != j
4355                   && SYMBOL_LINKAGE_NAME (syms[j].sym) != NULL
4356                   && strcmp (SYMBOL_LINKAGE_NAME (syms[i].sym),
4357                              SYMBOL_LINKAGE_NAME (syms[j].sym)) == 0
4358                   && SYMBOL_CLASS (syms[i].sym) == SYMBOL_CLASS (syms[j].sym)
4359                   && SYMBOL_VALUE_ADDRESS (syms[i].sym)
4360                   == SYMBOL_VALUE_ADDRESS (syms[j].sym))
4361                 {
4362                   int k;
4363                   for (k = i + 1; k < nsyms; k += 1)
4364                     syms[k - 1] = syms[k];
4365                   nsyms -= 1;
4366                   goto NextSymbol;
4367                 }
4368             }
4369         }
4370       i += 1;
4371     NextSymbol:
4372       ;
4373     }
4374   return nsyms;
4375 }
4376
4377 /* Given a type that corresponds to a renaming entity, use the type name
4378    to extract the scope (package name or function name, fully qualified,
4379    and following the GNAT encoding convention) where this renaming has been
4380    defined.  The string returned needs to be deallocated after use.  */
4381
4382 static char *
4383 xget_renaming_scope (struct type *renaming_type)
4384 {
4385   /* The renaming types adhere to the following convention:
4386      <scope>__<rename>___<XR extension>. 
4387      So, to extract the scope, we search for the "___XR" extension,
4388      and then backtrack until we find the first "__".  */
4389
4390   const char *name = type_name_no_tag (renaming_type);
4391   char *suffix = strstr (name, "___XR");
4392   char *last;
4393   int scope_len;
4394   char *scope;
4395
4396   /* Now, backtrack a bit until we find the first "__".  Start looking
4397      at suffix - 3, as the <rename> part is at least one character long.  */
4398
4399   for (last = suffix - 3; last > name; last--)
4400     if (last[0] == '_' && last[1] == '_')
4401       break;
4402
4403   /* Make a copy of scope and return it.  */
4404
4405   scope_len = last - name;
4406   scope = (char *) xmalloc ((scope_len + 1) * sizeof (char));
4407
4408   strncpy (scope, name, scope_len);
4409   scope[scope_len] = '\0';
4410
4411   return scope;
4412 }
4413
4414 /* Return nonzero if NAME corresponds to a package name.  */
4415
4416 static int
4417 is_package_name (const char *name)
4418 {
4419   /* Here, We take advantage of the fact that no symbols are generated
4420      for packages, while symbols are generated for each function.
4421      So the condition for NAME represent a package becomes equivalent
4422      to NAME not existing in our list of symbols.  There is only one
4423      small complication with library-level functions (see below).  */
4424
4425   char *fun_name;
4426
4427   /* If it is a function that has not been defined at library level,
4428      then we should be able to look it up in the symbols.  */
4429   if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
4430     return 0;
4431
4432   /* Library-level function names start with "_ada_".  See if function
4433      "_ada_" followed by NAME can be found.  */
4434
4435   /* Do a quick check that NAME does not contain "__", since library-level
4436      functions names can not contain "__" in them.  */
4437   if (strstr (name, "__") != NULL)
4438     return 0;
4439
4440   fun_name = xstrprintf ("_ada_%s", name);
4441
4442   return (standard_lookup (fun_name, NULL, VAR_DOMAIN) == NULL);
4443 }
4444
4445 /* Return nonzero if SYM corresponds to a renaming entity that is
4446    visible from FUNCTION_NAME.  */
4447
4448 static int
4449 renaming_is_visible (const struct symbol *sym, char *function_name)
4450 {
4451   char *scope = xget_renaming_scope (SYMBOL_TYPE (sym));
4452
4453   make_cleanup (xfree, scope);
4454
4455   /* If the rename has been defined in a package, then it is visible.  */
4456   if (is_package_name (scope))
4457     return 1;
4458
4459   /* Check that the rename is in the current function scope by checking
4460      that its name starts with SCOPE.  */
4461
4462   /* If the function name starts with "_ada_", it means that it is
4463      a library-level function.  Strip this prefix before doing the
4464      comparison, as the encoding for the renaming does not contain
4465      this prefix.  */
4466   if (strncmp (function_name, "_ada_", 5) == 0)
4467     function_name += 5;
4468
4469   return (strncmp (function_name, scope, strlen (scope)) == 0);
4470 }
4471
4472 /* Iterates over the SYMS list and remove any entry that corresponds to
4473    a renaming entity that is not visible from the function associated
4474    with CURRENT_BLOCK. 
4475    
4476    Rationale:
4477    GNAT emits a type following a specified encoding for each renaming
4478    entity.  Unfortunately, STABS currently does not support the definition
4479    of types that are local to a given lexical block, so all renamings types
4480    are emitted at library level.  As a consequence, if an application
4481    contains two renaming entities using the same name, and a user tries to
4482    print the value of one of these entities, the result of the ada symbol
4483    lookup will also contain the wrong renaming type.
4484
4485    This function partially covers for this limitation by attempting to
4486    remove from the SYMS list renaming symbols that should be visible
4487    from CURRENT_BLOCK.  However, there does not seem be a 100% reliable
4488    method with the current information available.  The implementation
4489    below has a couple of limitations (FIXME: brobecker-2003-05-12):  
4490    
4491       - When the user tries to print a rename in a function while there
4492         is another rename entity defined in a package:  Normally, the
4493         rename in the function has precedence over the rename in the
4494         package, so the latter should be removed from the list.  This is
4495         currently not the case.
4496         
4497       - This function will incorrectly remove valid renames if
4498         the CURRENT_BLOCK corresponds to a function which symbol name
4499         has been changed by an "Export" pragma.  As a consequence,
4500         the user will be unable to print such rename entities.  */
4501
4502 static int
4503 remove_out_of_scope_renamings (struct ada_symbol_info *syms,
4504                                int nsyms, struct block *current_block)
4505 {
4506   struct symbol *current_function;
4507   char *current_function_name;
4508   int i;
4509
4510   /* Extract the function name associated to CURRENT_BLOCK.
4511      Abort if unable to do so.  */
4512
4513   if (current_block == NULL)
4514     return nsyms;
4515
4516   current_function = block_function (current_block);
4517   if (current_function == NULL)
4518     return nsyms;
4519
4520   current_function_name = SYMBOL_LINKAGE_NAME (current_function);
4521   if (current_function_name == NULL)
4522     return nsyms;
4523
4524   /* Check each of the symbols, and remove it from the list if it is
4525      a type corresponding to a renaming that is out of the scope of
4526      the current block.  */
4527
4528   i = 0;
4529   while (i < nsyms)
4530     {
4531       if (ada_is_object_renaming (syms[i].sym)
4532           && !renaming_is_visible (syms[i].sym, current_function_name))
4533         {
4534           int j;
4535           for (j = i + 1; j < nsyms; j++)
4536             syms[j - 1] = syms[j];
4537           nsyms -= 1;
4538         }
4539       else
4540         i += 1;
4541     }
4542
4543   return nsyms;
4544 }
4545
4546 /* Find symbols in DOMAIN matching NAME0, in BLOCK0 and enclosing
4547    scope and in global scopes, returning the number of matches.  Sets
4548    *RESULTS to point to a vector of (SYM,BLOCK,SYMTAB) triples,
4549    indicating the symbols found and the blocks and symbol tables (if
4550    any) in which they were found.  This vector are transient---good only to 
4551    the next call of ada_lookup_symbol_list.  Any non-function/non-enumeral 
4552    symbol match within the nest of blocks whose innermost member is BLOCK0,
4553    is the one match returned (no other matches in that or
4554      enclosing blocks is returned).  If there are any matches in or
4555    surrounding BLOCK0, then these alone are returned.  Otherwise, the
4556    search extends to global and file-scope (static) symbol tables.
4557    Names prefixed with "standard__" are handled specially: "standard__" 
4558    is first stripped off, and only static and global symbols are searched.  */
4559
4560 int
4561 ada_lookup_symbol_list (const char *name0, const struct block *block0,
4562                         domain_enum namespace,
4563                         struct ada_symbol_info **results)
4564 {
4565   struct symbol *sym;
4566   struct symtab *s;
4567   struct partial_symtab *ps;
4568   struct blockvector *bv;
4569   struct objfile *objfile;
4570   struct block *block;
4571   const char *name;
4572   struct minimal_symbol *msymbol;
4573   int wild_match;
4574   int cacheIfUnique;
4575   int block_depth;
4576   int ndefns;
4577
4578   obstack_free (&symbol_list_obstack, NULL);
4579   obstack_init (&symbol_list_obstack);
4580
4581   cacheIfUnique = 0;
4582
4583   /* Search specified block and its superiors.  */
4584
4585   wild_match = (strstr (name0, "__") == NULL);
4586   name = name0;
4587   block = (struct block *) block0;      /* FIXME: No cast ought to be
4588                                            needed, but adding const will
4589                                            have a cascade effect.  */
4590   if (strncmp (name0, "standard__", sizeof ("standard__") - 1) == 0)
4591     {
4592       wild_match = 0;
4593       block = NULL;
4594       name = name0 + sizeof ("standard__") - 1;
4595     }
4596
4597   block_depth = 0;
4598   while (block != NULL)
4599     {
4600       block_depth += 1;
4601       ada_add_block_symbols (&symbol_list_obstack, block, name,
4602                              namespace, NULL, NULL, wild_match);
4603
4604       /* If we found a non-function match, assume that's the one.  */
4605       if (is_nonfunction (defns_collected (&symbol_list_obstack, 0),
4606                           num_defns_collected (&symbol_list_obstack)))
4607         goto done;
4608
4609       block = BLOCK_SUPERBLOCK (block);
4610     }
4611
4612   /* If no luck so far, try to find NAME as a local symbol in some lexically
4613      enclosing subprogram.  */
4614   if (num_defns_collected (&symbol_list_obstack) == 0 && block_depth > 2)
4615     add_symbols_from_enclosing_procs (&symbol_list_obstack,
4616                                       name, namespace, wild_match);
4617
4618   /* If we found ANY matches among non-global symbols, we're done.  */
4619
4620   if (num_defns_collected (&symbol_list_obstack) > 0)
4621     goto done;
4622
4623   cacheIfUnique = 1;
4624   if (lookup_cached_symbol (name0, namespace, &sym, &block, &s))
4625     {
4626       if (sym != NULL)
4627         add_defn_to_vec (&symbol_list_obstack, sym, block, s);
4628       goto done;
4629     }
4630
4631   /* Now add symbols from all global blocks: symbol tables, minimal symbol
4632      tables, and psymtab's.  */
4633
4634   ALL_SYMTABS (objfile, s)
4635   {
4636     QUIT;
4637     if (!s->primary)
4638       continue;
4639     bv = BLOCKVECTOR (s);
4640     block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
4641     ada_add_block_symbols (&symbol_list_obstack, block, name, namespace,
4642                            objfile, s, wild_match);
4643   }
4644
4645   if (namespace == VAR_DOMAIN)
4646     {
4647       ALL_MSYMBOLS (objfile, msymbol)
4648       {
4649         if (ada_match_name (SYMBOL_LINKAGE_NAME (msymbol), name, wild_match))
4650           {
4651             switch (MSYMBOL_TYPE (msymbol))
4652               {
4653               case mst_solib_trampoline:
4654                 break;
4655               default:
4656                 s = find_pc_symtab (SYMBOL_VALUE_ADDRESS (msymbol));
4657                 if (s != NULL)
4658                   {
4659                     int ndefns0 = num_defns_collected (&symbol_list_obstack);
4660                     QUIT;
4661                     bv = BLOCKVECTOR (s);
4662                     block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
4663                     ada_add_block_symbols (&symbol_list_obstack, block,
4664                                            SYMBOL_LINKAGE_NAME (msymbol),
4665                                            namespace, objfile, s, wild_match);
4666
4667                     if (num_defns_collected (&symbol_list_obstack) == ndefns0)
4668                       {
4669                         block = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
4670                         ada_add_block_symbols (&symbol_list_obstack, block,
4671                                                SYMBOL_LINKAGE_NAME (msymbol),
4672                                                namespace, objfile, s,
4673                                                wild_match);
4674                       }
4675                   }
4676               }
4677           }
4678       }
4679     }
4680
4681   ALL_PSYMTABS (objfile, ps)
4682   {
4683     QUIT;
4684     if (!ps->readin
4685         && ada_lookup_partial_symbol (ps, name, 1, namespace, wild_match))
4686       {
4687         s = PSYMTAB_TO_SYMTAB (ps);
4688         if (!s->primary)
4689           continue;
4690         bv = BLOCKVECTOR (s);
4691         block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
4692         ada_add_block_symbols (&symbol_list_obstack, block, name,
4693                                namespace, objfile, s, wild_match);
4694       }
4695   }
4696
4697   /* Now add symbols from all per-file blocks if we've gotten no hits
4698      (Not strictly correct, but perhaps better than an error).
4699      Do the symtabs first, then check the psymtabs.  */
4700
4701   if (num_defns_collected (&symbol_list_obstack) == 0)
4702     {
4703
4704       ALL_SYMTABS (objfile, s)
4705       {
4706         QUIT;
4707         if (!s->primary)
4708           continue;
4709         bv = BLOCKVECTOR (s);
4710         block = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
4711         ada_add_block_symbols (&symbol_list_obstack, block, name, namespace,
4712                                objfile, s, wild_match);
4713       }
4714
4715       ALL_PSYMTABS (objfile, ps)
4716       {
4717         QUIT;
4718         if (!ps->readin
4719             && ada_lookup_partial_symbol (ps, name, 0, namespace, wild_match))
4720           {
4721             s = PSYMTAB_TO_SYMTAB (ps);
4722             bv = BLOCKVECTOR (s);
4723             if (!s->primary)
4724               continue;
4725             block = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
4726             ada_add_block_symbols (&symbol_list_obstack, block, name,
4727                                    namespace, objfile, s, wild_match);
4728           }
4729       }
4730     }
4731
4732 done:
4733   ndefns = num_defns_collected (&symbol_list_obstack);
4734   *results = defns_collected (&symbol_list_obstack, 1);
4735
4736   ndefns = remove_extra_symbols (*results, ndefns);
4737
4738   if (ndefns == 0)
4739     cache_symbol (name0, namespace, NULL, NULL, NULL);
4740
4741   if (ndefns == 1 && cacheIfUnique)
4742     cache_symbol (name0, namespace, (*results)[0].sym, (*results)[0].block,
4743                   (*results)[0].symtab);
4744
4745   ndefns = remove_out_of_scope_renamings (*results, ndefns,
4746                                           (struct block *) block0);
4747
4748   return ndefns;
4749 }
4750
4751 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
4752    scope and in global scopes, or NULL if none.  NAME is folded and
4753    encoded first.  Otherwise, the result is as for ada_lookup_symbol_list,
4754    but is disambiguated by user query if needed.  *IS_A_FIELD_OF_THIS is
4755    set to 0 and *SYMTAB is set to the symbol table in which the symbol
4756    was found (in both cases, these assignments occur only if the
4757    pointers are non-null).  */
4758
4759
4760 struct symbol *
4761 ada_lookup_symbol (const char *name, const struct block *block0,
4762                    domain_enum namespace, int *is_a_field_of_this,
4763                    struct symtab **symtab)
4764 {
4765   struct ada_symbol_info *candidates;
4766   int n_candidates;
4767
4768   n_candidates = ada_lookup_symbol_list (ada_encode (ada_fold_name (name)),
4769                                          block0, namespace, &candidates);
4770
4771   if (n_candidates == 0)
4772     return NULL;
4773   else if (n_candidates != 1)
4774     user_select_syms (candidates, n_candidates, 1);
4775
4776   if (is_a_field_of_this != NULL)
4777     *is_a_field_of_this = 0;
4778
4779   if (symtab != NULL)
4780     {
4781       *symtab = candidates[0].symtab;
4782       if (*symtab == NULL && candidates[0].block != NULL)
4783         {
4784           struct objfile *objfile;
4785           struct symtab *s;
4786           struct block *b;
4787           struct blockvector *bv;
4788
4789           /* Search the list of symtabs for one which contains the
4790              address of the start of this block.  */
4791           ALL_SYMTABS (objfile, s)
4792           {
4793             bv = BLOCKVECTOR (s);
4794             b = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
4795             if (BLOCK_START (b) <= BLOCK_START (candidates[0].block)
4796                 && BLOCK_END (b) > BLOCK_START (candidates[0].block))
4797               {
4798                 *symtab = s;
4799                 return fixup_symbol_section (candidates[0].sym, objfile);
4800               }
4801             return fixup_symbol_section (candidates[0].sym, NULL);
4802           }
4803         }
4804     }
4805   return candidates[0].sym;
4806 }
4807
4808 static struct symbol *
4809 ada_lookup_symbol_nonlocal (const char *name,
4810                             const char *linkage_name,
4811                             const struct block *block,
4812                             const domain_enum domain, struct symtab **symtab)
4813 {
4814   if (linkage_name == NULL)
4815     linkage_name = name;
4816   return ada_lookup_symbol (linkage_name, block_static_block (block), domain,
4817                             NULL, symtab);
4818 }
4819
4820
4821 /* True iff STR is a possible encoded suffix of a normal Ada name
4822    that is to be ignored for matching purposes.  Suffixes of parallel
4823    names (e.g., XVE) are not included here.  Currently, the possible suffixes
4824    are given by either of the regular expression:
4825
4826    (__[0-9]+)?\.[0-9]+  [nested subprogram suffix, on platforms such 
4827                          as GNU/Linux]
4828    ___[0-9]+            [nested subprogram suffix, on platforms such as HP/UX]
4829    (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(LJM|X([FDBUP].*|R[^T]?)))?$
4830  */
4831
4832 static int
4833 is_name_suffix (const char *str)
4834 {
4835   int k;
4836   const char *matching;
4837   const int len = strlen (str);
4838
4839   /* (__[0-9]+)?\.[0-9]+ */
4840   matching = str;
4841   if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
4842     {
4843       matching += 3;
4844       while (isdigit (matching[0]))
4845         matching += 1;
4846       if (matching[0] == '\0')
4847         return 1;
4848     }
4849
4850   if (matching[0] == '.')
4851     {
4852       matching += 1;
4853       while (isdigit (matching[0]))
4854         matching += 1;
4855       if (matching[0] == '\0')
4856         return 1;
4857     }
4858
4859   /* ___[0-9]+ */
4860   if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
4861     {
4862       matching = str + 3;
4863       while (isdigit (matching[0]))
4864         matching += 1;
4865       if (matching[0] == '\0')
4866         return 1;
4867     }
4868
4869   /* ??? We should not modify STR directly, as we are doing below.  This
4870      is fine in this case, but may become problematic later if we find
4871      that this alternative did not work, and want to try matching
4872      another one from the begining of STR.  Since we modified it, we
4873      won't be able to find the begining of the string anymore!  */
4874   if (str[0] == 'X')
4875     {
4876       str += 1;
4877       while (str[0] != '_' && str[0] != '\0')
4878         {
4879           if (str[0] != 'n' && str[0] != 'b')
4880             return 0;
4881           str += 1;
4882         }
4883     }
4884   if (str[0] == '\000')
4885     return 1;
4886   if (str[0] == '_')
4887     {
4888       if (str[1] != '_' || str[2] == '\000')
4889         return 0;
4890       if (str[2] == '_')
4891         {
4892           if (strcmp (str + 3, "LJM") == 0)
4893             return 1;
4894           if (str[3] != 'X')
4895             return 0;
4896           if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
4897               || str[4] == 'U' || str[4] == 'P')
4898             return 1;
4899           if (str[4] == 'R' && str[5] != 'T')
4900             return 1;
4901           return 0;
4902         }
4903       if (!isdigit (str[2]))
4904         return 0;
4905       for (k = 3; str[k] != '\0'; k += 1)
4906         if (!isdigit (str[k]) && str[k] != '_')
4907           return 0;
4908       return 1;
4909     }
4910   if (str[0] == '$' && isdigit (str[1]))
4911     {
4912       for (k = 2; str[k] != '\0'; k += 1)
4913         if (!isdigit (str[k]) && str[k] != '_')
4914           return 0;
4915       return 1;
4916     }
4917   return 0;
4918 }
4919
4920 /* Return nonzero if the given string starts with a dot ('.')
4921    followed by zero or more digits.  
4922    
4923    Note: brobecker/2003-11-10: A forward declaration has not been
4924    added at the begining of this file yet, because this function
4925    is only used to work around a problem found during wild matching
4926    when trying to match minimal symbol names against symbol names
4927    obtained from dwarf-2 data.  This function is therefore currently
4928    only used in wild_match() and is likely to be deleted when the
4929    problem in dwarf-2 is fixed.  */
4930
4931 static int
4932 is_dot_digits_suffix (const char *str)
4933 {
4934   if (str[0] != '.')
4935     return 0;
4936
4937   str++;
4938   while (isdigit (str[0]))
4939     str++;
4940   return (str[0] == '\0');
4941 }
4942
4943 /* True if NAME represents a name of the form A1.A2....An, n>=1 and
4944    PATN[0..PATN_LEN-1] = Ak.Ak+1.....An for some k >= 1.  Ignores
4945    informational suffixes of NAME (i.e., for which is_name_suffix is
4946    true).  */
4947
4948 static int
4949 wild_match (const char *patn0, int patn_len, const char *name0)
4950 {
4951   int name_len;
4952   char *name;
4953   char *patn;
4954
4955   /* FIXME: brobecker/2003-11-10: For some reason, the symbol name
4956      stored in the symbol table for nested function names is sometimes
4957      different from the name of the associated entity stored in
4958      the dwarf-2 data: This is the case for nested subprograms, where
4959      the minimal symbol name contains a trailing ".[:digit:]+" suffix,
4960      while the symbol name from the dwarf-2 data does not.
4961
4962      Although the DWARF-2 standard documents that entity names stored
4963      in the dwarf-2 data should be identical to the name as seen in
4964      the source code, GNAT takes a different approach as we already use
4965      a special encoding mechanism to convey the information so that
4966      a C debugger can still use the information generated to debug
4967      Ada programs.  A corollary is that the symbol names in the dwarf-2
4968      data should match the names found in the symbol table.  I therefore
4969      consider this issue as a compiler defect.
4970
4971      Until the compiler is properly fixed, we work-around the problem
4972      by ignoring such suffixes during the match.  We do so by making
4973      a copy of PATN0 and NAME0, and then by stripping such a suffix
4974      if present.  We then perform the match on the resulting strings.  */
4975   {
4976     char *dot;
4977     name_len = strlen (name0);
4978
4979     name = (char *) alloca ((name_len + 1) * sizeof (char));
4980     strcpy (name, name0);
4981     dot = strrchr (name, '.');
4982     if (dot != NULL && is_dot_digits_suffix (dot))
4983       *dot = '\0';
4984
4985     patn = (char *) alloca ((patn_len + 1) * sizeof (char));
4986     strncpy (patn, patn0, patn_len);
4987     patn[patn_len] = '\0';
4988     dot = strrchr (patn, '.');
4989     if (dot != NULL && is_dot_digits_suffix (dot))
4990       {
4991         *dot = '\0';
4992         patn_len = dot - patn;
4993       }
4994   }
4995
4996   /* Now perform the wild match.  */
4997
4998   name_len = strlen (name);
4999   if (name_len >= patn_len + 5 && strncmp (name, "_ada_", 5) == 0
5000       && strncmp (patn, name + 5, patn_len) == 0
5001       && is_name_suffix (name + patn_len + 5))
5002     return 1;
5003
5004   while (name_len >= patn_len)
5005     {
5006       if (strncmp (patn, name, patn_len) == 0
5007           && is_name_suffix (name + patn_len))
5008         return 1;
5009       do
5010         {
5011           name += 1;
5012           name_len -= 1;
5013         }
5014       while (name_len > 0
5015              && name[0] != '.' && (name[0] != '_' || name[1] != '_'));
5016       if (name_len <= 0)
5017         return 0;
5018       if (name[0] == '_')
5019         {
5020           if (!islower (name[2]))
5021             return 0;
5022           name += 2;
5023           name_len -= 2;
5024         }
5025       else
5026         {
5027           if (!islower (name[1]))
5028             return 0;
5029           name += 1;
5030           name_len -= 1;
5031         }
5032     }
5033
5034   return 0;
5035 }
5036
5037
5038 /* Add symbols from BLOCK matching identifier NAME in DOMAIN to
5039    vector *defn_symbols, updating the list of symbols in OBSTACKP 
5040    (if necessary).  If WILD, treat as NAME with a wildcard prefix. 
5041    OBJFILE is the section containing BLOCK.
5042    SYMTAB is recorded with each symbol added.  */
5043
5044 static void
5045 ada_add_block_symbols (struct obstack *obstackp,
5046                        struct block *block, const char *name,
5047                        domain_enum domain, struct objfile *objfile,
5048                        struct symtab *symtab, int wild)
5049 {
5050   struct dict_iterator iter;
5051   int name_len = strlen (name);
5052   /* A matching argument symbol, if any.  */
5053   struct symbol *arg_sym;
5054   /* Set true when we find a matching non-argument symbol.  */
5055   int found_sym;
5056   struct symbol *sym;
5057
5058   arg_sym = NULL;
5059   found_sym = 0;
5060   if (wild)
5061     {
5062       struct symbol *sym;
5063       ALL_BLOCK_SYMBOLS (block, iter, sym)
5064       {
5065         if (SYMBOL_DOMAIN (sym) == domain
5066             && wild_match (name, name_len, SYMBOL_LINKAGE_NAME (sym)))
5067           {
5068             switch (SYMBOL_CLASS (sym))
5069               {
5070               case LOC_ARG:
5071               case LOC_LOCAL_ARG:
5072               case LOC_REF_ARG:
5073               case LOC_REGPARM:
5074               case LOC_REGPARM_ADDR:
5075               case LOC_BASEREG_ARG:
5076               case LOC_COMPUTED_ARG:
5077                 arg_sym = sym;
5078                 break;
5079               case LOC_UNRESOLVED:
5080                 continue;
5081               default:
5082                 found_sym = 1;
5083                 add_defn_to_vec (obstackp,
5084                                  fixup_symbol_section (sym, objfile),
5085                                  block, symtab);
5086                 break;
5087               }
5088           }
5089       }
5090     }
5091   else
5092     {
5093       ALL_BLOCK_SYMBOLS (block, iter, sym)
5094       {
5095         if (SYMBOL_DOMAIN (sym) == domain)
5096           {
5097             int cmp = strncmp (name, SYMBOL_LINKAGE_NAME (sym), name_len);
5098             if (cmp == 0
5099                 && is_name_suffix (SYMBOL_LINKAGE_NAME (sym) + name_len))
5100               {
5101                 switch (SYMBOL_CLASS (sym))
5102                   {
5103                   case LOC_ARG:
5104                   case LOC_LOCAL_ARG:
5105                   case LOC_REF_ARG:
5106                   case LOC_REGPARM:
5107                   case LOC_REGPARM_ADDR:
5108                   case LOC_BASEREG_ARG:
5109                   case LOC_COMPUTED_ARG:
5110                     arg_sym = sym;
5111                     break;
5112                   case LOC_UNRESOLVED:
5113                     break;
5114                   default:
5115                     found_sym = 1;
5116                     add_defn_to_vec (obstackp,
5117                                      fixup_symbol_section (sym, objfile),
5118                                      block, symtab);
5119                     break;
5120                   }
5121               }
5122           }
5123       }
5124     }
5125
5126   if (!found_sym && arg_sym != NULL)
5127     {
5128       add_defn_to_vec (obstackp,
5129                        fixup_symbol_section (arg_sym, objfile),
5130                        block, symtab);
5131     }
5132
5133   if (!wild)
5134     {
5135       arg_sym = NULL;
5136       found_sym = 0;
5137
5138       ALL_BLOCK_SYMBOLS (block, iter, sym)
5139       {
5140         if (SYMBOL_DOMAIN (sym) == domain)
5141           {
5142             int cmp;
5143
5144             cmp = (int) '_' - (int) SYMBOL_LINKAGE_NAME (sym)[0];
5145             if (cmp == 0)
5146               {
5147                 cmp = strncmp ("_ada_", SYMBOL_LINKAGE_NAME (sym), 5);
5148                 if (cmp == 0)
5149                   cmp = strncmp (name, SYMBOL_LINKAGE_NAME (sym) + 5,
5150                                  name_len);
5151               }
5152
5153             if (cmp == 0
5154                 && is_name_suffix (SYMBOL_LINKAGE_NAME (sym) + name_len + 5))
5155               {
5156                 switch (SYMBOL_CLASS (sym))
5157                   {
5158                   case LOC_ARG:
5159                   case LOC_LOCAL_ARG:
5160                   case LOC_REF_ARG:
5161                   case LOC_REGPARM:
5162                   case LOC_REGPARM_ADDR:
5163                   case LOC_BASEREG_ARG:
5164                   case LOC_COMPUTED_ARG:
5165                     arg_sym = sym;
5166                     break;
5167                   case LOC_UNRESOLVED:
5168                     break;
5169                   default:
5170                     found_sym = 1;
5171                     add_defn_to_vec (obstackp,
5172                                      fixup_symbol_section (sym, objfile),
5173                                      block, symtab);
5174                     break;
5175                   }
5176               }
5177           }
5178       end_loop2:;
5179       }
5180
5181       /* NOTE: This really shouldn't be needed for _ada_ symbols.
5182          They aren't parameters, right?  */
5183       if (!found_sym && arg_sym != NULL)
5184         {
5185           add_defn_to_vec (obstackp,
5186                            fixup_symbol_section (arg_sym, objfile),
5187                            block, symtab);
5188         }
5189     }
5190 }
5191 \f
5192 #ifdef GNAT_GDB
5193
5194                                 /* Symbol Completion */
5195
5196 /* If SYM_NAME is a completion candidate for TEXT, return this symbol
5197    name in a form that's appropriate for the completion.  The result
5198    does not need to be deallocated, but is only good until the next call.
5199
5200    TEXT_LEN is equal to the length of TEXT.
5201    Perform a wild match if WILD_MATCH is set.
5202    ENCODED should be set if TEXT represents the start of a symbol name
5203    in its encoded form.  */
5204
5205 static const char *
5206 symbol_completion_match (const char *sym_name,
5207                          const char *text, int text_len,
5208                          int wild_match, int encoded)
5209 {
5210   char *result;
5211   const int verbatim_match = (text[0] == '<');
5212   int match = 0;
5213
5214   if (verbatim_match)
5215     {
5216       /* Strip the leading angle bracket.  */
5217       text = text + 1;
5218       text_len--;
5219     }
5220
5221   /* First, test against the fully qualified name of the symbol.  */
5222
5223   if (strncmp (sym_name, text, text_len) == 0)
5224     match = 1;
5225
5226   if (match && !encoded)
5227     {
5228       /* One needed check before declaring a positive match is to verify
5229          that iff we are doing a verbatim match, the decoded version
5230          of the symbol name starts with '<'.  Otherwise, this symbol name
5231          is not a suitable completion.  */
5232       const char *sym_name_copy = sym_name;
5233       int has_angle_bracket;
5234
5235       sym_name = ada_decode (sym_name);
5236       has_angle_bracket = (sym_name[0] == '<');
5237       match = (has_angle_bracket == verbatim_match);
5238       sym_name = sym_name_copy;
5239     }
5240
5241   if (match && !verbatim_match)
5242     {
5243       /* When doing non-verbatim match, another check that needs to
5244          be done is to verify that the potentially matching symbol name
5245          does not include capital letters, because the ada-mode would
5246          not be able to understand these symbol names without the
5247          angle bracket notation.  */
5248       const char *tmp;
5249
5250       for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
5251       if (*tmp != '\0')
5252         match = 0;
5253     }
5254
5255   /* Second: Try wild matching...  */
5256
5257   if (!match && wild_match)
5258     {
5259       /* Since we are doing wild matching, this means that TEXT
5260          may represent an unqualified symbol name.  We therefore must
5261          also compare TEXT against the unqualified name of the symbol.  */
5262       sym_name = ada_unqualified_name (ada_decode (sym_name));
5263
5264       if (strncmp (sym_name, text, text_len) == 0)
5265         match = 1;
5266     }
5267
5268   /* Finally: If we found a mach, prepare the result to return.  */
5269
5270   if (!match)
5271     return NULL;
5272
5273   if (verbatim_match)
5274     sym_name = add_angle_brackets (sym_name);
5275
5276   if (!encoded)
5277     sym_name = ada_decode (sym_name);
5278
5279   return sym_name;
5280 }
5281
5282 /* A companion function to ada_make_symbol_completion_list().
5283    Check if SYM_NAME represents a symbol which name would be suitable
5284    to complete TEXT (TEXT_LEN is the length of TEXT), in which case
5285    it is appended at the end of the given string vector SV.
5286
5287    ORIG_TEXT is the string original string from the user command
5288    that needs to be completed.  WORD is the entire command on which
5289    completion should be performed.  These two parameters are used to
5290    determine which part of the symbol name should be added to the
5291    completion vector.
5292    if WILD_MATCH is set, then wild matching is performed.
5293    ENCODED should be set if TEXT represents a symbol name in its
5294    encoded formed (in which case the completion should also be
5295    encoded).  */
5296
5297 static void
5298 symbol_completion_add (struct string_vector *sv,
5299                        const char *sym_name,
5300                        const char *text, int text_len,
5301                        const char *orig_text, const char *word,
5302                        int wild_match, int encoded)
5303 {
5304   const char *match = symbol_completion_match (sym_name, text, text_len,
5305                                                wild_match, encoded);
5306   char *completion;
5307
5308   if (match == NULL)
5309     return;
5310
5311   /* We found a match, so add the appropriate completion to the given
5312      string vector.  */
5313
5314   if (word == orig_text)
5315     {
5316       completion = xmalloc (strlen (match) + 5);
5317       strcpy (completion, match);
5318     }
5319   else if (word > orig_text)
5320     {
5321       /* Return some portion of sym_name.  */
5322       completion = xmalloc (strlen (match) + 5);
5323       strcpy (completion, match + (word - orig_text));
5324     }
5325   else
5326     {
5327       /* Return some of ORIG_TEXT plus sym_name.  */
5328       completion = xmalloc (strlen (match) + (orig_text - word) + 5);
5329       strncpy (completion, word, orig_text - word);
5330       completion[orig_text - word] = '\0';
5331       strcat (completion, match);
5332     }
5333
5334   string_vector_append (sv, completion);
5335 }
5336
5337 /* Return a list of possible symbol names completing TEXT0.  The list
5338    is NULL terminated.  WORD is the entire command on which completion
5339    is made.  */
5340
5341 char **
5342 ada_make_symbol_completion_list (const char *text0, const char *word)
5343 {
5344   /* Note: This function is almost a copy of make_symbol_completion_list(),
5345      except it has been adapted for Ada.  It is somewhat of a shame to
5346      duplicate so much code, but we don't really have the infrastructure
5347      yet to develop a language-aware version of he symbol completer...  */
5348   char *text;
5349   int text_len;
5350   int wild_match;
5351   int encoded;
5352   struct string_vector result = xnew_string_vector (128);
5353   struct symbol *sym;
5354   struct symtab *s;
5355   struct partial_symtab *ps;
5356   struct minimal_symbol *msymbol;
5357   struct objfile *objfile;
5358   struct block *b, *surrounding_static_block = 0;
5359   int i;
5360   struct dict_iterator iter;
5361
5362   if (text0[0] == '<')
5363     {
5364       text = xstrdup (text0);
5365       make_cleanup (xfree, text);
5366       text_len = strlen (text);
5367       wild_match = 0;
5368       encoded = 1;
5369     }
5370   else
5371     {
5372       text = xstrdup (ada_encode (text0));
5373       make_cleanup (xfree, text);
5374       text_len = strlen (text);
5375       for (i = 0; i < text_len; i++)
5376         text[i] = tolower (text[i]);
5377
5378       /* FIXME: brobecker/2003-09-17: When we get rid of ADA_RETAIN_DOTS,
5379          we can restrict the wild_match check to searching "__" only.  */
5380       wild_match = (strstr (text0, "__") == NULL
5381                     && strchr (text0, '.') == NULL);
5382       encoded = (strstr (text0, "__") != NULL);
5383     }
5384
5385   /* First, look at the partial symtab symbols.  */
5386   ALL_PSYMTABS (objfile, ps)
5387   {
5388     struct partial_symbol **psym;
5389
5390     /* If the psymtab's been read in we'll get it when we search
5391        through the blockvector.  */
5392     if (ps->readin)
5393       continue;
5394
5395     for (psym = objfile->global_psymbols.list + ps->globals_offset;
5396          psym < (objfile->global_psymbols.list + ps->globals_offset
5397                  + ps->n_global_syms); psym++)
5398       {
5399         QUIT;
5400         symbol_completion_add (&result, SYMBOL_LINKAGE_NAME (*psym),
5401                                text, text_len, text0, word,
5402                                wild_match, encoded);
5403       }
5404
5405     for (psym = objfile->static_psymbols.list + ps->statics_offset;
5406          psym < (objfile->static_psymbols.list + ps->statics_offset
5407                  + ps->n_static_syms); psym++)
5408       {
5409         QUIT;
5410         symbol_completion_add (&result, SYMBOL_LINKAGE_NAME (*psym),
5411                                text, text_len, text0, word,
5412                                wild_match, encoded);
5413       }
5414   }
5415
5416   /* At this point scan through the misc symbol vectors and add each
5417      symbol you find to the list.  Eventually we want to ignore
5418      anything that isn't a text symbol (everything else will be
5419      handled by the psymtab code above).  */
5420
5421   ALL_MSYMBOLS (objfile, msymbol)
5422   {
5423     QUIT;
5424     symbol_completion_add (&result, SYMBOL_LINKAGE_NAME (msymbol),
5425                            text, text_len, text0, word, wild_match, encoded);
5426   }
5427
5428   /* Search upwards from currently selected frame (so that we can
5429      complete on local vars.  */
5430
5431   for (b = get_selected_block (0); b != NULL; b = BLOCK_SUPERBLOCK (b))
5432     {
5433       if (!BLOCK_SUPERBLOCK (b))
5434         surrounding_static_block = b;   /* For elmin of dups */
5435
5436       ALL_BLOCK_SYMBOLS (b, iter, sym)
5437       {
5438         symbol_completion_add (&result, SYMBOL_LINKAGE_NAME (sym),
5439                                text, text_len, text0, word,
5440                                wild_match, encoded);
5441       }
5442     }
5443
5444   /* Go through the symtabs and check the externs and statics for
5445      symbols which match.  */
5446
5447   ALL_SYMTABS (objfile, s)
5448   {
5449     QUIT;
5450     b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), GLOBAL_BLOCK);
5451     ALL_BLOCK_SYMBOLS (b, iter, sym)
5452     {
5453       symbol_completion_add (&result, SYMBOL_LINKAGE_NAME (sym),
5454                              text, text_len, text0, word,
5455                              wild_match, encoded);
5456     }
5457   }
5458
5459   ALL_SYMTABS (objfile, s)
5460   {
5461     QUIT;
5462     b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), STATIC_BLOCK);
5463     /* Don't do this block twice.  */
5464     if (b == surrounding_static_block)
5465       continue;
5466     ALL_BLOCK_SYMBOLS (b, iter, sym)
5467     {
5468       symbol_completion_add (&result, SYMBOL_LINKAGE_NAME (sym),
5469                              text, text_len, text0, word,
5470                              wild_match, encoded);
5471     }
5472   }
5473
5474   /* Append the closing NULL entry.  */
5475   string_vector_append (&result, NULL);
5476
5477   return (result.array);
5478 }
5479
5480 #endif /* GNAT_GDB */
5481 \f
5482 #ifdef GNAT_GDB
5483                                 /* Breakpoint-related */
5484
5485 /* Assuming that LINE is pointing at the beginning of an argument to
5486    'break', return a pointer to the delimiter for the initial segment
5487    of that name.  This is the first ':', ' ', or end of LINE.  */
5488
5489 char *
5490 ada_start_decode_line_1 (char *line)
5491 {
5492   /* NOTE: strpbrk would be more elegant, but I am reluctant to be
5493      the first to use such a library function in GDB code.  */
5494   char *p;
5495   for (p = line; *p != '\000' && *p != ' ' && *p != ':'; p += 1)
5496     ;
5497   return p;
5498 }
5499
5500 /* *SPEC points to a function and line number spec (as in a break
5501    command), following any initial file name specification.
5502
5503    Return all symbol table/line specfications (sals) consistent with the
5504    information in *SPEC and FILE_TABLE in the following sense:
5505      + FILE_TABLE is null, or the sal refers to a line in the file
5506        named by FILE_TABLE.
5507      + If *SPEC points to an argument with a trailing ':LINENUM',
5508        then the sal refers to that line (or one following it as closely as
5509        possible).
5510      + If *SPEC does not start with '*', the sal is in a function with
5511        that name.
5512
5513    Returns with 0 elements if no matching non-minimal symbols found.
5514
5515    If *SPEC begins with a function name of the form <NAME>, then NAME
5516    is taken as a literal name; otherwise the function name is subject
5517    to the usual encoding.
5518
5519    *SPEC is updated to point after the function/line number specification.
5520
5521    FUNFIRSTLINE is non-zero if we desire the first line of real code
5522    in each function.
5523
5524    If CANONICAL is non-NULL, and if any of the sals require a
5525    'canonical line spec', then *CANONICAL is set to point to an array
5526    of strings, corresponding to and equal in length to the returned
5527    list of sals, such that (*CANONICAL)[i] is non-null and contains a
5528    canonical line spec for the ith returned sal, if needed.  If no
5529    canonical line specs are required and CANONICAL is non-null,
5530    *CANONICAL is set to NULL.
5531
5532    A 'canonical line spec' is simply a name (in the format of the
5533    breakpoint command) that uniquely identifies a breakpoint position,
5534    with no further contextual information or user selection.  It is
5535    needed whenever the file name, function name, and line number
5536    information supplied is insufficient for this unique
5537    identification.  Currently overloaded functions, the name '*',
5538    or static functions without a filename yield a canonical line spec.
5539    The array and the line spec strings are allocated on the heap; it
5540    is the caller's responsibility to free them.  */
5541
5542 struct symtabs_and_lines
5543 ada_finish_decode_line_1 (char **spec, struct symtab *file_table,
5544                           int funfirstline, char ***canonical)
5545 {
5546   struct ada_symbol_info *symbols;
5547   const struct block *block;
5548   int n_matches, i, line_num;
5549   struct symtabs_and_lines selected;
5550   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
5551   char *name;
5552   int is_quoted;
5553
5554   int len;
5555   char *lower_name;
5556   char *unquoted_name;
5557
5558   if (file_table == NULL)
5559     block = block_static_block (get_selected_block (0));
5560   else
5561     block = BLOCKVECTOR_BLOCK (BLOCKVECTOR (file_table), STATIC_BLOCK);
5562
5563   if (canonical != NULL)
5564     *canonical = (char **) NULL;
5565
5566   is_quoted = (**spec && strchr (get_gdb_completer_quote_characters (),
5567                                  **spec) != NULL);
5568
5569   name = *spec;
5570   if (**spec == '*')
5571     *spec += 1;
5572   else
5573     {
5574       if (is_quoted)
5575         *spec = skip_quoted (*spec);
5576       while (**spec != '\000'
5577              && !strchr (ada_completer_word_break_characters, **spec))
5578         *spec += 1;
5579     }
5580   len = *spec - name;
5581
5582   line_num = -1;
5583   if (file_table != NULL && (*spec)[0] == ':' && isdigit ((*spec)[1]))
5584     {
5585       line_num = strtol (*spec + 1, spec, 10);
5586       while (**spec == ' ' || **spec == '\t')
5587         *spec += 1;
5588     }
5589
5590   if (name[0] == '*')
5591     {
5592       if (line_num == -1)
5593         error ("Wild-card function with no line number or file name.");
5594
5595       return ada_sals_for_line (file_table->filename, line_num,
5596                                 funfirstline, canonical, 0);
5597     }
5598
5599   if (name[0] == '\'')
5600     {
5601       name += 1;
5602       len -= 2;
5603     }
5604
5605   if (name[0] == '<')
5606     {
5607       unquoted_name = (char *) alloca (len - 1);
5608       memcpy (unquoted_name, name + 1, len - 2);
5609       unquoted_name[len - 2] = '\000';
5610       lower_name = NULL;
5611     }
5612   else
5613     {
5614       unquoted_name = (char *) alloca (len + 1);
5615       memcpy (unquoted_name, name, len);
5616       unquoted_name[len] = '\000';
5617       lower_name = (char *) alloca (len + 1);
5618       for (i = 0; i < len; i += 1)
5619         lower_name[i] = tolower (name[i]);
5620       lower_name[len] = '\000';
5621     }
5622
5623   n_matches = 0;
5624   if (lower_name != NULL)
5625     n_matches = ada_lookup_symbol_list (ada_encode (lower_name), block,
5626                                         VAR_DOMAIN, &symbols);
5627   if (n_matches == 0)
5628     n_matches = ada_lookup_symbol_list (unquoted_name, block,
5629                                         VAR_DOMAIN, &symbols);
5630   if (n_matches == 0 && line_num >= 0)
5631     error ("No line number information found for %s.", unquoted_name);
5632   else if (n_matches == 0)
5633     {
5634 #ifdef HPPA_COMPILER_BUG
5635       /* FIXME: See comment in symtab.c::decode_line_1 */
5636 #undef volatile
5637       volatile struct symtab_and_line val;
5638 #define volatile                /*nothing */
5639 #else
5640       struct symtab_and_line val;
5641 #endif
5642       struct minimal_symbol *msymbol;
5643
5644       init_sal (&val);
5645
5646       msymbol = NULL;
5647       if (lower_name != NULL)
5648         msymbol = ada_lookup_simple_minsym (ada_encode (lower_name));
5649       if (msymbol == NULL)
5650         msymbol = ada_lookup_simple_minsym (unquoted_name);
5651       if (msymbol != NULL)
5652         {
5653           val.pc = SYMBOL_VALUE_ADDRESS (msymbol);
5654           val.section = SYMBOL_BFD_SECTION (msymbol);
5655           if (funfirstline)
5656             {
5657               val.pc = gdbarch_convert_from_func_ptr_addr (current_gdbarch,
5658                                                            val.pc,
5659                                                            &current_target);
5660               SKIP_PROLOGUE (val.pc);
5661             }
5662           selected.sals = (struct symtab_and_line *)
5663             xmalloc (sizeof (struct symtab_and_line));
5664           selected.sals[0] = val;
5665           selected.nelts = 1;
5666           return selected;
5667         }
5668
5669       if (!have_full_symbols ()
5670           && !have_partial_symbols () && !have_minimal_symbols ())
5671         error ("No symbol table is loaded.  Use the \"file\" command.");
5672
5673       error ("Function \"%s\" not defined.", unquoted_name);
5674       return selected;          /* for lint */
5675     }
5676
5677   if (line_num >= 0)
5678     {
5679       struct symtabs_and_lines best_sal =
5680         find_sal_from_funcs_and_line (file_table->filename, line_num,
5681                                       symbols, n_matches);
5682       if (funfirstline)
5683         adjust_pc_past_prologue (&best_sal.sals[0].pc);
5684       return best_sal;
5685     }
5686   else
5687     {
5688       selected.nelts = user_select_syms (symbols, n_matches, n_matches);
5689     }
5690
5691   selected.sals = (struct symtab_and_line *)
5692     xmalloc (sizeof (struct symtab_and_line) * selected.nelts);
5693   memset (selected.sals, 0, selected.nelts * sizeof (selected.sals[i]));
5694   make_cleanup (xfree, selected.sals);
5695
5696   i = 0;
5697   while (i < selected.nelts)
5698     {
5699       if (SYMBOL_CLASS (symbols[i].sym) == LOC_BLOCK)
5700         selected.sals[i]
5701           = find_function_start_sal (symbols[i].sym, funfirstline);
5702       else if (SYMBOL_LINE (symbols[i].sym) != 0)
5703         {
5704           selected.sals[i].symtab =
5705             symbols[i].symtab
5706             ? symbols[i].symtab : symtab_for_sym (symbols[i].sym);
5707           selected.sals[i].line = SYMBOL_LINE (symbols[i].sym);
5708         }
5709       else if (line_num >= 0)
5710         {
5711           /* Ignore this choice */
5712           symbols[i] = symbols[selected.nelts - 1];
5713           selected.nelts -= 1;
5714           continue;
5715         }
5716       else
5717         error ("Line number not known for symbol \"%s\"", unquoted_name);
5718       i += 1;
5719     }
5720
5721   if (canonical != NULL && (line_num >= 0 || n_matches > 1))
5722     {
5723       *canonical = (char **) xmalloc (sizeof (char *) * selected.nelts);
5724       for (i = 0; i < selected.nelts; i += 1)
5725         (*canonical)[i] =
5726           extended_canonical_line_spec (selected.sals[i],
5727                                         SYMBOL_PRINT_NAME (symbols[i].sym));
5728     }
5729
5730   discard_cleanups (old_chain);
5731   return selected;
5732 }
5733
5734 /* The (single) sal corresponding to line LINE_NUM in a symbol table
5735    with file name FILENAME that occurs in one of the functions listed
5736    in the symbol fields of SYMBOLS[0 .. NSYMS-1].  */
5737
5738 static struct symtabs_and_lines
5739 find_sal_from_funcs_and_line (const char *filename, int line_num,
5740                               struct ada_symbol_info *symbols, int nsyms)
5741 {
5742   struct symtabs_and_lines sals;
5743   int best_index, best;
5744   struct linetable *best_linetable;
5745   struct objfile *objfile;
5746   struct symtab *s;
5747   struct symtab *best_symtab;
5748
5749   read_all_symtabs (filename);
5750
5751   best_index = 0;
5752   best_linetable = NULL;
5753   best_symtab = NULL;
5754   best = 0;
5755   ALL_SYMTABS (objfile, s)
5756   {
5757     struct linetable *l;
5758     int ind, exact;
5759
5760     QUIT;
5761
5762     if (strcmp (filename, s->filename) != 0)
5763       continue;
5764     l = LINETABLE (s);
5765     ind = find_line_in_linetable (l, line_num, symbols, nsyms, &exact);
5766     if (ind >= 0)
5767       {
5768         if (exact)
5769           {
5770             best_index = ind;
5771             best_linetable = l;
5772             best_symtab = s;
5773             goto done;
5774           }
5775         if (best == 0 || l->item[ind].line < best)
5776           {
5777             best = l->item[ind].line;
5778             best_index = ind;
5779             best_linetable = l;
5780             best_symtab = s;
5781           }
5782       }
5783   }
5784
5785   if (best == 0)
5786     error ("Line number not found in designated function.");
5787
5788 done:
5789
5790   sals.nelts = 1;
5791   sals.sals = (struct symtab_and_line *) xmalloc (sizeof (sals.sals[0]));
5792
5793   init_sal (&sals.sals[0]);
5794
5795   sals.sals[0].line = best_linetable->item[best_index].line;
5796   sals.sals[0].pc = best_linetable->item[best_index].pc;
5797   sals.sals[0].symtab = best_symtab;
5798
5799   return sals;
5800 }
5801
5802 /* Return the index in LINETABLE of the best match for LINE_NUM whose
5803    pc falls within one of the functions denoted by the symbol fields
5804    of SYMBOLS[0..NSYMS-1].  Set *EXACTP to 1 if the match is exact, 
5805    and 0 otherwise.  */
5806
5807 static int
5808 find_line_in_linetable (struct linetable *linetable, int line_num,
5809                         struct ada_symbol_info *symbols, int nsyms,
5810                         int *exactp)
5811 {
5812   int i, len, best_index, best;
5813
5814   if (line_num <= 0 || linetable == NULL)
5815     return -1;
5816
5817   len = linetable->nitems;
5818   for (i = 0, best_index = -1, best = 0; i < len; i += 1)
5819     {
5820       int k;
5821       struct linetable_entry *item = &(linetable->item[i]);
5822
5823       for (k = 0; k < nsyms; k += 1)
5824         {
5825           if (symbols[k].sym != NULL
5826               && SYMBOL_CLASS (symbols[k].sym) == LOC_BLOCK
5827               && item->pc >= BLOCK_START (SYMBOL_BLOCK_VALUE (symbols[k].sym))
5828               && item->pc < BLOCK_END (SYMBOL_BLOCK_VALUE (symbols[k].sym)))
5829             goto candidate;
5830         }
5831       continue;
5832
5833     candidate:
5834
5835       if (item->line == line_num)
5836         {
5837           *exactp = 1;
5838           return i;
5839         }
5840
5841       if (item->line > line_num && (best == 0 || item->line < best))
5842         {
5843           best = item->line;
5844           best_index = i;
5845         }
5846     }
5847
5848   *exactp = 0;
5849   return best_index;
5850 }
5851
5852 /* Find the smallest k >= LINE_NUM such that k is a line number in
5853    LINETABLE, and k falls strictly within a named function that begins at
5854    or before LINE_NUM.  Return -1 if there is no such k.  */
5855
5856 static int
5857 nearest_line_number_in_linetable (struct linetable *linetable, int line_num)
5858 {
5859   int i, len, best;
5860
5861   if (line_num <= 0 || linetable == NULL || linetable->nitems == 0)
5862     return -1;
5863   len = linetable->nitems;
5864
5865   i = 0;
5866   best = INT_MAX;
5867   while (i < len)
5868     {
5869       struct linetable_entry *item = &(linetable->item[i]);
5870
5871       if (item->line >= line_num && item->line < best)
5872         {
5873           char *func_name;
5874           CORE_ADDR start, end;
5875
5876           func_name = NULL;
5877           find_pc_partial_function (item->pc, &func_name, &start, &end);
5878
5879           if (func_name != NULL && item->pc < end)
5880             {
5881               if (item->line == line_num)
5882                 return line_num;
5883               else
5884                 {
5885                   struct symbol *sym =
5886                     standard_lookup (func_name, NULL, VAR_DOMAIN);
5887                   if (is_plausible_func_for_line (sym, line_num))
5888                     best = item->line;
5889                   else
5890                     {
5891                       do
5892                         i += 1;
5893                       while (i < len && linetable->item[i].pc < end);
5894                       continue;
5895                     }
5896                 }
5897             }
5898         }
5899
5900       i += 1;
5901     }
5902
5903   return (best == INT_MAX) ? -1 : best;
5904 }
5905
5906
5907 /* Return the next higher index, k, into LINETABLE such that k > IND,
5908    entry k in LINETABLE has a line number equal to LINE_NUM, k
5909    corresponds to a PC that is in a function different from that
5910    corresponding to IND, and falls strictly within a named function
5911    that begins at a line at or preceding STARTING_LINE.
5912    Return -1 if there is no such k.
5913    IND == -1 corresponds to no function.  */
5914
5915 static int
5916 find_next_line_in_linetable (struct linetable *linetable, int line_num,
5917                              int starting_line, int ind)
5918 {
5919   int i, len;
5920
5921   if (line_num <= 0 || linetable == NULL || ind >= linetable->nitems)
5922     return -1;
5923   len = linetable->nitems;
5924
5925   if (ind >= 0)
5926     {
5927       CORE_ADDR start, end;
5928
5929       if (find_pc_partial_function (linetable->item[ind].pc,
5930                                     (char **) NULL, &start, &end))
5931         {
5932           while (ind < len && linetable->item[ind].pc < end)
5933             ind += 1;
5934         }
5935       else
5936         ind += 1;
5937     }
5938   else
5939     ind = 0;
5940
5941   i = ind;
5942   while (i < len)
5943     {
5944       struct linetable_entry *item = &(linetable->item[i]);
5945
5946       if (item->line >= line_num)
5947         {
5948           char *func_name;
5949           CORE_ADDR start, end;
5950
5951           func_name = NULL;
5952           find_pc_partial_function (item->pc, &func_name, &start, &end);
5953
5954           if (func_name != NULL && item->pc < end)
5955             {
5956               if (item->line == line_num)
5957                 {
5958                   struct symbol *sym =
5959                     standard_lookup (func_name, NULL, VAR_DOMAIN);
5960                   if (is_plausible_func_for_line (sym, starting_line))
5961                     return i;
5962                   else
5963                     {
5964                       while ((i + 1) < len && linetable->item[i + 1].pc < end)
5965                         i += 1;
5966                     }
5967                 }
5968             }
5969         }
5970       i += 1;
5971     }
5972
5973   return -1;
5974 }
5975
5976 /* True iff function symbol SYM starts somewhere at or before line #
5977    LINE_NUM.  */
5978
5979 static int
5980 is_plausible_func_for_line (struct symbol *sym, int line_num)
5981 {
5982   struct symtab_and_line start_sal;
5983
5984   if (sym == NULL)
5985     return 0;
5986
5987   start_sal = find_function_start_sal (sym, 0);
5988
5989   return (start_sal.line != 0 && line_num >= start_sal.line);
5990 }
5991
5992 /* Read in all symbol tables corresponding to partial symbol tables
5993    with file name FILENAME.  */
5994
5995 static void
5996 read_all_symtabs (const char *filename)
5997 {
5998   struct partial_symtab *ps;
5999   struct objfile *objfile;
6000
6001   ALL_PSYMTABS (objfile, ps)
6002   {
6003     QUIT;
6004
6005     if (strcmp (filename, ps->filename) == 0)
6006       PSYMTAB_TO_SYMTAB (ps);
6007   }
6008 }
6009
6010 /* All sals corresponding to line LINE_NUM in a symbol table from file
6011    FILENAME, as filtered by the user.  Filter out any lines that
6012    reside in functions with "suppressed" names (not corresponding to
6013    explicit Ada functions), if there is at least one in a function
6014    with a non-suppressed name.  If CANONICAL is not null, set
6015    it to a corresponding array of canonical line specs.
6016    If ONE_LOCATION_ONLY is set and several matches are found for
6017    the given location, then automatically select the first match found
6018    instead of asking the user which instance should be returned.  */
6019
6020 struct symtabs_and_lines
6021 ada_sals_for_line (const char *filename, int line_num,
6022                    int funfirstline, char ***canonical, int one_location_only)
6023 {
6024   struct symtabs_and_lines result;
6025   struct objfile *objfile;
6026   struct symtab *s;
6027   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
6028   size_t len;
6029
6030   read_all_symtabs (filename);
6031
6032   result.sals =
6033     (struct symtab_and_line *) xmalloc (4 * sizeof (result.sals[0]));
6034   result.nelts = 0;
6035   len = 4;
6036   make_cleanup (free_current_contents, &result.sals);
6037
6038   ALL_SYMTABS (objfile, s)
6039   {
6040     int ind, target_line_num;
6041
6042     QUIT;
6043
6044     if (strcmp (s->filename, filename) != 0)
6045       continue;
6046
6047     target_line_num =
6048       nearest_line_number_in_linetable (LINETABLE (s), line_num);
6049     if (target_line_num == -1)
6050       continue;
6051
6052     ind = -1;
6053     while (1)
6054       {
6055         ind =
6056           find_next_line_in_linetable (LINETABLE (s),
6057                                        target_line_num, line_num, ind);
6058
6059         if (ind < 0)
6060           break;
6061
6062         GROW_VECT (result.sals, len, result.nelts + 1);
6063         init_sal (&result.sals[result.nelts]);
6064         result.sals[result.nelts].line = line_num;
6065         result.sals[result.nelts].pc = LINETABLE (s)->item[ind].pc;
6066         result.sals[result.nelts].symtab = s;
6067
6068         if (funfirstline)
6069           adjust_pc_past_prologue (&result.sals[result.nelts].pc);
6070
6071         result.nelts += 1;
6072       }
6073   }
6074
6075   if (canonical != NULL || result.nelts > 1)
6076     {
6077       int k, j, n;
6078       char **func_names = (char **) alloca (result.nelts * sizeof (char *));
6079       int first_choice = (result.nelts > 1) ? 2 : 1;
6080       int *choices = (int *) alloca (result.nelts * sizeof (int));
6081
6082       for (k = 0; k < result.nelts; k += 1)
6083         {
6084           find_pc_partial_function (result.sals[k].pc, &func_names[k],
6085                                     (CORE_ADDR *) NULL, (CORE_ADDR *) NULL);
6086           if (func_names[k] == NULL)
6087             error ("Could not find function for one or more breakpoints.");
6088         }
6089
6090       /* Remove suppressed names, unless all are suppressed.  */
6091       for (j = 0; j < result.nelts; j += 1)
6092         if (!is_suppressed_name (func_names[j]))
6093           {
6094             /* At least one name is unsuppressed, so remove all
6095                suppressed names.  */
6096             for (k = n = 0; k < result.nelts; k += 1)
6097               if (!is_suppressed_name (func_names[k]))
6098                 {
6099                   func_names[n] = func_names[k];
6100                   result.sals[n] = result.sals[k];
6101                   n += 1;
6102                 }
6103             result.nelts = n;
6104             break;
6105           }
6106
6107       if (result.nelts > 1)
6108         {
6109           if (one_location_only)
6110             {
6111               /* Automatically select the first of all possible choices.  */
6112               n = 1;
6113               choices[0] = 0;
6114             }
6115           else
6116             {
6117               printf_unfiltered ("[0] cancel\n");
6118               if (result.nelts > 1)
6119                 printf_unfiltered ("[1] all\n");
6120               for (k = 0; k < result.nelts; k += 1)
6121                 printf_unfiltered ("[%d] %s\n", k + first_choice,
6122                                    ada_decode (func_names[k]));
6123
6124               n = get_selections (choices, result.nelts, result.nelts,
6125                                   result.nelts > 1, "instance-choice");
6126             }
6127
6128           for (k = 0; k < n; k += 1)
6129             {
6130               result.sals[k] = result.sals[choices[k]];
6131               func_names[k] = func_names[choices[k]];
6132             }
6133           result.nelts = n;
6134         }
6135
6136       if (canonical != NULL && result.nelts == 0)
6137         *canonical = NULL;
6138       else if (canonical != NULL)
6139         {
6140           *canonical = (char **) xmalloc (result.nelts * sizeof (char **));
6141           make_cleanup (xfree, *canonical);
6142           for (k = 0; k < result.nelts; k += 1)
6143             {
6144               (*canonical)[k] =
6145                 extended_canonical_line_spec (result.sals[k], func_names[k]);
6146               if ((*canonical)[k] == NULL)
6147                 error ("Could not locate one or more breakpoints.");
6148               make_cleanup (xfree, (*canonical)[k]);
6149             }
6150         }
6151     }
6152
6153   if (result.nelts == 0)
6154     {
6155       do_cleanups (old_chain);
6156       result.sals = NULL;
6157     }
6158   else
6159     discard_cleanups (old_chain);
6160   return result;
6161 }
6162
6163
6164 /* A canonical line specification of the form FILE:NAME:LINENUM for
6165    symbol table and line data SAL.  NULL if insufficient
6166    information.  The caller is responsible for releasing any space
6167    allocated.  */
6168
6169 static char *
6170 extended_canonical_line_spec (struct symtab_and_line sal, const char *name)
6171 {
6172   char *r;
6173
6174   if (sal.symtab == NULL || sal.symtab->filename == NULL || sal.line <= 0)
6175     return NULL;
6176
6177   r = (char *) xmalloc (strlen (name) + strlen (sal.symtab->filename)
6178                         + sizeof (sal.line) * 3 + 3);
6179   sprintf (r, "%s:'%s':%d", sal.symtab->filename, name, sal.line);
6180   return r;
6181 }
6182
6183 \f
6184                                 /* Exception-related */
6185
6186 int
6187 ada_is_exception_sym (struct symbol *sym)
6188 {
6189   char *type_name = type_name_no_tag (SYMBOL_TYPE (sym));
6190
6191   return (SYMBOL_CLASS (sym) != LOC_TYPEDEF
6192           && SYMBOL_CLASS (sym) != LOC_BLOCK
6193           && SYMBOL_CLASS (sym) != LOC_CONST
6194           && type_name != NULL && strcmp (type_name, "exception") == 0);
6195 }
6196
6197 /* Return type of Ada breakpoint associated with bp_stat:
6198    0 if not an Ada-specific breakpoint, 1 for break on specific exception,
6199    2 for break on unhandled exception, 3 for assert.  */
6200
6201 static int
6202 ada_exception_breakpoint_type (bpstat bs)
6203 {
6204   return ((!bs || !bs->breakpoint_at) ? 0
6205           : bs->breakpoint_at->break_on_exception);
6206 }
6207
6208 /* True iff FRAME is very likely to be that of a function that is
6209    part of the runtime system.  This is all very heuristic, but is
6210    intended to be used as advice as to what frames are uninteresting
6211    to most users.  */
6212
6213 static int
6214 is_known_support_routine (struct frame_info *frame)
6215 {
6216   struct frame_info *next_frame = get_next_frame (frame);
6217   /* If frame is not innermost, that normally means that frame->pc
6218      points to *after* the call instruction, and we want to get the line
6219      containing the call, never the next line.  But if the next frame is
6220      a signal_handler_caller or a dummy frame, then the next frame was
6221      not entered as the result of a call, and we want to get the line
6222      containing frame->pc.  */
6223   const int pc_is_after_call =
6224     next_frame != NULL
6225     && get_frame_type (next_frame) != SIGTRAMP_FRAME
6226     && get_frame_type (next_frame) != DUMMY_FRAME;
6227   struct symtab_and_line sal
6228     = find_pc_line (get_frame_pc (frame), pc_is_after_call);
6229   char *func_name;
6230   int i;
6231   struct stat st;
6232
6233   /* The heuristic:
6234      1. The symtab is null (indicating no debugging symbols)
6235      2. The symtab's filename does not exist.
6236      3. The object file's name is one of the standard libraries.
6237      4. The symtab's file name has the form of an Ada library source file.
6238      5. The function at frame's PC has a GNAT-compiler-generated name.  */
6239
6240   if (sal.symtab == NULL)
6241     return 1;
6242
6243   /* On some systems (e.g. VxWorks), the kernel contains debugging
6244      symbols; in this case, the filename referenced by these symbols
6245      does not exists.  */
6246
6247   if (stat (sal.symtab->filename, &st))
6248     return 1;
6249
6250   for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
6251     {
6252       re_comp (known_runtime_file_name_patterns[i]);
6253       if (re_exec (sal.symtab->filename))
6254         return 1;
6255     }
6256   if (sal.symtab->objfile != NULL)
6257     {
6258       for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
6259         {
6260           re_comp (known_runtime_file_name_patterns[i]);
6261           if (re_exec (sal.symtab->objfile->name))
6262             return 1;
6263         }
6264     }
6265
6266   /* If the frame PC points after the call instruction, then we need to
6267      decrement it in order to search for the function associated to this
6268      PC.  Otherwise, if the associated call was the last instruction of
6269      the function, we might either find the wrong function or even fail
6270      during the function name lookup.  */
6271   if (pc_is_after_call)
6272     func_name = function_name_from_pc (get_frame_pc (frame) - 1);
6273   else
6274     func_name = function_name_from_pc (get_frame_pc (frame));
6275
6276   if (func_name == NULL)
6277     return 1;
6278
6279   for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
6280     {
6281       re_comp (known_auxiliary_function_name_patterns[i]);
6282       if (re_exec (func_name))
6283         return 1;
6284     }
6285
6286   return 0;
6287 }
6288
6289 /* Find the first frame that contains debugging information and that is not
6290    part of the Ada run-time, starting from FI and moving upward.  */
6291
6292 void
6293 ada_find_printable_frame (struct frame_info *fi)
6294 {
6295   for (; fi != NULL; fi = get_prev_frame (fi))
6296     {
6297       if (!is_known_support_routine (fi))
6298         {
6299           select_frame (fi);
6300           break;
6301         }
6302     }
6303
6304 }
6305
6306 /* Name found for exception associated with last bpstat sent to
6307    ada_adjust_exception_stop.  Set to the null string if that bpstat
6308    did not correspond to an Ada exception or no name could be found.  */
6309
6310 static char last_exception_name[256];
6311
6312 /* If BS indicates a stop in an Ada exception, try to go up to a frame
6313    that will be meaningful to the user, and save the name of the last
6314    exception (truncated, if necessary) in last_exception_name.  */
6315
6316 void
6317 ada_adjust_exception_stop (bpstat bs)
6318 {
6319   CORE_ADDR addr;
6320   struct frame_info *fi;
6321   int frame_level;
6322   char *selected_frame_func;
6323
6324   addr = 0;
6325   last_exception_name[0] = '\0';
6326   fi = get_selected_frame ();
6327   selected_frame_func = function_name_from_pc (get_frame_pc (fi));
6328
6329   switch (ada_exception_breakpoint_type (bs))
6330     {
6331     default:
6332       return;
6333     case 1:
6334       break;
6335     case 2:
6336       /* Unhandled exceptions.  Select the frame corresponding to
6337          ada.exceptions.process_raise_exception.  This frame is at
6338          least 2 levels up, so we simply skip the first 2 frames
6339          without checking the name of their associated function.  */
6340       for (frame_level = 0; frame_level < 2; frame_level += 1)
6341         if (fi != NULL)
6342           fi = get_prev_frame (fi);
6343       while (fi != NULL)
6344         {
6345           const char *func_name = function_name_from_pc (get_frame_pc (fi));
6346           if (func_name != NULL
6347               && strcmp (func_name, process_raise_exception_name) == 0)
6348             break;              /* We found the frame we were looking for...  */
6349           fi = get_prev_frame (fi);
6350         }
6351       if (fi == NULL)
6352         break;
6353       select_frame (fi);
6354       break;
6355     }
6356
6357   addr = parse_and_eval_address ("e.full_name");
6358
6359   if (addr != 0)
6360     read_memory (addr, last_exception_name, sizeof (last_exception_name) - 1);
6361   last_exception_name[sizeof (last_exception_name) - 1] = '\0';
6362   ada_find_printable_frame (get_selected_frame ());
6363 }
6364
6365 /* Output Ada exception name (if any) associated with last call to
6366    ada_adjust_exception_stop.  */
6367
6368 void
6369 ada_print_exception_stop (bpstat bs)
6370 {
6371   if (last_exception_name[0] != '\000')
6372     {
6373       ui_out_text (uiout, last_exception_name);
6374       ui_out_text (uiout, " at ");
6375     }
6376 }
6377
6378 /* Parses the CONDITION string associated with a breakpoint exception
6379    to get the name of the exception on which the breakpoint has been
6380    set.  The returned string needs to be deallocated after use.  */
6381
6382 static char *
6383 exception_name_from_cond (const char *condition)
6384 {
6385   char *start, *end, *exception_name;
6386   int exception_name_len;
6387
6388   start = strrchr (condition, '&') + 1;
6389   end = strchr (start, ')') - 1;
6390   exception_name_len = end - start + 1;
6391
6392   exception_name =
6393     (char *) xmalloc ((exception_name_len + 1) * sizeof (char));
6394   sprintf (exception_name, "%.*s", exception_name_len, start);
6395
6396   return exception_name;
6397 }
6398
6399 /* Print Ada-specific exception information about B, other than task
6400    clause.  Return non-zero iff B was an Ada exception breakpoint.  */
6401
6402 int
6403 ada_print_exception_breakpoint_nontask (struct breakpoint *b)
6404 {
6405   if (b->break_on_exception == 1)
6406     {
6407       if (b->cond_string)       /* the breakpoint is on a specific exception.  */
6408         {
6409           char *exception_name = exception_name_from_cond (b->cond_string);
6410
6411           make_cleanup (xfree, exception_name);
6412
6413           ui_out_text (uiout, "on ");
6414           if (ui_out_is_mi_like_p (uiout))
6415             ui_out_field_string (uiout, "exception", exception_name);
6416           else
6417             {
6418               ui_out_text (uiout, "exception ");
6419               ui_out_text (uiout, exception_name);
6420               ui_out_text (uiout, " ");
6421             }
6422         }
6423       else
6424         ui_out_text (uiout, "on all exceptions");
6425     }
6426   else if (b->break_on_exception == 2)
6427     ui_out_text (uiout, "on unhandled exception");
6428   else if (b->break_on_exception == 3)
6429     ui_out_text (uiout, "on assert failure");
6430   else
6431     return 0;
6432   return 1;
6433 }
6434
6435 /* Print task identifier for breakpoint B, if it is an Ada-specific
6436    breakpoint with non-zero tasking information.  */
6437
6438 void
6439 ada_print_exception_breakpoint_task (struct breakpoint *b)
6440 {
6441   if (b->task != 0)
6442     {
6443       ui_out_text (uiout, " task ");
6444       ui_out_field_int (uiout, "task", b->task);
6445     }
6446 }
6447
6448 /* Cause the appropriate error if no appropriate runtime symbol is
6449    found to set a breakpoint, using ERR_DESC to describe the
6450    breakpoint.  */
6451
6452 static void
6453 error_breakpoint_runtime_sym_not_found (const char *err_desc)
6454 {
6455   /* If we are not debugging an Ada program, we can not put exception
6456      breakpoints!  */
6457
6458   if (ada_update_initial_language (language_unknown, NULL) != language_ada)
6459     error ("Unable to break on %s.  Is this an Ada main program?", err_desc);
6460
6461   /* If the symbol does not exist, then check that the program is
6462      already started, to make sure that shared libraries have been
6463      loaded.  If it is not started, this may mean that the symbol is
6464      in a shared library.  */
6465
6466   if (ptid_get_pid (inferior_ptid) == 0)
6467     error ("Unable to break on %s. Try to start the program first.",
6468            err_desc);
6469
6470   /* At this point, we know that we are debugging an Ada program and
6471      that the inferior has been started, but we still are not able to
6472      find the run-time symbols. That can mean that we are in
6473      configurable run time mode, or that a-except as been optimized
6474      out by the linker...  In any case, at this point it is not worth
6475      supporting this feature.  */
6476
6477   error ("Cannot break on %s in this configuration.", err_desc);
6478 }
6479
6480 /* Test if NAME is currently defined, and that either ALLOW_TRAMP or
6481    the symbol is not a shared-library trampoline.  Return the result of
6482    the test.  */
6483
6484 static int
6485 is_runtime_sym_defined (const char *name, int allow_tramp)
6486 {
6487   struct minimal_symbol *msym;
6488
6489   msym = lookup_minimal_symbol (name, NULL, NULL);
6490   return (msym != NULL && msym->type != mst_unknown
6491           && (allow_tramp || msym->type != mst_solib_trampoline));
6492 }
6493
6494 /* If ARG points to an Ada exception or assert breakpoint, rewrite
6495    into equivalent form.  Return resulting argument string.  Set
6496    *BREAK_ON_EXCEPTIONP to 1 for ordinary break on exception, 2 for
6497    break on unhandled, 3 for assert, 0 otherwise.  */
6498
6499 char *
6500 ada_breakpoint_rewrite (char *arg, int *break_on_exceptionp)
6501 {
6502   if (arg == NULL)
6503     return arg;
6504   *break_on_exceptionp = 0;
6505   if (current_language->la_language == language_ada
6506       && strncmp (arg, "exception", 9) == 0
6507       && (arg[9] == ' ' || arg[9] == '\t' || arg[9] == '\0'))
6508     {
6509       char *tok, *end_tok;
6510       int toklen;
6511       int has_exception_propagation =
6512         is_runtime_sym_defined (raise_sym_name, 1);
6513
6514       *break_on_exceptionp = 1;
6515
6516       tok = arg + 9;
6517       while (*tok == ' ' || *tok == '\t')
6518         tok += 1;
6519
6520       end_tok = tok;
6521
6522       while (*end_tok != ' ' && *end_tok != '\t' && *end_tok != '\000')
6523         end_tok += 1;
6524
6525       toklen = end_tok - tok;
6526
6527       arg = (char *) xmalloc (sizeof (longest_exception_template) + toklen);
6528       make_cleanup (xfree, arg);
6529       if (toklen == 0)
6530         {
6531           if (has_exception_propagation)
6532             sprintf (arg, "'%s'", raise_sym_name);
6533           else
6534             error_breakpoint_runtime_sym_not_found ("exception");
6535         }
6536       else if (strncmp (tok, "unhandled", toklen) == 0)
6537         {
6538           if (is_runtime_sym_defined (raise_unhandled_sym_name, 1))
6539             sprintf (arg, "'%s'", raise_unhandled_sym_name);
6540           else
6541             error_breakpoint_runtime_sym_not_found ("exception");
6542
6543           *break_on_exceptionp = 2;
6544         }
6545       else
6546         {
6547           if (is_runtime_sym_defined (raise_sym_name, 0))
6548             sprintf (arg, "'%s' if long_integer(e) = long_integer(&%.*s)",
6549                      raise_sym_name, toklen, tok);
6550           else
6551             error_breakpoint_runtime_sym_not_found ("specific exception");
6552         }
6553     }
6554   else if (current_language->la_language == language_ada
6555            && strncmp (arg, "assert", 6) == 0
6556            && (arg[6] == ' ' || arg[6] == '\t' || arg[6] == '\0'))
6557     {
6558       char *tok = arg + 6;
6559
6560       if (!is_runtime_sym_defined (raise_assert_sym_name, 1))
6561         error_breakpoint_runtime_sym_not_found ("failed assertion");
6562
6563       *break_on_exceptionp = 3;
6564
6565       arg =
6566         (char *) xmalloc (sizeof (raise_assert_sym_name) + strlen (tok) + 2);
6567       make_cleanup (xfree, arg);
6568       sprintf (arg, "'%s'%s", raise_assert_sym_name, tok);
6569     }
6570   return arg;
6571 }
6572 #endif /* GNAT_GDB */
6573 \f
6574                                 /* Field Access */
6575
6576 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
6577    to be invisible to users.  */
6578
6579 int
6580 ada_is_ignored_field (struct type *type, int field_num)
6581 {
6582   if (field_num < 0 || field_num > TYPE_NFIELDS (type))
6583     return 1;
6584   else
6585     {
6586       const char *name = TYPE_FIELD_NAME (type, field_num);
6587       return (name == NULL
6588               || (name[0] == '_' && strncmp (name, "_parent", 7) != 0));
6589     }
6590 }
6591
6592 /* True iff TYPE has a tag field.  If REFOK, then TYPE may also be a
6593    pointer or reference type whose ultimate target has a tag field. */
6594
6595 int
6596 ada_is_tagged_type (struct type *type, int refok)
6597 {
6598   return (ada_lookup_struct_elt_type (type, "_tag", refok, 1, NULL) != NULL);
6599 }
6600
6601 /* True iff TYPE represents the type of X'Tag */
6602
6603 int
6604 ada_is_tag_type (struct type *type)
6605 {
6606   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_PTR)
6607     return 0;
6608   else
6609     {
6610       const char *name = ada_type_name (TYPE_TARGET_TYPE (type));
6611       return (name != NULL
6612               && strcmp (name, "ada__tags__dispatch_table") == 0);
6613     }
6614 }
6615
6616 /* The type of the tag on VAL.  */
6617
6618 struct type *
6619 ada_tag_type (struct value *val)
6620 {
6621   return ada_lookup_struct_elt_type (VALUE_TYPE (val), "_tag", 1, 0, NULL);
6622 }
6623
6624 /* The value of the tag on VAL.  */
6625
6626 struct value *
6627 ada_value_tag (struct value *val)
6628 {
6629   return ada_value_struct_elt (val, "_tag", "record");
6630 }
6631
6632 /* The value of the tag on the object of type TYPE whose contents are
6633    saved at VALADDR, if it is non-null, or is at memory address
6634    ADDRESS. */
6635
6636 static struct value *
6637 value_tag_from_contents_and_address (struct type *type, char *valaddr,
6638                                      CORE_ADDR address)
6639 {
6640   int tag_byte_offset, dummy1, dummy2;
6641   struct type *tag_type;
6642   if (find_struct_field ("_tag", type, 0, &tag_type, &tag_byte_offset,
6643                          &dummy1, &dummy2))
6644     {
6645       char *valaddr1 = (valaddr == NULL) ? NULL : valaddr + tag_byte_offset;
6646       CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6647
6648       return value_from_contents_and_address (tag_type, valaddr1, address1);
6649     }
6650   return NULL;
6651 }
6652
6653 static struct type *
6654 type_from_tag (struct value *tag)
6655 {
6656   const char *type_name = ada_tag_name (tag);
6657   if (type_name != NULL)
6658     return ada_find_any_type (ada_encode (type_name));
6659   return NULL;
6660 }
6661
6662 struct tag_args
6663 {
6664   struct value *tag;
6665   char *name;
6666 };
6667
6668 /* Wrapper function used by ada_tag_name.  Given a struct tag_args*
6669    value ARGS, sets ARGS->name to the tag name of ARGS->tag.  
6670    The value stored in ARGS->name is valid until the next call to 
6671    ada_tag_name_1.  */
6672
6673 static int
6674 ada_tag_name_1 (void *args0)
6675 {
6676   struct tag_args *args = (struct tag_args *) args0;
6677   static char name[1024];
6678   char *p;
6679   struct value *val;
6680   args->name = NULL;
6681   val = ada_value_struct_elt (args->tag, "tsd", NULL);
6682   if (val == NULL)
6683     return 0;
6684   val = ada_value_struct_elt (val, "expanded_name", NULL);
6685   if (val == NULL)
6686     return 0;
6687   read_memory_string (value_as_address (val), name, sizeof (name) - 1);
6688   for (p = name; *p != '\0'; p += 1)
6689     if (isalpha (*p))
6690       *p = tolower (*p);
6691   args->name = name;
6692   return 0;
6693 }
6694
6695 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6696  * a C string.  */
6697
6698 const char *
6699 ada_tag_name (struct value *tag)
6700 {
6701   struct tag_args args;
6702   if (!ada_is_tag_type (VALUE_TYPE (tag)))
6703     return NULL;
6704   args.tag = tag;
6705   args.name = NULL;
6706   catch_errors (ada_tag_name_1, &args, NULL, RETURN_MASK_ALL);
6707   return args.name;
6708 }
6709
6710 /* The parent type of TYPE, or NULL if none.  */
6711
6712 struct type *
6713 ada_parent_type (struct type *type)
6714 {
6715   int i;
6716
6717   CHECK_TYPEDEF (type);
6718
6719   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
6720     return NULL;
6721
6722   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
6723     if (ada_is_parent_field (type, i))
6724       return check_typedef (TYPE_FIELD_TYPE (type, i));
6725
6726   return NULL;
6727 }
6728
6729 /* True iff field number FIELD_NUM of structure type TYPE contains the
6730    parent-type (inherited) fields of a derived type.  Assumes TYPE is
6731    a structure type with at least FIELD_NUM+1 fields.  */
6732
6733 int
6734 ada_is_parent_field (struct type *type, int field_num)
6735 {
6736   const char *name = TYPE_FIELD_NAME (check_typedef (type), field_num);
6737   return (name != NULL
6738           && (strncmp (name, "PARENT", 6) == 0
6739               || strncmp (name, "_parent", 7) == 0));
6740 }
6741
6742 /* True iff field number FIELD_NUM of structure type TYPE is a
6743    transparent wrapper field (which should be silently traversed when doing
6744    field selection and flattened when printing).  Assumes TYPE is a
6745    structure type with at least FIELD_NUM+1 fields.  Such fields are always
6746    structures.  */
6747
6748 int
6749 ada_is_wrapper_field (struct type *type, int field_num)
6750 {
6751   const char *name = TYPE_FIELD_NAME (type, field_num);
6752   return (name != NULL
6753           && (strncmp (name, "PARENT", 6) == 0
6754               || strcmp (name, "REP") == 0
6755               || strncmp (name, "_parent", 7) == 0
6756               || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6757 }
6758
6759 /* True iff field number FIELD_NUM of structure or union type TYPE
6760    is a variant wrapper.  Assumes TYPE is a structure type with at least
6761    FIELD_NUM+1 fields.  */
6762
6763 int
6764 ada_is_variant_part (struct type *type, int field_num)
6765 {
6766   struct type *field_type = TYPE_FIELD_TYPE (type, field_num);
6767   return (TYPE_CODE (field_type) == TYPE_CODE_UNION
6768           || (is_dynamic_field (type, field_num)
6769               && (TYPE_CODE (TYPE_TARGET_TYPE (field_type)) 
6770                   == TYPE_CODE_UNION)));
6771 }
6772
6773 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6774    whose discriminants are contained in the record type OUTER_TYPE,
6775    returns the type of the controlling discriminant for the variant.  */
6776
6777 struct type *
6778 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6779 {
6780   char *name = ada_variant_discrim_name (var_type);
6781   struct type *type =
6782     ada_lookup_struct_elt_type (outer_type, name, 1, 1, NULL);
6783   if (type == NULL)
6784     return builtin_type_int;
6785   else
6786     return type;
6787 }
6788
6789 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6790    valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6791    represents a 'when others' clause; otherwise 0.  */
6792
6793 int
6794 ada_is_others_clause (struct type *type, int field_num)
6795 {
6796   const char *name = TYPE_FIELD_NAME (type, field_num);
6797   return (name != NULL && name[0] == 'O');
6798 }
6799
6800 /* Assuming that TYPE0 is the type of the variant part of a record,
6801    returns the name of the discriminant controlling the variant.
6802    The value is valid until the next call to ada_variant_discrim_name.  */
6803
6804 char *
6805 ada_variant_discrim_name (struct type *type0)
6806 {
6807   static char *result = NULL;
6808   static size_t result_len = 0;
6809   struct type *type;
6810   const char *name;
6811   const char *discrim_end;
6812   const char *discrim_start;
6813
6814   if (TYPE_CODE (type0) == TYPE_CODE_PTR)
6815     type = TYPE_TARGET_TYPE (type0);
6816   else
6817     type = type0;
6818
6819   name = ada_type_name (type);
6820
6821   if (name == NULL || name[0] == '\000')
6822     return "";
6823
6824   for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6825        discrim_end -= 1)
6826     {
6827       if (strncmp (discrim_end, "___XVN", 6) == 0)
6828         break;
6829     }
6830   if (discrim_end == name)
6831     return "";
6832
6833   for (discrim_start = discrim_end; discrim_start != name + 3;
6834        discrim_start -= 1)
6835     {
6836       if (discrim_start == name + 1)
6837         return "";
6838       if ((discrim_start > name + 3
6839            && strncmp (discrim_start - 3, "___", 3) == 0)
6840           || discrim_start[-1] == '.')
6841         break;
6842     }
6843
6844   GROW_VECT (result, result_len, discrim_end - discrim_start + 1);
6845   strncpy (result, discrim_start, discrim_end - discrim_start);
6846   result[discrim_end - discrim_start] = '\0';
6847   return result;
6848 }
6849
6850 /* Scan STR for a subtype-encoded number, beginning at position K.
6851    Put the position of the character just past the number scanned in
6852    *NEW_K, if NEW_K!=NULL.  Put the scanned number in *R, if R!=NULL.
6853    Return 1 if there was a valid number at the given position, and 0
6854    otherwise.  A "subtype-encoded" number consists of the absolute value
6855    in decimal, followed by the letter 'm' to indicate a negative number.
6856    Assumes 0m does not occur.  */
6857
6858 int
6859 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
6860 {
6861   ULONGEST RU;
6862
6863   if (!isdigit (str[k]))
6864     return 0;
6865
6866   /* Do it the hard way so as not to make any assumption about
6867      the relationship of unsigned long (%lu scan format code) and
6868      LONGEST.  */
6869   RU = 0;
6870   while (isdigit (str[k]))
6871     {
6872       RU = RU * 10 + (str[k] - '0');
6873       k += 1;
6874     }
6875
6876   if (str[k] == 'm')
6877     {
6878       if (R != NULL)
6879         *R = (-(LONGEST) (RU - 1)) - 1;
6880       k += 1;
6881     }
6882   else if (R != NULL)
6883     *R = (LONGEST) RU;
6884
6885   /* NOTE on the above: Technically, C does not say what the results of
6886      - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6887      number representable as a LONGEST (although either would probably work
6888      in most implementations).  When RU>0, the locution in the then branch
6889      above is always equivalent to the negative of RU.  */
6890
6891   if (new_k != NULL)
6892     *new_k = k;
6893   return 1;
6894 }
6895
6896 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6897    and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6898    in the range encoded by field FIELD_NUM of TYPE; otherwise 0.  */
6899
6900 int
6901 ada_in_variant (LONGEST val, struct type *type, int field_num)
6902 {
6903   const char *name = TYPE_FIELD_NAME (type, field_num);
6904   int p;
6905
6906   p = 0;
6907   while (1)
6908     {
6909       switch (name[p])
6910         {
6911         case '\0':
6912           return 0;
6913         case 'S':
6914           {
6915             LONGEST W;
6916             if (!ada_scan_number (name, p + 1, &W, &p))
6917               return 0;
6918             if (val == W)
6919               return 1;
6920             break;
6921           }
6922         case 'R':
6923           {
6924             LONGEST L, U;
6925             if (!ada_scan_number (name, p + 1, &L, &p)
6926                 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6927               return 0;
6928             if (val >= L && val <= U)
6929               return 1;
6930             break;
6931           }
6932         case 'O':
6933           return 1;
6934         default:
6935           return 0;
6936         }
6937     }
6938 }
6939
6940 /* FIXME: Lots of redundancy below.  Try to consolidate. */
6941
6942 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6943    ARG_TYPE, extract and return the value of one of its (non-static)
6944    fields.  FIELDNO says which field.   Differs from value_primitive_field
6945    only in that it can handle packed values of arbitrary type.  */
6946
6947 static struct value *
6948 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
6949                            struct type *arg_type)
6950 {
6951   struct type *type;
6952
6953   CHECK_TYPEDEF (arg_type);
6954   type = TYPE_FIELD_TYPE (arg_type, fieldno);
6955
6956   /* Handle packed fields.  */
6957
6958   if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0)
6959     {
6960       int bit_pos = TYPE_FIELD_BITPOS (arg_type, fieldno);
6961       int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);
6962
6963       return ada_value_primitive_packed_val (arg1, VALUE_CONTENTS (arg1),
6964                                              offset + bit_pos / 8,
6965                                              bit_pos % 8, bit_size, type);
6966     }
6967   else
6968     return value_primitive_field (arg1, offset, fieldno, arg_type);
6969 }
6970
6971 /* Find field with name NAME in object of type TYPE.  If found, return 1
6972    after setting *FIELD_TYPE_P to the field's type, *BYTE_OFFSET_P to 
6973    OFFSET + the byte offset of the field within an object of that type, 
6974    *BIT_OFFSET_P to the bit offset modulo byte size of the field, and
6975    *BIT_SIZE_P to its size in bits if the field is packed, and 0 otherwise.
6976    Looks inside wrappers for the field.  Returns 0 if field not
6977    found. */
6978 static int
6979 find_struct_field (char *name, struct type *type, int offset,
6980                    struct type **field_type_p,
6981                    int *byte_offset_p, int *bit_offset_p, int *bit_size_p)
6982 {
6983   int i;
6984
6985   CHECK_TYPEDEF (type);
6986   *field_type_p = NULL;
6987   *byte_offset_p = *bit_offset_p = *bit_size_p = 0;
6988
6989   for (i = TYPE_NFIELDS (type) - 1; i >= 0; i -= 1)
6990     {
6991       int bit_pos = TYPE_FIELD_BITPOS (type, i);
6992       int fld_offset = offset + bit_pos / 8;
6993       char *t_field_name = TYPE_FIELD_NAME (type, i);
6994
6995       if (t_field_name == NULL)
6996         continue;
6997
6998       else if (field_name_match (t_field_name, name))
6999         {
7000           int bit_size = TYPE_FIELD_BITSIZE (type, i);
7001           *field_type_p = TYPE_FIELD_TYPE (type, i);
7002           *byte_offset_p = fld_offset;
7003           *bit_offset_p = bit_pos % 8;
7004           *bit_size_p = bit_size;
7005           return 1;
7006         }
7007       else if (ada_is_wrapper_field (type, i))
7008         {
7009           if (find_struct_field (name, TYPE_FIELD_TYPE (type, i), fld_offset,
7010                                  field_type_p, byte_offset_p, bit_offset_p,
7011                                  bit_size_p))
7012             return 1;
7013         }
7014       else if (ada_is_variant_part (type, i))
7015         {
7016           int j;
7017           struct type *field_type = check_typedef (TYPE_FIELD_TYPE (type, i));
7018
7019           for (j = TYPE_NFIELDS (field_type) - 1; j >= 0; j -= 1)
7020             {
7021               if (find_struct_field (name, TYPE_FIELD_TYPE (field_type, j),
7022                                      fld_offset
7023                                      + TYPE_FIELD_BITPOS (field_type, j) / 8,
7024                                      field_type_p, byte_offset_p,
7025                                      bit_offset_p, bit_size_p))
7026                 return 1;
7027             }
7028         }
7029     }
7030   return 0;
7031 }
7032
7033
7034
7035 /* Look for a field NAME in ARG.  Adjust the address of ARG by OFFSET bytes,
7036    and search in it assuming it has (class) type TYPE.
7037    If found, return value, else return NULL.
7038
7039    Searches recursively through wrapper fields (e.g., '_parent').  */
7040
7041 static struct value *
7042 ada_search_struct_field (char *name, struct value *arg, int offset,
7043                          struct type *type)
7044 {
7045   int i;
7046   CHECK_TYPEDEF (type);
7047
7048   for (i = TYPE_NFIELDS (type) - 1; i >= 0; i -= 1)
7049     {
7050       char *t_field_name = TYPE_FIELD_NAME (type, i);
7051
7052       if (t_field_name == NULL)
7053         continue;
7054
7055       else if (field_name_match (t_field_name, name))
7056         return ada_value_primitive_field (arg, offset, i, type);
7057
7058       else if (ada_is_wrapper_field (type, i))
7059         {
7060           struct value *v =     /* Do not let indent join lines here. */
7061             ada_search_struct_field (name, arg,
7062                                      offset + TYPE_FIELD_BITPOS (type, i) / 8,
7063                                      TYPE_FIELD_TYPE (type, i));
7064           if (v != NULL)
7065             return v;
7066         }
7067
7068       else if (ada_is_variant_part (type, i))
7069         {
7070           int j;
7071           struct type *field_type = check_typedef (TYPE_FIELD_TYPE (type, i));
7072           int var_offset = offset + TYPE_FIELD_BITPOS (type, i) / 8;
7073
7074           for (j = TYPE_NFIELDS (field_type) - 1; j >= 0; j -= 1)
7075             {
7076               struct value *v = ada_search_struct_field /* Force line break.  */
7077                 (name, arg,
7078                  var_offset + TYPE_FIELD_BITPOS (field_type, j) / 8,
7079                  TYPE_FIELD_TYPE (field_type, j));
7080               if (v != NULL)
7081                 return v;
7082             }
7083         }
7084     }
7085   return NULL;
7086 }
7087
7088 /* Given ARG, a value of type (pointer or reference to a)*
7089    structure/union, extract the component named NAME from the ultimate
7090    target structure/union and return it as a value with its
7091    appropriate type.  If ARG is a pointer or reference and the field
7092    is not packed, returns a reference to the field, otherwise the
7093    value of the field (an lvalue if ARG is an lvalue).     
7094
7095    The routine searches for NAME among all members of the structure itself
7096    and (recursively) among all members of any wrapper members
7097    (e.g., '_parent').
7098
7099    ERR is a name (for use in error messages) that identifies the class
7100    of entity that ARG is supposed to be.  ERR may be null, indicating
7101    that on error, the function simply returns NULL, and does not
7102    throw an error.  (FIXME: True only if ARG is a pointer or reference
7103    at the moment). */
7104
7105 struct value *
7106 ada_value_struct_elt (struct value *arg, char *name, char *err)
7107 {
7108   struct type *t, *t1;
7109   struct value *v;
7110
7111   v = NULL;
7112   t1 = t = check_typedef (VALUE_TYPE (arg));
7113   if (TYPE_CODE (t) == TYPE_CODE_REF)
7114     {
7115       t1 = TYPE_TARGET_TYPE (t);
7116       if (t1 == NULL)
7117         {
7118           if (err == NULL)
7119             return NULL;
7120           else
7121             error ("Bad value type in a %s.", err);
7122         }
7123       CHECK_TYPEDEF (t1);
7124       if (TYPE_CODE (t1) == TYPE_CODE_PTR)
7125         {
7126           COERCE_REF (arg);
7127           t = t1;
7128         }
7129     }
7130
7131   while (TYPE_CODE (t) == TYPE_CODE_PTR)
7132     {
7133       t1 = TYPE_TARGET_TYPE (t);
7134       if (t1 == NULL)
7135         {
7136           if (err == NULL)
7137             return NULL;
7138           else
7139             error ("Bad value type in a %s.", err);
7140         }
7141       CHECK_TYPEDEF (t1);
7142       if (TYPE_CODE (t1) == TYPE_CODE_PTR)
7143         {
7144           arg = value_ind (arg);
7145           t = t1;
7146         }
7147       else
7148         break;
7149     }
7150
7151   if (TYPE_CODE (t1) != TYPE_CODE_STRUCT && TYPE_CODE (t1) != TYPE_CODE_UNION)
7152     {
7153       if (err == NULL)
7154         return NULL;
7155       else
7156         error ("Attempt to extract a component of a value that is not a %s.",
7157                err);
7158     }
7159
7160   if (t1 == t)
7161     v = ada_search_struct_field (name, arg, 0, t);
7162   else
7163     {
7164       int bit_offset, bit_size, byte_offset;
7165       struct type *field_type;
7166       CORE_ADDR address;
7167
7168       if (TYPE_CODE (t) == TYPE_CODE_PTR)
7169         address = value_as_address (arg);
7170       else
7171         address = unpack_pointer (t, VALUE_CONTENTS (arg));
7172
7173       t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL, address, NULL);
7174       if (find_struct_field (name, t1, 0,
7175                              &field_type, &byte_offset, &bit_offset,
7176                              &bit_size))
7177         {
7178           if (bit_size != 0)
7179             {
7180               arg = ada_value_ind (arg);
7181               v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
7182                                                   bit_offset, bit_size,
7183                                                   field_type);
7184             }
7185           else
7186             v = value_from_pointer (lookup_reference_type (field_type),
7187                                     address + byte_offset);
7188         }
7189     }
7190
7191   if (v == NULL && err != NULL)
7192     error ("There is no member named %s.", name);
7193
7194   return v;
7195 }
7196
7197 /* Given a type TYPE, look up the type of the component of type named NAME.
7198    If DISPP is non-null, add its byte displacement from the beginning of a
7199    structure (pointed to by a value) of type TYPE to *DISPP (does not
7200    work for packed fields).
7201
7202    Matches any field whose name has NAME as a prefix, possibly
7203    followed by "___".
7204
7205    TYPE can be either a struct or union. If REFOK, TYPE may also 
7206    be a (pointer or reference)+ to a struct or union, and the
7207    ultimate target type will be searched.
7208
7209    Looks recursively into variant clauses and parent types.
7210
7211    If NOERR is nonzero, return NULL if NAME is not suitably defined or
7212    TYPE is not a type of the right kind.  */
7213
7214 static struct type *
7215 ada_lookup_struct_elt_type (struct type *type, char *name, int refok,
7216                             int noerr, int *dispp)
7217 {
7218   int i;
7219
7220   if (name == NULL)
7221     goto BadName;
7222
7223   if (refok && type != NULL)
7224     while (1)
7225       {
7226         CHECK_TYPEDEF (type);
7227         if (TYPE_CODE (type) != TYPE_CODE_PTR
7228             && TYPE_CODE (type) != TYPE_CODE_REF)
7229           break;
7230         type = TYPE_TARGET_TYPE (type);
7231       }
7232
7233   if (type == NULL
7234       || (TYPE_CODE (type) != TYPE_CODE_STRUCT
7235           && TYPE_CODE (type) != TYPE_CODE_UNION))
7236     {
7237       if (noerr)
7238         return NULL;
7239       else
7240         {
7241           target_terminal_ours ();
7242           gdb_flush (gdb_stdout);
7243           fprintf_unfiltered (gdb_stderr, "Type ");
7244           if (type == NULL)
7245             fprintf_unfiltered (gdb_stderr, "(null)");
7246           else
7247             type_print (type, "", gdb_stderr, -1);
7248           error (" is not a structure or union type");
7249         }
7250     }
7251
7252   type = to_static_fixed_type (type);
7253
7254   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
7255     {
7256       char *t_field_name = TYPE_FIELD_NAME (type, i);
7257       struct type *t;
7258       int disp;
7259
7260       if (t_field_name == NULL)
7261         continue;
7262
7263       else if (field_name_match (t_field_name, name))
7264         {
7265           if (dispp != NULL)
7266             *dispp += TYPE_FIELD_BITPOS (type, i) / 8;
7267           return check_typedef (TYPE_FIELD_TYPE (type, i));
7268         }
7269
7270       else if (ada_is_wrapper_field (type, i))
7271         {
7272           disp = 0;
7273           t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (type, i), name,
7274                                           0, 1, &disp);
7275           if (t != NULL)
7276             {
7277               if (dispp != NULL)
7278                 *dispp += disp + TYPE_FIELD_BITPOS (type, i) / 8;
7279               return t;
7280             }
7281         }
7282
7283       else if (ada_is_variant_part (type, i))
7284         {
7285           int j;
7286           struct type *field_type = check_typedef (TYPE_FIELD_TYPE (type, i));
7287
7288           for (j = TYPE_NFIELDS (field_type) - 1; j >= 0; j -= 1)
7289             {
7290               disp = 0;
7291               t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (field_type, j),
7292                                               name, 0, 1, &disp);
7293               if (t != NULL)
7294                 {
7295                   if (dispp != NULL)
7296                     *dispp += disp + TYPE_FIELD_BITPOS (type, i) / 8;
7297                   return t;
7298                 }
7299             }
7300         }
7301
7302     }
7303
7304 BadName:
7305   if (!noerr)
7306     {
7307       target_terminal_ours ();
7308       gdb_flush (gdb_stdout);
7309       fprintf_unfiltered (gdb_stderr, "Type ");
7310       type_print (type, "", gdb_stderr, -1);
7311       fprintf_unfiltered (gdb_stderr, " has no component named ");
7312       error ("%s", name == NULL ? "<null>" : name);
7313     }
7314
7315   return NULL;
7316 }
7317
7318 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7319    within a value of type OUTER_TYPE that is stored in GDB at
7320    OUTER_VALADDR, determine which variant clause (field number in VAR_TYPE,
7321    numbering from 0) is applicable.  Returns -1 if none are.  */
7322
7323 int
7324 ada_which_variant_applies (struct type *var_type, struct type *outer_type,
7325                            char *outer_valaddr)
7326 {
7327   int others_clause;
7328   int i;
7329   int disp;
7330   struct type *discrim_type;
7331   char *discrim_name = ada_variant_discrim_name (var_type);
7332   LONGEST discrim_val;
7333
7334   disp = 0;
7335   discrim_type =
7336     ada_lookup_struct_elt_type (outer_type, discrim_name, 1, 1, &disp);
7337   if (discrim_type == NULL)
7338     return -1;
7339   discrim_val = unpack_long (discrim_type, outer_valaddr + disp);
7340
7341   others_clause = -1;
7342   for (i = 0; i < TYPE_NFIELDS (var_type); i += 1)
7343     {
7344       if (ada_is_others_clause (var_type, i))
7345         others_clause = i;
7346       else if (ada_in_variant (discrim_val, var_type, i))
7347         return i;
7348     }
7349
7350   return others_clause;
7351 }
7352 \f
7353
7354
7355                                 /* Dynamic-Sized Records */
7356
7357 /* Strategy: The type ostensibly attached to a value with dynamic size
7358    (i.e., a size that is not statically recorded in the debugging
7359    data) does not accurately reflect the size or layout of the value.
7360    Our strategy is to convert these values to values with accurate,
7361    conventional types that are constructed on the fly.  */
7362
7363 /* There is a subtle and tricky problem here.  In general, we cannot
7364    determine the size of dynamic records without its data.  However,
7365    the 'struct value' data structure, which GDB uses to represent
7366    quantities in the inferior process (the target), requires the size
7367    of the type at the time of its allocation in order to reserve space
7368    for GDB's internal copy of the data.  That's why the
7369    'to_fixed_xxx_type' routines take (target) addresses as parameters,
7370    rather than struct value*s.
7371
7372    However, GDB's internal history variables ($1, $2, etc.) are
7373    struct value*s containing internal copies of the data that are not, in
7374    general, the same as the data at their corresponding addresses in
7375    the target.  Fortunately, the types we give to these values are all
7376    conventional, fixed-size types (as per the strategy described
7377    above), so that we don't usually have to perform the
7378    'to_fixed_xxx_type' conversions to look at their values.
7379    Unfortunately, there is one exception: if one of the internal
7380    history variables is an array whose elements are unconstrained
7381    records, then we will need to create distinct fixed types for each
7382    element selected.  */
7383
7384 /* The upshot of all of this is that many routines take a (type, host
7385    address, target address) triple as arguments to represent a value.
7386    The host address, if non-null, is supposed to contain an internal
7387    copy of the relevant data; otherwise, the program is to consult the
7388    target at the target address.  */
7389
7390 /* Assuming that VAL0 represents a pointer value, the result of
7391    dereferencing it.  Differs from value_ind in its treatment of
7392    dynamic-sized types.  */
7393
7394 struct value *
7395 ada_value_ind (struct value *val0)
7396 {
7397   struct value *val = unwrap_value (value_ind (val0));
7398   return ada_to_fixed_value (val);
7399 }
7400
7401 /* The value resulting from dereferencing any "reference to"
7402    qualifiers on VAL0.  */
7403
7404 static struct value *
7405 ada_coerce_ref (struct value *val0)
7406 {
7407   if (TYPE_CODE (VALUE_TYPE (val0)) == TYPE_CODE_REF)
7408     {
7409       struct value *val = val0;
7410       COERCE_REF (val);
7411       val = unwrap_value (val);
7412       return ada_to_fixed_value (val);
7413     }
7414   else
7415     return val0;
7416 }
7417
7418 /* Return OFF rounded upward if necessary to a multiple of
7419    ALIGNMENT (a power of 2).  */
7420
7421 static unsigned int
7422 align_value (unsigned int off, unsigned int alignment)
7423 {
7424   return (off + alignment - 1) & ~(alignment - 1);
7425 }
7426
7427 /* Return the bit alignment required for field #F of template type TYPE.  */
7428
7429 static unsigned int
7430 field_alignment (struct type *type, int f)
7431 {
7432   const char *name = TYPE_FIELD_NAME (type, f);
7433   int len = (name == NULL) ? 0 : strlen (name);
7434   int align_offset;
7435
7436   if (!isdigit (name[len - 1]))
7437     return 1;
7438
7439   if (isdigit (name[len - 2]))
7440     align_offset = len - 2;
7441   else
7442     align_offset = len - 1;
7443
7444   if (align_offset < 7 || strncmp ("___XV", name + align_offset - 6, 5) != 0)
7445     return TARGET_CHAR_BIT;
7446
7447   return atoi (name + align_offset) * TARGET_CHAR_BIT;
7448 }
7449
7450 /* Find a symbol named NAME.  Ignores ambiguity.  */
7451
7452 struct symbol *
7453 ada_find_any_symbol (const char *name)
7454 {
7455   struct symbol *sym;
7456
7457   sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
7458   if (sym != NULL && SYMBOL_CLASS (sym) == LOC_TYPEDEF)
7459     return sym;
7460
7461   sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
7462   return sym;
7463 }
7464
7465 /* Find a type named NAME.  Ignores ambiguity.  */
7466
7467 struct type *
7468 ada_find_any_type (const char *name)
7469 {
7470   struct symbol *sym = ada_find_any_symbol (name);
7471
7472   if (sym != NULL)
7473     return SYMBOL_TYPE (sym);
7474
7475   return NULL;
7476 }
7477
7478 /* Given a symbol NAME and its associated BLOCK, search all symbols
7479    for its ___XR counterpart, which is the ``renaming'' symbol
7480    associated to NAME.  Return this symbol if found, return
7481    NULL otherwise.  */
7482
7483 struct symbol *
7484 ada_find_renaming_symbol (const char *name, struct block *block)
7485 {
7486   const struct symbol *function_sym = block_function (block);
7487   char *rename;
7488
7489   if (function_sym != NULL)
7490     {
7491       /* If the symbol is defined inside a function, NAME is not fully
7492          qualified.  This means we need to prepend the function name
7493          as well as adding the ``___XR'' suffix to build the name of
7494          the associated renaming symbol.  */
7495       char *function_name = SYMBOL_LINKAGE_NAME (function_sym);
7496       const int function_name_len = strlen (function_name);
7497       const int rename_len = function_name_len + 2      /*  "__" */
7498         + strlen (name) + 6 /* "___XR\0" */ ;
7499
7500       /* Library-level functions are a special case, as GNAT adds
7501          a ``_ada_'' prefix to the function name to avoid namespace
7502          pollution.  However, the renaming symbol themselves do not
7503          have this prefix, so we need to skip this prefix if present.  */
7504       if (function_name_len > 5 /* "_ada_" */
7505           && strstr (function_name, "_ada_") == function_name)
7506         function_name = function_name + 5;
7507
7508       rename = (char *) alloca (rename_len * sizeof (char));
7509       sprintf (rename, "%s__%s___XR", function_name, name);
7510     }
7511   else
7512     {
7513       const int rename_len = strlen (name) + 6;
7514       rename = (char *) alloca (rename_len * sizeof (char));
7515       sprintf (rename, "%s___XR", name);
7516     }
7517
7518   return ada_find_any_symbol (rename);
7519 }
7520
7521 /* Because of GNAT encoding conventions, several GDB symbols may match a
7522    given type name.  If the type denoted by TYPE0 is to be preferred to
7523    that of TYPE1 for purposes of type printing, return non-zero;
7524    otherwise return 0.  */
7525
7526 int
7527 ada_prefer_type (struct type *type0, struct type *type1)
7528 {
7529   if (type1 == NULL)
7530     return 1;
7531   else if (type0 == NULL)
7532     return 0;
7533   else if (TYPE_CODE (type1) == TYPE_CODE_VOID)
7534     return 1;
7535   else if (TYPE_CODE (type0) == TYPE_CODE_VOID)
7536     return 0;
7537   else if (TYPE_NAME (type1) == NULL && TYPE_NAME (type0) != NULL)
7538     return 1;
7539   else if (ada_is_packed_array_type (type0))
7540     return 1;
7541   else if (ada_is_array_descriptor_type (type0)
7542            && !ada_is_array_descriptor_type (type1))
7543     return 1;
7544   else if (ada_renaming_type (type0) != NULL
7545            && ada_renaming_type (type1) == NULL)
7546     return 1;
7547   return 0;
7548 }
7549
7550 /* The name of TYPE, which is either its TYPE_NAME, or, if that is
7551    null, its TYPE_TAG_NAME.  Null if TYPE is null.  */
7552
7553 char *
7554 ada_type_name (struct type *type)
7555 {
7556   if (type == NULL)
7557     return NULL;
7558   else if (TYPE_NAME (type) != NULL)
7559     return TYPE_NAME (type);
7560   else
7561     return TYPE_TAG_NAME (type);
7562 }
7563
7564 /* Find a parallel type to TYPE whose name is formed by appending
7565    SUFFIX to the name of TYPE.  */
7566
7567 struct type *
7568 ada_find_parallel_type (struct type *type, const char *suffix)
7569 {
7570   static char *name;
7571   static size_t name_len = 0;
7572   int len;
7573   char *typename = ada_type_name (type);
7574
7575   if (typename == NULL)
7576     return NULL;
7577
7578   len = strlen (typename);
7579
7580   GROW_VECT (name, name_len, len + strlen (suffix) + 1);
7581
7582   strcpy (name, typename);
7583   strcpy (name + len, suffix);
7584
7585   return ada_find_any_type (name);
7586 }
7587
7588
7589 /* If TYPE is a variable-size record type, return the corresponding template
7590    type describing its fields.  Otherwise, return NULL.  */
7591
7592 static struct type *
7593 dynamic_template_type (struct type *type)
7594 {
7595   CHECK_TYPEDEF (type);
7596
7597   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT
7598       || ada_type_name (type) == NULL)
7599     return NULL;
7600   else
7601     {
7602       int len = strlen (ada_type_name (type));
7603       if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7604         return type;
7605       else
7606         return ada_find_parallel_type (type, "___XVE");
7607     }
7608 }
7609
7610 /* Assuming that TEMPL_TYPE is a union or struct type, returns
7611    non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size.  */
7612
7613 static int
7614 is_dynamic_field (struct type *templ_type, int field_num)
7615 {
7616   const char *name = TYPE_FIELD_NAME (templ_type, field_num);
7617   return name != NULL
7618     && TYPE_CODE (TYPE_FIELD_TYPE (templ_type, field_num)) == TYPE_CODE_PTR
7619     && strstr (name, "___XVL") != NULL;
7620 }
7621
7622 /* The index of the variant field of TYPE, or -1 if TYPE does not
7623    represent a variant record type.  */
7624
7625 static int
7626 variant_field_index (struct type *type)
7627 {
7628   int f;
7629
7630   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
7631     return -1;
7632
7633   for (f = 0; f < TYPE_NFIELDS (type); f += 1)
7634     {
7635       if (ada_is_variant_part (type, f))
7636         return f;
7637     }
7638   return -1;
7639 }
7640
7641 /* A record type with no fields.  */
7642
7643 static struct type *
7644 empty_record (struct objfile *objfile)
7645 {
7646   struct type *type = alloc_type (objfile);
7647   TYPE_CODE (type) = TYPE_CODE_STRUCT;
7648   TYPE_NFIELDS (type) = 0;
7649   TYPE_FIELDS (type) = NULL;
7650   TYPE_NAME (type) = "<empty>";
7651   TYPE_TAG_NAME (type) = NULL;
7652   TYPE_FLAGS (type) = 0;
7653   TYPE_LENGTH (type) = 0;
7654   return type;
7655 }
7656
7657 /* An ordinary record type (with fixed-length fields) that describes
7658    the value of type TYPE at VALADDR or ADDRESS (see comments at
7659    the beginning of this section) VAL according to GNAT conventions.
7660    DVAL0 should describe the (portion of a) record that contains any
7661    necessary discriminants.  It should be NULL if VALUE_TYPE (VAL) is
7662    an outer-level type (i.e., as opposed to a branch of a variant.)  A
7663    variant field (unless unchecked) is replaced by a particular branch
7664    of the variant.
7665
7666    If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7667    length are not statically known are discarded.  As a consequence,
7668    VALADDR, ADDRESS and DVAL0 are ignored.
7669
7670    NOTE: Limitations: For now, we assume that dynamic fields and
7671    variants occupy whole numbers of bytes.  However, they need not be
7672    byte-aligned.  */
7673
7674 struct type *
7675 ada_template_to_fixed_record_type_1 (struct type *type, char *valaddr,
7676                                      CORE_ADDR address, struct value *dval0,
7677                                      int keep_dynamic_fields)
7678 {
7679   struct value *mark = value_mark ();
7680   struct value *dval;
7681   struct type *rtype;
7682   int nfields, bit_len;
7683   int variant_field;
7684   long off;
7685   int fld_bit_len, bit_incr;
7686   int f;
7687
7688   /* Compute the number of fields in this record type that are going
7689      to be processed: unless keep_dynamic_fields, this includes only
7690      fields whose position and length are static will be processed.  */
7691   if (keep_dynamic_fields)
7692     nfields = TYPE_NFIELDS (type);
7693   else
7694     {
7695       nfields = 0;
7696       while (nfields < TYPE_NFIELDS (type)
7697              && !ada_is_variant_part (type, nfields)
7698              && !is_dynamic_field (type, nfields))
7699         nfields++;
7700     }
7701
7702   rtype = alloc_type (TYPE_OBJFILE (type));
7703   TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
7704   INIT_CPLUS_SPECIFIC (rtype);
7705   TYPE_NFIELDS (rtype) = nfields;
7706   TYPE_FIELDS (rtype) = (struct field *)
7707     TYPE_ALLOC (rtype, nfields * sizeof (struct field));
7708   memset (TYPE_FIELDS (rtype), 0, sizeof (struct field) * nfields);
7709   TYPE_NAME (rtype) = ada_type_name (type);
7710   TYPE_TAG_NAME (rtype) = NULL;
7711   TYPE_FLAGS (rtype) |= TYPE_FLAG_FIXED_INSTANCE;
7712
7713   off = 0;
7714   bit_len = 0;
7715   variant_field = -1;
7716
7717   for (f = 0; f < nfields; f += 1)
7718     {
7719       off = align_value (off, field_alignment (type, f))
7720         + TYPE_FIELD_BITPOS (type, f);
7721       TYPE_FIELD_BITPOS (rtype, f) = off;
7722       TYPE_FIELD_BITSIZE (rtype, f) = 0;
7723
7724       if (ada_is_variant_part (type, f))
7725         {
7726           variant_field = f;
7727           fld_bit_len = bit_incr = 0;
7728         }
7729       else if (is_dynamic_field (type, f))
7730         {
7731           if (dval0 == NULL)
7732             dval = value_from_contents_and_address (rtype, valaddr, address);
7733           else
7734             dval = dval0;
7735
7736           TYPE_FIELD_TYPE (rtype, f) =
7737             ada_to_fixed_type
7738             (ada_get_base_type
7739              (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type, f))),
7740              cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7741              cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
7742           TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
7743           bit_incr = fld_bit_len =
7744             TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, f)) * TARGET_CHAR_BIT;
7745         }
7746       else
7747         {
7748           TYPE_FIELD_TYPE (rtype, f) = TYPE_FIELD_TYPE (type, f);
7749           TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
7750           if (TYPE_FIELD_BITSIZE (type, f) > 0)
7751             bit_incr = fld_bit_len =
7752               TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
7753           else
7754             bit_incr = fld_bit_len =
7755               TYPE_LENGTH (TYPE_FIELD_TYPE (type, f)) * TARGET_CHAR_BIT;
7756         }
7757       if (off + fld_bit_len > bit_len)
7758         bit_len = off + fld_bit_len;
7759       off += bit_incr;
7760       TYPE_LENGTH (rtype) =
7761         align_value (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
7762     }
7763
7764   /* We handle the variant part, if any, at the end because of certain
7765      odd cases in which it is re-ordered so as NOT the last field of
7766      the record.  This can happen in the presence of representation
7767      clauses.  */
7768   if (variant_field >= 0)
7769     {
7770       struct type *branch_type;
7771
7772       off = TYPE_FIELD_BITPOS (rtype, variant_field);
7773
7774       if (dval0 == NULL)
7775         dval = value_from_contents_and_address (rtype, valaddr, address);
7776       else
7777         dval = dval0;
7778
7779       branch_type =
7780         to_fixed_variant_branch_type
7781         (TYPE_FIELD_TYPE (type, variant_field),
7782          cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7783          cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
7784       if (branch_type == NULL)
7785         {
7786           for (f = variant_field + 1; f < TYPE_NFIELDS (rtype); f += 1)
7787             TYPE_FIELDS (rtype)[f - 1] = TYPE_FIELDS (rtype)[f];
7788           TYPE_NFIELDS (rtype) -= 1;
7789         }
7790       else
7791         {
7792           TYPE_FIELD_TYPE (rtype, variant_field) = branch_type;
7793           TYPE_FIELD_NAME (rtype, variant_field) = "S";
7794           fld_bit_len =
7795             TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, variant_field)) *
7796             TARGET_CHAR_BIT;
7797           if (off + fld_bit_len > bit_len)
7798             bit_len = off + fld_bit_len;
7799           TYPE_LENGTH (rtype) =
7800             align_value (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
7801         }
7802     }
7803
7804   TYPE_LENGTH (rtype) = align_value (TYPE_LENGTH (rtype), TYPE_LENGTH (type));
7805
7806   value_free_to_mark (mark);
7807   if (TYPE_LENGTH (rtype) > varsize_limit)
7808     error ("record type with dynamic size is larger than varsize-limit");
7809   return rtype;
7810 }
7811
7812 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
7813    of 1.  */
7814
7815 static struct type *
7816 template_to_fixed_record_type (struct type *type, char *valaddr,
7817                                CORE_ADDR address, struct value *dval0)
7818 {
7819   return ada_template_to_fixed_record_type_1 (type, valaddr,
7820                                               address, dval0, 1);
7821 }
7822
7823 /* An ordinary record type in which ___XVL-convention fields and
7824    ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
7825    static approximations, containing all possible fields.  Uses
7826    no runtime values.  Useless for use in values, but that's OK,
7827    since the results are used only for type determinations.   Works on both
7828    structs and unions.  Representation note: to save space, we memorize
7829    the result of this function in the TYPE_TARGET_TYPE of the
7830    template type.  */
7831
7832 static struct type *
7833 template_to_static_fixed_type (struct type *type0)
7834 {
7835   struct type *type;
7836   int nfields;
7837   int f;
7838
7839   if (TYPE_TARGET_TYPE (type0) != NULL)
7840     return TYPE_TARGET_TYPE (type0);
7841
7842   nfields = TYPE_NFIELDS (type0);
7843   type = type0;
7844
7845   for (f = 0; f < nfields; f += 1)
7846     {
7847       struct type *field_type = CHECK_TYPEDEF (TYPE_FIELD_TYPE (type0, f));
7848       struct type *new_type;
7849
7850       if (is_dynamic_field (type0, f))
7851         new_type = to_static_fixed_type (TYPE_TARGET_TYPE (field_type));
7852       else
7853         new_type = to_static_fixed_type (field_type);
7854       if (type == type0 && new_type != field_type)
7855         {
7856           TYPE_TARGET_TYPE (type0) = type = alloc_type (TYPE_OBJFILE (type0));
7857           TYPE_CODE (type) = TYPE_CODE (type0);
7858           INIT_CPLUS_SPECIFIC (type);
7859           TYPE_NFIELDS (type) = nfields;
7860           TYPE_FIELDS (type) = (struct field *)
7861             TYPE_ALLOC (type, nfields * sizeof (struct field));
7862           memcpy (TYPE_FIELDS (type), TYPE_FIELDS (type0),
7863                   sizeof (struct field) * nfields);
7864           TYPE_NAME (type) = ada_type_name (type0);
7865           TYPE_TAG_NAME (type) = NULL;
7866           TYPE_FLAGS (type) |= TYPE_FLAG_FIXED_INSTANCE;
7867           TYPE_LENGTH (type) = 0;
7868         }
7869       TYPE_FIELD_TYPE (type, f) = new_type;
7870       TYPE_FIELD_NAME (type, f) = TYPE_FIELD_NAME (type0, f);
7871     }
7872   return type;
7873 }
7874
7875 /* Given an object of type TYPE whose contents are at VALADDR and
7876    whose address in memory is ADDRESS, returns a revision of TYPE --
7877    a non-dynamic-sized record with a variant part -- in which
7878    the variant part is replaced with the appropriate branch.  Looks
7879    for discriminant values in DVAL0, which can be NULL if the record
7880    contains the necessary discriminant values.  */
7881
7882 static struct type *
7883 to_record_with_fixed_variant_part (struct type *type, char *valaddr,
7884                                    CORE_ADDR address, struct value *dval0)
7885 {
7886   struct value *mark = value_mark ();
7887   struct value *dval;
7888   struct type *rtype;
7889   struct type *branch_type;
7890   int nfields = TYPE_NFIELDS (type);
7891   int variant_field = variant_field_index (type);
7892
7893   if (variant_field == -1)
7894     return type;
7895
7896   if (dval0 == NULL)
7897     dval = value_from_contents_and_address (type, valaddr, address);
7898   else
7899     dval = dval0;
7900
7901   rtype = alloc_type (TYPE_OBJFILE (type));
7902   TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
7903   INIT_CPLUS_SPECIFIC (rtype);
7904   TYPE_NFIELDS (rtype) = nfields;
7905   TYPE_FIELDS (rtype) =
7906     (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
7907   memcpy (TYPE_FIELDS (rtype), TYPE_FIELDS (type),
7908           sizeof (struct field) * nfields);
7909   TYPE_NAME (rtype) = ada_type_name (type);
7910   TYPE_TAG_NAME (rtype) = NULL;
7911   TYPE_FLAGS (rtype) |= TYPE_FLAG_FIXED_INSTANCE;
7912   TYPE_LENGTH (rtype) = TYPE_LENGTH (type);
7913
7914   branch_type = to_fixed_variant_branch_type
7915     (TYPE_FIELD_TYPE (type, variant_field),
7916      cond_offset_host (valaddr,
7917                        TYPE_FIELD_BITPOS (type, variant_field)
7918                        / TARGET_CHAR_BIT),
7919      cond_offset_target (address,
7920                          TYPE_FIELD_BITPOS (type, variant_field)
7921                          / TARGET_CHAR_BIT), dval);
7922   if (branch_type == NULL)
7923     {
7924       int f;
7925       for (f = variant_field + 1; f < nfields; f += 1)
7926         TYPE_FIELDS (rtype)[f - 1] = TYPE_FIELDS (rtype)[f];
7927       TYPE_NFIELDS (rtype) -= 1;
7928     }
7929   else
7930     {
7931       TYPE_FIELD_TYPE (rtype, variant_field) = branch_type;
7932       TYPE_FIELD_NAME (rtype, variant_field) = "S";
7933       TYPE_FIELD_BITSIZE (rtype, variant_field) = 0;
7934       TYPE_LENGTH (rtype) += TYPE_LENGTH (branch_type);
7935     }
7936   TYPE_LENGTH (rtype) -= TYPE_LENGTH (TYPE_FIELD_TYPE (type, variant_field));
7937
7938   value_free_to_mark (mark);
7939   return rtype;
7940 }
7941
7942 /* An ordinary record type (with fixed-length fields) that describes
7943    the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
7944    beginning of this section].   Any necessary discriminants' values
7945    should be in DVAL, a record value; it may be NULL if the object
7946    at ADDR itself contains any necessary discriminant values.
7947    Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
7948    values from the record are needed.  Except in the case that DVAL,
7949    VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
7950    unchecked) is replaced by a particular branch of the variant.
7951
7952    NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
7953    is questionable and may be removed.  It can arise during the
7954    processing of an unconstrained-array-of-record type where all the
7955    variant branches have exactly the same size.  This is because in
7956    such cases, the compiler does not bother to use the XVS convention
7957    when encoding the record.  I am currently dubious of this
7958    shortcut and suspect the compiler should be altered.  FIXME.  */
7959
7960 static struct type *
7961 to_fixed_record_type (struct type *type0, char *valaddr,
7962                       CORE_ADDR address, struct value *dval)
7963 {
7964   struct type *templ_type;
7965
7966   if (TYPE_FLAGS (type0) & TYPE_FLAG_FIXED_INSTANCE)
7967     return type0;
7968
7969   templ_type = dynamic_template_type (type0);
7970
7971   if (templ_type != NULL)
7972     return template_to_fixed_record_type (templ_type, valaddr, address, dval);
7973   else if (variant_field_index (type0) >= 0)
7974     {
7975       if (dval == NULL && valaddr == NULL && address == 0)
7976         return type0;
7977       return to_record_with_fixed_variant_part (type0, valaddr, address,
7978                                                 dval);
7979     }
7980   else
7981     {
7982       TYPE_FLAGS (type0) |= TYPE_FLAG_FIXED_INSTANCE;
7983       return type0;
7984     }
7985
7986 }
7987
7988 /* An ordinary record type (with fixed-length fields) that describes
7989    the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
7990    union type.  Any necessary discriminants' values should be in DVAL,
7991    a record value.  That is, this routine selects the appropriate
7992    branch of the union at ADDR according to the discriminant value
7993    indicated in the union's type name.  */
7994
7995 static struct type *
7996 to_fixed_variant_branch_type (struct type *var_type0, char *valaddr,
7997                               CORE_ADDR address, struct value *dval)
7998 {
7999   int which;
8000   struct type *templ_type;
8001   struct type *var_type;
8002
8003   if (TYPE_CODE (var_type0) == TYPE_CODE_PTR)
8004     var_type = TYPE_TARGET_TYPE (var_type0);
8005   else
8006     var_type = var_type0;
8007
8008   templ_type = ada_find_parallel_type (var_type, "___XVU");
8009
8010   if (templ_type != NULL)
8011     var_type = templ_type;
8012
8013   which =
8014     ada_which_variant_applies (var_type,
8015                                VALUE_TYPE (dval), VALUE_CONTENTS (dval));
8016
8017   if (which < 0)
8018     return empty_record (TYPE_OBJFILE (var_type));
8019   else if (is_dynamic_field (var_type, which))
8020     return to_fixed_record_type
8021       (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (var_type, which)),
8022        valaddr, address, dval);
8023   else if (variant_field_index (TYPE_FIELD_TYPE (var_type, which)) >= 0)
8024     return
8025       to_fixed_record_type
8026       (TYPE_FIELD_TYPE (var_type, which), valaddr, address, dval);
8027   else
8028     return TYPE_FIELD_TYPE (var_type, which);
8029 }
8030
8031 /* Assuming that TYPE0 is an array type describing the type of a value
8032    at ADDR, and that DVAL describes a record containing any
8033    discriminants used in TYPE0, returns a type for the value that
8034    contains no dynamic components (that is, no components whose sizes
8035    are determined by run-time quantities).  Unless IGNORE_TOO_BIG is
8036    true, gives an error message if the resulting type's size is over
8037    varsize_limit.  */
8038
8039 static struct type *
8040 to_fixed_array_type (struct type *type0, struct value *dval,
8041                      int ignore_too_big)
8042 {
8043   struct type *index_type_desc;
8044   struct type *result;
8045
8046   if (ada_is_packed_array_type (type0)  /* revisit? */
8047       || (TYPE_FLAGS (type0) & TYPE_FLAG_FIXED_INSTANCE))
8048     return type0;
8049
8050   index_type_desc = ada_find_parallel_type (type0, "___XA");
8051   if (index_type_desc == NULL)
8052     {
8053       struct type *elt_type0 = check_typedef (TYPE_TARGET_TYPE (type0));
8054       /* NOTE: elt_type---the fixed version of elt_type0---should never
8055          depend on the contents of the array in properly constructed
8056          debugging data.  */
8057       struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval);
8058
8059       if (elt_type0 == elt_type)
8060         result = type0;
8061       else
8062         result = create_array_type (alloc_type (TYPE_OBJFILE (type0)),
8063                                     elt_type, TYPE_INDEX_TYPE (type0));
8064     }
8065   else
8066     {
8067       int i;
8068       struct type *elt_type0;
8069
8070       elt_type0 = type0;
8071       for (i = TYPE_NFIELDS (index_type_desc); i > 0; i -= 1)
8072         elt_type0 = TYPE_TARGET_TYPE (elt_type0);
8073
8074       /* NOTE: result---the fixed version of elt_type0---should never
8075          depend on the contents of the array in properly constructed
8076          debugging data.  */
8077       result = ada_to_fixed_type (check_typedef (elt_type0), 0, 0, dval);
8078       for (i = TYPE_NFIELDS (index_type_desc) - 1; i >= 0; i -= 1)
8079         {
8080           struct type *range_type =
8081             to_fixed_range_type (TYPE_FIELD_NAME (index_type_desc, i),
8082                                  dval, TYPE_OBJFILE (type0));
8083           result = create_array_type (alloc_type (TYPE_OBJFILE (type0)),
8084                                       result, range_type);
8085         }
8086       if (!ignore_too_big && TYPE_LENGTH (result) > varsize_limit)
8087         error ("array type with dynamic size is larger than varsize-limit");
8088     }
8089
8090   TYPE_FLAGS (result) |= TYPE_FLAG_FIXED_INSTANCE;
8091   return result;
8092 }
8093
8094
8095 /* A standard type (containing no dynamically sized components)
8096    corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8097    DVAL describes a record containing any discriminants used in TYPE0,
8098    and may be NULL if there are none, or if the object of type TYPE at
8099    ADDRESS or in VALADDR contains these discriminants.  */
8100
8101 struct type *
8102 ada_to_fixed_type (struct type *type, char *valaddr,
8103                    CORE_ADDR address, struct value *dval)
8104 {
8105   CHECK_TYPEDEF (type);
8106   switch (TYPE_CODE (type))
8107     {
8108     default:
8109       return type;
8110     case TYPE_CODE_STRUCT:
8111       {
8112         struct type *static_type = to_static_fixed_type (type);
8113         if (ada_is_tagged_type (static_type, 0))
8114           {
8115             struct type *real_type =
8116               type_from_tag (value_tag_from_contents_and_address (static_type,
8117                                                                   valaddr,
8118                                                                   address));
8119             if (real_type != NULL)
8120               type = real_type;
8121           }
8122         return to_fixed_record_type (type, valaddr, address, NULL);
8123       }
8124     case TYPE_CODE_ARRAY:
8125       return to_fixed_array_type (type, dval, 1);
8126     case TYPE_CODE_UNION:
8127       if (dval == NULL)
8128         return type;
8129       else
8130         return to_fixed_variant_branch_type (type, valaddr, address, dval);
8131     }
8132 }
8133
8134 /* A standard (static-sized) type corresponding as well as possible to
8135    TYPE0, but based on no runtime data.  */
8136
8137 static struct type *
8138 to_static_fixed_type (struct type *type0)
8139 {
8140   struct type *type;
8141
8142   if (type0 == NULL)
8143     return NULL;
8144
8145   if (TYPE_FLAGS (type0) & TYPE_FLAG_FIXED_INSTANCE)
8146     return type0;
8147
8148   CHECK_TYPEDEF (type0);
8149
8150   switch (TYPE_CODE (type0))
8151     {
8152     default:
8153       return type0;
8154     case TYPE_CODE_STRUCT:
8155       type = dynamic_template_type (type0);
8156       if (type != NULL)
8157         return template_to_static_fixed_type (type);
8158       else
8159         return template_to_static_fixed_type (type0);
8160     case TYPE_CODE_UNION:
8161       type = ada_find_parallel_type (type0, "___XVU");
8162       if (type != NULL)
8163         return template_to_static_fixed_type (type);
8164       else
8165         return template_to_static_fixed_type (type0);
8166     }
8167 }
8168
8169 /* A static approximation of TYPE with all type wrappers removed.  */
8170
8171 static struct type *
8172 static_unwrap_type (struct type *type)
8173 {
8174   if (ada_is_aligner_type (type))
8175     {
8176       struct type *type1 = TYPE_FIELD_TYPE (check_typedef (type), 0);
8177       if (ada_type_name (type1) == NULL)
8178         TYPE_NAME (type1) = ada_type_name (type);
8179
8180       return static_unwrap_type (type1);
8181     }
8182   else
8183     {
8184       struct type *raw_real_type = ada_get_base_type (type);
8185       if (raw_real_type == type)
8186         return type;
8187       else
8188         return to_static_fixed_type (raw_real_type);
8189     }
8190 }
8191
8192 /* In some cases, incomplete and private types require
8193    cross-references that are not resolved as records (for example,
8194       type Foo;
8195       type FooP is access Foo;
8196       V: FooP;
8197       type Foo is array ...;
8198    ).  In these cases, since there is no mechanism for producing
8199    cross-references to such types, we instead substitute for FooP a
8200    stub enumeration type that is nowhere resolved, and whose tag is
8201    the name of the actual type.  Call these types "non-record stubs".  */
8202
8203 /* A type equivalent to TYPE that is not a non-record stub, if one
8204    exists, otherwise TYPE.  */
8205
8206 struct type *
8207 ada_completed_type (struct type *type)
8208 {
8209   CHECK_TYPEDEF (type);
8210   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_ENUM
8211       || (TYPE_FLAGS (type) & TYPE_FLAG_STUB) == 0
8212       || TYPE_TAG_NAME (type) == NULL)
8213     return type;
8214   else
8215     {
8216       char *name = TYPE_TAG_NAME (type);
8217       struct type *type1 = ada_find_any_type (name);
8218       return (type1 == NULL) ? type : type1;
8219     }
8220 }
8221
8222 /* A value representing the data at VALADDR/ADDRESS as described by
8223    type TYPE0, but with a standard (static-sized) type that correctly
8224    describes it.  If VAL0 is not NULL and TYPE0 already is a standard
8225    type, then return VAL0 [this feature is simply to avoid redundant
8226    creation of struct values].  */
8227
8228 static struct value *
8229 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
8230                            struct value *val0)
8231 {
8232   struct type *type = ada_to_fixed_type (type0, 0, address, NULL);
8233   if (type == type0 && val0 != NULL)
8234     return val0;
8235   else
8236     return value_from_contents_and_address (type, 0, address);
8237 }
8238
8239 /* A value representing VAL, but with a standard (static-sized) type
8240    that correctly describes it.  Does not necessarily create a new
8241    value.  */
8242
8243 static struct value *
8244 ada_to_fixed_value (struct value *val)
8245 {
8246   return ada_to_fixed_value_create (VALUE_TYPE (val),
8247                                     VALUE_ADDRESS (val) + VALUE_OFFSET (val),
8248                                     val);
8249 }
8250
8251 /* If the PC is pointing inside a function prologue, then re-adjust it
8252    past this prologue.  */
8253
8254 static void
8255 adjust_pc_past_prologue (CORE_ADDR *pc)
8256 {
8257   struct symbol *func_sym = find_pc_function (*pc);
8258
8259   if (func_sym)
8260     {
8261       const struct symtab_and_line sal =
8262         find_function_start_sal (func_sym, 1);
8263
8264       if (*pc <= sal.pc)
8265         *pc = sal.pc;
8266     }
8267 }
8268
8269 /* A value representing VAL, but with a standard (static-sized) type
8270    chosen to approximate the real type of VAL as well as possible, but
8271    without consulting any runtime values.  For Ada dynamic-sized
8272    types, therefore, the type of the result is likely to be inaccurate.  */
8273
8274 struct value *
8275 ada_to_static_fixed_value (struct value *val)
8276 {
8277   struct type *type =
8278     to_static_fixed_type (static_unwrap_type (VALUE_TYPE (val)));
8279   if (type == VALUE_TYPE (val))
8280     return val;
8281   else
8282     return coerce_unspec_val_to_type (val, type);
8283 }
8284 \f
8285
8286 /* Attributes */
8287
8288 /* Table mapping attribute numbers to names.
8289    NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h.  */
8290
8291 static const char *attribute_names[] = {
8292   "<?>",
8293
8294   "first",
8295   "last",
8296   "length",
8297   "image",
8298   "max",
8299   "min",
8300   "modulus",
8301   "pos",
8302   "size",
8303   "tag",
8304   "val",
8305   0
8306 };
8307
8308 const char *
8309 ada_attribute_name (enum exp_opcode n)
8310 {
8311   if (n >= OP_ATR_FIRST && n <= (int) OP_ATR_VAL)
8312     return attribute_names[n - OP_ATR_FIRST + 1];
8313   else
8314     return attribute_names[0];
8315 }
8316
8317 /* Evaluate the 'POS attribute applied to ARG.  */
8318
8319 static LONGEST
8320 pos_atr (struct value *arg)
8321 {
8322   struct type *type = VALUE_TYPE (arg);
8323
8324   if (!discrete_type_p (type))
8325     error ("'POS only defined on discrete types");
8326
8327   if (TYPE_CODE (type) == TYPE_CODE_ENUM)
8328     {
8329       int i;
8330       LONGEST v = value_as_long (arg);
8331
8332       for (i = 0; i < TYPE_NFIELDS (type); i += 1)
8333         {
8334           if (v == TYPE_FIELD_BITPOS (type, i))
8335             return i;
8336         }
8337       error ("enumeration value is invalid: can't find 'POS");
8338     }
8339   else
8340     return value_as_long (arg);
8341 }
8342
8343 static struct value *
8344 value_pos_atr (struct value *arg)
8345 {
8346   return value_from_longest (builtin_type_ada_int, pos_atr (arg));
8347 }
8348
8349 /* Evaluate the TYPE'VAL attribute applied to ARG.  */
8350
8351 static struct value *
8352 value_val_atr (struct type *type, struct value *arg)
8353 {
8354   if (!discrete_type_p (type))
8355     error ("'VAL only defined on discrete types");
8356   if (!integer_type_p (VALUE_TYPE (arg)))
8357     error ("'VAL requires integral argument");
8358
8359   if (TYPE_CODE (type) == TYPE_CODE_ENUM)
8360     {
8361       long pos = value_as_long (arg);
8362       if (pos < 0 || pos >= TYPE_NFIELDS (type))
8363         error ("argument to 'VAL out of range");
8364       return value_from_longest (type, TYPE_FIELD_BITPOS (type, pos));
8365     }
8366   else
8367     return value_from_longest (type, value_as_long (arg));
8368 }
8369 \f
8370
8371                                 /* Evaluation */
8372
8373 /* True if TYPE appears to be an Ada character type.
8374    [At the moment, this is true only for Character and Wide_Character;
8375    It is a heuristic test that could stand improvement].  */
8376
8377 int
8378 ada_is_character_type (struct type *type)
8379 {
8380   const char *name = ada_type_name (type);
8381   return
8382     name != NULL
8383     && (TYPE_CODE (type) == TYPE_CODE_CHAR
8384         || TYPE_CODE (type) == TYPE_CODE_INT
8385         || TYPE_CODE (type) == TYPE_CODE_RANGE)
8386     && (strcmp (name, "character") == 0
8387         || strcmp (name, "wide_character") == 0
8388         || strcmp (name, "unsigned char") == 0);
8389 }
8390
8391 /* True if TYPE appears to be an Ada string type.  */
8392
8393 int
8394 ada_is_string_type (struct type *type)
8395 {
8396   CHECK_TYPEDEF (type);
8397   if (type != NULL
8398       && TYPE_CODE (type) != TYPE_CODE_PTR
8399       && (ada_is_simple_array_type (type)
8400           || ada_is_array_descriptor_type (type))
8401       && ada_array_arity (type) == 1)
8402     {
8403       struct type *elttype = ada_array_element_type (type, 1);
8404
8405       return ada_is_character_type (elttype);
8406     }
8407   else
8408     return 0;
8409 }
8410
8411
8412 /* True if TYPE is a struct type introduced by the compiler to force the
8413    alignment of a value.  Such types have a single field with a
8414    distinctive name.  */
8415
8416 int
8417 ada_is_aligner_type (struct type *type)
8418 {
8419   CHECK_TYPEDEF (type);
8420   return (TYPE_CODE (type) == TYPE_CODE_STRUCT
8421           && TYPE_NFIELDS (type) == 1
8422           && strcmp (TYPE_FIELD_NAME (type, 0), "F") == 0);
8423 }
8424
8425 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
8426    the parallel type.  */
8427
8428 struct type *
8429 ada_get_base_type (struct type *raw_type)
8430 {
8431   struct type *real_type_namer;
8432   struct type *raw_real_type;
8433
8434   if (raw_type == NULL || TYPE_CODE (raw_type) != TYPE_CODE_STRUCT)
8435     return raw_type;
8436
8437   real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
8438   if (real_type_namer == NULL
8439       || TYPE_CODE (real_type_namer) != TYPE_CODE_STRUCT
8440       || TYPE_NFIELDS (real_type_namer) != 1)
8441     return raw_type;
8442
8443   raw_real_type = ada_find_any_type (TYPE_FIELD_NAME (real_type_namer, 0));
8444   if (raw_real_type == NULL)
8445     return raw_type;
8446   else
8447     return raw_real_type;
8448 }
8449
8450 /* The type of value designated by TYPE, with all aligners removed.  */
8451
8452 struct type *
8453 ada_aligned_type (struct type *type)
8454 {
8455   if (ada_is_aligner_type (type))
8456     return ada_aligned_type (TYPE_FIELD_TYPE (type, 0));
8457   else
8458     return ada_get_base_type (type);
8459 }
8460
8461
8462 /* The address of the aligned value in an object at address VALADDR
8463    having type TYPE.  Assumes ada_is_aligner_type (TYPE).  */
8464
8465 char *
8466 ada_aligned_value_addr (struct type *type, char *valaddr)
8467 {
8468   if (ada_is_aligner_type (type))
8469     return ada_aligned_value_addr (TYPE_FIELD_TYPE (type, 0),
8470                                    valaddr +
8471                                    TYPE_FIELD_BITPOS (type,
8472                                                       0) / TARGET_CHAR_BIT);
8473   else
8474     return valaddr;
8475 }
8476
8477
8478
8479 /* The printed representation of an enumeration literal with encoded
8480    name NAME.  The value is good to the next call of ada_enum_name.  */
8481 const char *
8482 ada_enum_name (const char *name)
8483 {
8484   static char *result;
8485   static size_t result_len = 0;
8486   char *tmp;
8487
8488   /* First, unqualify the enumeration name:
8489      1. Search for the last '.' character.  If we find one, then skip
8490      all the preceeding characters, the unqualified name starts
8491      right after that dot.
8492      2. Otherwise, we may be debugging on a target where the compiler
8493      translates dots into "__".  Search forward for double underscores,
8494      but stop searching when we hit an overloading suffix, which is
8495      of the form "__" followed by digits.  */
8496
8497   tmp = strrchr (name, '.');
8498   if (tmp != NULL)
8499     name = tmp + 1;
8500   else
8501     {
8502       while ((tmp = strstr (name, "__")) != NULL)
8503         {
8504           if (isdigit (tmp[2]))
8505             break;
8506           else
8507             name = tmp + 2;
8508         }
8509     }
8510
8511   if (name[0] == 'Q')
8512     {
8513       int v;
8514       if (name[1] == 'U' || name[1] == 'W')
8515         {
8516           if (sscanf (name + 2, "%x", &v) != 1)
8517             return name;
8518         }
8519       else
8520         return name;
8521
8522       GROW_VECT (result, result_len, 16);
8523       if (isascii (v) && isprint (v))
8524         sprintf (result, "'%c'", v);
8525       else if (name[1] == 'U')
8526         sprintf (result, "[\"%02x\"]", v);
8527       else
8528         sprintf (result, "[\"%04x\"]", v);
8529
8530       return result;
8531     }
8532   else
8533     {
8534       tmp = strstr (name, "__");
8535       if (tmp == NULL)
8536         tmp = strstr (name, "$");
8537       if (tmp != NULL)
8538         {
8539           GROW_VECT (result, result_len, tmp - name + 1);
8540           strncpy (result, name, tmp - name);
8541           result[tmp - name] = '\0';
8542           return result;
8543         }
8544
8545       return name;
8546     }
8547 }
8548
8549 static struct value *
8550 evaluate_subexp (struct type *expect_type, struct expression *exp, int *pos,
8551                  enum noside noside)
8552 {
8553   return (*exp->language_defn->la_exp_desc->evaluate_exp)
8554     (expect_type, exp, pos, noside);
8555 }
8556
8557 /* Evaluate the subexpression of EXP starting at *POS as for
8558    evaluate_type, updating *POS to point just past the evaluated
8559    expression.  */
8560
8561 static struct value *
8562 evaluate_subexp_type (struct expression *exp, int *pos)
8563 {
8564   return (*exp->language_defn->la_exp_desc->evaluate_exp)
8565     (NULL_TYPE, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
8566 }
8567
8568 /* If VAL is wrapped in an aligner or subtype wrapper, return the
8569    value it wraps.  */
8570
8571 static struct value *
8572 unwrap_value (struct value *val)
8573 {
8574   struct type *type = check_typedef (VALUE_TYPE (val));
8575   if (ada_is_aligner_type (type))
8576     {
8577       struct value *v = value_struct_elt (&val, NULL, "F",
8578                                           NULL, "internal structure");
8579       struct type *val_type = check_typedef (VALUE_TYPE (v));
8580       if (ada_type_name (val_type) == NULL)
8581         TYPE_NAME (val_type) = ada_type_name (type);
8582
8583       return unwrap_value (v);
8584     }
8585   else
8586     {
8587       struct type *raw_real_type =
8588         ada_completed_type (ada_get_base_type (type));
8589
8590       if (type == raw_real_type)
8591         return val;
8592
8593       return
8594         coerce_unspec_val_to_type
8595         (val, ada_to_fixed_type (raw_real_type, 0,
8596                                  VALUE_ADDRESS (val) + VALUE_OFFSET (val),
8597                                  NULL));
8598     }
8599 }
8600
8601 static struct value *
8602 cast_to_fixed (struct type *type, struct value *arg)
8603 {
8604   LONGEST val;
8605
8606   if (type == VALUE_TYPE (arg))
8607     return arg;
8608   else if (ada_is_fixed_point_type (VALUE_TYPE (arg)))
8609     val = ada_float_to_fixed (type,
8610                               ada_fixed_to_float (VALUE_TYPE (arg),
8611                                                   value_as_long (arg)));
8612   else
8613     {
8614       DOUBLEST argd =
8615         value_as_double (value_cast (builtin_type_double, value_copy (arg)));
8616       val = ada_float_to_fixed (type, argd);
8617     }
8618
8619   return value_from_longest (type, val);
8620 }
8621
8622 static struct value *
8623 cast_from_fixed_to_double (struct value *arg)
8624 {
8625   DOUBLEST val = ada_fixed_to_float (VALUE_TYPE (arg),
8626                                      value_as_long (arg));
8627   return value_from_double (builtin_type_double, val);
8628 }
8629
8630 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
8631    return the converted value.  */
8632
8633 static struct value *
8634 coerce_for_assign (struct type *type, struct value *val)
8635 {
8636   struct type *type2 = VALUE_TYPE (val);
8637   if (type == type2)
8638     return val;
8639
8640   CHECK_TYPEDEF (type2);
8641   CHECK_TYPEDEF (type);
8642
8643   if (TYPE_CODE (type2) == TYPE_CODE_PTR
8644       && TYPE_CODE (type) == TYPE_CODE_ARRAY)
8645     {
8646       val = ada_value_ind (val);
8647       type2 = VALUE_TYPE (val);
8648     }
8649
8650   if (TYPE_CODE (type2) == TYPE_CODE_ARRAY
8651       && TYPE_CODE (type) == TYPE_CODE_ARRAY)
8652     {
8653       if (TYPE_LENGTH (type2) != TYPE_LENGTH (type)
8654           || TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
8655           != TYPE_LENGTH (TYPE_TARGET_TYPE (type2)))
8656         error ("Incompatible types in assignment");
8657       VALUE_TYPE (val) = type;
8658     }
8659   return val;
8660 }
8661
8662 static struct value *
8663 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
8664 {
8665   struct value *val;
8666   struct type *type1, *type2;
8667   LONGEST v, v1, v2;
8668
8669   COERCE_REF (arg1);
8670   COERCE_REF (arg2);
8671   type1 = base_type (check_typedef (VALUE_TYPE (arg1)));
8672   type2 = base_type (check_typedef (VALUE_TYPE (arg2)));
8673
8674   if (TYPE_CODE (type1) != TYPE_CODE_INT
8675       || TYPE_CODE (type2) != TYPE_CODE_INT)
8676     return value_binop (arg1, arg2, op);
8677
8678   switch (op)
8679     {
8680     case BINOP_MOD:
8681     case BINOP_DIV:
8682     case BINOP_REM:
8683       break;
8684     default:
8685       return value_binop (arg1, arg2, op);
8686     }
8687
8688   v2 = value_as_long (arg2);
8689   if (v2 == 0)
8690     error ("second operand of %s must not be zero.", op_string (op));
8691
8692   if (TYPE_UNSIGNED (type1) || op == BINOP_MOD)
8693     return value_binop (arg1, arg2, op);
8694
8695   v1 = value_as_long (arg1);
8696   switch (op)
8697     {
8698     case BINOP_DIV:
8699       v = v1 / v2;
8700       if (!TRUNCATION_TOWARDS_ZERO && v1 * (v1 % v2) < 0)
8701         v += v > 0 ? -1 : 1;
8702       break;
8703     case BINOP_REM:
8704       v = v1 % v2;
8705       if (v * v1 < 0)
8706         v -= v2;
8707       break;
8708     default:
8709       /* Should not reach this point.  */
8710       v = 0;
8711     }
8712
8713   val = allocate_value (type1);
8714   store_unsigned_integer (VALUE_CONTENTS_RAW (val),
8715                           TYPE_LENGTH (VALUE_TYPE (val)), v);
8716   return val;
8717 }
8718
8719 static int
8720 ada_value_equal (struct value *arg1, struct value *arg2)
8721 {
8722   if (ada_is_direct_array_type (VALUE_TYPE (arg1))
8723       || ada_is_direct_array_type (VALUE_TYPE (arg2)))
8724     {
8725       arg1 = ada_coerce_to_simple_array (arg1);
8726       arg2 = ada_coerce_to_simple_array (arg2);
8727       if (TYPE_CODE (VALUE_TYPE (arg1)) != TYPE_CODE_ARRAY
8728           || TYPE_CODE (VALUE_TYPE (arg2)) != TYPE_CODE_ARRAY)
8729         error ("Attempt to compare array with non-array");
8730       /* FIXME: The following works only for types whose
8731          representations use all bits (no padding or undefined bits)
8732          and do not have user-defined equality.  */
8733       return
8734         TYPE_LENGTH (VALUE_TYPE (arg1)) == TYPE_LENGTH (VALUE_TYPE (arg2))
8735         && memcmp (VALUE_CONTENTS (arg1), VALUE_CONTENTS (arg2),
8736                    TYPE_LENGTH (VALUE_TYPE (arg1))) == 0;
8737     }
8738   return value_equal (arg1, arg2);
8739 }
8740
8741 struct value *
8742 ada_evaluate_subexp (struct type *expect_type, struct expression *exp,
8743                      int *pos, enum noside noside)
8744 {
8745   enum exp_opcode op;
8746   int tem, tem2, tem3;
8747   int pc;
8748   struct value *arg1 = NULL, *arg2 = NULL, *arg3;
8749   struct type *type;
8750   int nargs;
8751   struct value **argvec;
8752
8753   pc = *pos;
8754   *pos += 1;
8755   op = exp->elts[pc].opcode;
8756
8757   switch (op)
8758     {
8759     default:
8760       *pos -= 1;
8761       return
8762         unwrap_value (evaluate_subexp_standard
8763                       (expect_type, exp, pos, noside));
8764
8765     case OP_STRING:
8766       {
8767         struct value *result;
8768         *pos -= 1;
8769         result = evaluate_subexp_standard (expect_type, exp, pos, noside);
8770         /* The result type will have code OP_STRING, bashed there from 
8771            OP_ARRAY.  Bash it back.  */
8772         if (TYPE_CODE (VALUE_TYPE (result)) == TYPE_CODE_STRING)
8773           TYPE_CODE (VALUE_TYPE (result)) = TYPE_CODE_ARRAY;
8774         return result;
8775       }
8776
8777     case UNOP_CAST:
8778       (*pos) += 2;
8779       type = exp->elts[pc + 1].type;
8780       arg1 = evaluate_subexp (type, exp, pos, noside);
8781       if (noside == EVAL_SKIP)
8782         goto nosideret;
8783       if (type != check_typedef (VALUE_TYPE (arg1)))
8784         {
8785           if (ada_is_fixed_point_type (type))
8786             arg1 = cast_to_fixed (type, arg1);
8787           else if (ada_is_fixed_point_type (VALUE_TYPE (arg1)))
8788             arg1 = value_cast (type, cast_from_fixed_to_double (arg1));
8789           else if (VALUE_LVAL (arg1) == lval_memory)
8790             {
8791               /* This is in case of the really obscure (and undocumented,
8792                  but apparently expected) case of (Foo) Bar.all, where Bar
8793                  is an integer constant and Foo is a dynamic-sized type.
8794                  If we don't do this, ARG1 will simply be relabeled with
8795                  TYPE.  */
8796               if (noside == EVAL_AVOID_SIDE_EFFECTS)
8797                 return value_zero (to_static_fixed_type (type), not_lval);
8798               arg1 =
8799                 ada_to_fixed_value_create
8800                 (type, VALUE_ADDRESS (arg1) + VALUE_OFFSET (arg1), 0);
8801             }
8802           else
8803             arg1 = value_cast (type, arg1);
8804         }
8805       return arg1;
8806
8807     case UNOP_QUAL:
8808       (*pos) += 2;
8809       type = exp->elts[pc + 1].type;
8810       return ada_evaluate_subexp (type, exp, pos, noside);
8811
8812     case BINOP_ASSIGN:
8813       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8814       arg2 = evaluate_subexp (VALUE_TYPE (arg1), exp, pos, noside);
8815       if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
8816         return arg1;
8817       if (ada_is_fixed_point_type (VALUE_TYPE (arg1)))
8818         arg2 = cast_to_fixed (VALUE_TYPE (arg1), arg2);
8819       else if (ada_is_fixed_point_type (VALUE_TYPE (arg2)))
8820         error
8821           ("Fixed-point values must be assigned to fixed-point variables");
8822       else
8823         arg2 = coerce_for_assign (VALUE_TYPE (arg1), arg2);
8824       return ada_value_assign (arg1, arg2);
8825
8826     case BINOP_ADD:
8827       arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
8828       arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
8829       if (noside == EVAL_SKIP)
8830         goto nosideret;
8831       if ((ada_is_fixed_point_type (VALUE_TYPE (arg1))
8832            || ada_is_fixed_point_type (VALUE_TYPE (arg2)))
8833           && VALUE_TYPE (arg1) != VALUE_TYPE (arg2))
8834         error ("Operands of fixed-point addition must have the same type");
8835       return value_cast (VALUE_TYPE (arg1), value_add (arg1, arg2));
8836
8837     case BINOP_SUB:
8838       arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
8839       arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
8840       if (noside == EVAL_SKIP)
8841         goto nosideret;
8842       if ((ada_is_fixed_point_type (VALUE_TYPE (arg1))
8843            || ada_is_fixed_point_type (VALUE_TYPE (arg2)))
8844           && VALUE_TYPE (arg1) != VALUE_TYPE (arg2))
8845         error ("Operands of fixed-point subtraction must have the same type");
8846       return value_cast (VALUE_TYPE (arg1), value_sub (arg1, arg2));
8847
8848     case BINOP_MUL:
8849     case BINOP_DIV:
8850       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8851       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8852       if (noside == EVAL_SKIP)
8853         goto nosideret;
8854       else if (noside == EVAL_AVOID_SIDE_EFFECTS
8855                && (op == BINOP_DIV || op == BINOP_REM || op == BINOP_MOD))
8856         return value_zero (VALUE_TYPE (arg1), not_lval);
8857       else
8858         {
8859           if (ada_is_fixed_point_type (VALUE_TYPE (arg1)))
8860             arg1 = cast_from_fixed_to_double (arg1);
8861           if (ada_is_fixed_point_type (VALUE_TYPE (arg2)))
8862             arg2 = cast_from_fixed_to_double (arg2);
8863           return ada_value_binop (arg1, arg2, op);
8864         }
8865
8866     case BINOP_REM:
8867     case BINOP_MOD:
8868       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8869       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8870       if (noside == EVAL_SKIP)
8871         goto nosideret;
8872       else if (noside == EVAL_AVOID_SIDE_EFFECTS
8873                && (op == BINOP_DIV || op == BINOP_REM || op == BINOP_MOD))
8874         return value_zero (VALUE_TYPE (arg1), not_lval);
8875       else
8876         return ada_value_binop (arg1, arg2, op);
8877
8878     case BINOP_EQUAL:
8879     case BINOP_NOTEQUAL:
8880       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8881       arg2 = evaluate_subexp (VALUE_TYPE (arg1), exp, pos, noside);
8882       if (noside == EVAL_SKIP)
8883         goto nosideret;
8884       if (noside == EVAL_AVOID_SIDE_EFFECTS)
8885         tem = 0;
8886       else
8887         tem = ada_value_equal (arg1, arg2);
8888       if (op == BINOP_NOTEQUAL)
8889         tem = !tem;
8890       return value_from_longest (LA_BOOL_TYPE, (LONGEST) tem);
8891
8892     case UNOP_NEG:
8893       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8894       if (noside == EVAL_SKIP)
8895         goto nosideret;
8896       else if (ada_is_fixed_point_type (VALUE_TYPE (arg1)))
8897         return value_cast (VALUE_TYPE (arg1), value_neg (arg1));
8898       else
8899         return value_neg (arg1);
8900
8901     case OP_VAR_VALUE:
8902       *pos -= 1;
8903       if (noside == EVAL_SKIP)
8904         {
8905           *pos += 4;
8906           goto nosideret;
8907         }
8908       else if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
8909         /* Only encountered when an unresolved symbol occurs in a
8910            context other than a function call, in which case, it is
8911            illegal.  */
8912         error ("Unexpected unresolved symbol, %s, during evaluation",
8913                SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
8914       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
8915         {
8916           *pos += 4;
8917           return value_zero
8918             (to_static_fixed_type
8919              (static_unwrap_type (SYMBOL_TYPE (exp->elts[pc + 2].symbol))),
8920              not_lval);
8921         }
8922       else
8923         {
8924           arg1 =
8925             unwrap_value (evaluate_subexp_standard
8926                           (expect_type, exp, pos, noside));
8927           return ada_to_fixed_value (arg1);
8928         }
8929
8930     case OP_FUNCALL:
8931       (*pos) += 2;
8932
8933       /* Allocate arg vector, including space for the function to be
8934          called in argvec[0] and a terminating NULL.  */
8935       nargs = longest_to_int (exp->elts[pc + 1].longconst);
8936       argvec =
8937         (struct value **) alloca (sizeof (struct value *) * (nargs + 2));
8938
8939       if (exp->elts[*pos].opcode == OP_VAR_VALUE
8940           && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
8941         error ("Unexpected unresolved symbol, %s, during evaluation",
8942                SYMBOL_PRINT_NAME (exp->elts[pc + 5].symbol));
8943       else
8944         {
8945           for (tem = 0; tem <= nargs; tem += 1)
8946             argvec[tem] = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8947           argvec[tem] = 0;
8948
8949           if (noside == EVAL_SKIP)
8950             goto nosideret;
8951         }
8952
8953       if (ada_is_packed_array_type (desc_base_type (VALUE_TYPE (argvec[0]))))
8954         argvec[0] = ada_coerce_to_simple_array (argvec[0]);
8955       else if (TYPE_CODE (VALUE_TYPE (argvec[0])) == TYPE_CODE_REF
8956                || (TYPE_CODE (VALUE_TYPE (argvec[0])) == TYPE_CODE_ARRAY
8957                    && VALUE_LVAL (argvec[0]) == lval_memory))
8958         argvec[0] = value_addr (argvec[0]);
8959
8960       type = check_typedef (VALUE_TYPE (argvec[0]));
8961       if (TYPE_CODE (type) == TYPE_CODE_PTR)
8962         {
8963           switch (TYPE_CODE (check_typedef (TYPE_TARGET_TYPE (type))))
8964             {
8965             case TYPE_CODE_FUNC:
8966               type = check_typedef (TYPE_TARGET_TYPE (type));
8967               break;
8968             case TYPE_CODE_ARRAY:
8969               break;
8970             case TYPE_CODE_STRUCT:
8971               if (noside != EVAL_AVOID_SIDE_EFFECTS)
8972                 argvec[0] = ada_value_ind (argvec[0]);
8973               type = check_typedef (TYPE_TARGET_TYPE (type));
8974               break;
8975             default:
8976               error ("cannot subscript or call something of type `%s'",
8977                      ada_type_name (VALUE_TYPE (argvec[0])));
8978               break;
8979             }
8980         }
8981
8982       switch (TYPE_CODE (type))
8983         {
8984         case TYPE_CODE_FUNC:
8985           if (noside == EVAL_AVOID_SIDE_EFFECTS)
8986             return allocate_value (TYPE_TARGET_TYPE (type));
8987           return call_function_by_hand (argvec[0], nargs, argvec + 1);
8988         case TYPE_CODE_STRUCT:
8989           {
8990             int arity;
8991
8992             arity = ada_array_arity (type);
8993             type = ada_array_element_type (type, nargs);
8994             if (type == NULL)
8995               error ("cannot subscript or call a record");
8996             if (arity != nargs)
8997               error ("wrong number of subscripts; expecting %d", arity);
8998             if (noside == EVAL_AVOID_SIDE_EFFECTS)
8999               return allocate_value (ada_aligned_type (type));
9000             return
9001               unwrap_value (ada_value_subscript
9002                             (argvec[0], nargs, argvec + 1));
9003           }
9004         case TYPE_CODE_ARRAY:
9005           if (noside == EVAL_AVOID_SIDE_EFFECTS)
9006             {
9007               type = ada_array_element_type (type, nargs);
9008               if (type == NULL)
9009                 error ("element type of array unknown");
9010               else
9011                 return allocate_value (ada_aligned_type (type));
9012             }
9013           return
9014             unwrap_value (ada_value_subscript
9015                           (ada_coerce_to_simple_array (argvec[0]),
9016                            nargs, argvec + 1));
9017         case TYPE_CODE_PTR:     /* Pointer to array */
9018           type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
9019           if (noside == EVAL_AVOID_SIDE_EFFECTS)
9020             {
9021               type = ada_array_element_type (type, nargs);
9022               if (type == NULL)
9023                 error ("element type of array unknown");
9024               else
9025                 return allocate_value (ada_aligned_type (type));
9026             }
9027           return
9028             unwrap_value (ada_value_ptr_subscript (argvec[0], type,
9029                                                    nargs, argvec + 1));
9030
9031         default:
9032           error ("Internal error in evaluate_subexp");
9033         }
9034
9035     case TERNOP_SLICE:
9036       {
9037         struct value *array = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9038         struct value *low_bound_val =
9039           evaluate_subexp (NULL_TYPE, exp, pos, noside);
9040         LONGEST low_bound = pos_atr (low_bound_val);
9041         LONGEST high_bound
9042           = pos_atr (evaluate_subexp (NULL_TYPE, exp, pos, noside));
9043         if (noside == EVAL_SKIP)
9044           goto nosideret;
9045
9046         /* If this is a reference to an aligner type, then remove all
9047            the aligners.  */
9048         if (TYPE_CODE (VALUE_TYPE (array)) == TYPE_CODE_REF
9049             && ada_is_aligner_type (TYPE_TARGET_TYPE (VALUE_TYPE (array))))
9050           TYPE_TARGET_TYPE (VALUE_TYPE (array)) =
9051             ada_aligned_type (TYPE_TARGET_TYPE (VALUE_TYPE (array)));
9052
9053         if (ada_is_packed_array_type (VALUE_TYPE (array)))
9054           error ("cannot slice a packed array");
9055
9056         /* If this is a reference to an array or an array lvalue,
9057            convert to a pointer.  */
9058         if (TYPE_CODE (VALUE_TYPE (array)) == TYPE_CODE_REF
9059             || (TYPE_CODE (VALUE_TYPE (array)) == TYPE_CODE_ARRAY
9060                 && VALUE_LVAL (array) == lval_memory))
9061           array = value_addr (array);
9062
9063         if (noside == EVAL_AVOID_SIDE_EFFECTS
9064             && ada_is_array_descriptor_type (check_typedef
9065                                              (VALUE_TYPE (array))))
9066           return empty_array (ada_type_of_array (array, 0), low_bound);
9067
9068         array = ada_coerce_to_simple_array_ptr (array);
9069
9070         if (TYPE_CODE (VALUE_TYPE (array)) == TYPE_CODE_PTR)
9071           {
9072             if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
9073               return empty_array (TYPE_TARGET_TYPE (VALUE_TYPE (array)),
9074                                   low_bound);
9075             else
9076               {
9077                 struct type *arr_type0 =
9078                   to_fixed_array_type (TYPE_TARGET_TYPE (VALUE_TYPE (array)),
9079                                        NULL, 1);
9080                 return ada_value_slice_ptr (array, arr_type0,
9081                                             (int) low_bound, 
9082                                             (int) high_bound);
9083               }
9084           }
9085         else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9086           return array;
9087         else if (high_bound < low_bound)
9088           return empty_array (VALUE_TYPE (array), low_bound);
9089         else
9090           return ada_value_slice (array, (int) low_bound, (int) high_bound);
9091       }
9092
9093     case UNOP_IN_RANGE:
9094       (*pos) += 2;
9095       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9096       type = exp->elts[pc + 1].type;
9097
9098       if (noside == EVAL_SKIP)
9099         goto nosideret;
9100
9101       switch (TYPE_CODE (type))
9102         {
9103         default:
9104           lim_warning ("Membership test incompletely implemented; "
9105                        "always returns true", 0);
9106           return value_from_longest (builtin_type_int, (LONGEST) 1);
9107
9108         case TYPE_CODE_RANGE:
9109           arg2 = value_from_longest (builtin_type_int, TYPE_LOW_BOUND (type));
9110           arg3 = value_from_longest (builtin_type_int,
9111                                      TYPE_HIGH_BOUND (type));
9112           return
9113             value_from_longest (builtin_type_int,
9114                                 (value_less (arg1, arg3)
9115                                  || value_equal (arg1, arg3))
9116                                 && (value_less (arg2, arg1)
9117                                     || value_equal (arg2, arg1)));
9118         }
9119
9120     case BINOP_IN_BOUNDS:
9121       (*pos) += 2;
9122       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9123       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9124
9125       if (noside == EVAL_SKIP)
9126         goto nosideret;
9127
9128       if (noside == EVAL_AVOID_SIDE_EFFECTS)
9129         return value_zero (builtin_type_int, not_lval);
9130
9131       tem = longest_to_int (exp->elts[pc + 1].longconst);
9132
9133       if (tem < 1 || tem > ada_array_arity (VALUE_TYPE (arg2)))
9134         error ("invalid dimension number to '%s", "range");
9135
9136       arg3 = ada_array_bound (arg2, tem, 1);
9137       arg2 = ada_array_bound (arg2, tem, 0);
9138
9139       return
9140         value_from_longest (builtin_type_int,
9141                             (value_less (arg1, arg3)
9142                              || value_equal (arg1, arg3))
9143                             && (value_less (arg2, arg1)
9144                                 || value_equal (arg2, arg1)));
9145
9146     case TERNOP_IN_RANGE:
9147       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9148       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9149       arg3 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9150
9151       if (noside == EVAL_SKIP)
9152         goto nosideret;
9153
9154       return
9155         value_from_longest (builtin_type_int,
9156                             (value_less (arg1, arg3)
9157                              || value_equal (arg1, arg3))
9158                             && (value_less (arg2, arg1)
9159                                 || value_equal (arg2, arg1)));
9160
9161     case OP_ATR_FIRST:
9162     case OP_ATR_LAST:
9163     case OP_ATR_LENGTH:
9164       {
9165         struct type *type_arg;
9166         if (exp->elts[*pos].opcode == OP_TYPE)
9167           {
9168             evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
9169             arg1 = NULL;
9170             type_arg = exp->elts[pc + 2].type;
9171           }
9172         else
9173           {
9174             arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9175             type_arg = NULL;
9176           }
9177
9178         if (exp->elts[*pos].opcode != OP_LONG)
9179           error ("illegal operand to '%s", ada_attribute_name (op));
9180         tem = longest_to_int (exp->elts[*pos + 2].longconst);
9181         *pos += 4;
9182
9183         if (noside == EVAL_SKIP)
9184           goto nosideret;
9185
9186         if (type_arg == NULL)
9187           {
9188             arg1 = ada_coerce_ref (arg1);
9189
9190             if (ada_is_packed_array_type (VALUE_TYPE (arg1)))
9191               arg1 = ada_coerce_to_simple_array (arg1);
9192
9193             if (tem < 1 || tem > ada_array_arity (VALUE_TYPE (arg1)))
9194               error ("invalid dimension number to '%s",
9195                      ada_attribute_name (op));
9196
9197             if (noside == EVAL_AVOID_SIDE_EFFECTS)
9198               {
9199                 type = ada_index_type (VALUE_TYPE (arg1), tem);
9200                 if (type == NULL)
9201                   error
9202                     ("attempt to take bound of something that is not an array");
9203                 return allocate_value (type);
9204               }
9205
9206             switch (op)
9207               {
9208               default:          /* Should never happen.  */
9209                 error ("unexpected attribute encountered");
9210               case OP_ATR_FIRST:
9211                 return ada_array_bound (arg1, tem, 0);
9212               case OP_ATR_LAST:
9213                 return ada_array_bound (arg1, tem, 1);
9214               case OP_ATR_LENGTH:
9215                 return ada_array_length (arg1, tem);
9216               }
9217           }
9218         else if (discrete_type_p (type_arg))
9219           {
9220             struct type *range_type;
9221             char *name = ada_type_name (type_arg);
9222             range_type = NULL;
9223             if (name != NULL && TYPE_CODE (type_arg) != TYPE_CODE_ENUM)
9224               range_type =
9225                 to_fixed_range_type (name, NULL, TYPE_OBJFILE (type_arg));
9226             if (range_type == NULL)
9227               range_type = type_arg;
9228             switch (op)
9229               {
9230               default:
9231                 error ("unexpected attribute encountered");
9232               case OP_ATR_FIRST:
9233                 return discrete_type_low_bound (range_type);
9234               case OP_ATR_LAST:
9235                 return discrete_type_high_bound (range_type);
9236               case OP_ATR_LENGTH:
9237                 error ("the 'length attribute applies only to array types");
9238               }
9239           }
9240         else if (TYPE_CODE (type_arg) == TYPE_CODE_FLT)
9241           error ("unimplemented type attribute");
9242         else
9243           {
9244             LONGEST low, high;
9245
9246             if (ada_is_packed_array_type (type_arg))
9247               type_arg = decode_packed_array_type (type_arg);
9248
9249             if (tem < 1 || tem > ada_array_arity (type_arg))
9250               error ("invalid dimension number to '%s",
9251                      ada_attribute_name (op));
9252
9253             type = ada_index_type (type_arg, tem);
9254             if (type == NULL)
9255               error
9256                 ("attempt to take bound of something that is not an array");
9257             if (noside == EVAL_AVOID_SIDE_EFFECTS)
9258               return allocate_value (type);
9259
9260             switch (op)
9261               {
9262               default:
9263                 error ("unexpected attribute encountered");
9264               case OP_ATR_FIRST:
9265                 low = ada_array_bound_from_type (type_arg, tem, 0, &type);
9266                 return value_from_longest (type, low);
9267               case OP_ATR_LAST:
9268                 high = ada_array_bound_from_type (type_arg, tem, 1, &type);
9269                 return value_from_longest (type, high);
9270               case OP_ATR_LENGTH:
9271                 low = ada_array_bound_from_type (type_arg, tem, 0, &type);
9272                 high = ada_array_bound_from_type (type_arg, tem, 1, NULL);
9273                 return value_from_longest (type, high - low + 1);
9274               }
9275           }
9276       }
9277
9278     case OP_ATR_TAG:
9279       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9280       if (noside == EVAL_SKIP)
9281         goto nosideret;
9282
9283       if (noside == EVAL_AVOID_SIDE_EFFECTS)
9284         return value_zero (ada_tag_type (arg1), not_lval);
9285
9286       return ada_value_tag (arg1);
9287
9288     case OP_ATR_MIN:
9289     case OP_ATR_MAX:
9290       evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
9291       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9292       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9293       if (noside == EVAL_SKIP)
9294         goto nosideret;
9295       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9296         return value_zero (VALUE_TYPE (arg1), not_lval);
9297       else
9298         return value_binop (arg1, arg2,
9299                             op == OP_ATR_MIN ? BINOP_MIN : BINOP_MAX);
9300
9301     case OP_ATR_MODULUS:
9302       {
9303         struct type *type_arg = exp->elts[pc + 2].type;
9304         evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
9305
9306         if (noside == EVAL_SKIP)
9307           goto nosideret;
9308
9309         if (!ada_is_modular_type (type_arg))
9310           error ("'modulus must be applied to modular type");
9311
9312         return value_from_longest (TYPE_TARGET_TYPE (type_arg),
9313                                    ada_modulus (type_arg));
9314       }
9315
9316
9317     case OP_ATR_POS:
9318       evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
9319       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9320       if (noside == EVAL_SKIP)
9321         goto nosideret;
9322       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9323         return value_zero (builtin_type_ada_int, not_lval);
9324       else
9325         return value_pos_atr (arg1);
9326
9327     case OP_ATR_SIZE:
9328       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9329       if (noside == EVAL_SKIP)
9330         goto nosideret;
9331       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9332         return value_zero (builtin_type_ada_int, not_lval);
9333       else
9334         return value_from_longest (builtin_type_ada_int,
9335                                    TARGET_CHAR_BIT
9336                                    * TYPE_LENGTH (VALUE_TYPE (arg1)));
9337
9338     case OP_ATR_VAL:
9339       evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
9340       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9341       type = exp->elts[pc + 2].type;
9342       if (noside == EVAL_SKIP)
9343         goto nosideret;
9344       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9345         return value_zero (type, not_lval);
9346       else
9347         return value_val_atr (type, arg1);
9348
9349     case BINOP_EXP:
9350       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9351       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9352       if (noside == EVAL_SKIP)
9353         goto nosideret;
9354       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9355         return value_zero (VALUE_TYPE (arg1), not_lval);
9356       else
9357         return value_binop (arg1, arg2, op);
9358
9359     case UNOP_PLUS:
9360       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9361       if (noside == EVAL_SKIP)
9362         goto nosideret;
9363       else
9364         return arg1;
9365
9366     case UNOP_ABS:
9367       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9368       if (noside == EVAL_SKIP)
9369         goto nosideret;
9370       if (value_less (arg1, value_zero (VALUE_TYPE (arg1), not_lval)))
9371         return value_neg (arg1);
9372       else
9373         return arg1;
9374
9375     case UNOP_IND:
9376       if (expect_type && TYPE_CODE (expect_type) == TYPE_CODE_PTR)
9377         expect_type = TYPE_TARGET_TYPE (check_typedef (expect_type));
9378       arg1 = evaluate_subexp (expect_type, exp, pos, noside);
9379       if (noside == EVAL_SKIP)
9380         goto nosideret;
9381       type = check_typedef (VALUE_TYPE (arg1));
9382       if (noside == EVAL_AVOID_SIDE_EFFECTS)
9383         {
9384           if (ada_is_array_descriptor_type (type))
9385             /* GDB allows dereferencing GNAT array descriptors.  */
9386             {
9387               struct type *arrType = ada_type_of_array (arg1, 0);
9388               if (arrType == NULL)
9389                 error ("Attempt to dereference null array pointer.");
9390               return value_at_lazy (arrType, 0, NULL);
9391             }
9392           else if (TYPE_CODE (type) == TYPE_CODE_PTR
9393                    || TYPE_CODE (type) == TYPE_CODE_REF
9394                    /* In C you can dereference an array to get the 1st elt.  */
9395                    || TYPE_CODE (type) == TYPE_CODE_ARRAY)
9396             return
9397               value_zero
9398               (to_static_fixed_type
9399                (ada_aligned_type (check_typedef (TYPE_TARGET_TYPE (type)))),
9400                lval_memory);
9401           else if (TYPE_CODE (type) == TYPE_CODE_INT)
9402             /* GDB allows dereferencing an int.  */
9403             return value_zero (builtin_type_int, lval_memory);
9404           else
9405             error ("Attempt to take contents of a non-pointer value.");
9406         }
9407       arg1 = ada_coerce_ref (arg1);     /* FIXME: What is this for?? */
9408       type = check_typedef (VALUE_TYPE (arg1));
9409
9410       if (ada_is_array_descriptor_type (type))
9411         /* GDB allows dereferencing GNAT array descriptors.  */
9412         return ada_coerce_to_simple_array (arg1);
9413       else
9414         return ada_value_ind (arg1);
9415
9416     case STRUCTOP_STRUCT:
9417       tem = longest_to_int (exp->elts[pc + 1].longconst);
9418       (*pos) += 3 + BYTES_TO_EXP_ELEM (tem + 1);
9419       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9420       if (noside == EVAL_SKIP)
9421         goto nosideret;
9422       if (noside == EVAL_AVOID_SIDE_EFFECTS)
9423         {
9424           struct type *type1 = VALUE_TYPE (arg1);
9425           if (ada_is_tagged_type (type1, 1))
9426             {
9427               type = ada_lookup_struct_elt_type (type1,
9428                                                  &exp->elts[pc + 2].string,
9429                                                  1, 1, NULL);
9430               if (type == NULL)
9431                 /* In this case, we assume that the field COULD exist
9432                    in some extension of the type.  Return an object of 
9433                    "type" void, which will match any formal 
9434                    (see ada_type_match). */
9435                 return value_zero (builtin_type_void, lval_memory);
9436             }
9437           else
9438             type =
9439               ada_lookup_struct_elt_type (type1, &exp->elts[pc + 2].string, 1,
9440                                           0, NULL);
9441
9442           return value_zero (ada_aligned_type (type), lval_memory);
9443         }
9444       else
9445         return
9446           ada_to_fixed_value (unwrap_value
9447                               (ada_value_struct_elt
9448                                (arg1, &exp->elts[pc + 2].string, "record")));
9449     case OP_TYPE:
9450       /* The value is not supposed to be used.  This is here to make it
9451          easier to accommodate expressions that contain types.  */
9452       (*pos) += 2;
9453       if (noside == EVAL_SKIP)
9454         goto nosideret;
9455       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9456         return allocate_value (builtin_type_void);
9457       else
9458         error ("Attempt to use a type name as an expression");
9459     }
9460
9461 nosideret:
9462   return value_from_longest (builtin_type_long, (LONGEST) 1);
9463 }
9464 \f
9465
9466                                 /* Fixed point */
9467
9468 /* If TYPE encodes an Ada fixed-point type, return the suffix of the
9469    type name that encodes the 'small and 'delta information.
9470    Otherwise, return NULL.  */
9471
9472 static const char *
9473 fixed_type_info (struct type *type)
9474 {
9475   const char *name = ada_type_name (type);
9476   enum type_code code = (type == NULL) ? TYPE_CODE_UNDEF : TYPE_CODE (type);
9477
9478   if ((code == TYPE_CODE_INT || code == TYPE_CODE_RANGE) && name != NULL)
9479     {
9480       const char *tail = strstr (name, "___XF_");
9481       if (tail == NULL)
9482         return NULL;
9483       else
9484         return tail + 5;
9485     }
9486   else if (code == TYPE_CODE_RANGE && TYPE_TARGET_TYPE (type) != type)
9487     return fixed_type_info (TYPE_TARGET_TYPE (type));
9488   else
9489     return NULL;
9490 }
9491
9492 /* Returns non-zero iff TYPE represents an Ada fixed-point type.  */
9493
9494 int
9495 ada_is_fixed_point_type (struct type *type)
9496 {
9497   return fixed_type_info (type) != NULL;
9498 }
9499
9500 /* Return non-zero iff TYPE represents a System.Address type.  */
9501
9502 int
9503 ada_is_system_address_type (struct type *type)
9504 {
9505   return (TYPE_NAME (type)
9506           && strcmp (TYPE_NAME (type), "system__address") == 0);
9507 }
9508
9509 /* Assuming that TYPE is the representation of an Ada fixed-point
9510    type, return its delta, or -1 if the type is malformed and the
9511    delta cannot be determined.  */
9512
9513 DOUBLEST
9514 ada_delta (struct type *type)
9515 {
9516   const char *encoding = fixed_type_info (type);
9517   long num, den;
9518
9519   if (sscanf (encoding, "_%ld_%ld", &num, &den) < 2)
9520     return -1.0;
9521   else
9522     return (DOUBLEST) num / (DOUBLEST) den;
9523 }
9524
9525 /* Assuming that ada_is_fixed_point_type (TYPE), return the scaling
9526    factor ('SMALL value) associated with the type.  */
9527
9528 static DOUBLEST
9529 scaling_factor (struct type *type)
9530 {
9531   const char *encoding = fixed_type_info (type);
9532   unsigned long num0, den0, num1, den1;
9533   int n;
9534
9535   n = sscanf (encoding, "_%lu_%lu_%lu_%lu", &num0, &den0, &num1, &den1);
9536
9537   if (n < 2)
9538     return 1.0;
9539   else if (n == 4)
9540     return (DOUBLEST) num1 / (DOUBLEST) den1;
9541   else
9542     return (DOUBLEST) num0 / (DOUBLEST) den0;
9543 }
9544
9545
9546 /* Assuming that X is the representation of a value of fixed-point
9547    type TYPE, return its floating-point equivalent.  */
9548
9549 DOUBLEST
9550 ada_fixed_to_float (struct type *type, LONGEST x)
9551 {
9552   return (DOUBLEST) x *scaling_factor (type);
9553 }
9554
9555 /* The representation of a fixed-point value of type TYPE
9556    corresponding to the value X.  */
9557
9558 LONGEST
9559 ada_float_to_fixed (struct type *type, DOUBLEST x)
9560 {
9561   return (LONGEST) (x / scaling_factor (type) + 0.5);
9562 }
9563
9564
9565                                 /* VAX floating formats */
9566
9567 /* Non-zero iff TYPE represents one of the special VAX floating-point
9568    types.  */
9569
9570 int
9571 ada_is_vax_floating_type (struct type *type)
9572 {
9573   int name_len =
9574     (ada_type_name (type) == NULL) ? 0 : strlen (ada_type_name (type));
9575   return
9576     name_len > 6
9577     && (TYPE_CODE (type) == TYPE_CODE_INT
9578         || TYPE_CODE (type) == TYPE_CODE_RANGE)
9579     && strncmp (ada_type_name (type) + name_len - 6, "___XF", 5) == 0;
9580 }
9581
9582 /* The type of special VAX floating-point type this is, assuming
9583    ada_is_vax_floating_point.  */
9584
9585 int
9586 ada_vax_float_type_suffix (struct type *type)
9587 {
9588   return ada_type_name (type)[strlen (ada_type_name (type)) - 1];
9589 }
9590
9591 /* A value representing the special debugging function that outputs
9592    VAX floating-point values of the type represented by TYPE.  Assumes
9593    ada_is_vax_floating_type (TYPE).  */
9594
9595 struct value *
9596 ada_vax_float_print_function (struct type *type)
9597 {
9598   switch (ada_vax_float_type_suffix (type))
9599     {
9600     case 'F':
9601       return get_var_value ("DEBUG_STRING_F", 0);
9602     case 'D':
9603       return get_var_value ("DEBUG_STRING_D", 0);
9604     case 'G':
9605       return get_var_value ("DEBUG_STRING_G", 0);
9606     default:
9607       error ("invalid VAX floating-point type");
9608     }
9609 }
9610 \f
9611
9612                                 /* Range types */
9613
9614 /* Scan STR beginning at position K for a discriminant name, and
9615    return the value of that discriminant field of DVAL in *PX.  If
9616    PNEW_K is not null, put the position of the character beyond the
9617    name scanned in *PNEW_K.  Return 1 if successful; return 0 and do
9618    not alter *PX and *PNEW_K if unsuccessful.  */
9619
9620 static int
9621 scan_discrim_bound (char *str, int k, struct value *dval, LONGEST * px,
9622                     int *pnew_k)
9623 {
9624   static char *bound_buffer = NULL;
9625   static size_t bound_buffer_len = 0;
9626   char *bound;
9627   char *pend;
9628   struct value *bound_val;
9629
9630   if (dval == NULL || str == NULL || str[k] == '\0')
9631     return 0;
9632
9633   pend = strstr (str + k, "__");
9634   if (pend == NULL)
9635     {
9636       bound = str + k;
9637       k += strlen (bound);
9638     }
9639   else
9640     {
9641       GROW_VECT (bound_buffer, bound_buffer_len, pend - (str + k) + 1);
9642       bound = bound_buffer;
9643       strncpy (bound_buffer, str + k, pend - (str + k));
9644       bound[pend - (str + k)] = '\0';
9645       k = pend - str;
9646     }
9647
9648   bound_val = ada_search_struct_field (bound, dval, 0, VALUE_TYPE (dval));
9649   if (bound_val == NULL)
9650     return 0;
9651
9652   *px = value_as_long (bound_val);
9653   if (pnew_k != NULL)
9654     *pnew_k = k;
9655   return 1;
9656 }
9657
9658 /* Value of variable named NAME in the current environment.  If
9659    no such variable found, then if ERR_MSG is null, returns 0, and
9660    otherwise causes an error with message ERR_MSG.  */
9661
9662 static struct value *
9663 get_var_value (char *name, char *err_msg)
9664 {
9665   struct ada_symbol_info *syms;
9666   int nsyms;
9667
9668   nsyms = ada_lookup_symbol_list (name, get_selected_block (0), VAR_DOMAIN,
9669                                   &syms);
9670
9671   if (nsyms != 1)
9672     {
9673       if (err_msg == NULL)
9674         return 0;
9675       else
9676         error ("%s", err_msg);
9677     }
9678
9679   return value_of_variable (syms[0].sym, syms[0].block);
9680 }
9681
9682 /* Value of integer variable named NAME in the current environment.  If
9683    no such variable found, returns 0, and sets *FLAG to 0.  If
9684    successful, sets *FLAG to 1.  */
9685
9686 LONGEST
9687 get_int_var_value (char *name, int *flag)
9688 {
9689   struct value *var_val = get_var_value (name, 0);
9690
9691   if (var_val == 0)
9692     {
9693       if (flag != NULL)
9694         *flag = 0;
9695       return 0;
9696     }
9697   else
9698     {
9699       if (flag != NULL)
9700         *flag = 1;
9701       return value_as_long (var_val);
9702     }
9703 }
9704
9705
9706 /* Return a range type whose base type is that of the range type named
9707    NAME in the current environment, and whose bounds are calculated
9708    from NAME according to the GNAT range encoding conventions.
9709    Extract discriminant values, if needed, from DVAL.  If a new type
9710    must be created, allocate in OBJFILE's space.  The bounds
9711    information, in general, is encoded in NAME, the base type given in
9712    the named range type.  */
9713
9714 static struct type *
9715 to_fixed_range_type (char *name, struct value *dval, struct objfile *objfile)
9716 {
9717   struct type *raw_type = ada_find_any_type (name);
9718   struct type *base_type;
9719   char *subtype_info;
9720
9721   if (raw_type == NULL)
9722     base_type = builtin_type_int;
9723   else if (TYPE_CODE (raw_type) == TYPE_CODE_RANGE)
9724     base_type = TYPE_TARGET_TYPE (raw_type);
9725   else
9726     base_type = raw_type;
9727
9728   subtype_info = strstr (name, "___XD");
9729   if (subtype_info == NULL)
9730     return raw_type;
9731   else
9732     {
9733       static char *name_buf = NULL;
9734       static size_t name_len = 0;
9735       int prefix_len = subtype_info - name;
9736       LONGEST L, U;
9737       struct type *type;
9738       char *bounds_str;
9739       int n;
9740
9741       GROW_VECT (name_buf, name_len, prefix_len + 5);
9742       strncpy (name_buf, name, prefix_len);
9743       name_buf[prefix_len] = '\0';
9744
9745       subtype_info += 5;
9746       bounds_str = strchr (subtype_info, '_');
9747       n = 1;
9748
9749       if (*subtype_info == 'L')
9750         {
9751           if (!ada_scan_number (bounds_str, n, &L, &n)
9752               && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
9753             return raw_type;
9754           if (bounds_str[n] == '_')
9755             n += 2;
9756           else if (bounds_str[n] == '.')        /* FIXME? SGI Workshop kludge.  */
9757             n += 1;
9758           subtype_info += 1;
9759         }
9760       else
9761         {
9762           int ok;
9763           strcpy (name_buf + prefix_len, "___L");
9764           L = get_int_var_value (name_buf, &ok);
9765           if (!ok)
9766             {
9767               lim_warning ("Unknown lower bound, using 1.", 1);
9768               L = 1;
9769             }
9770         }
9771
9772       if (*subtype_info == 'U')
9773         {
9774           if (!ada_scan_number (bounds_str, n, &U, &n)
9775               && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
9776             return raw_type;
9777         }
9778       else
9779         {
9780           int ok;
9781           strcpy (name_buf + prefix_len, "___U");
9782           U = get_int_var_value (name_buf, &ok);
9783           if (!ok)
9784             {
9785               lim_warning ("Unknown upper bound, using %ld.", (long) L);
9786               U = L;
9787             }
9788         }
9789
9790       if (objfile == NULL)
9791         objfile = TYPE_OBJFILE (base_type);
9792       type = create_range_type (alloc_type (objfile), base_type, L, U);
9793       TYPE_NAME (type) = name;
9794       return type;
9795     }
9796 }
9797
9798 /* True iff NAME is the name of a range type.  */
9799
9800 int
9801 ada_is_range_type_name (const char *name)
9802 {
9803   return (name != NULL && strstr (name, "___XD"));
9804 }
9805 \f
9806
9807                                 /* Modular types */
9808
9809 /* True iff TYPE is an Ada modular type.  */
9810
9811 int
9812 ada_is_modular_type (struct type *type)
9813 {
9814   struct type *subranged_type = base_type (type);
9815
9816   return (subranged_type != NULL && TYPE_CODE (type) == TYPE_CODE_RANGE
9817           && TYPE_CODE (subranged_type) != TYPE_CODE_ENUM
9818           && TYPE_UNSIGNED (subranged_type));
9819 }
9820
9821 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE.  */
9822
9823 LONGEST
9824 ada_modulus (struct type * type)
9825 {
9826   return TYPE_HIGH_BOUND (type) + 1;
9827 }
9828 \f
9829                                 /* Operators */
9830 /* Information about operators given special treatment in functions
9831    below.  */
9832 /* Format: OP_DEFN (<operator>, <operator length>, <# args>, <binop>).  */
9833
9834 #define ADA_OPERATORS \
9835     OP_DEFN (OP_VAR_VALUE, 4, 0, 0) \
9836     OP_DEFN (BINOP_IN_BOUNDS, 3, 2, 0) \
9837     OP_DEFN (TERNOP_IN_RANGE, 1, 3, 0) \
9838     OP_DEFN (OP_ATR_FIRST, 1, 2, 0) \
9839     OP_DEFN (OP_ATR_LAST, 1, 2, 0) \
9840     OP_DEFN (OP_ATR_LENGTH, 1, 2, 0) \
9841     OP_DEFN (OP_ATR_IMAGE, 1, 2, 0) \
9842     OP_DEFN (OP_ATR_MAX, 1, 3, 0) \
9843     OP_DEFN (OP_ATR_MIN, 1, 3, 0) \
9844     OP_DEFN (OP_ATR_MODULUS, 1, 1, 0) \
9845     OP_DEFN (OP_ATR_POS, 1, 2, 0) \
9846     OP_DEFN (OP_ATR_SIZE, 1, 1, 0) \
9847     OP_DEFN (OP_ATR_TAG, 1, 1, 0) \
9848     OP_DEFN (OP_ATR_VAL, 1, 2, 0) \
9849     OP_DEFN (UNOP_QUAL, 3, 1, 0) \
9850     OP_DEFN (UNOP_IN_RANGE, 3, 1, 0)
9851
9852 static void
9853 ada_operator_length (struct expression *exp, int pc, int *oplenp, int *argsp)
9854 {
9855   switch (exp->elts[pc - 1].opcode)
9856     {
9857     default:
9858       operator_length_standard (exp, pc, oplenp, argsp);
9859       break;
9860
9861 #define OP_DEFN(op, len, args, binop) \
9862     case op: *oplenp = len; *argsp = args; break;
9863       ADA_OPERATORS;
9864 #undef OP_DEFN
9865     }
9866 }
9867
9868 static char *
9869 ada_op_name (enum exp_opcode opcode)
9870 {
9871   switch (opcode)
9872     {
9873     default:
9874       return op_name_standard (opcode);
9875 #define OP_DEFN(op, len, args, binop) case op: return #op;
9876       ADA_OPERATORS;
9877 #undef OP_DEFN
9878     }
9879 }
9880
9881 /* As for operator_length, but assumes PC is pointing at the first
9882    element of the operator, and gives meaningful results only for the 
9883    Ada-specific operators.  */
9884
9885 static void
9886 ada_forward_operator_length (struct expression *exp, int pc,
9887                              int *oplenp, int *argsp)
9888 {
9889   switch (exp->elts[pc].opcode)
9890     {
9891     default:
9892       *oplenp = *argsp = 0;
9893       break;
9894 #define OP_DEFN(op, len, args, binop) \
9895     case op: *oplenp = len; *argsp = args; break;
9896       ADA_OPERATORS;
9897 #undef OP_DEFN
9898     }
9899 }
9900
9901 static int
9902 ada_dump_subexp_body (struct expression *exp, struct ui_file *stream, int elt)
9903 {
9904   enum exp_opcode op = exp->elts[elt].opcode;
9905   int oplen, nargs;
9906   int pc = elt;
9907   int i;
9908
9909   ada_forward_operator_length (exp, elt, &oplen, &nargs);
9910
9911   switch (op)
9912     {
9913       /* Ada attributes ('Foo).  */
9914     case OP_ATR_FIRST:
9915     case OP_ATR_LAST:
9916     case OP_ATR_LENGTH:
9917     case OP_ATR_IMAGE:
9918     case OP_ATR_MAX:
9919     case OP_ATR_MIN:
9920     case OP_ATR_MODULUS:
9921     case OP_ATR_POS:
9922     case OP_ATR_SIZE:
9923     case OP_ATR_TAG:
9924     case OP_ATR_VAL:
9925       break;
9926
9927     case UNOP_IN_RANGE:
9928     case UNOP_QUAL:
9929       fprintf_filtered (stream, "Type @");
9930       gdb_print_host_address (exp->elts[pc + 1].type, stream);
9931       fprintf_filtered (stream, " (");
9932       type_print (exp->elts[pc + 1].type, NULL, stream, 0);
9933       fprintf_filtered (stream, ")");
9934       break;
9935     case BINOP_IN_BOUNDS:
9936       fprintf_filtered (stream, " (%d)", (int) exp->elts[pc + 2].longconst);
9937       break;
9938     case TERNOP_IN_RANGE:
9939       break;
9940
9941     default:
9942       return dump_subexp_body_standard (exp, stream, elt);
9943     }
9944
9945   elt += oplen;
9946   for (i = 0; i < nargs; i += 1)
9947     elt = dump_subexp (exp, stream, elt);
9948
9949   return elt;
9950 }
9951
9952 /* The Ada extension of print_subexp (q.v.).  */
9953
9954 static void
9955 ada_print_subexp (struct expression *exp, int *pos,
9956                   struct ui_file *stream, enum precedence prec)
9957 {
9958   int oplen, nargs;
9959   int pc = *pos;
9960   enum exp_opcode op = exp->elts[pc].opcode;
9961
9962   ada_forward_operator_length (exp, pc, &oplen, &nargs);
9963
9964   switch (op)
9965     {
9966     default:
9967       print_subexp_standard (exp, pos, stream, prec);
9968       return;
9969
9970     case OP_VAR_VALUE:
9971       *pos += oplen;
9972       fputs_filtered (SYMBOL_NATURAL_NAME (exp->elts[pc + 2].symbol), stream);
9973       return;
9974
9975     case BINOP_IN_BOUNDS:
9976       *pos += oplen;
9977       print_subexp (exp, pos, stream, PREC_SUFFIX);
9978       fputs_filtered (" in ", stream);
9979       print_subexp (exp, pos, stream, PREC_SUFFIX);
9980       fputs_filtered ("'range", stream);
9981       if (exp->elts[pc + 1].longconst > 1)
9982         fprintf_filtered (stream, "(%ld)",
9983                           (long) exp->elts[pc + 1].longconst);
9984       return;
9985
9986     case TERNOP_IN_RANGE:
9987       *pos += oplen;
9988       if (prec >= PREC_EQUAL)
9989         fputs_filtered ("(", stream);
9990       print_subexp (exp, pos, stream, PREC_SUFFIX);
9991       fputs_filtered (" in ", stream);
9992       print_subexp (exp, pos, stream, PREC_EQUAL);
9993       fputs_filtered (" .. ", stream);
9994       print_subexp (exp, pos, stream, PREC_EQUAL);
9995       if (prec >= PREC_EQUAL)
9996         fputs_filtered (")", stream);
9997       return;
9998
9999     case OP_ATR_FIRST:
10000     case OP_ATR_LAST:
10001     case OP_ATR_LENGTH:
10002     case OP_ATR_IMAGE:
10003     case OP_ATR_MAX:
10004     case OP_ATR_MIN:
10005     case OP_ATR_MODULUS:
10006     case OP_ATR_POS:
10007     case OP_ATR_SIZE:
10008     case OP_ATR_TAG:
10009     case OP_ATR_VAL:
10010       *pos += oplen;
10011       if (exp->elts[*pos].opcode == OP_TYPE)
10012         {
10013           if (TYPE_CODE (exp->elts[*pos + 1].type) != TYPE_CODE_VOID)
10014             LA_PRINT_TYPE (exp->elts[*pos + 1].type, "", stream, 0, 0);
10015           *pos += 3;
10016         }
10017       else
10018         print_subexp (exp, pos, stream, PREC_SUFFIX);
10019       fprintf_filtered (stream, "'%s", ada_attribute_name (op));
10020       if (nargs > 1)
10021         {
10022           int tem;
10023           for (tem = 1; tem < nargs; tem += 1)
10024             {
10025               fputs_filtered ((tem == 1) ? " (" : ", ", stream);
10026               print_subexp (exp, pos, stream, PREC_ABOVE_COMMA);
10027             }
10028           fputs_filtered (")", stream);
10029         }
10030       return;
10031
10032     case UNOP_QUAL:
10033       *pos += oplen;
10034       type_print (exp->elts[pc + 1].type, "", stream, 0);
10035       fputs_filtered ("'(", stream);
10036       print_subexp (exp, pos, stream, PREC_PREFIX);
10037       fputs_filtered (")", stream);
10038       return;
10039
10040     case UNOP_IN_RANGE:
10041       *pos += oplen;
10042       print_subexp (exp, pos, stream, PREC_SUFFIX);
10043       fputs_filtered (" in ", stream);
10044       LA_PRINT_TYPE (exp->elts[pc + 1].type, "", stream, 1, 0);
10045       return;
10046     }
10047 }
10048
10049 /* Table mapping opcodes into strings for printing operators
10050    and precedences of the operators.  */
10051
10052 static const struct op_print ada_op_print_tab[] = {
10053   {":=", BINOP_ASSIGN, PREC_ASSIGN, 1},
10054   {"or else", BINOP_LOGICAL_OR, PREC_LOGICAL_OR, 0},
10055   {"and then", BINOP_LOGICAL_AND, PREC_LOGICAL_AND, 0},
10056   {"or", BINOP_BITWISE_IOR, PREC_BITWISE_IOR, 0},
10057   {"xor", BINOP_BITWISE_XOR, PREC_BITWISE_XOR, 0},
10058   {"and", BINOP_BITWISE_AND, PREC_BITWISE_AND, 0},
10059   {"=", BINOP_EQUAL, PREC_EQUAL, 0},
10060   {"/=", BINOP_NOTEQUAL, PREC_EQUAL, 0},
10061   {"<=", BINOP_LEQ, PREC_ORDER, 0},
10062   {">=", BINOP_GEQ, PREC_ORDER, 0},
10063   {">", BINOP_GTR, PREC_ORDER, 0},
10064   {"<", BINOP_LESS, PREC_ORDER, 0},
10065   {">>", BINOP_RSH, PREC_SHIFT, 0},
10066   {"<<", BINOP_LSH, PREC_SHIFT, 0},
10067   {"+", BINOP_ADD, PREC_ADD, 0},
10068   {"-", BINOP_SUB, PREC_ADD, 0},
10069   {"&", BINOP_CONCAT, PREC_ADD, 0},
10070   {"*", BINOP_MUL, PREC_MUL, 0},
10071   {"/", BINOP_DIV, PREC_MUL, 0},
10072   {"rem", BINOP_REM, PREC_MUL, 0},
10073   {"mod", BINOP_MOD, PREC_MUL, 0},
10074   {"**", BINOP_EXP, PREC_REPEAT, 0},
10075   {"@", BINOP_REPEAT, PREC_REPEAT, 0},
10076   {"-", UNOP_NEG, PREC_PREFIX, 0},
10077   {"+", UNOP_PLUS, PREC_PREFIX, 0},
10078   {"not ", UNOP_LOGICAL_NOT, PREC_PREFIX, 0},
10079   {"not ", UNOP_COMPLEMENT, PREC_PREFIX, 0},
10080   {"abs ", UNOP_ABS, PREC_PREFIX, 0},
10081   {".all", UNOP_IND, PREC_SUFFIX, 1},
10082   {"'access", UNOP_ADDR, PREC_SUFFIX, 1},
10083   {"'size", OP_ATR_SIZE, PREC_SUFFIX, 1},
10084   {NULL, 0, 0, 0}
10085 };
10086 \f
10087                                 /* Fundamental Ada Types */
10088
10089 /* Create a fundamental Ada type using default reasonable for the current
10090    target machine.
10091
10092    Some object/debugging file formats (DWARF version 1, COFF, etc) do not
10093    define fundamental types such as "int" or "double".  Others (stabs or
10094    DWARF version 2, etc) do define fundamental types.  For the formats which
10095    don't provide fundamental types, gdb can create such types using this
10096    function.
10097
10098    FIXME:  Some compilers distinguish explicitly signed integral types
10099    (signed short, signed int, signed long) from "regular" integral types
10100    (short, int, long) in the debugging information.  There is some dis-
10101    agreement as to how useful this feature is.  In particular, gcc does
10102    not support this.  Also, only some debugging formats allow the
10103    distinction to be passed on to a debugger.  For now, we always just
10104    use "short", "int", or "long" as the type name, for both the implicit
10105    and explicitly signed types.  This also makes life easier for the
10106    gdb test suite since we don't have to account for the differences
10107    in output depending upon what the compiler and debugging format
10108    support.  We will probably have to re-examine the issue when gdb
10109    starts taking it's fundamental type information directly from the
10110    debugging information supplied by the compiler.  fnf@cygnus.com */
10111
10112 static struct type *
10113 ada_create_fundamental_type (struct objfile *objfile, int typeid)
10114 {
10115   struct type *type = NULL;
10116
10117   switch (typeid)
10118     {
10119     default:
10120       /* FIXME:  For now, if we are asked to produce a type not in this
10121          language, create the equivalent of a C integer type with the
10122          name "<?type?>".  When all the dust settles from the type
10123          reconstruction work, this should probably become an error.  */
10124       type = init_type (TYPE_CODE_INT,
10125                         TARGET_INT_BIT / TARGET_CHAR_BIT,
10126                         0, "<?type?>", objfile);
10127       warning ("internal error: no Ada fundamental type %d", typeid);
10128       break;
10129     case FT_VOID:
10130       type = init_type (TYPE_CODE_VOID,
10131                         TARGET_CHAR_BIT / TARGET_CHAR_BIT,
10132                         0, "void", objfile);
10133       break;
10134     case FT_CHAR:
10135       type = init_type (TYPE_CODE_INT,
10136                         TARGET_CHAR_BIT / TARGET_CHAR_BIT,
10137                         0, "character", objfile);
10138       break;
10139     case FT_SIGNED_CHAR:
10140       type = init_type (TYPE_CODE_INT,
10141                         TARGET_CHAR_BIT / TARGET_CHAR_BIT,
10142                         0, "signed char", objfile);
10143       break;
10144     case FT_UNSIGNED_CHAR:
10145       type = init_type (TYPE_CODE_INT,
10146                         TARGET_CHAR_BIT / TARGET_CHAR_BIT,
10147                         TYPE_FLAG_UNSIGNED, "unsigned char", objfile);
10148       break;
10149     case FT_SHORT:
10150       type = init_type (TYPE_CODE_INT,
10151                         TARGET_SHORT_BIT / TARGET_CHAR_BIT,
10152                         0, "short_integer", objfile);
10153       break;
10154     case FT_SIGNED_SHORT:
10155       type = init_type (TYPE_CODE_INT,
10156                         TARGET_SHORT_BIT / TARGET_CHAR_BIT,
10157                         0, "short_integer", objfile);
10158       break;
10159     case FT_UNSIGNED_SHORT:
10160       type = init_type (TYPE_CODE_INT,
10161                         TARGET_SHORT_BIT / TARGET_CHAR_BIT,
10162                         TYPE_FLAG_UNSIGNED, "unsigned short", objfile);
10163       break;
10164     case FT_INTEGER:
10165       type = init_type (TYPE_CODE_INT,
10166                         TARGET_INT_BIT / TARGET_CHAR_BIT,
10167                         0, "integer", objfile);
10168       break;
10169     case FT_SIGNED_INTEGER:
10170       type = init_type (TYPE_CODE_INT, TARGET_INT_BIT / TARGET_CHAR_BIT, 0, "integer", objfile);        /* FIXME -fnf */
10171       break;
10172     case FT_UNSIGNED_INTEGER:
10173       type = init_type (TYPE_CODE_INT,
10174                         TARGET_INT_BIT / TARGET_CHAR_BIT,
10175                         TYPE_FLAG_UNSIGNED, "unsigned int", objfile);
10176       break;
10177     case FT_LONG:
10178       type = init_type (TYPE_CODE_INT,
10179                         TARGET_LONG_BIT / TARGET_CHAR_BIT,
10180                         0, "long_integer", objfile);
10181       break;
10182     case FT_SIGNED_LONG:
10183       type = init_type (TYPE_CODE_INT,
10184                         TARGET_LONG_BIT / TARGET_CHAR_BIT,
10185                         0, "long_integer", objfile);
10186       break;
10187     case FT_UNSIGNED_LONG:
10188       type = init_type (TYPE_CODE_INT,
10189                         TARGET_LONG_BIT / TARGET_CHAR_BIT,
10190                         TYPE_FLAG_UNSIGNED, "unsigned long", objfile);
10191       break;
10192     case FT_LONG_LONG:
10193       type = init_type (TYPE_CODE_INT,
10194                         TARGET_LONG_LONG_BIT / TARGET_CHAR_BIT,
10195                         0, "long_long_integer", objfile);
10196       break;
10197     case FT_SIGNED_LONG_LONG:
10198       type = init_type (TYPE_CODE_INT,
10199                         TARGET_LONG_LONG_BIT / TARGET_CHAR_BIT,
10200                         0, "long_long_integer", objfile);
10201       break;
10202     case FT_UNSIGNED_LONG_LONG:
10203       type = init_type (TYPE_CODE_INT,
10204                         TARGET_LONG_LONG_BIT / TARGET_CHAR_BIT,
10205                         TYPE_FLAG_UNSIGNED, "unsigned long long", objfile);
10206       break;
10207     case FT_FLOAT:
10208       type = init_type (TYPE_CODE_FLT,
10209                         TARGET_FLOAT_BIT / TARGET_CHAR_BIT,
10210                         0, "float", objfile);
10211       break;
10212     case FT_DBL_PREC_FLOAT:
10213       type = init_type (TYPE_CODE_FLT,
10214                         TARGET_DOUBLE_BIT / TARGET_CHAR_BIT,
10215                         0, "long_float", objfile);
10216       break;
10217     case FT_EXT_PREC_FLOAT:
10218       type = init_type (TYPE_CODE_FLT,
10219                         TARGET_LONG_DOUBLE_BIT / TARGET_CHAR_BIT,
10220                         0, "long_long_float", objfile);
10221       break;
10222     }
10223   return (type);
10224 }
10225
10226 struct type *builtin_type_ada_int;
10227 struct type *builtin_type_ada_short;
10228 struct type *builtin_type_ada_long;
10229 struct type *builtin_type_ada_long_long;
10230 struct type *builtin_type_ada_char;
10231 struct type *builtin_type_ada_float;
10232 struct type *builtin_type_ada_double;
10233 struct type *builtin_type_ada_long_double;
10234 struct type *builtin_type_ada_natural;
10235 struct type *builtin_type_ada_positive;
10236 struct type *builtin_type_ada_system_address;
10237
10238 struct type **const (ada_builtin_types[]) =
10239 {
10240   &builtin_type_ada_int,
10241     &builtin_type_ada_long,
10242     &builtin_type_ada_short,
10243     &builtin_type_ada_char,
10244     &builtin_type_ada_float,
10245     &builtin_type_ada_double,
10246     &builtin_type_ada_long_long,
10247     &builtin_type_ada_long_double,
10248     &builtin_type_ada_natural, &builtin_type_ada_positive,
10249     /* The following types are carried over from C for convenience.  */
10250 &builtin_type_int,
10251     &builtin_type_long,
10252     &builtin_type_short,
10253     &builtin_type_char,
10254     &builtin_type_float,
10255     &builtin_type_double,
10256     &builtin_type_long_long,
10257     &builtin_type_void,
10258     &builtin_type_signed_char,
10259     &builtin_type_unsigned_char,
10260     &builtin_type_unsigned_short,
10261     &builtin_type_unsigned_int,
10262     &builtin_type_unsigned_long,
10263     &builtin_type_unsigned_long_long,
10264     &builtin_type_long_double,
10265     &builtin_type_complex, &builtin_type_double_complex, 0};
10266
10267 static void
10268 build_ada_types (struct gdbarch *current_gdbarch)
10269 {
10270   builtin_type_ada_int =
10271     init_type (TYPE_CODE_INT, TARGET_INT_BIT / TARGET_CHAR_BIT,
10272                0, "integer", (struct objfile *) NULL);
10273   builtin_type_ada_long =
10274     init_type (TYPE_CODE_INT, TARGET_LONG_BIT / TARGET_CHAR_BIT,
10275                0, "long_integer", (struct objfile *) NULL);
10276   builtin_type_ada_short =
10277     init_type (TYPE_CODE_INT, TARGET_SHORT_BIT / TARGET_CHAR_BIT,
10278                0, "short_integer", (struct objfile *) NULL);
10279   builtin_type_ada_char =
10280     init_type (TYPE_CODE_INT, TARGET_CHAR_BIT / TARGET_CHAR_BIT,
10281                0, "character", (struct objfile *) NULL);
10282   builtin_type_ada_float =
10283     init_type (TYPE_CODE_FLT, TARGET_FLOAT_BIT / TARGET_CHAR_BIT,
10284                0, "float", (struct objfile *) NULL);
10285   builtin_type_ada_double =
10286     init_type (TYPE_CODE_FLT, TARGET_DOUBLE_BIT / TARGET_CHAR_BIT,
10287                0, "long_float", (struct objfile *) NULL);
10288   builtin_type_ada_long_long =
10289     init_type (TYPE_CODE_INT, TARGET_LONG_LONG_BIT / TARGET_CHAR_BIT,
10290                0, "long_long_integer", (struct objfile *) NULL);
10291   builtin_type_ada_long_double =
10292     init_type (TYPE_CODE_FLT, TARGET_LONG_DOUBLE_BIT / TARGET_CHAR_BIT,
10293                0, "long_long_float", (struct objfile *) NULL);
10294   builtin_type_ada_natural =
10295     init_type (TYPE_CODE_INT, TARGET_INT_BIT / TARGET_CHAR_BIT,
10296                0, "natural", (struct objfile *) NULL);
10297   builtin_type_ada_positive =
10298     init_type (TYPE_CODE_INT, TARGET_INT_BIT / TARGET_CHAR_BIT,
10299                0, "positive", (struct objfile *) NULL);
10300
10301
10302   builtin_type_ada_system_address =
10303     lookup_pointer_type (init_type (TYPE_CODE_VOID, 1, 0, "void",
10304                                     (struct objfile *) NULL));
10305   TYPE_NAME (builtin_type_ada_system_address) = "system__address";
10306 }
10307
10308 \f
10309                                 /* Language vector */
10310
10311 /* Not really used, but needed in the ada_language_defn.  */
10312
10313 static void
10314 emit_char (int c, struct ui_file *stream, int quoter)
10315 {
10316   ada_emit_char (c, stream, quoter, 1);
10317 }
10318
10319 static int
10320 parse (void)
10321 {
10322   warnings_issued = 0;
10323   return ada_parse ();
10324 }
10325
10326 static const struct exp_descriptor ada_exp_descriptor = {
10327   ada_print_subexp,
10328   ada_operator_length,
10329   ada_op_name,
10330   ada_dump_subexp_body,
10331   ada_evaluate_subexp
10332 };
10333
10334 const struct language_defn ada_language_defn = {
10335   "ada",                        /* Language name */
10336   language_ada,
10337   ada_builtin_types,
10338   range_check_off,
10339   type_check_off,
10340   case_sensitive_on,            /* Yes, Ada is case-insensitive, but
10341                                    that's not quite what this means.  */
10342 #ifdef GNAT_GDB
10343   ada_lookup_symbol,
10344   ada_lookup_minimal_symbol,
10345 #endif /* GNAT_GDB */
10346   array_row_major,
10347   &ada_exp_descriptor,
10348   parse,
10349   ada_error,
10350   resolve,
10351   ada_printchar,                /* Print a character constant */
10352   ada_printstr,                 /* Function to print string constant */
10353   emit_char,                    /* Function to print single char (not used) */
10354   ada_create_fundamental_type,  /* Create fundamental type in this language */
10355   ada_print_type,               /* Print a type using appropriate syntax */
10356   ada_val_print,                /* Print a value using appropriate syntax */
10357   ada_value_print,              /* Print a top-level value */
10358   NULL,                         /* Language specific skip_trampoline */
10359   NULL,                         /* value_of_this */
10360   ada_lookup_symbol_nonlocal,   /* Looking up non-local symbols.  */
10361   basic_lookup_transparent_type,        /* lookup_transparent_type */
10362   ada_la_decode,                /* Language specific symbol demangler */
10363   NULL,                         /* Language specific class_name_from_physname */
10364   ada_op_print_tab,             /* expression operators for printing */
10365   0,                            /* c-style arrays */
10366   1,                            /* String lower bound */
10367   &builtin_type_ada_char,
10368   ada_get_gdb_completer_word_break_characters,
10369 #ifdef GNAT_GDB
10370   ada_translate_error_message,  /* Substitute Ada-specific terminology
10371                                    in errors and warnings.  */
10372 #endif /* GNAT_GDB */
10373   LANG_MAGIC
10374 };
10375
10376 void
10377 _initialize_ada_language (void)
10378 {
10379
10380   build_ada_types (current_gdbarch);
10381   gdbarch_data_register_post_init (build_ada_types);
10382   add_language (&ada_language_defn);
10383
10384   varsize_limit = 65536;
10385 #ifdef GNAT_GDB
10386   add_setshow_uinteger_cmd ("varsize-limit", class_support,
10387                             &varsize_limit, "\
10388 Set the maximum number of bytes allowed in a dynamic-sized object.", "\
10389 Show the maximum number of bytes allowed in a dynamic-sized object.",
10390                             NULL, NULL, &setlist, &showlist);
10391   obstack_init (&cache_space);
10392 #endif /* GNAT_GDB */
10393
10394   obstack_init (&symbol_list_obstack);
10395
10396   decoded_names_store = htab_create_alloc
10397     (256, htab_hash_string, (int (*)(const void *, const void *)) streq,
10398      NULL, xcalloc, xfree);
10399 }