gdb/ada-lang.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Ada language support routines for GDB, the GNU debugger.

  2.    Copyright (C) 1992-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */


  14. #include "defs.h"
  15. #include <ctype.h>
  16. #include "demangle.h"
  17. #include "gdb_regex.h"
  18. #include "frame.h"
  19. #include "symtab.h"
  20. #include "gdbtypes.h"
  21. #include "gdbcmd.h"
  22. #include "expression.h"
  23. #include "parser-defs.h"
  24. #include "language.h"
  25. #include "varobj.h"
  26. #include "c-lang.h"
  27. #include "inferior.h"
  28. #include "symfile.h"
  29. #include "objfiles.h"
  30. #include "breakpoint.h"
  31. #include "gdbcore.h"
  32. #include "hashtab.h"
  33. #include "gdb_obstack.h"
  34. #include "ada-lang.h"
  35. #include "completer.h"
  36. #include <sys/stat.h>
  37. #include "ui-out.h"
  38. #include "block.h"
  39. #include "infcall.h"
  40. #include "dictionary.h"
  41. #include "annotate.h"
  42. #include "valprint.h"
  43. #include "source.h"
  44. #include "observer.h"
  45. #include "vec.h"
  46. #include "stack.h"
  47. #include "gdb_vecs.h"
  48. #include "typeprint.h"

  49. #include "psymtab.h"
  50. #include "value.h"
  51. #include "mi/mi-common.h"
  52. #include "arch-utils.h"
  53. #include "cli/cli-utils.h"

  54. /* Define whether or not the C operator '/' truncates towards zero for
  55.    differently signed operands (truncation direction is undefined in C).
  56.    Copied from valarith.c.  */

  57. #ifndef TRUNCATION_TOWARDS_ZERO
  58. #define TRUNCATION_TOWARDS_ZERO ((-5 / 2) == -2)
  59. #endif

  60. static struct type *desc_base_type (struct type *);

  61. static struct type *desc_bounds_type (struct type *);

  62. static struct value *desc_bounds (struct value *);

  63. static int fat_pntr_bounds_bitpos (struct type *);

  64. static int fat_pntr_bounds_bitsize (struct type *);

  65. static struct type *desc_data_target_type (struct type *);

  66. static struct value *desc_data (struct value *);

  67. static int fat_pntr_data_bitpos (struct type *);

  68. static int fat_pntr_data_bitsize (struct type *);

  69. static struct value *desc_one_bound (struct value *, int, int);

  70. static int desc_bound_bitpos (struct type *, int, int);

  71. static int desc_bound_bitsize (struct type *, int, int);

  72. static struct type *desc_index_type (struct type *, int);

  73. static int desc_arity (struct type *);

  74. static int ada_type_match (struct type *, struct type *, int);

  75. static int ada_args_match (struct symbol *, struct value **, int);

  76. static int full_match (const char *, const char *);

  77. static struct value *make_array_descriptor (struct type *, struct value *);

  78. static void ada_add_block_symbols (struct obstack *,
  79.                                    const struct block *, const char *,
  80.                                    domain_enum, struct objfile *, int);

  81. static int is_nonfunction (struct ada_symbol_info *, int);

  82. static void add_defn_to_vec (struct obstack *, struct symbol *,
  83.                              const struct block *);

  84. static int num_defns_collected (struct obstack *);

  85. static struct ada_symbol_info *defns_collected (struct obstack *, int);

  86. static struct value *resolve_subexp (struct expression **, int *, int,
  87.                                      struct type *);

  88. static void replace_operator_with_call (struct expression **, int, int, int,
  89.                                         struct symbol *, const struct block *);

  90. static int possible_user_operator_p (enum exp_opcode, struct value **);

  91. static char *ada_op_name (enum exp_opcode);

  92. static const char *ada_decoded_op_name (enum exp_opcode);

  93. static int numeric_type_p (struct type *);

  94. static int integer_type_p (struct type *);

  95. static int scalar_type_p (struct type *);

  96. static int discrete_type_p (struct type *);

  97. static enum ada_renaming_category parse_old_style_renaming (struct type *,
  98.                                                             const char **,
  99.                                                             int *,
  100.                                                             const char **);

  101. static struct symbol *find_old_style_renaming_symbol (const char *,
  102.                                                       const struct block *);

  103. static struct type *ada_lookup_struct_elt_type (struct type *, char *,
  104.                                                 int, int, int *);

  105. static struct value *evaluate_subexp_type (struct expression *, int *);

  106. static struct type *ada_find_parallel_type_with_name (struct type *,
  107.                                                       const char *);

  108. static int is_dynamic_field (struct type *, int);

  109. static struct type *to_fixed_variant_branch_type (struct type *,
  110.                                                   const gdb_byte *,
  111.                                                   CORE_ADDR, struct value *);

  112. static struct type *to_fixed_array_type (struct type *, struct value *, int);

  113. static struct type *to_fixed_range_type (struct type *, struct value *);

  114. static struct type *to_static_fixed_type (struct type *);
  115. static struct type *static_unwrap_type (struct type *type);

  116. static struct value *unwrap_value (struct value *);

  117. static struct type *constrained_packed_array_type (struct type *, long *);

  118. static struct type *decode_constrained_packed_array_type (struct type *);

  119. static long decode_packed_array_bitsize (struct type *);

  120. static struct value *decode_constrained_packed_array (struct value *);

  121. static int ada_is_packed_array_type  (struct type *);

  122. static int ada_is_unconstrained_packed_array_type (struct type *);

  123. static struct value *value_subscript_packed (struct value *, int,
  124.                                              struct value **);

  125. static void move_bits (gdb_byte *, int, const gdb_byte *, int, int, int);

  126. static struct value *coerce_unspec_val_to_type (struct value *,
  127.                                                 struct type *);

  128. static struct value *get_var_value (char *, char *);

  129. static int lesseq_defined_than (struct symbol *, struct symbol *);

  130. static int equiv_types (struct type *, struct type *);

  131. static int is_name_suffix (const char *);

  132. static int advance_wild_match (const char **, const char *, int);

  133. static int wild_match (const char *, const char *);

  134. static struct value *ada_coerce_ref (struct value *);

  135. static LONGEST pos_atr (struct value *);

  136. static struct value *value_pos_atr (struct type *, struct value *);

  137. static struct value *value_val_atr (struct type *, struct value *);

  138. static struct symbol *standard_lookup (const char *, const struct block *,
  139.                                        domain_enum);

  140. static struct value *ada_search_struct_field (char *, struct value *, int,
  141.                                               struct type *);

  142. static struct value *ada_value_primitive_field (struct value *, int, int,
  143.                                                 struct type *);

  144. static int find_struct_field (const char *, struct type *, int,
  145.                               struct type **, int *, int *, int *, int *);

  146. static struct value *ada_to_fixed_value_create (struct type *, CORE_ADDR,
  147.                                                 struct value *);

  148. static int ada_resolve_function (struct ada_symbol_info *, int,
  149.                                  struct value **, int, const char *,
  150.                                  struct type *);

  151. static int ada_is_direct_array_type (struct type *);

  152. static void ada_language_arch_info (struct gdbarch *,
  153.                                     struct language_arch_info *);

  154. static struct value *ada_index_struct_field (int, struct value *, int,
  155.                                              struct type *);

  156. static struct value *assign_aggregate (struct value *, struct value *,
  157.                                        struct expression *,
  158.                                        int *, enum noside);

  159. static void aggregate_assign_from_choices (struct value *, struct value *,
  160.                                            struct expression *,
  161.                                            int *, LONGEST *, int *,
  162.                                            int, LONGEST, LONGEST);

  163. static void aggregate_assign_positional (struct value *, struct value *,
  164.                                          struct expression *,
  165.                                          int *, LONGEST *, int *, int,
  166.                                          LONGEST, LONGEST);


  167. static void aggregate_assign_others (struct value *, struct value *,
  168.                                      struct expression *,
  169.                                      int *, LONGEST *, int, LONGEST, LONGEST);


  170. static void add_component_interval (LONGEST, LONGEST, LONGEST *, int *, int);


  171. static struct value *ada_evaluate_subexp (struct type *, struct expression *,
  172.                                           int *, enum noside);

  173. static void ada_forward_operator_length (struct expression *, int, int *,
  174.                                          int *);

  175. static struct type *ada_find_any_type (const char *name);


  176. /* The result of a symbol lookup to be stored in our symbol cache.  */

  177. struct cache_entry
  178. {
  179.   /* The name used to perform the lookup.  */
  180.   const char *name;
  181.   /* The namespace used during the lookup.  */
  182.   domain_enum namespace;
  183.   /* The symbol returned by the lookup, or NULL if no matching symbol
  184.      was found.  */
  185.   struct symbol *sym;
  186.   /* The block where the symbol was found, or NULL if no matching
  187.      symbol was found.  */
  188.   const struct block *block;
  189.   /* A pointer to the next entry with the same hash.  */
  190.   struct cache_entry *next;
  191. };

  192. /* The Ada symbol cache, used to store the result of Ada-mode symbol
  193.    lookups in the course of executing the user's commands.

  194.    The cache is implemented using a simple, fixed-sized hash.
  195.    The size is fixed on the grounds that there are not likely to be
  196.    all that many symbols looked up during any given session, regardless
  197.    of the size of the symbol table.  If we decide to go to a resizable
  198.    table, let's just use the stuff from libiberty instead.  */

  199. #define HASH_SIZE 1009

  200. struct ada_symbol_cache
  201. {
  202.   /* An obstack used to store the entries in our cache.  */
  203.   struct obstack cache_space;

  204.   /* The root of the hash table used to implement our symbol cache.  */
  205.   struct cache_entry *root[HASH_SIZE];
  206. };

  207. static void ada_free_symbol_cache (struct ada_symbol_cache *sym_cache);

  208. /* Maximum-sized dynamic type.  */
  209. static unsigned int varsize_limit;

  210. /* FIXME: brobecker/2003-09-17: No longer a const because it is
  211.    returned by a function that does not return a const char *.  */
  212. static char *ada_completer_word_break_characters =
  213. #ifdef VMS
  214.   " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
  215. #else
  216.   " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
  217. #endif

  218. /* The name of the symbol to use to get the name of the main subprogram.  */
  219. static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
  220.   = "__gnat_ada_main_program_name";

  221. /* Limit on the number of warnings to raise per expression evaluation.  */
  222. static int warning_limit = 2;

  223. /* Number of warning messages issued; reset to 0 by cleanups after
  224.    expression evaluation.  */
  225. static int warnings_issued = 0;

  226. static const char *known_runtime_file_name_patterns[] = {
  227.   ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
  228. };

  229. static const char *known_auxiliary_function_name_patterns[] = {
  230.   ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
  231. };

  232. /* Space for allocating results of ada_lookup_symbol_list.  */
  233. static struct obstack symbol_list_obstack;

  234. /* Maintenance-related settings for this module.  */

  235. static struct cmd_list_element *maint_set_ada_cmdlist;
  236. static struct cmd_list_element *maint_show_ada_cmdlist;

  237. /* Implement the "maintenance set ada" (prefix) command.  */

  238. static void
  239. maint_set_ada_cmd (char *args, int from_tty)
  240. {
  241.   help_list (maint_set_ada_cmdlist, "maintenance set ada ", all_commands,
  242.              gdb_stdout);
  243. }

  244. /* Implement the "maintenance show ada" (prefix) command.  */

  245. static void
  246. maint_show_ada_cmd (char *args, int from_tty)
  247. {
  248.   cmd_show_list (maint_show_ada_cmdlist, from_tty, "");
  249. }

  250. /* The "maintenance ada set/show ignore-descriptive-type" value.  */

  251. static int ada_ignore_descriptive_types_p = 0;

  252.                         /* Inferior-specific data.  */

  253. /* Per-inferior data for this module.  */

  254. struct ada_inferior_data
  255. {
  256.   /* The ada__tags__type_specific_data type, which is used when decoding
  257.      tagged types.  With older versions of GNAT, this type was directly
  258.      accessible through a component ("tsd") in the object tag.  But this
  259.      is no longer the case, so we cache it for each inferior.  */
  260.   struct type *tsd_type;

  261.   /* The exception_support_info data.  This data is used to determine
  262.      how to implement support for Ada exception catchpoints in a given
  263.      inferior.  */
  264.   const struct exception_support_info *exception_info;
  265. };

  266. /* Our key to this module's inferior data.  */
  267. static const struct inferior_data *ada_inferior_data;

  268. /* A cleanup routine for our inferior data.  */
  269. static void
  270. ada_inferior_data_cleanup (struct inferior *inf, void *arg)
  271. {
  272.   struct ada_inferior_data *data;

  273.   data = inferior_data (inf, ada_inferior_data);
  274.   if (data != NULL)
  275.     xfree (data);
  276. }

  277. /* Return our inferior data for the given inferior (INF).

  278.    This function always returns a valid pointer to an allocated
  279.    ada_inferior_data structure.  If INF's inferior data has not
  280.    been previously set, this functions creates a new one with all
  281.    fields set to zero, sets INF's inferior to it, and then returns
  282.    a pointer to that newly allocated ada_inferior_data.  */

  283. static struct ada_inferior_data *
  284. get_ada_inferior_data (struct inferior *inf)
  285. {
  286.   struct ada_inferior_data *data;

  287.   data = inferior_data (inf, ada_inferior_data);
  288.   if (data == NULL)
  289.     {
  290.       data = XCNEW (struct ada_inferior_data);
  291.       set_inferior_data (inf, ada_inferior_data, data);
  292.     }

  293.   return data;
  294. }

  295. /* Perform all necessary cleanups regarding our module's inferior data
  296.    that is required after the inferior INF just exited.  */

  297. static void
  298. ada_inferior_exit (struct inferior *inf)
  299. {
  300.   ada_inferior_data_cleanup (inf, NULL);
  301.   set_inferior_data (inf, ada_inferior_data, NULL);
  302. }


  303.                         /* program-space-specific data.  */

  304. /* This module's per-program-space data.  */
  305. struct ada_pspace_data
  306. {
  307.   /* The Ada symbol cache.  */
  308.   struct ada_symbol_cache *sym_cache;
  309. };

  310. /* Key to our per-program-space data.  */
  311. static const struct program_space_data *ada_pspace_data_handle;

  312. /* Return this module's data for the given program space (PSPACE).
  313.    If not is found, add a zero'ed one now.

  314.    This function always returns a valid object.  */

  315. static struct ada_pspace_data *
  316. get_ada_pspace_data (struct program_space *pspace)
  317. {
  318.   struct ada_pspace_data *data;

  319.   data = program_space_data (pspace, ada_pspace_data_handle);
  320.   if (data == NULL)
  321.     {
  322.       data = XCNEW (struct ada_pspace_data);
  323.       set_program_space_data (pspace, ada_pspace_data_handle, data);
  324.     }

  325.   return data;
  326. }

  327. /* The cleanup callback for this module's per-program-space data.  */

  328. static void
  329. ada_pspace_data_cleanup (struct program_space *pspace, void *data)
  330. {
  331.   struct ada_pspace_data *pspace_data = data;

  332.   if (pspace_data->sym_cache != NULL)
  333.     ada_free_symbol_cache (pspace_data->sym_cache);
  334.   xfree (pspace_data);
  335. }

  336.                         /* Utilities */

  337. /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
  338.    all typedef layers have been peeled.  Otherwise, return TYPE.

  339.    Normally, we really expect a typedef type to only have 1 typedef layer.
  340.    In other words, we really expect the target type of a typedef type to be
  341.    a non-typedef type.  This is particularly true for Ada units, because
  342.    the language does not have a typedef vs not-typedef distinction.
  343.    In that respect, the Ada compiler has been trying to eliminate as many
  344.    typedef definitions in the debugging information, since they generally
  345.    do not bring any extra information (we still use typedef under certain
  346.    circumstances related mostly to the GNAT encoding).

  347.    Unfortunately, we have seen situations where the debugging information
  348.    generated by the compiler leads to such multiple typedef layers.  For
  349.    instance, consider the following example with stabs:

  350.      .stabs  "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
  351.      .stabs  "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0

  352.    This is an error in the debugging information which causes type
  353.    pck__float_array___XUP to be defined twice, and the second time,
  354.    it is defined as a typedef of a typedef.

  355.    This is on the fringe of legality as far as debugging information is
  356.    concerned, and certainly unexpected.  But it is easy to handle these
  357.    situations correctly, so we can afford to be lenient in this case.  */

  358. static struct type *
  359. ada_typedef_target_type (struct type *type)
  360. {
  361.   while (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
  362.     type = TYPE_TARGET_TYPE (type);
  363.   return type;
  364. }

  365. /* Given DECODED_NAME a string holding a symbol name in its
  366.    decoded form (ie using the Ada dotted notation), returns
  367.    its unqualified name.  */

  368. static const char *
  369. ada_unqualified_name (const char *decoded_name)
  370. {
  371.   const char *result;

  372.   /* If the decoded name starts with '<', it means that the encoded
  373.      name does not follow standard naming conventions, and thus that
  374.      it is not your typical Ada symbol name.  Trying to unqualify it
  375.      is therefore pointless and possibly erroneous.  */
  376.   if (decoded_name[0] == '<')
  377.     return decoded_name;

  378.   result = strrchr (decoded_name, '.');
  379.   if (result != NULL)
  380.     result++;                   /* Skip the dot...  */
  381.   else
  382.     result = decoded_name;

  383.   return result;
  384. }

  385. /* Return a string starting with '<', followed by STR, and '>'.
  386.    The result is good until the next call.  */

  387. static char *
  388. add_angle_brackets (const char *str)
  389. {
  390.   static char *result = NULL;

  391.   xfree (result);
  392.   result = xstrprintf ("<%s>", str);
  393.   return result;
  394. }

  395. static char *
  396. ada_get_gdb_completer_word_break_characters (void)
  397. {
  398.   return ada_completer_word_break_characters;
  399. }

  400. /* Print an array element index using the Ada syntax.  */

  401. static void
  402. ada_print_array_index (struct value *index_value, struct ui_file *stream,
  403.                        const struct value_print_options *options)
  404. {
  405.   LA_VALUE_PRINT (index_value, stream, options);
  406.   fprintf_filtered (stream, " => ");
  407. }

  408. /* Assuming VECT points to an array of *SIZE objects of size
  409.    ELEMENT_SIZE, grow it to contain at least MIN_SIZE objects,
  410.    updating *SIZE as necessary and returning the (new) array.  */

  411. void *
  412. grow_vect (void *vect, size_t *size, size_t min_size, int element_size)
  413. {
  414.   if (*size < min_size)
  415.     {
  416.       *size *= 2;
  417.       if (*size < min_size)
  418.         *size = min_size;
  419.       vect = xrealloc (vect, *size * element_size);
  420.     }
  421.   return vect;
  422. }

  423. /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
  424.    suffix of FIELD_NAME beginning "___".  */

  425. static int
  426. field_name_match (const char *field_name, const char *target)
  427. {
  428.   int len = strlen (target);

  429.   return
  430.     (strncmp (field_name, target, len) == 0
  431.      && (field_name[len] == '\0'
  432.          || (strncmp (field_name + len, "___", 3) == 0
  433.              && strcmp (field_name + strlen (field_name) - 6,
  434.                         "___XVN") != 0)));
  435. }


  436. /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
  437.    a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
  438.    and return its index.  This function also handles fields whose name
  439.    have ___ suffixes because the compiler sometimes alters their name
  440.    by adding such a suffix to represent fields with certain constraints.
  441.    If the field could not be found, return a negative number if
  442.    MAYBE_MISSING is set.  Otherwise raise an error.  */

  443. int
  444. ada_get_field_index (const struct type *type, const char *field_name,
  445.                      int maybe_missing)
  446. {
  447.   int fieldno;
  448.   struct type *struct_type = check_typedef ((struct type *) type);

  449.   for (fieldno = 0; fieldno < TYPE_NFIELDS (struct_type); fieldno++)
  450.     if (field_name_match (TYPE_FIELD_NAME (struct_type, fieldno), field_name))
  451.       return fieldno;

  452.   if (!maybe_missing)
  453.     error (_("Unable to find field %s in struct %s.  Aborting"),
  454.            field_name, TYPE_NAME (struct_type));

  455.   return -1;
  456. }

  457. /* The length of the prefix of NAME prior to any "___" suffix.  */

  458. int
  459. ada_name_prefix_len (const char *name)
  460. {
  461.   if (name == NULL)
  462.     return 0;
  463.   else
  464.     {
  465.       const char *p = strstr (name, "___");

  466.       if (p == NULL)
  467.         return strlen (name);
  468.       else
  469.         return p - name;
  470.     }
  471. }

  472. /* Return non-zero if SUFFIX is a suffix of STR.
  473.    Return zero if STR is null.  */

  474. static int
  475. is_suffix (const char *str, const char *suffix)
  476. {
  477.   int len1, len2;

  478.   if (str == NULL)
  479.     return 0;
  480.   len1 = strlen (str);
  481.   len2 = strlen (suffix);
  482.   return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
  483. }

  484. /* The contents of value VAL, treated as a value of type TYPE.  The
  485.    result is an lval in memory if VAL is.  */

  486. static struct value *
  487. coerce_unspec_val_to_type (struct value *val, struct type *type)
  488. {
  489.   type = ada_check_typedef (type);
  490.   if (value_type (val) == type)
  491.     return val;
  492.   else
  493.     {
  494.       struct value *result;

  495.       /* Make sure that the object size is not unreasonable before
  496.          trying to allocate some memory for it.  */
  497.       ada_ensure_varsize_limit (type);

  498.       if (value_lazy (val)
  499.           || TYPE_LENGTH (type) > TYPE_LENGTH (value_type (val)))
  500.         result = allocate_value_lazy (type);
  501.       else
  502.         {
  503.           result = allocate_value (type);
  504.           value_contents_copy_raw (result, 0, val, 0, TYPE_LENGTH (type));
  505.         }
  506.       set_value_component_location (result, val);
  507.       set_value_bitsize (result, value_bitsize (val));
  508.       set_value_bitpos (result, value_bitpos (val));
  509.       set_value_address (result, value_address (val));
  510.       return result;
  511.     }
  512. }

  513. static const gdb_byte *
  514. cond_offset_host (const gdb_byte *valaddr, long offset)
  515. {
  516.   if (valaddr == NULL)
  517.     return NULL;
  518.   else
  519.     return valaddr + offset;
  520. }

  521. static CORE_ADDR
  522. cond_offset_target (CORE_ADDR address, long offset)
  523. {
  524.   if (address == 0)
  525.     return 0;
  526.   else
  527.     return address + offset;
  528. }

  529. /* Issue a warning (as for the definition of warning in utils.c, but
  530.    with exactly one argument rather than ...), unless the limit on the
  531.    number of warnings has passed during the evaluation of the current
  532.    expression.  */

  533. /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
  534.    provided by "complaint".  */
  535. static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);

  536. static void
  537. lim_warning (const char *format, ...)
  538. {
  539.   va_list args;

  540.   va_start (args, format);
  541.   warnings_issued += 1;
  542.   if (warnings_issued <= warning_limit)
  543.     vwarning (format, args);

  544.   va_end (args);
  545. }

  546. /* Issue an error if the size of an object of type T is unreasonable,
  547.    i.e. if it would be a bad idea to allocate a value of this type in
  548.    GDB.  */

  549. void
  550. ada_ensure_varsize_limit (const struct type *type)
  551. {
  552.   if (TYPE_LENGTH (type) > varsize_limit)
  553.     error (_("object size is larger than varsize-limit"));
  554. }

  555. /* Maximum value of a SIZE-byte signed integer type.  */
  556. static LONGEST
  557. max_of_size (int size)
  558. {
  559.   LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);

  560.   return top_bit | (top_bit - 1);
  561. }

  562. /* Minimum value of a SIZE-byte signed integer type.  */
  563. static LONGEST
  564. min_of_size (int size)
  565. {
  566.   return -max_of_size (size) - 1;
  567. }

  568. /* Maximum value of a SIZE-byte unsigned integer type.  */
  569. static ULONGEST
  570. umax_of_size (int size)
  571. {
  572.   ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);

  573.   return top_bit | (top_bit - 1);
  574. }

  575. /* Maximum value of integral type T, as a signed quantity.  */
  576. static LONGEST
  577. max_of_type (struct type *t)
  578. {
  579.   if (TYPE_UNSIGNED (t))
  580.     return (LONGEST) umax_of_size (TYPE_LENGTH (t));
  581.   else
  582.     return max_of_size (TYPE_LENGTH (t));
  583. }

  584. /* Minimum value of integral type T, as a signed quantity.  */
  585. static LONGEST
  586. min_of_type (struct type *t)
  587. {
  588.   if (TYPE_UNSIGNED (t))
  589.     return 0;
  590.   else
  591.     return min_of_size (TYPE_LENGTH (t));
  592. }

  593. /* The largest value in the domain of TYPE, a discrete type, as an integer.  */
  594. LONGEST
  595. ada_discrete_type_high_bound (struct type *type)
  596. {
  597.   type = resolve_dynamic_type (type, 0);
  598.   switch (TYPE_CODE (type))
  599.     {
  600.     case TYPE_CODE_RANGE:
  601.       return TYPE_HIGH_BOUND (type);
  602.     case TYPE_CODE_ENUM:
  603.       return TYPE_FIELD_ENUMVAL (type, TYPE_NFIELDS (type) - 1);
  604.     case TYPE_CODE_BOOL:
  605.       return 1;
  606.     case TYPE_CODE_CHAR:
  607.     case TYPE_CODE_INT:
  608.       return max_of_type (type);
  609.     default:
  610.       error (_("Unexpected type in ada_discrete_type_high_bound."));
  611.     }
  612. }

  613. /* The smallest value in the domain of TYPE, a discrete type, as an integer.  */
  614. LONGEST
  615. ada_discrete_type_low_bound (struct type *type)
  616. {
  617.   type = resolve_dynamic_type (type, 0);
  618.   switch (TYPE_CODE (type))
  619.     {
  620.     case TYPE_CODE_RANGE:
  621.       return TYPE_LOW_BOUND (type);
  622.     case TYPE_CODE_ENUM:
  623.       return TYPE_FIELD_ENUMVAL (type, 0);
  624.     case TYPE_CODE_BOOL:
  625.       return 0;
  626.     case TYPE_CODE_CHAR:
  627.     case TYPE_CODE_INT:
  628.       return min_of_type (type);
  629.     default:
  630.       error (_("Unexpected type in ada_discrete_type_low_bound."));
  631.     }
  632. }

  633. /* The identity on non-range types.  For range types, the underlying
  634.    non-range scalar type.  */

  635. static struct type *
  636. get_base_type (struct type *type)
  637. {
  638.   while (type != NULL && TYPE_CODE (type) == TYPE_CODE_RANGE)
  639.     {
  640.       if (type == TYPE_TARGET_TYPE (type) || TYPE_TARGET_TYPE (type) == NULL)
  641.         return type;
  642.       type = TYPE_TARGET_TYPE (type);
  643.     }
  644.   return type;
  645. }

  646. /* Return a decoded version of the given VALUE.  This means returning
  647.    a value whose type is obtained by applying all the GNAT-specific
  648.    encondings, making the resulting type a static but standard description
  649.    of the initial type.  */

  650. struct value *
  651. ada_get_decoded_value (struct value *value)
  652. {
  653.   struct type *type = ada_check_typedef (value_type (value));

  654.   if (ada_is_array_descriptor_type (type)
  655.       || (ada_is_constrained_packed_array_type (type)
  656.           && TYPE_CODE (type) != TYPE_CODE_PTR))
  657.     {
  658.       if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)  /* array access type.  */
  659.         value = ada_coerce_to_simple_array_ptr (value);
  660.       else
  661.         value = ada_coerce_to_simple_array (value);
  662.     }
  663.   else
  664.     value = ada_to_fixed_value (value);

  665.   return value;
  666. }

  667. /* Same as ada_get_decoded_value, but with the given TYPE.
  668.    Because there is no associated actual value for this type,
  669.    the resulting type might be a best-effort approximation in
  670.    the case of dynamic types.  */

  671. struct type *
  672. ada_get_decoded_type (struct type *type)
  673. {
  674.   type = to_static_fixed_type (type);
  675.   if (ada_is_constrained_packed_array_type (type))
  676.     type = ada_coerce_to_simple_array_type (type);
  677.   return type;
  678. }



  679.                                 /* Language Selection */

  680. /* If the main program is in Ada, return language_ada, otherwise return LANG
  681.    (the main program is in Ada iif the adainit symbol is found).  */

  682. enum language
  683. ada_update_initial_language (enum language lang)
  684. {
  685.   if (lookup_minimal_symbol ("adainit", (const char *) NULL,
  686.                              (struct objfile *) NULL).minsym != NULL)
  687.     return language_ada;

  688.   return lang;
  689. }

  690. /* If the main procedure is written in Ada, then return its name.
  691.    The result is good until the next call.  Return NULL if the main
  692.    procedure doesn't appear to be in Ada.  */

  693. char *
  694. ada_main_name (void)
  695. {
  696.   struct bound_minimal_symbol msym;
  697.   static char *main_program_name = NULL;

  698.   /* For Ada, the name of the main procedure is stored in a specific
  699.      string constant, generated by the binder.  Look for that symbol,
  700.      extract its address, and then read that string.  If we didn't find
  701.      that string, then most probably the main procedure is not written
  702.      in Ada.  */
  703.   msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);

  704.   if (msym.minsym != NULL)
  705.     {
  706.       CORE_ADDR main_program_name_addr;
  707.       int err_code;

  708.       main_program_name_addr = BMSYMBOL_VALUE_ADDRESS (msym);
  709.       if (main_program_name_addr == 0)
  710.         error (_("Invalid address for Ada main program name."));

  711.       xfree (main_program_name);
  712.       target_read_string (main_program_name_addr, &main_program_name,
  713.                           1024, &err_code);

  714.       if (err_code != 0)
  715.         return NULL;
  716.       return main_program_name;
  717.     }

  718.   /* The main procedure doesn't seem to be in Ada.  */
  719.   return NULL;
  720. }

  721.                                 /* Symbols */

  722. /* Table of Ada operators and their GNAT-encoded names.  Last entry is pair
  723.    of NULLs.  */

  724. const struct ada_opname_map ada_opname_table[] = {
  725.   {"Oadd", "\"+\"", BINOP_ADD},
  726.   {"Osubtract", "\"-\"", BINOP_SUB},
  727.   {"Omultiply", "\"*\"", BINOP_MUL},
  728.   {"Odivide", "\"/\"", BINOP_DIV},
  729.   {"Omod", "\"mod\"", BINOP_MOD},
  730.   {"Orem", "\"rem\"", BINOP_REM},
  731.   {"Oexpon", "\"**\"", BINOP_EXP},
  732.   {"Olt", "\"<\"", BINOP_LESS},
  733.   {"Ole", "\"<=\"", BINOP_LEQ},
  734.   {"Ogt", "\">\"", BINOP_GTR},
  735.   {"Oge", "\">=\"", BINOP_GEQ},
  736.   {"Oeq", "\"=\"", BINOP_EQUAL},
  737.   {"One", "\"/=\"", BINOP_NOTEQUAL},
  738.   {"Oand", "\"and\"", BINOP_BITWISE_AND},
  739.   {"Oor", "\"or\"", BINOP_BITWISE_IOR},
  740.   {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
  741.   {"Oconcat", "\"&\"", BINOP_CONCAT},
  742.   {"Oabs", "\"abs\"", UNOP_ABS},
  743.   {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
  744.   {"Oadd", "\"+\"", UNOP_PLUS},
  745.   {"Osubtract", "\"-\"", UNOP_NEG},
  746.   {NULL, NULL}
  747. };

  748. /* The "encoded" form of DECODED, according to GNAT conventions.
  749.    The result is valid until the next call to ada_encode.  */

  750. char *
  751. ada_encode (const char *decoded)
  752. {
  753.   static char *encoding_buffer = NULL;
  754.   static size_t encoding_buffer_size = 0;
  755.   const char *p;
  756.   int k;

  757.   if (decoded == NULL)
  758.     return NULL;

  759.   GROW_VECT (encoding_buffer, encoding_buffer_size,
  760.              2 * strlen (decoded) + 10);

  761.   k = 0;
  762.   for (p = decoded; *p != '\0'; p += 1)
  763.     {
  764.       if (*p == '.')
  765.         {
  766.           encoding_buffer[k] = encoding_buffer[k + 1] = '_';
  767.           k += 2;
  768.         }
  769.       else if (*p == '"')
  770.         {
  771.           const struct ada_opname_map *mapping;

  772.           for (mapping = ada_opname_table;
  773.                mapping->encoded != NULL
  774.                && strncmp (mapping->decoded, p,
  775.                            strlen (mapping->decoded)) != 0; mapping += 1)
  776.             ;
  777.           if (mapping->encoded == NULL)
  778.             error (_("invalid Ada operator name: %s"), p);
  779.           strcpy (encoding_buffer + k, mapping->encoded);
  780.           k += strlen (mapping->encoded);
  781.           break;
  782.         }
  783.       else
  784.         {
  785.           encoding_buffer[k] = *p;
  786.           k += 1;
  787.         }
  788.     }

  789.   encoding_buffer[k] = '\0';
  790.   return encoding_buffer;
  791. }

  792. /* Return NAME folded to lower case, or, if surrounded by single
  793.    quotes, unfolded, but with the quotes stripped away.  Result good
  794.    to next call.  */

  795. char *
  796. ada_fold_name (const char *name)
  797. {
  798.   static char *fold_buffer = NULL;
  799.   static size_t fold_buffer_size = 0;

  800.   int len = strlen (name);
  801.   GROW_VECT (fold_buffer, fold_buffer_size, len + 1);

  802.   if (name[0] == '\'')
  803.     {
  804.       strncpy (fold_buffer, name + 1, len - 2);
  805.       fold_buffer[len - 2] = '\000';
  806.     }
  807.   else
  808.     {
  809.       int i;

  810.       for (i = 0; i <= len; i += 1)
  811.         fold_buffer[i] = tolower (name[i]);
  812.     }

  813.   return fold_buffer;
  814. }

  815. /* Return nonzero if C is either a digit or a lowercase alphabet character.  */

  816. static int
  817. is_lower_alphanum (const char c)
  818. {
  819.   return (isdigit (c) || (isalpha (c) && islower (c)));
  820. }

  821. /* ENCODED is the linkage name of a symbol and LEN contains its length.
  822.    This function saves in LEN the length of that same symbol name but
  823.    without either of these suffixes:
  824.      . .{DIGIT}+
  825.      . ${DIGIT}+
  826.      . ___{DIGIT}+
  827.      . __{DIGIT}+.

  828.    These are suffixes introduced by the compiler for entities such as
  829.    nested subprogram for instance, in order to avoid name clashes.
  830.    They do not serve any purpose for the debugger.  */

  831. static void
  832. ada_remove_trailing_digits (const char *encoded, int *len)
  833. {
  834.   if (*len > 1 && isdigit (encoded[*len - 1]))
  835.     {
  836.       int i = *len - 2;

  837.       while (i > 0 && isdigit (encoded[i]))
  838.         i--;
  839.       if (i >= 0 && encoded[i] == '.')
  840.         *len = i;
  841.       else if (i >= 0 && encoded[i] == '$')
  842.         *len = i;
  843.       else if (i >= 2 && strncmp (encoded + i - 2, "___", 3) == 0)
  844.         *len = i - 2;
  845.       else if (i >= 1 && strncmp (encoded + i - 1, "__", 2) == 0)
  846.         *len = i - 1;
  847.     }
  848. }

  849. /* Remove the suffix introduced by the compiler for protected object
  850.    subprograms.  */

  851. static void
  852. ada_remove_po_subprogram_suffix (const char *encoded, int *len)
  853. {
  854.   /* Remove trailing N.  */

  855.   /* Protected entry subprograms are broken into two
  856.      separate subprograms: The first one is unprotected, and has
  857.      a 'N' suffix; the second is the protected version, and has
  858.      the 'P' suffix.  The second calls the first one after handling
  859.      the protection.  Since the P subprograms are internally generated,
  860.      we leave these names undecoded, giving the user a clue that this
  861.      entity is internal.  */

  862.   if (*len > 1
  863.       && encoded[*len - 1] == 'N'
  864.       && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
  865.     *len = *len - 1;
  866. }

  867. /* Remove trailing X[bn]* suffixes (indicating names in package bodies).  */

  868. static void
  869. ada_remove_Xbn_suffix (const char *encoded, int *len)
  870. {
  871.   int i = *len - 1;

  872.   while (i > 0 && (encoded[i] == 'b' || encoded[i] == 'n'))
  873.     i--;

  874.   if (encoded[i] != 'X')
  875.     return;

  876.   if (i == 0)
  877.     return;

  878.   if (isalnum (encoded[i-1]))
  879.     *len = i;
  880. }

  881. /* If ENCODED follows the GNAT entity encoding conventions, then return
  882.    the decoded form of ENCODED.  Otherwise, return "<%s>" where "%s" is
  883.    replaced by ENCODED.

  884.    The resulting string is valid until the next call of ada_decode.
  885.    If the string is unchanged by decoding, the original string pointer
  886.    is returned.  */

  887. const char *
  888. ada_decode (const char *encoded)
  889. {
  890.   int i, j;
  891.   int len0;
  892.   const char *p;
  893.   char *decoded;
  894.   int at_start_name;
  895.   static char *decoding_buffer = NULL;
  896.   static size_t decoding_buffer_size = 0;

  897.   /* The name of the Ada main procedure starts with "_ada_".
  898.      This prefix is not part of the decoded name, so skip this part
  899.      if we see this prefix.  */
  900.   if (strncmp (encoded, "_ada_", 5) == 0)
  901.     encoded += 5;

  902.   /* If the name starts with '_', then it is not a properly encoded
  903.      name, so do not attempt to decode it.  Similarly, if the name
  904.      starts with '<', the name should not be decoded.  */
  905.   if (encoded[0] == '_' || encoded[0] == '<')
  906.     goto Suppress;

  907.   len0 = strlen (encoded);

  908.   ada_remove_trailing_digits (encoded, &len0);
  909.   ada_remove_po_subprogram_suffix (encoded, &len0);

  910.   /* Remove the ___X.* suffix if present.  Do not forget to verify that
  911.      the suffix is located before the current "end" of ENCODED.  We want
  912.      to avoid re-matching parts of ENCODED that have previously been
  913.      marked as discarded (by decrementing LEN0).  */
  914.   p = strstr (encoded, "___");
  915.   if (p != NULL && p - encoded < len0 - 3)
  916.     {
  917.       if (p[3] == 'X')
  918.         len0 = p - encoded;
  919.       else
  920.         goto Suppress;
  921.     }

  922.   /* Remove any trailing TKB suffix.  It tells us that this symbol
  923.      is for the body of a task, but that information does not actually
  924.      appear in the decoded name.  */

  925.   if (len0 > 3 && strncmp (encoded + len0 - 3, "TKB", 3) == 0)
  926.     len0 -= 3;

  927.   /* Remove any trailing TB suffix.  The TB suffix is slightly different
  928.      from the TKB suffix because it is used for non-anonymous task
  929.      bodies.  */

  930.   if (len0 > 2 && strncmp (encoded + len0 - 2, "TB", 2) == 0)
  931.     len0 -= 2;

  932.   /* Remove trailing "B" suffixes.  */
  933.   /* FIXME: brobecker/2006-04-19: Not sure what this are used for...  */

  934.   if (len0 > 1 && strncmp (encoded + len0 - 1, "B", 1) == 0)
  935.     len0 -= 1;

  936.   /* Make decoded big enough for possible expansion by operator name.  */

  937.   GROW_VECT (decoding_buffer, decoding_buffer_size, 2 * len0 + 1);
  938.   decoded = decoding_buffer;

  939.   /* Remove trailing __{digit}+ or trailing ${digit}+.  */

  940.   if (len0 > 1 && isdigit (encoded[len0 - 1]))
  941.     {
  942.       i = len0 - 2;
  943.       while ((i >= 0 && isdigit (encoded[i]))
  944.              || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
  945.         i -= 1;
  946.       if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
  947.         len0 = i - 1;
  948.       else if (encoded[i] == '$')
  949.         len0 = i;
  950.     }

  951.   /* The first few characters that are not alphabetic are not part
  952.      of any encoding we use, so we can copy them over verbatim.  */

  953.   for (i = 0, j = 0; i < len0 && !isalpha (encoded[i]); i += 1, j += 1)
  954.     decoded[j] = encoded[i];

  955.   at_start_name = 1;
  956.   while (i < len0)
  957.     {
  958.       /* Is this a symbol function?  */
  959.       if (at_start_name && encoded[i] == 'O')
  960.         {
  961.           int k;

  962.           for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
  963.             {
  964.               int op_len = strlen (ada_opname_table[k].encoded);
  965.               if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
  966.                             op_len - 1) == 0)
  967.                   && !isalnum (encoded[i + op_len]))
  968.                 {
  969.                   strcpy (decoded + j, ada_opname_table[k].decoded);
  970.                   at_start_name = 0;
  971.                   i += op_len;
  972.                   j += strlen (ada_opname_table[k].decoded);
  973.                   break;
  974.                 }
  975.             }
  976.           if (ada_opname_table[k].encoded != NULL)
  977.             continue;
  978.         }
  979.       at_start_name = 0;

  980.       /* Replace "TK__" with "__", which will eventually be translated
  981.          into "." (just below).  */

  982.       if (i < len0 - 4 && strncmp (encoded + i, "TK__", 4) == 0)
  983.         i += 2;

  984.       /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
  985.          be translated into "." (just below).  These are internal names
  986.          generated for anonymous blocks inside which our symbol is nested.  */

  987.       if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
  988.           && encoded [i+2] == 'B' && encoded [i+3] == '_'
  989.           && isdigit (encoded [i+4]))
  990.         {
  991.           int k = i + 5;

  992.           while (k < len0 && isdigit (encoded[k]))
  993.             k++;  /* Skip any extra digit.  */

  994.           /* Double-check that the "__B_{DIGITS}+" sequence we found
  995.              is indeed followed by "__".  */
  996.           if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
  997.             i = k;
  998.         }

  999.       /* Remove _E{DIGITS}+[sb] */

  1000.       /* Just as for protected object subprograms, there are 2 categories
  1001.          of subprograms created by the compiler for each entry.  The first
  1002.          one implements the actual entry code, and has a suffix following
  1003.          the convention above; the second one implements the barrier and
  1004.          uses the same convention as above, except that the 'E' is replaced
  1005.          by a 'B'.

  1006.          Just as above, we do not decode the name of barrier functions
  1007.          to give the user a clue that the code he is debugging has been
  1008.          internally generated.  */

  1009.       if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
  1010.           && isdigit (encoded[i+2]))
  1011.         {
  1012.           int k = i + 3;

  1013.           while (k < len0 && isdigit (encoded[k]))
  1014.             k++;

  1015.           if (k < len0
  1016.               && (encoded[k] == 'b' || encoded[k] == 's'))
  1017.             {
  1018.               k++;
  1019.               /* Just as an extra precaution, make sure that if this
  1020.                  suffix is followed by anything else, it is a '_'.
  1021.                  Otherwise, we matched this sequence by accident.  */
  1022.               if (k == len0
  1023.                   || (k < len0 && encoded[k] == '_'))
  1024.                 i = k;
  1025.             }
  1026.         }

  1027.       /* Remove trailing "N" in [a-z0-9]+N__.  The N is added by
  1028.          the GNAT front-end in protected object subprograms.  */

  1029.       if (i < len0 + 3
  1030.           && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
  1031.         {
  1032.           /* Backtrack a bit up until we reach either the begining of
  1033.              the encoded name, or "__".  Make sure that we only find
  1034.              digits or lowercase characters.  */
  1035.           const char *ptr = encoded + i - 1;

  1036.           while (ptr >= encoded && is_lower_alphanum (ptr[0]))
  1037.             ptr--;
  1038.           if (ptr < encoded
  1039.               || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
  1040.             i++;
  1041.         }

  1042.       if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
  1043.         {
  1044.           /* This is a X[bn]* sequence not separated from the previous
  1045.              part of the name with a non-alpha-numeric character (in other
  1046.              words, immediately following an alpha-numeric character), then
  1047.              verify that it is placed at the end of the encoded name.  If
  1048.              not, then the encoding is not valid and we should abort the
  1049.              decoding.  Otherwise, just skip it, it is used in body-nested
  1050.              package names.  */
  1051.           do
  1052.             i += 1;
  1053.           while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
  1054.           if (i < len0)
  1055.             goto Suppress;
  1056.         }
  1057.       else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
  1058.         {
  1059.          /* Replace '__' by '.'.  */
  1060.           decoded[j] = '.';
  1061.           at_start_name = 1;
  1062.           i += 2;
  1063.           j += 1;
  1064.         }
  1065.       else
  1066.         {
  1067.           /* It's a character part of the decoded name, so just copy it
  1068.              over.  */
  1069.           decoded[j] = encoded[i];
  1070.           i += 1;
  1071.           j += 1;
  1072.         }
  1073.     }
  1074.   decoded[j] = '\000';

  1075.   /* Decoded names should never contain any uppercase character.
  1076.      Double-check this, and abort the decoding if we find one.  */

  1077.   for (i = 0; decoded[i] != '\0'; i += 1)
  1078.     if (isupper (decoded[i]) || decoded[i] == ' ')
  1079.       goto Suppress;

  1080.   if (strcmp (decoded, encoded) == 0)
  1081.     return encoded;
  1082.   else
  1083.     return decoded;

  1084. Suppress:
  1085.   GROW_VECT (decoding_buffer, decoding_buffer_size, strlen (encoded) + 3);
  1086.   decoded = decoding_buffer;
  1087.   if (encoded[0] == '<')
  1088.     strcpy (decoded, encoded);
  1089.   else
  1090.     xsnprintf (decoded, decoding_buffer_size, "<%s>", encoded);
  1091.   return decoded;

  1092. }

  1093. /* Table for keeping permanent unique copies of decoded names.  Once
  1094.    allocated, names in this table are never released.  While this is a
  1095.    storage leak, it should not be significant unless there are massive
  1096.    changes in the set of decoded names in successive versions of a
  1097.    symbol table loaded during a single session.  */
  1098. static struct htab *decoded_names_store;

  1099. /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
  1100.    in the language-specific part of GSYMBOL, if it has not been
  1101.    previously computed.  Tries to save the decoded name in the same
  1102.    obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
  1103.    in any case, the decoded symbol has a lifetime at least that of
  1104.    GSYMBOL).
  1105.    The GSYMBOL parameter is "mutable" in the C++ sense: logically
  1106.    const, but nevertheless modified to a semantically equivalent form
  1107.    when a decoded name is cached in it.  */

  1108. const char *
  1109. ada_decode_symbol (const struct general_symbol_info *arg)
  1110. {
  1111.   struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
  1112.   const char **resultp =
  1113.     &gsymbol->language_specific.mangled_lang.demangled_name;

  1114.   if (!gsymbol->ada_mangled)
  1115.     {
  1116.       const char *decoded = ada_decode (gsymbol->name);
  1117.       struct obstack *obstack = gsymbol->language_specific.obstack;

  1118.       gsymbol->ada_mangled = 1;

  1119.       if (obstack != NULL)
  1120.         *resultp = obstack_copy0 (obstack, decoded, strlen (decoded));
  1121.       else
  1122.         {
  1123.           /* Sometimes, we can't find a corresponding objfile, in
  1124.              which case, we put the result on the heap.  Since we only
  1125.              decode when needed, we hope this usually does not cause a
  1126.              significant memory leak (FIXME).  */

  1127.           char **slot = (char **) htab_find_slot (decoded_names_store,
  1128.                                                   decoded, INSERT);

  1129.           if (*slot == NULL)
  1130.             *slot = xstrdup (decoded);
  1131.           *resultp = *slot;
  1132.         }
  1133.     }

  1134.   return *resultp;
  1135. }

  1136. static char *
  1137. ada_la_decode (const char *encoded, int options)
  1138. {
  1139.   return xstrdup (ada_decode (encoded));
  1140. }

  1141. /* Returns non-zero iff SYM_NAME matches NAME, ignoring any trailing
  1142.    suffixes that encode debugging information or leading _ada_ on
  1143.    SYM_NAME (see is_name_suffix commentary for the debugging
  1144.    information that is ignored).  If WILD, then NAME need only match a
  1145.    suffix of SYM_NAME minus the same suffixes.  Also returns 0 if
  1146.    either argument is NULL.  */

  1147. static int
  1148. match_name (const char *sym_name, const char *name, int wild)
  1149. {
  1150.   if (sym_name == NULL || name == NULL)
  1151.     return 0;
  1152.   else if (wild)
  1153.     return wild_match (sym_name, name) == 0;
  1154.   else
  1155.     {
  1156.       int len_name = strlen (name);

  1157.       return (strncmp (sym_name, name, len_name) == 0
  1158.               && is_name_suffix (sym_name + len_name))
  1159.         || (strncmp (sym_name, "_ada_", 5) == 0
  1160.             && strncmp (sym_name + 5, name, len_name) == 0
  1161.             && is_name_suffix (sym_name + len_name + 5));
  1162.     }
  1163. }


  1164.                                 /* Arrays */

  1165. /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
  1166.    generated by the GNAT compiler to describe the index type used
  1167.    for each dimension of an array, check whether it follows the latest
  1168.    known encoding.  If not, fix it up to conform to the latest encoding.
  1169.    Otherwise, do nothing.  This function also does nothing if
  1170.    INDEX_DESC_TYPE is NULL.

  1171.    The GNAT encoding used to describle the array index type evolved a bit.
  1172.    Initially, the information would be provided through the name of each
  1173.    field of the structure type only, while the type of these fields was
  1174.    described as unspecified and irrelevant.  The debugger was then expected
  1175.    to perform a global type lookup using the name of that field in order
  1176.    to get access to the full index type description.  Because these global
  1177.    lookups can be very expensive, the encoding was later enhanced to make
  1178.    the global lookup unnecessary by defining the field type as being
  1179.    the full index type description.

  1180.    The purpose of this routine is to allow us to support older versions
  1181.    of the compiler by detecting the use of the older encoding, and by
  1182.    fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
  1183.    we essentially replace each field's meaningless type by the associated
  1184.    index subtype).  */

  1185. void
  1186. ada_fixup_array_indexes_type (struct type *index_desc_type)
  1187. {
  1188.   int i;

  1189.   if (index_desc_type == NULL)
  1190.     return;
  1191.   gdb_assert (TYPE_NFIELDS (index_desc_type) > 0);

  1192.   /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
  1193.      to check one field only, no need to check them all).  If not, return
  1194.      now.

  1195.      If our INDEX_DESC_TYPE was generated using the older encoding,
  1196.      the field type should be a meaningless integer type whose name
  1197.      is not equal to the field name.  */
  1198.   if (TYPE_NAME (TYPE_FIELD_TYPE (index_desc_type, 0)) != NULL
  1199.       && strcmp (TYPE_NAME (TYPE_FIELD_TYPE (index_desc_type, 0)),
  1200.                  TYPE_FIELD_NAME (index_desc_type, 0)) == 0)
  1201.     return;

  1202.   /* Fixup each field of INDEX_DESC_TYPE.  */
  1203.   for (i = 0; i < TYPE_NFIELDS (index_desc_type); i++)
  1204.    {
  1205.      const char *name = TYPE_FIELD_NAME (index_desc_type, i);
  1206.      struct type *raw_type = ada_check_typedef (ada_find_any_type (name));

  1207.      if (raw_type)
  1208.        TYPE_FIELD_TYPE (index_desc_type, i) = raw_type;
  1209.    }
  1210. }

  1211. /* Names of MAX_ADA_DIMENS bounds in P_BOUNDS fields of array descriptors.  */

  1212. static char *bound_name[] = {
  1213.   "LB0", "UB0", "LB1", "UB1", "LB2", "UB2", "LB3", "UB3",
  1214.   "LB4", "UB4", "LB5", "UB5", "LB6", "UB6", "LB7", "UB7"
  1215. };

  1216. /* Maximum number of array dimensions we are prepared to handle.  */

  1217. #define MAX_ADA_DIMENS (sizeof(bound_name) / (2*sizeof(char *)))


  1218. /* The desc_* routines return primitive portions of array descriptors
  1219.    (fat pointers).  */

  1220. /* The descriptor or array type, if any, indicated by TYPE; removes
  1221.    level of indirection, if needed.  */

  1222. static struct type *
  1223. desc_base_type (struct type *type)
  1224. {
  1225.   if (type == NULL)
  1226.     return NULL;
  1227.   type = ada_check_typedef (type);
  1228.   if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
  1229.     type = ada_typedef_target_type (type);

  1230.   if (type != NULL
  1231.       && (TYPE_CODE (type) == TYPE_CODE_PTR
  1232.           || TYPE_CODE (type) == TYPE_CODE_REF))
  1233.     return ada_check_typedef (TYPE_TARGET_TYPE (type));
  1234.   else
  1235.     return type;
  1236. }

  1237. /* True iff TYPE indicates a "thin" array pointer type.  */

  1238. static int
  1239. is_thin_pntr (struct type *type)
  1240. {
  1241.   return
  1242.     is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
  1243.     || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
  1244. }

  1245. /* The descriptor type for thin pointer type TYPE.  */

  1246. static struct type *
  1247. thin_descriptor_type (struct type *type)
  1248. {
  1249.   struct type *base_type = desc_base_type (type);

  1250.   if (base_type == NULL)
  1251.     return NULL;
  1252.   if (is_suffix (ada_type_name (base_type), "___XVE"))
  1253.     return base_type;
  1254.   else
  1255.     {
  1256.       struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");

  1257.       if (alt_type == NULL)
  1258.         return base_type;
  1259.       else
  1260.         return alt_type;
  1261.     }
  1262. }

  1263. /* A pointer to the array data for thin-pointer value VAL.  */

  1264. static struct value *
  1265. thin_data_pntr (struct value *val)
  1266. {
  1267.   struct type *type = ada_check_typedef (value_type (val));
  1268.   struct type *data_type = desc_data_target_type (thin_descriptor_type (type));

  1269.   data_type = lookup_pointer_type (data_type);

  1270.   if (TYPE_CODE (type) == TYPE_CODE_PTR)
  1271.     return value_cast (data_type, value_copy (val));
  1272.   else
  1273.     return value_from_longest (data_type, value_address (val));
  1274. }

  1275. /* True iff TYPE indicates a "thick" array pointer type.  */

  1276. static int
  1277. is_thick_pntr (struct type *type)
  1278. {
  1279.   type = desc_base_type (type);
  1280.   return (type != NULL && TYPE_CODE (type) == TYPE_CODE_STRUCT
  1281.           && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
  1282. }

  1283. /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
  1284.    pointer to one, the type of its bounds data; otherwise, NULL.  */

  1285. static struct type *
  1286. desc_bounds_type (struct type *type)
  1287. {
  1288.   struct type *r;

  1289.   type = desc_base_type (type);

  1290.   if (type == NULL)
  1291.     return NULL;
  1292.   else if (is_thin_pntr (type))
  1293.     {
  1294.       type = thin_descriptor_type (type);
  1295.       if (type == NULL)
  1296.         return NULL;
  1297.       r = lookup_struct_elt_type (type, "BOUNDS", 1);
  1298.       if (r != NULL)
  1299.         return ada_check_typedef (r);
  1300.     }
  1301.   else if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
  1302.     {
  1303.       r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
  1304.       if (r != NULL)
  1305.         return ada_check_typedef (TYPE_TARGET_TYPE (ada_check_typedef (r)));
  1306.     }
  1307.   return NULL;
  1308. }

  1309. /* If ARR is an array descriptor (fat or thin pointer), or pointer to
  1310.    one, a pointer to its bounds data.   Otherwise NULL.  */

  1311. static struct value *
  1312. desc_bounds (struct value *arr)
  1313. {
  1314.   struct type *type = ada_check_typedef (value_type (arr));

  1315.   if (is_thin_pntr (type))
  1316.     {
  1317.       struct type *bounds_type =
  1318.         desc_bounds_type (thin_descriptor_type (type));
  1319.       LONGEST addr;

  1320.       if (bounds_type == NULL)
  1321.         error (_("Bad GNAT array descriptor"));

  1322.       /* NOTE: The following calculation is not really kosher, but
  1323.          since desc_type is an XVE-encoded type (and shouldn't be),
  1324.          the correct calculation is a real pain.  FIXME (and fix GCC).  */
  1325.       if (TYPE_CODE (type) == TYPE_CODE_PTR)
  1326.         addr = value_as_long (arr);
  1327.       else
  1328.         addr = value_address (arr);

  1329.       return
  1330.         value_from_longest (lookup_pointer_type (bounds_type),
  1331.                             addr - TYPE_LENGTH (bounds_type));
  1332.     }

  1333.   else if (is_thick_pntr (type))
  1334.     {
  1335.       struct value *p_bounds = value_struct_elt (&arr, NULL, "P_BOUNDS", NULL,
  1336.                                                _("Bad GNAT array descriptor"));
  1337.       struct type *p_bounds_type = value_type (p_bounds);

  1338.       if (p_bounds_type
  1339.           && TYPE_CODE (p_bounds_type) == TYPE_CODE_PTR)
  1340.         {
  1341.           struct type *target_type = TYPE_TARGET_TYPE (p_bounds_type);

  1342.           if (TYPE_STUB (target_type))
  1343.             p_bounds = value_cast (lookup_pointer_type
  1344.                                    (ada_check_typedef (target_type)),
  1345.                                    p_bounds);
  1346.         }
  1347.       else
  1348.         error (_("Bad GNAT array descriptor"));

  1349.       return p_bounds;
  1350.     }
  1351.   else
  1352.     return NULL;
  1353. }

  1354. /* If TYPE is the type of an array-descriptor (fat pointer),  the bit
  1355.    position of the field containing the address of the bounds data.  */

  1356. static int
  1357. fat_pntr_bounds_bitpos (struct type *type)
  1358. {
  1359.   return TYPE_FIELD_BITPOS (desc_base_type (type), 1);
  1360. }

  1361. /* If TYPE is the type of an array-descriptor (fat pointer), the bit
  1362.    size of the field containing the address of the bounds data.  */

  1363. static int
  1364. fat_pntr_bounds_bitsize (struct type *type)
  1365. {
  1366.   type = desc_base_type (type);

  1367.   if (TYPE_FIELD_BITSIZE (type, 1) > 0)
  1368.     return TYPE_FIELD_BITSIZE (type, 1);
  1369.   else
  1370.     return 8 * TYPE_LENGTH (ada_check_typedef (TYPE_FIELD_TYPE (type, 1)));
  1371. }

  1372. /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
  1373.    pointer to one, the type of its array data (a array-with-no-bounds type);
  1374.    otherwise, NULL.  Use ada_type_of_array to get an array type with bounds
  1375.    data.  */

  1376. static struct type *
  1377. desc_data_target_type (struct type *type)
  1378. {
  1379.   type = desc_base_type (type);

  1380.   /* NOTE: The following is bogus; see comment in desc_bounds.  */
  1381.   if (is_thin_pntr (type))
  1382.     return desc_base_type (TYPE_FIELD_TYPE (thin_descriptor_type (type), 1));
  1383.   else if (is_thick_pntr (type))
  1384.     {
  1385.       struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);

  1386.       if (data_type
  1387.           && TYPE_CODE (ada_check_typedef (data_type)) == TYPE_CODE_PTR)
  1388.         return ada_check_typedef (TYPE_TARGET_TYPE (data_type));
  1389.     }

  1390.   return NULL;
  1391. }

  1392. /* If ARR is an array descriptor (fat or thin pointer), a pointer to
  1393.    its array data.  */

  1394. static struct value *
  1395. desc_data (struct value *arr)
  1396. {
  1397.   struct type *type = value_type (arr);

  1398.   if (is_thin_pntr (type))
  1399.     return thin_data_pntr (arr);
  1400.   else if (is_thick_pntr (type))
  1401.     return value_struct_elt (&arr, NULL, "P_ARRAY", NULL,
  1402.                              _("Bad GNAT array descriptor"));
  1403.   else
  1404.     return NULL;
  1405. }


  1406. /* If TYPE is the type of an array-descriptor (fat pointer), the bit
  1407.    position of the field containing the address of the data.  */

  1408. static int
  1409. fat_pntr_data_bitpos (struct type *type)
  1410. {
  1411.   return TYPE_FIELD_BITPOS (desc_base_type (type), 0);
  1412. }

  1413. /* If TYPE is the type of an array-descriptor (fat pointer), the bit
  1414.    size of the field containing the address of the data.  */

  1415. static int
  1416. fat_pntr_data_bitsize (struct type *type)
  1417. {
  1418.   type = desc_base_type (type);

  1419.   if (TYPE_FIELD_BITSIZE (type, 0) > 0)
  1420.     return TYPE_FIELD_BITSIZE (type, 0);
  1421.   else
  1422.     return TARGET_CHAR_BIT * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 0));
  1423. }

  1424. /* If BOUNDS is an array-bounds structure (or pointer to one), return
  1425.    the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
  1426.    bound, if WHICH is 1.  The first bound is I=1.  */

  1427. static struct value *
  1428. desc_one_bound (struct value *bounds, int i, int which)
  1429. {
  1430.   return value_struct_elt (&bounds, NULL, bound_name[2 * i + which - 2], NULL,
  1431.                            _("Bad GNAT array descriptor bounds"));
  1432. }

  1433. /* If BOUNDS is an array-bounds structure type, return the bit position
  1434.    of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
  1435.    bound, if WHICH is 1.  The first bound is I=1.  */

  1436. static int
  1437. desc_bound_bitpos (struct type *type, int i, int which)
  1438. {
  1439.   return TYPE_FIELD_BITPOS (desc_base_type (type), 2 * i + which - 2);
  1440. }

  1441. /* If BOUNDS is an array-bounds structure type, return the bit field size
  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. static int
  1445. desc_bound_bitsize (struct type *type, int i, int which)
  1446. {
  1447.   type = desc_base_type (type);

  1448.   if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
  1449.     return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
  1450.   else
  1451.     return 8 * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 2 * i + which - 2));
  1452. }

  1453. /* If TYPE is the type of an array-bounds structure, the type of its
  1454.    Ith bound (numbering from 1).  Otherwise, NULL.  */

  1455. static struct type *
  1456. desc_index_type (struct type *type, int i)
  1457. {
  1458.   type = desc_base_type (type);

  1459.   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
  1460.     return lookup_struct_elt_type (type, bound_name[2 * i - 2], 1);
  1461.   else
  1462.     return NULL;
  1463. }

  1464. /* The number of index positions in the array-bounds type TYPE.
  1465.    Return 0 if TYPE is NULL.  */

  1466. static int
  1467. desc_arity (struct type *type)
  1468. {
  1469.   type = desc_base_type (type);

  1470.   if (type != NULL)
  1471.     return TYPE_NFIELDS (type) / 2;
  1472.   return 0;
  1473. }

  1474. /* Non-zero iff TYPE is a simple array type (not a pointer to one) or
  1475.    an array descriptor type (representing an unconstrained array
  1476.    type).  */

  1477. static int
  1478. ada_is_direct_array_type (struct type *type)
  1479. {
  1480.   if (type == NULL)
  1481.     return 0;
  1482.   type = ada_check_typedef (type);
  1483.   return (TYPE_CODE (type) == TYPE_CODE_ARRAY
  1484.           || ada_is_array_descriptor_type (type));
  1485. }

  1486. /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
  1487. * to one.  */

  1488. static int
  1489. ada_is_array_type (struct type *type)
  1490. {
  1491.   while (type != NULL
  1492.          && (TYPE_CODE (type) == TYPE_CODE_PTR
  1493.              || TYPE_CODE (type) == TYPE_CODE_REF))
  1494.     type = TYPE_TARGET_TYPE (type);
  1495.   return ada_is_direct_array_type (type);
  1496. }

  1497. /* Non-zero iff TYPE is a simple array type or pointer to one.  */

  1498. int
  1499. ada_is_simple_array_type (struct type *type)
  1500. {
  1501.   if (type == NULL)
  1502.     return 0;
  1503.   type = ada_check_typedef (type);
  1504.   return (TYPE_CODE (type) == TYPE_CODE_ARRAY
  1505.           || (TYPE_CODE (type) == TYPE_CODE_PTR
  1506.               && TYPE_CODE (ada_check_typedef (TYPE_TARGET_TYPE (type)))
  1507.                  == TYPE_CODE_ARRAY));
  1508. }

  1509. /* Non-zero iff TYPE belongs to a GNAT array descriptor.  */

  1510. int
  1511. ada_is_array_descriptor_type (struct type *type)
  1512. {
  1513.   struct type *data_type = desc_data_target_type (type);

  1514.   if (type == NULL)
  1515.     return 0;
  1516.   type = ada_check_typedef (type);
  1517.   return (data_type != NULL
  1518.           && TYPE_CODE (data_type) == TYPE_CODE_ARRAY
  1519.           && desc_arity (desc_bounds_type (type)) > 0);
  1520. }

  1521. /* Non-zero iff type is a partially mal-formed GNAT array
  1522.    descriptor.  FIXME: This is to compensate for some problems with
  1523.    debugging output from GNAT.  Re-examine periodically to see if it
  1524.    is still needed.  */

  1525. int
  1526. ada_is_bogus_array_descriptor (struct type *type)
  1527. {
  1528.   return
  1529.     type != NULL
  1530.     && TYPE_CODE (type) == TYPE_CODE_STRUCT
  1531.     && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
  1532.         || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
  1533.     && !ada_is_array_descriptor_type (type);
  1534. }


  1535. /* If ARR has a record type in the form of a standard GNAT array descriptor,
  1536.    (fat pointer) returns the type of the array data described---specifically,
  1537.    a pointer-to-array type.  If BOUNDS is non-zero, the bounds data are filled
  1538.    in from the descriptor; otherwise, they are left unspecified.  If
  1539.    the ARR denotes a null array descriptor and BOUNDS is non-zero,
  1540.    returns NULL.  The result is simply the type of ARR if ARR is not
  1541.    a descriptor.  */
  1542. struct type *
  1543. ada_type_of_array (struct value *arr, int bounds)
  1544. {
  1545.   if (ada_is_constrained_packed_array_type (value_type (arr)))
  1546.     return decode_constrained_packed_array_type (value_type (arr));

  1547.   if (!ada_is_array_descriptor_type (value_type (arr)))
  1548.     return value_type (arr);

  1549.   if (!bounds)
  1550.     {
  1551.       struct type *array_type =
  1552.         ada_check_typedef (desc_data_target_type (value_type (arr)));

  1553.       if (ada_is_unconstrained_packed_array_type (value_type (arr)))
  1554.         TYPE_FIELD_BITSIZE (array_type, 0) =
  1555.           decode_packed_array_bitsize (value_type (arr));

  1556.       return array_type;
  1557.     }
  1558.   else
  1559.     {
  1560.       struct type *elt_type;
  1561.       int arity;
  1562.       struct value *descriptor;

  1563.       elt_type = ada_array_element_type (value_type (arr), -1);
  1564.       arity = ada_array_arity (value_type (arr));

  1565.       if (elt_type == NULL || arity == 0)
  1566.         return ada_check_typedef (value_type (arr));

  1567.       descriptor = desc_bounds (arr);
  1568.       if (value_as_long (descriptor) == 0)
  1569.         return NULL;
  1570.       while (arity > 0)
  1571.         {
  1572.           struct type *range_type = alloc_type_copy (value_type (arr));
  1573.           struct type *array_type = alloc_type_copy (value_type (arr));
  1574.           struct value *low = desc_one_bound (descriptor, arity, 0);
  1575.           struct value *high = desc_one_bound (descriptor, arity, 1);

  1576.           arity -= 1;
  1577.           create_static_range_type (range_type, value_type (low),
  1578.                                     longest_to_int (value_as_long (low)),
  1579.                                     longest_to_int (value_as_long (high)));
  1580.           elt_type = create_array_type (array_type, elt_type, range_type);

  1581.           if (ada_is_unconstrained_packed_array_type (value_type (arr)))
  1582.             {
  1583.               /* We need to store the element packed bitsize, as well as
  1584.                  recompute the array size, because it was previously
  1585.                  computed based on the unpacked element size.  */
  1586.               LONGEST lo = value_as_long (low);
  1587.               LONGEST hi = value_as_long (high);

  1588.               TYPE_FIELD_BITSIZE (elt_type, 0) =
  1589.                 decode_packed_array_bitsize (value_type (arr));
  1590.               /* If the array has no element, then the size is already
  1591.                  zero, and does not need to be recomputed.  */
  1592.               if (lo < hi)
  1593.                 {
  1594.                   int array_bitsize =
  1595.                         (hi - lo + 1) * TYPE_FIELD_BITSIZE (elt_type, 0);

  1596.                   TYPE_LENGTH (array_type) = (array_bitsize + 7) / 8;
  1597.                 }
  1598.             }
  1599.         }

  1600.       return lookup_pointer_type (elt_type);
  1601.     }
  1602. }

  1603. /* If ARR does not represent an array, returns ARR unchanged.
  1604.    Otherwise, returns either a standard GDB array with bounds set
  1605.    appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
  1606.    GDB array.  Returns NULL if ARR is a null fat pointer.  */

  1607. struct value *
  1608. ada_coerce_to_simple_array_ptr (struct value *arr)
  1609. {
  1610.   if (ada_is_array_descriptor_type (value_type (arr)))
  1611.     {
  1612.       struct type *arrType = ada_type_of_array (arr, 1);

  1613.       if (arrType == NULL)
  1614.         return NULL;
  1615.       return value_cast (arrType, value_copy (desc_data (arr)));
  1616.     }
  1617.   else if (ada_is_constrained_packed_array_type (value_type (arr)))
  1618.     return decode_constrained_packed_array (arr);
  1619.   else
  1620.     return arr;
  1621. }

  1622. /* If ARR does not represent an array, returns ARR unchanged.
  1623.    Otherwise, returns a standard GDB array describing ARR (which may
  1624.    be ARR itself if it already is in the proper form).  */

  1625. struct value *
  1626. ada_coerce_to_simple_array (struct value *arr)
  1627. {
  1628.   if (ada_is_array_descriptor_type (value_type (arr)))
  1629.     {
  1630.       struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);

  1631.       if (arrVal == NULL)
  1632.         error (_("Bounds unavailable for null array pointer."));
  1633.       ada_ensure_varsize_limit (TYPE_TARGET_TYPE (value_type (arrVal)));
  1634.       return value_ind (arrVal);
  1635.     }
  1636.   else if (ada_is_constrained_packed_array_type (value_type (arr)))
  1637.     return decode_constrained_packed_array (arr);
  1638.   else
  1639.     return arr;
  1640. }

  1641. /* If TYPE represents a GNAT array type, return it translated to an
  1642.    ordinary GDB array type (possibly with BITSIZE fields indicating
  1643.    packing).  For other types, is the identity.  */

  1644. struct type *
  1645. ada_coerce_to_simple_array_type (struct type *type)
  1646. {
  1647.   if (ada_is_constrained_packed_array_type (type))
  1648.     return decode_constrained_packed_array_type (type);

  1649.   if (ada_is_array_descriptor_type (type))
  1650.     return ada_check_typedef (desc_data_target_type (type));

  1651.   return type;
  1652. }

  1653. /* Non-zero iff TYPE represents a standard GNAT packed-array type.  */

  1654. static int
  1655. ada_is_packed_array_type  (struct type *type)
  1656. {
  1657.   if (type == NULL)
  1658.     return 0;
  1659.   type = desc_base_type (type);
  1660.   type = ada_check_typedef (type);
  1661.   return
  1662.     ada_type_name (type) != NULL
  1663.     && strstr (ada_type_name (type), "___XP") != NULL;
  1664. }

  1665. /* Non-zero iff TYPE represents a standard GNAT constrained
  1666.    packed-array type.  */

  1667. int
  1668. ada_is_constrained_packed_array_type (struct type *type)
  1669. {
  1670.   return ada_is_packed_array_type (type)
  1671.     && !ada_is_array_descriptor_type (type);
  1672. }

  1673. /* Non-zero iff TYPE represents an array descriptor for a
  1674.    unconstrained packed-array type.  */

  1675. static int
  1676. ada_is_unconstrained_packed_array_type (struct type *type)
  1677. {
  1678.   return ada_is_packed_array_type (type)
  1679.     && ada_is_array_descriptor_type (type);
  1680. }

  1681. /* Given that TYPE encodes a packed array type (constrained or unconstrained),
  1682.    return the size of its elements in bits.  */

  1683. static long
  1684. decode_packed_array_bitsize (struct type *type)
  1685. {
  1686.   const char *raw_name;
  1687.   const char *tail;
  1688.   long bits;

  1689.   /* Access to arrays implemented as fat pointers are encoded as a typedef
  1690.      of the fat pointer type.  We need the name of the fat pointer type
  1691.      to do the decoding, so strip the typedef layer.  */
  1692.   if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
  1693.     type = ada_typedef_target_type (type);

  1694.   raw_name = ada_type_name (ada_check_typedef (type));
  1695.   if (!raw_name)
  1696.     raw_name = ada_type_name (desc_base_type (type));

  1697.   if (!raw_name)
  1698.     return 0;

  1699.   tail = strstr (raw_name, "___XP");
  1700.   gdb_assert (tail != NULL);

  1701.   if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
  1702.     {
  1703.       lim_warning
  1704.         (_("could not understand bit size information on packed array"));
  1705.       return 0;
  1706.     }

  1707.   return bits;
  1708. }

  1709. /* Given that TYPE is a standard GDB array type with all bounds filled
  1710.    in, and that the element size of its ultimate scalar constituents
  1711.    (that is, either its elements, or, if it is an array of arrays, its
  1712.    elements' elements, etc.) is *ELT_BITS, return an identical type,
  1713.    but with the bit sizes of its elements (and those of any
  1714.    constituent arrays) recorded in the BITSIZE components of its
  1715.    TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
  1716.    in bits.

  1717.    Note that, for arrays whose index type has an XA encoding where
  1718.    a bound references a record discriminant, getting that discriminant,
  1719.    and therefore the actual value of that bound, is not possible
  1720.    because none of the given parameters gives us access to the record.
  1721.    This function assumes that it is OK in the context where it is being
  1722.    used to return an array whose bounds are still dynamic and where
  1723.    the length is arbitrary.  */

  1724. static struct type *
  1725. constrained_packed_array_type (struct type *type, long *elt_bits)
  1726. {
  1727.   struct type *new_elt_type;
  1728.   struct type *new_type;
  1729.   struct type *index_type_desc;
  1730.   struct type *index_type;
  1731.   LONGEST low_bound, high_bound;

  1732.   type = ada_check_typedef (type);
  1733.   if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
  1734.     return type;

  1735.   index_type_desc = ada_find_parallel_type (type, "___XA");
  1736.   if (index_type_desc)
  1737.     index_type = to_fixed_range_type (TYPE_FIELD_TYPE (index_type_desc, 0),
  1738.                                       NULL);
  1739.   else
  1740.     index_type = TYPE_INDEX_TYPE (type);

  1741.   new_type = alloc_type_copy (type);
  1742.   new_elt_type =
  1743.     constrained_packed_array_type (ada_check_typedef (TYPE_TARGET_TYPE (type)),
  1744.                                    elt_bits);
  1745.   create_array_type (new_type, new_elt_type, index_type);
  1746.   TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
  1747.   TYPE_NAME (new_type) = ada_type_name (type);

  1748.   if ((TYPE_CODE (check_typedef (index_type)) == TYPE_CODE_RANGE
  1749.        && is_dynamic_type (check_typedef (index_type)))
  1750.       || get_discrete_bounds (index_type, &low_bound, &high_bound) < 0)
  1751.     low_bound = high_bound = 0;
  1752.   if (high_bound < low_bound)
  1753.     *elt_bits = TYPE_LENGTH (new_type) = 0;
  1754.   else
  1755.     {
  1756.       *elt_bits *= (high_bound - low_bound + 1);
  1757.       TYPE_LENGTH (new_type) =
  1758.         (*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
  1759.     }

  1760.   TYPE_FIXED_INSTANCE (new_type) = 1;
  1761.   return new_type;
  1762. }

  1763. /* The array type encoded by TYPE, where
  1764.    ada_is_constrained_packed_array_type (TYPE).  */

  1765. static struct type *
  1766. decode_constrained_packed_array_type (struct type *type)
  1767. {
  1768.   const char *raw_name = ada_type_name (ada_check_typedef (type));
  1769.   char *name;
  1770.   const char *tail;
  1771.   struct type *shadow_type;
  1772.   long bits;

  1773.   if (!raw_name)
  1774.     raw_name = ada_type_name (desc_base_type (type));

  1775.   if (!raw_name)
  1776.     return NULL;

  1777.   name = (char *) alloca (strlen (raw_name) + 1);
  1778.   tail = strstr (raw_name, "___XP");
  1779.   type = desc_base_type (type);

  1780.   memcpy (name, raw_name, tail - raw_name);
  1781.   name[tail - raw_name] = '\000';

  1782.   shadow_type = ada_find_parallel_type_with_name (type, name);

  1783.   if (shadow_type == NULL)
  1784.     {
  1785.       lim_warning (_("could not find bounds information on packed array"));
  1786.       return NULL;
  1787.     }
  1788.   CHECK_TYPEDEF (shadow_type);

  1789.   if (TYPE_CODE (shadow_type) != TYPE_CODE_ARRAY)
  1790.     {
  1791.       lim_warning (_("could not understand bounds "
  1792.                      "information on packed array"));
  1793.       return NULL;
  1794.     }

  1795.   bits = decode_packed_array_bitsize (type);
  1796.   return constrained_packed_array_type (shadow_type, &bits);
  1797. }

  1798. /* Given that ARR is a struct value *indicating a GNAT constrained packed
  1799.    array, returns a simple array that denotes that array.  Its type is a
  1800.    standard GDB array type except that the BITSIZEs of the array
  1801.    target types are set to the number of bits in each element, and the
  1802.    type length is set appropriately.  */

  1803. static struct value *
  1804. decode_constrained_packed_array (struct value *arr)
  1805. {
  1806.   struct type *type;

  1807.   /* If our value is a pointer, then dereference it. Likewise if
  1808.      the value is a reference.  Make sure that this operation does not
  1809.      cause the target type to be fixed, as this would indirectly cause
  1810.      this array to be decoded.  The rest of the routine assumes that
  1811.      the array hasn't been decoded yet, so we use the basic "coerce_ref"
  1812.      and "value_ind" routines to perform the dereferencing, as opposed
  1813.      to using "ada_coerce_ref" or "ada_value_ind".  */
  1814.   arr = coerce_ref (arr);
  1815.   if (TYPE_CODE (ada_check_typedef (value_type (arr))) == TYPE_CODE_PTR)
  1816.     arr = value_ind (arr);

  1817.   type = decode_constrained_packed_array_type (value_type (arr));
  1818.   if (type == NULL)
  1819.     {
  1820.       error (_("can't unpack array"));
  1821.       return NULL;
  1822.     }

  1823.   if (gdbarch_bits_big_endian (get_type_arch (value_type (arr)))
  1824.       && ada_is_modular_type (value_type (arr)))
  1825.     {
  1826.        /* This is a (right-justified) modular type representing a packed
  1827.           array with no wrapper.  In order to interpret the value through
  1828.           the (left-justified) packed array type we just built, we must
  1829.           first left-justify it.  */
  1830.       int bit_size, bit_pos;
  1831.       ULONGEST mod;

  1832.       mod = ada_modulus (value_type (arr)) - 1;
  1833.       bit_size = 0;
  1834.       while (mod > 0)
  1835.         {
  1836.           bit_size += 1;
  1837.           mod >>= 1;
  1838.         }
  1839.       bit_pos = HOST_CHAR_BIT * TYPE_LENGTH (value_type (arr)) - bit_size;
  1840.       arr = ada_value_primitive_packed_val (arr, NULL,
  1841.                                             bit_pos / HOST_CHAR_BIT,
  1842.                                             bit_pos % HOST_CHAR_BIT,
  1843.                                             bit_size,
  1844.                                             type);
  1845.     }

  1846.   return coerce_unspec_val_to_type (arr, type);
  1847. }


  1848. /* The value of the element of packed array ARR at the ARITY indices
  1849.    given in IND.   ARR must be a simple array.  */

  1850. static struct value *
  1851. value_subscript_packed (struct value *arr, int arity, struct value **ind)
  1852. {
  1853.   int i;
  1854.   int bits, elt_off, bit_off;
  1855.   long elt_total_bit_offset;
  1856.   struct type *elt_type;
  1857.   struct value *v;

  1858.   bits = 0;
  1859.   elt_total_bit_offset = 0;
  1860.   elt_type = ada_check_typedef (value_type (arr));
  1861.   for (i = 0; i < arity; i += 1)
  1862.     {
  1863.       if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY
  1864.           || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
  1865.         error
  1866.           (_("attempt to do packed indexing of "
  1867.              "something other than a packed array"));
  1868.       else
  1869.         {
  1870.           struct type *range_type = TYPE_INDEX_TYPE (elt_type);
  1871.           LONGEST lowerbound, upperbound;
  1872.           LONGEST idx;

  1873.           if (get_discrete_bounds (range_type, &lowerbound, &upperbound) < 0)
  1874.             {
  1875.               lim_warning (_("don't know bounds of array"));
  1876.               lowerbound = upperbound = 0;
  1877.             }

  1878.           idx = pos_atr (ind[i]);
  1879.           if (idx < lowerbound || idx > upperbound)
  1880.             lim_warning (_("packed array index %ld out of bounds"),
  1881.                          (long) idx);
  1882.           bits = TYPE_FIELD_BITSIZE (elt_type, 0);
  1883.           elt_total_bit_offset += (idx - lowerbound) * bits;
  1884.           elt_type = ada_check_typedef (TYPE_TARGET_TYPE (elt_type));
  1885.         }
  1886.     }
  1887.   elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
  1888.   bit_off = elt_total_bit_offset % HOST_CHAR_BIT;

  1889.   v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
  1890.                                       bits, elt_type);
  1891.   return v;
  1892. }

  1893. /* Non-zero iff TYPE includes negative integer values.  */

  1894. static int
  1895. has_negatives (struct type *type)
  1896. {
  1897.   switch (TYPE_CODE (type))
  1898.     {
  1899.     default:
  1900.       return 0;
  1901.     case TYPE_CODE_INT:
  1902.       return !TYPE_UNSIGNED (type);
  1903.     case TYPE_CODE_RANGE:
  1904.       return TYPE_LOW_BOUND (type) < 0;
  1905.     }
  1906. }


  1907. /* Create a new value of type TYPE from the contents of OBJ starting
  1908.    at byte OFFSET, and bit offset BIT_OFFSET within that byte,
  1909.    proceeding for BIT_SIZE bits.  If OBJ is an lval in memory, then
  1910.    assigning through the result will set the field fetched from.
  1911.    VALADDR is ignored unless OBJ is NULL, in which case,
  1912.    VALADDR+OFFSET must address the start of storage containing the
  1913.    packed value.  The value returned  in this case is never an lval.
  1914.    Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT.  */

  1915. struct value *
  1916. ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
  1917.                                 long offset, int bit_offset, int bit_size,
  1918.                                 struct type *type)
  1919. {
  1920.   struct value *v;
  1921.   int src,                      /* Index into the source area */
  1922.     targ,                       /* Index into the target area */
  1923.     srcBitsLeft,                /* Number of source bits left to move */
  1924.     nsrc, ntarg,                /* Number of source and target bytes */
  1925.     unusedLS,                   /* Number of bits in next significant
  1926.                                    byte of source that are unused */
  1927.     accumSize;                  /* Number of meaningful bits in accum */
  1928.   unsigned char *bytes;         /* First byte containing data to unpack */
  1929.   unsigned char *unpacked;
  1930.   unsigned long accum;          /* Staging area for bits being transferred */
  1931.   unsigned char sign;
  1932.   int len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
  1933.   /* Transmit bytes from least to most significant; delta is the direction
  1934.      the indices move.  */
  1935.   int delta = gdbarch_bits_big_endian (get_type_arch (type)) ? -1 : 1;

  1936.   type = ada_check_typedef (type);

  1937.   if (obj == NULL)
  1938.     {
  1939.       v = allocate_value (type);
  1940.       bytes = (unsigned char *) (valaddr + offset);
  1941.     }
  1942.   else if (VALUE_LVAL (obj) == lval_memory && value_lazy (obj))
  1943.     {
  1944.       v = value_at (type, value_address (obj));
  1945.       type = value_type (v);
  1946.       bytes = (unsigned char *) alloca (len);
  1947.       read_memory (value_address (v) + offset, bytes, len);
  1948.     }
  1949.   else
  1950.     {
  1951.       v = allocate_value (type);
  1952.       bytes = (unsigned char *) value_contents (obj) + offset;
  1953.     }

  1954.   if (obj != NULL)
  1955.     {
  1956.       long new_offset = offset;

  1957.       set_value_component_location (v, obj);
  1958.       set_value_bitpos (v, bit_offset + value_bitpos (obj));
  1959.       set_value_bitsize (v, bit_size);
  1960.       if (value_bitpos (v) >= HOST_CHAR_BIT)
  1961.         {
  1962.           ++new_offset;
  1963.           set_value_bitpos (v, value_bitpos (v) - HOST_CHAR_BIT);
  1964.         }
  1965.       set_value_offset (v, new_offset);

  1966.       /* Also set the parent value.  This is needed when trying to
  1967.          assign a new value (in inferior memory).  */
  1968.       set_value_parent (v, obj);
  1969.     }
  1970.   else
  1971.     set_value_bitsize (v, bit_size);
  1972.   unpacked = (unsigned char *) value_contents (v);

  1973.   srcBitsLeft = bit_size;
  1974.   nsrc = len;
  1975.   ntarg = TYPE_LENGTH (type);
  1976.   sign = 0;
  1977.   if (bit_size == 0)
  1978.     {
  1979.       memset (unpacked, 0, TYPE_LENGTH (type));
  1980.       return v;
  1981.     }
  1982.   else if (gdbarch_bits_big_endian (get_type_arch (type)))
  1983.     {
  1984.       src = len - 1;
  1985.       if (has_negatives (type)
  1986.           && ((bytes[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
  1987.         sign = ~0;

  1988.       unusedLS =
  1989.         (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
  1990.         % HOST_CHAR_BIT;

  1991.       switch (TYPE_CODE (type))
  1992.         {
  1993.         case TYPE_CODE_ARRAY:
  1994.         case TYPE_CODE_UNION:
  1995.         case TYPE_CODE_STRUCT:
  1996.           /* Non-scalar values must be aligned at a byte boundary...  */
  1997.           accumSize =
  1998.             (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
  1999.           /* ... And are placed at the beginning (most-significant) bytes
  2000.              of the target.  */
  2001.           targ = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
  2002.           ntarg = targ + 1;
  2003.           break;
  2004.         default:
  2005.           accumSize = 0;
  2006.           targ = TYPE_LENGTH (type) - 1;
  2007.           break;
  2008.         }
  2009.     }
  2010.   else
  2011.     {
  2012.       int sign_bit_offset = (bit_size + bit_offset - 1) % 8;

  2013.       src = targ = 0;
  2014.       unusedLS = bit_offset;
  2015.       accumSize = 0;

  2016.       if (has_negatives (type) && (bytes[len - 1] & (1 << sign_bit_offset)))
  2017.         sign = ~0;
  2018.     }

  2019.   accum = 0;
  2020.   while (nsrc > 0)
  2021.     {
  2022.       /* Mask for removing bits of the next source byte that are not
  2023.          part of the value.  */
  2024.       unsigned int unusedMSMask =
  2025.         (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
  2026.         1;
  2027.       /* Sign-extend bits for this byte.  */
  2028.       unsigned int signMask = sign & ~unusedMSMask;

  2029.       accum |=
  2030.         (((bytes[src] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
  2031.       accumSize += HOST_CHAR_BIT - unusedLS;
  2032.       if (accumSize >= HOST_CHAR_BIT)
  2033.         {
  2034.           unpacked[targ] = accum & ~(~0L << HOST_CHAR_BIT);
  2035.           accumSize -= HOST_CHAR_BIT;
  2036.           accum >>= HOST_CHAR_BIT;
  2037.           ntarg -= 1;
  2038.           targ += delta;
  2039.         }
  2040.       srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
  2041.       unusedLS = 0;
  2042.       nsrc -= 1;
  2043.       src += delta;
  2044.     }
  2045.   while (ntarg > 0)
  2046.     {
  2047.       accum |= sign << accumSize;
  2048.       unpacked[targ] = accum & ~(~0L << HOST_CHAR_BIT);
  2049.       accumSize -= HOST_CHAR_BIT;
  2050.       accum >>= HOST_CHAR_BIT;
  2051.       ntarg -= 1;
  2052.       targ += delta;
  2053.     }

  2054.   return v;
  2055. }

  2056. /* Move N bits from SOURCE, starting at bit offset SRC_OFFSET to
  2057.    TARGET, starting at bit offset TARG_OFFSET.  SOURCE and TARGET must
  2058.    not overlap.  */
  2059. static void
  2060. move_bits (gdb_byte *target, int targ_offset, const gdb_byte *source,
  2061.            int src_offset, int n, int bits_big_endian_p)
  2062. {
  2063.   unsigned int accum, mask;
  2064.   int accum_bits, chunk_size;

  2065.   target += targ_offset / HOST_CHAR_BIT;
  2066.   targ_offset %= HOST_CHAR_BIT;
  2067.   source += src_offset / HOST_CHAR_BIT;
  2068.   src_offset %= HOST_CHAR_BIT;
  2069.   if (bits_big_endian_p)
  2070.     {
  2071.       accum = (unsigned char) *source;
  2072.       source += 1;
  2073.       accum_bits = HOST_CHAR_BIT - src_offset;

  2074.       while (n > 0)
  2075.         {
  2076.           int unused_right;

  2077.           accum = (accum << HOST_CHAR_BIT) + (unsigned char) *source;
  2078.           accum_bits += HOST_CHAR_BIT;
  2079.           source += 1;
  2080.           chunk_size = HOST_CHAR_BIT - targ_offset;
  2081.           if (chunk_size > n)
  2082.             chunk_size = n;
  2083.           unused_right = HOST_CHAR_BIT - (chunk_size + targ_offset);
  2084.           mask = ((1 << chunk_size) - 1) << unused_right;
  2085.           *target =
  2086.             (*target & ~mask)
  2087.             | ((accum >> (accum_bits - chunk_size - unused_right)) & mask);
  2088.           n -= chunk_size;
  2089.           accum_bits -= chunk_size;
  2090.           target += 1;
  2091.           targ_offset = 0;
  2092.         }
  2093.     }
  2094.   else
  2095.     {
  2096.       accum = (unsigned char) *source >> src_offset;
  2097.       source += 1;
  2098.       accum_bits = HOST_CHAR_BIT - src_offset;

  2099.       while (n > 0)
  2100.         {
  2101.           accum = accum + ((unsigned char) *source << accum_bits);
  2102.           accum_bits += HOST_CHAR_BIT;
  2103.           source += 1;
  2104.           chunk_size = HOST_CHAR_BIT - targ_offset;
  2105.           if (chunk_size > n)
  2106.             chunk_size = n;
  2107.           mask = ((1 << chunk_size) - 1) << targ_offset;
  2108.           *target = (*target & ~mask) | ((accum << targ_offset) & mask);
  2109.           n -= chunk_size;
  2110.           accum_bits -= chunk_size;
  2111.           accum >>= chunk_size;
  2112.           target += 1;
  2113.           targ_offset = 0;
  2114.         }
  2115.     }
  2116. }

  2117. /* Store the contents of FROMVAL into the location of TOVAL.
  2118.    Return a new value with the location of TOVAL and contents of
  2119.    FROMVAL.   Handles assignment into packed fields that have
  2120.    floating-point or non-scalar types.  */

  2121. static struct value *
  2122. ada_value_assign (struct value *toval, struct value *fromval)
  2123. {
  2124.   struct type *type = value_type (toval);
  2125.   int bits = value_bitsize (toval);

  2126.   toval = ada_coerce_ref (toval);
  2127.   fromval = ada_coerce_ref (fromval);

  2128.   if (ada_is_direct_array_type (value_type (toval)))
  2129.     toval = ada_coerce_to_simple_array (toval);
  2130.   if (ada_is_direct_array_type (value_type (fromval)))
  2131.     fromval = ada_coerce_to_simple_array (fromval);

  2132.   if (!deprecated_value_modifiable (toval))
  2133.     error (_("Left operand of assignment is not a modifiable lvalue."));

  2134.   if (VALUE_LVAL (toval) == lval_memory
  2135.       && bits > 0
  2136.       && (TYPE_CODE (type) == TYPE_CODE_FLT
  2137.           || TYPE_CODE (type) == TYPE_CODE_STRUCT))
  2138.     {
  2139.       int len = (value_bitpos (toval)
  2140.                  + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
  2141.       int from_size;
  2142.       gdb_byte *buffer = alloca (len);
  2143.       struct value *val;
  2144.       CORE_ADDR to_addr = value_address (toval);

  2145.       if (TYPE_CODE (type) == TYPE_CODE_FLT)
  2146.         fromval = value_cast (type, fromval);

  2147.       read_memory (to_addr, buffer, len);
  2148.       from_size = value_bitsize (fromval);
  2149.       if (from_size == 0)
  2150.         from_size = TYPE_LENGTH (value_type (fromval)) * TARGET_CHAR_BIT;
  2151.       if (gdbarch_bits_big_endian (get_type_arch (type)))
  2152.         move_bits (buffer, value_bitpos (toval),
  2153.                    value_contents (fromval), from_size - bits, bits, 1);
  2154.       else
  2155.         move_bits (buffer, value_bitpos (toval),
  2156.                    value_contents (fromval), 0, bits, 0);
  2157.       write_memory_with_notification (to_addr, buffer, len);

  2158.       val = value_copy (toval);
  2159.       memcpy (value_contents_raw (val), value_contents (fromval),
  2160.               TYPE_LENGTH (type));
  2161.       deprecated_set_value_type (val, type);

  2162.       return val;
  2163.     }

  2164.   return value_assign (toval, fromval);
  2165. }


  2166. /* Given that COMPONENT is a memory lvalue that is part of the lvalue
  2167. * CONTAINER, assign the contents of VAL to COMPONENTS's place in
  2168. * CONTAINER.  Modifies the VALUE_CONTENTS of CONTAINER only, not
  2169. * COMPONENT, and not the inferior's memory.  The current contents
  2170. * of COMPONENT are ignored.  */
  2171. static void
  2172. value_assign_to_component (struct value *container, struct value *component,
  2173.                            struct value *val)
  2174. {
  2175.   LONGEST offset_in_container =
  2176.     (LONGEST)  (value_address (component) - value_address (container));
  2177.   int bit_offset_in_container =
  2178.     value_bitpos (component) - value_bitpos (container);
  2179.   int bits;

  2180.   val = value_cast (value_type (component), val);

  2181.   if (value_bitsize (component) == 0)
  2182.     bits = TARGET_CHAR_BIT * TYPE_LENGTH (value_type (component));
  2183.   else
  2184.     bits = value_bitsize (component);

  2185.   if (gdbarch_bits_big_endian (get_type_arch (value_type (container))))
  2186.     move_bits (value_contents_writeable (container) + offset_in_container,
  2187.                value_bitpos (container) + bit_offset_in_container,
  2188.                value_contents (val),
  2189.                TYPE_LENGTH (value_type (component)) * TARGET_CHAR_BIT - bits,
  2190.                bits, 1);
  2191.   else
  2192.     move_bits (value_contents_writeable (container) + offset_in_container,
  2193.                value_bitpos (container) + bit_offset_in_container,
  2194.                value_contents (val), 0, bits, 0);
  2195. }

  2196. /* The value of the element of array ARR at the ARITY indices given in IND.
  2197.    ARR may be either a simple array, GNAT array descriptor, or pointer
  2198.    thereto.  */

  2199. struct value *
  2200. ada_value_subscript (struct value *arr, int arity, struct value **ind)
  2201. {
  2202.   int k;
  2203.   struct value *elt;
  2204.   struct type *elt_type;

  2205.   elt = ada_coerce_to_simple_array (arr);

  2206.   elt_type = ada_check_typedef (value_type (elt));
  2207.   if (TYPE_CODE (elt_type) == TYPE_CODE_ARRAY
  2208.       && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
  2209.     return value_subscript_packed (elt, arity, ind);

  2210.   for (k = 0; k < arity; k += 1)
  2211.     {
  2212.       if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY)
  2213.         error (_("too many subscripts (%d expected)"), k);
  2214.       elt = value_subscript (elt, pos_atr (ind[k]));
  2215.     }
  2216.   return elt;
  2217. }

  2218. /* Assuming ARR is a pointer to a GDB array, the value of the element
  2219.    of *ARR at the ARITY indices given in IND.
  2220.    Does not read the entire array into memory.  */

  2221. static struct value *
  2222. ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
  2223. {
  2224.   int k;
  2225.   struct type *type
  2226.     = check_typedef (value_enclosing_type (ada_value_ind (arr)));

  2227.   for (k = 0; k < arity; k += 1)
  2228.     {
  2229.       LONGEST lwb, upb;

  2230.       if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
  2231.         error (_("too many subscripts (%d expected)"), k);
  2232.       arr = value_cast (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
  2233.                         value_copy (arr));
  2234.       get_discrete_bounds (TYPE_INDEX_TYPE (type), &lwb, &upb);
  2235.       arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
  2236.       type = TYPE_TARGET_TYPE (type);
  2237.     }

  2238.   return value_ind (arr);
  2239. }

  2240. /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
  2241.    actual type of ARRAY_PTR is ignored), returns the Ada slice of HIGH-LOW+1
  2242.    elements starting at index LOW.  The lower bound of this array is LOW, as
  2243.    per Ada rules.  */
  2244. static struct value *
  2245. ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
  2246.                           int low, int high)
  2247. {
  2248.   struct type *type0 = ada_check_typedef (type);
  2249.   CORE_ADDR base = value_as_address (array_ptr)
  2250.     + ((low - ada_discrete_type_low_bound (TYPE_INDEX_TYPE (type0)))
  2251.        * TYPE_LENGTH (TYPE_TARGET_TYPE (type0)));
  2252.   struct type *index_type
  2253.     = create_static_range_type (NULL,
  2254.                                 TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (type0)),
  2255.                                 low, high);
  2256.   struct type *slice_type =
  2257.     create_array_type (NULL, TYPE_TARGET_TYPE (type0), index_type);

  2258.   return value_at_lazy (slice_type, base);
  2259. }


  2260. static struct value *
  2261. ada_value_slice (struct value *array, int low, int high)
  2262. {
  2263.   struct type *type = ada_check_typedef (value_type (array));
  2264.   struct type *index_type
  2265.     = create_static_range_type (NULL, TYPE_INDEX_TYPE (type), low, high);
  2266.   struct type *slice_type =
  2267.     create_array_type (NULL, TYPE_TARGET_TYPE (type), index_type);

  2268.   return value_cast (slice_type, value_slice (array, low, high - low + 1));
  2269. }

  2270. /* If type is a record type in the form of a standard GNAT array
  2271.    descriptor, returns the number of dimensions for type.  If arr is a
  2272.    simple array, returns the number of "array of"s that prefix its
  2273.    type designation.  Otherwise, returns 0.  */

  2274. int
  2275. ada_array_arity (struct type *type)
  2276. {
  2277.   int arity;

  2278.   if (type == NULL)
  2279.     return 0;

  2280.   type = desc_base_type (type);

  2281.   arity = 0;
  2282.   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
  2283.     return desc_arity (desc_bounds_type (type));
  2284.   else
  2285.     while (TYPE_CODE (type) == TYPE_CODE_ARRAY)
  2286.       {
  2287.         arity += 1;
  2288.         type = ada_check_typedef (TYPE_TARGET_TYPE (type));
  2289.       }

  2290.   return arity;
  2291. }

  2292. /* If TYPE is a record type in the form of a standard GNAT array
  2293.    descriptor or a simple array type, returns the element type for
  2294.    TYPE after indexing by NINDICES indices, or by all indices if
  2295.    NINDICES is -1.  Otherwise, returns NULL.  */

  2296. struct type *
  2297. ada_array_element_type (struct type *type, int nindices)
  2298. {
  2299.   type = desc_base_type (type);

  2300.   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
  2301.     {
  2302.       int k;
  2303.       struct type *p_array_type;

  2304.       p_array_type = desc_data_target_type (type);

  2305.       k = ada_array_arity (type);
  2306.       if (k == 0)
  2307.         return NULL;

  2308.       /* Initially p_array_type = elt_type(*)[]...(k times)...[].  */
  2309.       if (nindices >= 0 && k > nindices)
  2310.         k = nindices;
  2311.       while (k > 0 && p_array_type != NULL)
  2312.         {
  2313.           p_array_type = ada_check_typedef (TYPE_TARGET_TYPE (p_array_type));
  2314.           k -= 1;
  2315.         }
  2316.       return p_array_type;
  2317.     }
  2318.   else if (TYPE_CODE (type) == TYPE_CODE_ARRAY)
  2319.     {
  2320.       while (nindices != 0 && TYPE_CODE (type) == TYPE_CODE_ARRAY)
  2321.         {
  2322.           type = TYPE_TARGET_TYPE (type);
  2323.           nindices -= 1;
  2324.         }
  2325.       return type;
  2326.     }

  2327.   return NULL;
  2328. }

  2329. /* The type of nth index in arrays of given type (n numbering from 1).
  2330.    Does not examine memory.  Throws an error if N is invalid or TYPE
  2331.    is not an array typeNAME is the name of the Ada attribute being
  2332.    evaluated ('range, 'first, 'last, or 'length); it is used in building
  2333.    the error message.  */

  2334. static struct type *
  2335. ada_index_type (struct type *type, int n, const char *name)
  2336. {
  2337.   struct type *result_type;

  2338.   type = desc_base_type (type);

  2339.   if (n < 0 || n > ada_array_arity (type))
  2340.     error (_("invalid dimension number to '%s"), name);

  2341.   if (ada_is_simple_array_type (type))
  2342.     {
  2343.       int i;

  2344.       for (i = 1; i < n; i += 1)
  2345.         type = TYPE_TARGET_TYPE (type);
  2346.       result_type = TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (type));
  2347.       /* FIXME: The stabs type r(0,0);bound;bound in an array type
  2348.          has a target type of TYPE_CODE_UNDEF.  We compensate here, but
  2349.          perhaps stabsread.c would make more sense.  */
  2350.       if (result_type && TYPE_CODE (result_type) == TYPE_CODE_UNDEF)
  2351.         result_type = NULL;
  2352.     }
  2353.   else
  2354.     {
  2355.       result_type = desc_index_type (desc_bounds_type (type), n);
  2356.       if (result_type == NULL)
  2357.         error (_("attempt to take bound of something that is not an array"));
  2358.     }

  2359.   return result_type;
  2360. }

  2361. /* Given that arr is an array type, returns the lower bound of the
  2362.    Nth index (numbering from 1) if WHICH is 0, and the upper bound if
  2363.    WHICH is 1.  This returns bounds 0 .. -1 if ARR_TYPE is an
  2364.    array-descriptor type.  It works for other arrays with bounds supplied
  2365.    by run-time quantities other than discriminants.  */

  2366. static LONGEST
  2367. ada_array_bound_from_type (struct type *arr_type, int n, int which)
  2368. {
  2369.   struct type *type, *index_type_desc, *index_type;
  2370.   int i;

  2371.   gdb_assert (which == 0 || which == 1);

  2372.   if (ada_is_constrained_packed_array_type (arr_type))
  2373.     arr_type = decode_constrained_packed_array_type (arr_type);

  2374.   if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
  2375.     return (LONGEST) - which;

  2376.   if (TYPE_CODE (arr_type) == TYPE_CODE_PTR)
  2377.     type = TYPE_TARGET_TYPE (arr_type);
  2378.   else
  2379.     type = arr_type;

  2380.   index_type_desc = ada_find_parallel_type (type, "___XA");
  2381.   ada_fixup_array_indexes_type (index_type_desc);
  2382.   if (index_type_desc != NULL)
  2383.     index_type = to_fixed_range_type (TYPE_FIELD_TYPE (index_type_desc, n - 1),
  2384.                                       NULL);
  2385.   else
  2386.     {
  2387.       struct type *elt_type = check_typedef (type);

  2388.       for (i = 1; i < n; i++)
  2389.         elt_type = check_typedef (TYPE_TARGET_TYPE (elt_type));

  2390.       index_type = TYPE_INDEX_TYPE (elt_type);
  2391.     }

  2392.   return
  2393.     (LONGEST) (which == 0
  2394.                ? ada_discrete_type_low_bound (index_type)
  2395.                : ada_discrete_type_high_bound (index_type));
  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. static LONGEST
  2402. ada_array_bound (struct value *arr, int n, int which)
  2403. {
  2404.   struct type *arr_type;

  2405.   if (TYPE_CODE (check_typedef (value_type (arr))) == TYPE_CODE_PTR)
  2406.     arr = value_ind (arr);
  2407.   arr_type = value_enclosing_type (arr);

  2408.   if (ada_is_constrained_packed_array_type (arr_type))
  2409.     return ada_array_bound (decode_constrained_packed_array (arr), n, which);
  2410.   else if (ada_is_simple_array_type (arr_type))
  2411.     return ada_array_bound_from_type (arr_type, n, which);
  2412.   else
  2413.     return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
  2414. }

  2415. /* Given that arr is an array value, returns the length of the
  2416.    nth index.  This routine will also work for arrays with bounds
  2417.    supplied by run-time quantities other than discriminants.
  2418.    Does not work for arrays indexed by enumeration types with representation
  2419.    clauses at the moment.  */

  2420. static LONGEST
  2421. ada_array_length (struct value *arr, int n)
  2422. {
  2423.   struct type *arr_type;

  2424.   if (TYPE_CODE (check_typedef (value_type (arr))) == TYPE_CODE_PTR)
  2425.     arr = value_ind (arr);
  2426.   arr_type = value_enclosing_type (arr);

  2427.   if (ada_is_constrained_packed_array_type (arr_type))
  2428.     return ada_array_length (decode_constrained_packed_array (arr), n);

  2429.   if (ada_is_simple_array_type (arr_type))
  2430.     return (ada_array_bound_from_type (arr_type, n, 1)
  2431.             - ada_array_bound_from_type (arr_type, n, 0) + 1);
  2432.   else
  2433.     return (value_as_long (desc_one_bound (desc_bounds (arr), n, 1))
  2434.             - value_as_long (desc_one_bound (desc_bounds (arr), n, 0)) + 1);
  2435. }

  2436. /* An empty array whose type is that of ARR_TYPE (an array type),
  2437.    with bounds LOW to LOW-1.  */

  2438. static struct value *
  2439. empty_array (struct type *arr_type, int low)
  2440. {
  2441.   struct type *arr_type0 = ada_check_typedef (arr_type);
  2442.   struct type *index_type
  2443.     = create_static_range_type
  2444.         (NULL, TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (arr_type0)),  low, low - 1);
  2445.   struct type *elt_type = ada_array_element_type (arr_type0, 1);

  2446.   return allocate_value (create_array_type (NULL, elt_type, index_type));
  2447. }


  2448.                                 /* Name resolution */

  2449. /* The "decoded" name for the user-definable Ada operator corresponding
  2450.    to OP.  */

  2451. static const char *
  2452. ada_decoded_op_name (enum exp_opcode op)
  2453. {
  2454.   int i;

  2455.   for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
  2456.     {
  2457.       if (ada_opname_table[i].op == op)
  2458.         return ada_opname_table[i].decoded;
  2459.     }
  2460.   error (_("Could not find operator name for opcode"));
  2461. }


  2462. /* Same as evaluate_type (*EXP), but resolves ambiguous symbol
  2463.    references (marked by OP_VAR_VALUE nodes in which the symbol has an
  2464.    undefined namespace) and converts operators that are
  2465.    user-defined into appropriate function calls.  If CONTEXT_TYPE is
  2466.    non-null, it provides a preferred result type [at the moment, only
  2467.    type void has any effect---causing procedures to be preferred over
  2468.    functions in calls].  A null CONTEXT_TYPE indicates that a non-void
  2469.    return type is preferred.  May change (expand) *EXP.  */

  2470. static void
  2471. resolve (struct expression **expp, int void_context_p)
  2472. {
  2473.   struct type *context_type = NULL;
  2474.   int pc = 0;

  2475.   if (void_context_p)
  2476.     context_type = builtin_type ((*expp)->gdbarch)->builtin_void;

  2477.   resolve_subexp (expp, &pc, 1, context_type);
  2478. }

  2479. /* Resolve the operator of the subexpression beginning at
  2480.    position *POS of *EXPP.  "Resolving" consists of replacing
  2481.    the symbols that have undefined namespaces in OP_VAR_VALUE nodes
  2482.    with their resolutions, replacing built-in operators with
  2483.    function calls to user-defined operators, where appropriate, and,
  2484.    when DEPROCEDURE_P is non-zero, converting function-valued variables
  2485.    into parameterless calls.  May expand *EXPP.  The CONTEXT_TYPE functions
  2486.    are as in ada_resolve, above.  */

  2487. static struct value *
  2488. resolve_subexp (struct expression **expp, int *pos, int deprocedure_p,
  2489.                 struct type *context_type)
  2490. {
  2491.   int pc = *pos;
  2492.   int i;
  2493.   struct expression *exp;       /* Convenience: == *expp.  */
  2494.   enum exp_opcode op = (*expp)->elts[pc].opcode;
  2495.   struct value **argvec;        /* Vector of operand types (alloca'ed).  */
  2496.   int nargs;                    /* Number of operands.  */
  2497.   int oplen;

  2498.   argvec = NULL;
  2499.   nargs = 0;
  2500.   exp = *expp;

  2501.   /* Pass one: resolve operands, saving their types and updating *pos,
  2502.      if needed.  */
  2503.   switch (op)
  2504.     {
  2505.     case OP_FUNCALL:
  2506.       if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
  2507.           && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
  2508.         *pos += 7;
  2509.       else
  2510.         {
  2511.           *pos += 3;
  2512.           resolve_subexp (expp, pos, 0, NULL);
  2513.         }
  2514.       nargs = longest_to_int (exp->elts[pc + 1].longconst);
  2515.       break;

  2516.     case UNOP_ADDR:
  2517.       *pos += 1;
  2518.       resolve_subexp (expp, pos, 0, NULL);
  2519.       break;

  2520.     case UNOP_QUAL:
  2521.       *pos += 3;
  2522.       resolve_subexp (expp, pos, 1, check_typedef (exp->elts[pc + 1].type));
  2523.       break;

  2524.     case OP_ATR_MODULUS:
  2525.     case OP_ATR_SIZE:
  2526.     case OP_ATR_TAG:
  2527.     case OP_ATR_FIRST:
  2528.     case OP_ATR_LAST:
  2529.     case OP_ATR_LENGTH:
  2530.     case OP_ATR_POS:
  2531.     case OP_ATR_VAL:
  2532.     case OP_ATR_MIN:
  2533.     case OP_ATR_MAX:
  2534.     case TERNOP_IN_RANGE:
  2535.     case BINOP_IN_BOUNDS:
  2536.     case UNOP_IN_RANGE:
  2537.     case OP_AGGREGATE:
  2538.     case OP_OTHERS:
  2539.     case OP_CHOICES:
  2540.     case OP_POSITIONAL:
  2541.     case OP_DISCRETE_RANGE:
  2542.     case OP_NAME:
  2543.       ada_forward_operator_length (exp, pc, &oplen, &nargs);
  2544.       *pos += oplen;
  2545.       break;

  2546.     case BINOP_ASSIGN:
  2547.       {
  2548.         struct value *arg1;

  2549.         *pos += 1;
  2550.         arg1 = resolve_subexp (expp, pos, 0, NULL);
  2551.         if (arg1 == NULL)
  2552.           resolve_subexp (expp, pos, 1, NULL);
  2553.         else
  2554.           resolve_subexp (expp, pos, 1, value_type (arg1));
  2555.         break;
  2556.       }

  2557.     case UNOP_CAST:
  2558.       *pos += 3;
  2559.       nargs = 1;
  2560.       break;

  2561.     case BINOP_ADD:
  2562.     case BINOP_SUB:
  2563.     case BINOP_MUL:
  2564.     case BINOP_DIV:
  2565.     case BINOP_REM:
  2566.     case BINOP_MOD:
  2567.     case BINOP_EXP:
  2568.     case BINOP_CONCAT:
  2569.     case BINOP_LOGICAL_AND:
  2570.     case BINOP_LOGICAL_OR:
  2571.     case BINOP_BITWISE_AND:
  2572.     case BINOP_BITWISE_IOR:
  2573.     case BINOP_BITWISE_XOR:

  2574.     case BINOP_EQUAL:
  2575.     case BINOP_NOTEQUAL:
  2576.     case BINOP_LESS:
  2577.     case BINOP_GTR:
  2578.     case BINOP_LEQ:
  2579.     case BINOP_GEQ:

  2580.     case BINOP_REPEAT:
  2581.     case BINOP_SUBSCRIPT:
  2582.     case BINOP_COMMA:
  2583.       *pos += 1;
  2584.       nargs = 2;
  2585.       break;

  2586.     case UNOP_NEG:
  2587.     case UNOP_PLUS:
  2588.     case UNOP_LOGICAL_NOT:
  2589.     case UNOP_ABS:
  2590.     case UNOP_IND:
  2591.       *pos += 1;
  2592.       nargs = 1;
  2593.       break;

  2594.     case OP_LONG:
  2595.     case OP_DOUBLE:
  2596.     case OP_VAR_VALUE:
  2597.       *pos += 4;
  2598.       break;

  2599.     case OP_TYPE:
  2600.     case OP_BOOL:
  2601.     case OP_LAST:
  2602.     case OP_INTERNALVAR:
  2603.       *pos += 3;
  2604.       break;

  2605.     case UNOP_MEMVAL:
  2606.       *pos += 3;
  2607.       nargs = 1;
  2608.       break;

  2609.     case OP_REGISTER:
  2610.       *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
  2611.       break;

  2612.     case STRUCTOP_STRUCT:
  2613.       *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
  2614.       nargs = 1;
  2615.       break;

  2616.     case TERNOP_SLICE:
  2617.       *pos += 1;
  2618.       nargs = 3;
  2619.       break;

  2620.     case OP_STRING:
  2621.       break;

  2622.     default:
  2623.       error (_("Unexpected operator during name resolution"));
  2624.     }

  2625.   argvec = (struct value * *) alloca (sizeof (struct value *) * (nargs + 1));
  2626.   for (i = 0; i < nargs; i += 1)
  2627.     argvec[i] = resolve_subexp (expp, pos, 1, NULL);
  2628.   argvec[i] = NULL;
  2629.   exp = *expp;

  2630.   /* Pass two: perform any resolution on principal operator.  */
  2631.   switch (op)
  2632.     {
  2633.     default:
  2634.       break;

  2635.     case OP_VAR_VALUE:
  2636.       if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
  2637.         {
  2638.           struct ada_symbol_info *candidates;
  2639.           int n_candidates;

  2640.           n_candidates =
  2641.             ada_lookup_symbol_list (SYMBOL_LINKAGE_NAME
  2642.                                     (exp->elts[pc + 2].symbol),
  2643.                                     exp->elts[pc + 1].block, VAR_DOMAIN,
  2644.                                     &candidates);

  2645.           if (n_candidates > 1)
  2646.             {
  2647.               /* Types tend to get re-introduced locally, so if there
  2648.                  are any local symbols that are not types, first filter
  2649.                  out all types.  */
  2650.               int j;
  2651.               for (j = 0; j < n_candidates; j += 1)
  2652.                 switch (SYMBOL_CLASS (candidates[j].sym))
  2653.                   {
  2654.                   case LOC_REGISTER:
  2655.                   case LOC_ARG:
  2656.                   case LOC_REF_ARG:
  2657.                   case LOC_REGPARM_ADDR:
  2658.                   case LOC_LOCAL:
  2659.                   case LOC_COMPUTED:
  2660.                     goto FoundNonType;
  2661.                   default:
  2662.                     break;
  2663.                   }
  2664.             FoundNonType:
  2665.               if (j < n_candidates)
  2666.                 {
  2667.                   j = 0;
  2668.                   while (j < n_candidates)
  2669.                     {
  2670.                       if (SYMBOL_CLASS (candidates[j].sym) == LOC_TYPEDEF)
  2671.                         {
  2672.                           candidates[j] = candidates[n_candidates - 1];
  2673.                           n_candidates -= 1;
  2674.                         }
  2675.                       else
  2676.                         j += 1;
  2677.                     }
  2678.                 }
  2679.             }

  2680.           if (n_candidates == 0)
  2681.             error (_("No definition found for %s"),
  2682.                    SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
  2683.           else if (n_candidates == 1)
  2684.             i = 0;
  2685.           else if (deprocedure_p
  2686.                    && !is_nonfunction (candidates, n_candidates))
  2687.             {
  2688.               i = ada_resolve_function
  2689.                 (candidates, n_candidates, NULL, 0,
  2690.                  SYMBOL_LINKAGE_NAME (exp->elts[pc + 2].symbol),
  2691.                  context_type);
  2692.               if (i < 0)
  2693.                 error (_("Could not find a match for %s"),
  2694.                        SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
  2695.             }
  2696.           else
  2697.             {
  2698.               printf_filtered (_("Multiple matches for %s\n"),
  2699.                                SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
  2700.               user_select_syms (candidates, n_candidates, 1);
  2701.               i = 0;
  2702.             }

  2703.           exp->elts[pc + 1].block = candidates[i].block;
  2704.           exp->elts[pc + 2].symbol = candidates[i].sym;
  2705.           if (innermost_block == NULL
  2706.               || contained_in (candidates[i].block, innermost_block))
  2707.             innermost_block = candidates[i].block;
  2708.         }

  2709.       if (deprocedure_p
  2710.           && (TYPE_CODE (SYMBOL_TYPE (exp->elts[pc + 2].symbol))
  2711.               == TYPE_CODE_FUNC))
  2712.         {
  2713.           replace_operator_with_call (expp, pc, 0, 0,
  2714.                                       exp->elts[pc + 2].symbol,
  2715.                                       exp->elts[pc + 1].block);
  2716.           exp = *expp;
  2717.         }
  2718.       break;

  2719.     case OP_FUNCALL:
  2720.       {
  2721.         if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
  2722.             && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
  2723.           {
  2724.             struct ada_symbol_info *candidates;
  2725.             int n_candidates;

  2726.             n_candidates =
  2727.               ada_lookup_symbol_list (SYMBOL_LINKAGE_NAME
  2728.                                       (exp->elts[pc + 5].symbol),
  2729.                                       exp->elts[pc + 4].block, VAR_DOMAIN,
  2730.                                       &candidates);
  2731.             if (n_candidates == 1)
  2732.               i = 0;
  2733.             else
  2734.               {
  2735.                 i = ada_resolve_function
  2736.                   (candidates, n_candidates,
  2737.                    argvec, nargs,
  2738.                    SYMBOL_LINKAGE_NAME (exp->elts[pc + 5].symbol),
  2739.                    context_type);
  2740.                 if (i < 0)
  2741.                   error (_("Could not find a match for %s"),
  2742.                          SYMBOL_PRINT_NAME (exp->elts[pc + 5].symbol));
  2743.               }

  2744.             exp->elts[pc + 4].block = candidates[i].block;
  2745.             exp->elts[pc + 5].symbol = candidates[i].sym;
  2746.             if (innermost_block == NULL
  2747.                 || contained_in (candidates[i].block, innermost_block))
  2748.               innermost_block = candidates[i].block;
  2749.           }
  2750.       }
  2751.       break;
  2752.     case BINOP_ADD:
  2753.     case BINOP_SUB:
  2754.     case BINOP_MUL:
  2755.     case BINOP_DIV:
  2756.     case BINOP_REM:
  2757.     case BINOP_MOD:
  2758.     case BINOP_CONCAT:
  2759.     case BINOP_BITWISE_AND:
  2760.     case BINOP_BITWISE_IOR:
  2761.     case BINOP_BITWISE_XOR:
  2762.     case BINOP_EQUAL:
  2763.     case BINOP_NOTEQUAL:
  2764.     case BINOP_LESS:
  2765.     case BINOP_GTR:
  2766.     case BINOP_LEQ:
  2767.     case BINOP_GEQ:
  2768.     case BINOP_EXP:
  2769.     case UNOP_NEG:
  2770.     case UNOP_PLUS:
  2771.     case UNOP_LOGICAL_NOT:
  2772.     case UNOP_ABS:
  2773.       if (possible_user_operator_p (op, argvec))
  2774.         {
  2775.           struct ada_symbol_info *candidates;
  2776.           int n_candidates;

  2777.           n_candidates =
  2778.             ada_lookup_symbol_list (ada_encode (ada_decoded_op_name (op)),
  2779.                                     (struct block *) NULL, VAR_DOMAIN,
  2780.                                     &candidates);
  2781.           i = ada_resolve_function (candidates, n_candidates, argvec, nargs,
  2782.                                     ada_decoded_op_name (op), NULL);
  2783.           if (i < 0)
  2784.             break;

  2785.           replace_operator_with_call (expp, pc, nargs, 1,
  2786.                                       candidates[i].sym, candidates[i].block);
  2787.           exp = *expp;
  2788.         }
  2789.       break;

  2790.     case OP_TYPE:
  2791.     case OP_REGISTER:
  2792.       return NULL;
  2793.     }

  2794.   *pos = pc;
  2795.   return evaluate_subexp_type (exp, pos);
  2796. }

  2797. /* Return non-zero if formal type FTYPE matches actual type ATYPE.  If
  2798.    MAY_DEREF is non-zero, the formal may be a pointer and the actual
  2799.    a non-pointer.  */
  2800. /* The term "match" here is rather loose.  The match is heuristic and
  2801.    liberal.  */

  2802. static int
  2803. ada_type_match (struct type *ftype, struct type *atype, int may_deref)
  2804. {
  2805.   ftype = ada_check_typedef (ftype);
  2806.   atype = ada_check_typedef (atype);

  2807.   if (TYPE_CODE (ftype) == TYPE_CODE_REF)
  2808.     ftype = TYPE_TARGET_TYPE (ftype);
  2809.   if (TYPE_CODE (atype) == TYPE_CODE_REF)
  2810.     atype = TYPE_TARGET_TYPE (atype);

  2811.   switch (TYPE_CODE (ftype))
  2812.     {
  2813.     default:
  2814.       return TYPE_CODE (ftype) == TYPE_CODE (atype);
  2815.     case TYPE_CODE_PTR:
  2816.       if (TYPE_CODE (atype) == TYPE_CODE_PTR)
  2817.         return ada_type_match (TYPE_TARGET_TYPE (ftype),
  2818.                                TYPE_TARGET_TYPE (atype), 0);
  2819.       else
  2820.         return (may_deref
  2821.                 && ada_type_match (TYPE_TARGET_TYPE (ftype), atype, 0));
  2822.     case TYPE_CODE_INT:
  2823.     case TYPE_CODE_ENUM:
  2824.     case TYPE_CODE_RANGE:
  2825.       switch (TYPE_CODE (atype))
  2826.         {
  2827.         case TYPE_CODE_INT:
  2828.         case TYPE_CODE_ENUM:
  2829.         case TYPE_CODE_RANGE:
  2830.           return 1;
  2831.         default:
  2832.           return 0;
  2833.         }

  2834.     case TYPE_CODE_ARRAY:
  2835.       return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
  2836.               || ada_is_array_descriptor_type (atype));

  2837.     case TYPE_CODE_STRUCT:
  2838.       if (ada_is_array_descriptor_type (ftype))
  2839.         return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
  2840.                 || ada_is_array_descriptor_type (atype));
  2841.       else
  2842.         return (TYPE_CODE (atype) == TYPE_CODE_STRUCT
  2843.                 && !ada_is_array_descriptor_type (atype));

  2844.     case TYPE_CODE_UNION:
  2845.     case TYPE_CODE_FLT:
  2846.       return (TYPE_CODE (atype) == TYPE_CODE (ftype));
  2847.     }
  2848. }

  2849. /* Return non-zero if the formals of FUNC "sufficiently match" the
  2850.    vector of actual argument types ACTUALS of size N_ACTUALS.  FUNC
  2851.    may also be an enumeral, in which case it is treated as a 0-
  2852.    argument function.  */

  2853. static int
  2854. ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
  2855. {
  2856.   int i;
  2857.   struct type *func_type = SYMBOL_TYPE (func);

  2858.   if (SYMBOL_CLASS (func) == LOC_CONST
  2859.       && TYPE_CODE (func_type) == TYPE_CODE_ENUM)
  2860.     return (n_actuals == 0);
  2861.   else if (func_type == NULL || TYPE_CODE (func_type) != TYPE_CODE_FUNC)
  2862.     return 0;

  2863.   if (TYPE_NFIELDS (func_type) != n_actuals)
  2864.     return 0;

  2865.   for (i = 0; i < n_actuals; i += 1)
  2866.     {
  2867.       if (actuals[i] == NULL)
  2868.         return 0;
  2869.       else
  2870.         {
  2871.           struct type *ftype = ada_check_typedef (TYPE_FIELD_TYPE (func_type,
  2872.                                                                    i));
  2873.           struct type *atype = ada_check_typedef (value_type (actuals[i]));

  2874.           if (!ada_type_match (ftype, atype, 1))
  2875.             return 0;
  2876.         }
  2877.     }
  2878.   return 1;
  2879. }

  2880. /* False iff function type FUNC_TYPE definitely does not produce a value
  2881.    compatible with type CONTEXT_TYPE.  Conservatively returns 1 if
  2882.    FUNC_TYPE is not a valid function type with a non-null return type
  2883.    or an enumerated typeA null CONTEXT_TYPE indicates any non-void type.  */

  2884. static int
  2885. return_match (struct type *func_type, struct type *context_type)
  2886. {
  2887.   struct type *return_type;

  2888.   if (func_type == NULL)
  2889.     return 1;

  2890.   if (TYPE_CODE (func_type) == TYPE_CODE_FUNC)
  2891.     return_type = get_base_type (TYPE_TARGET_TYPE (func_type));
  2892.   else
  2893.     return_type = get_base_type (func_type);
  2894.   if (return_type == NULL)
  2895.     return 1;

  2896.   context_type = get_base_type (context_type);

  2897.   if (TYPE_CODE (return_type) == TYPE_CODE_ENUM)
  2898.     return context_type == NULL || return_type == context_type;
  2899.   else if (context_type == NULL)
  2900.     return TYPE_CODE (return_type) != TYPE_CODE_VOID;
  2901.   else
  2902.     return TYPE_CODE (return_type) == TYPE_CODE (context_type);
  2903. }


  2904. /* Returns the index in SYMS[0..NSYMS-1] that contains  the symbol for the
  2905.    function (if any) that matches the types of the NARGS arguments in
  2906.    ARGS.  If CONTEXT_TYPE is non-null and there is at least one match
  2907.    that returns that type, then eliminate matches that don't.  If
  2908.    CONTEXT_TYPE is void and there is at least one match that does not
  2909.    return void, eliminate all matches that do.

  2910.    Asks the user if there is more than one match remaining.  Returns -1
  2911.    if there is no such symbol or none is selected.  NAME is used
  2912.    solely for messages.  May re-arrange and modify SYMS in
  2913.    the process; the index returned is for the modified vector.  */

  2914. static int
  2915. ada_resolve_function (struct ada_symbol_info syms[],
  2916.                       int nsyms, struct value **args, int nargs,
  2917.                       const char *name, struct type *context_type)
  2918. {
  2919.   int fallback;
  2920.   int k;
  2921.   int m;                        /* Number of hits */

  2922.   m = 0;
  2923.   /* In the first pass of the loop, we only accept functions matching
  2924.      context_type.  If none are found, we add a second pass of the loop
  2925.      where every function is accepted.  */
  2926.   for (fallback = 0; m == 0 && fallback < 2; fallback++)
  2927.     {
  2928.       for (k = 0; k < nsyms; k += 1)
  2929.         {
  2930.           struct type *type = ada_check_typedef (SYMBOL_TYPE (syms[k].sym));

  2931.           if (ada_args_match (syms[k].sym, args, nargs)
  2932.               && (fallback || return_match (type, context_type)))
  2933.             {
  2934.               syms[m] = syms[k];
  2935.               m += 1;
  2936.             }
  2937.         }
  2938.     }

  2939.   if (m == 0)
  2940.     return -1;
  2941.   else if (m > 1)
  2942.     {
  2943.       printf_filtered (_("Multiple matches for %s\n"), name);
  2944.       user_select_syms (syms, m, 1);
  2945.       return 0;
  2946.     }
  2947.   return 0;
  2948. }

  2949. /* Returns true (non-zero) iff decoded name N0 should appear before N1
  2950.    in a listing of choices during disambiguation (see sort_choices, below).
  2951.    The idea is that overloadings of a subprogram name from the
  2952.    same package should sort in their source order.  We settle for ordering
  2953.    such symbols by their trailing number (__N  or $N).  */

  2954. static int
  2955. encoded_ordered_before (const char *N0, const char *N1)
  2956. {
  2957.   if (N1 == NULL)
  2958.     return 0;
  2959.   else if (N0 == NULL)
  2960.     return 1;
  2961.   else
  2962.     {
  2963.       int k0, k1;

  2964.       for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
  2965.         ;
  2966.       for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
  2967.         ;
  2968.       if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
  2969.           && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
  2970.         {
  2971.           int n0, n1;

  2972.           n0 = k0;
  2973.           while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
  2974.             n0 -= 1;
  2975.           n1 = k1;
  2976.           while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
  2977.             n1 -= 1;
  2978.           if (n0 == n1 && strncmp (N0, N1, n0) == 0)
  2979.             return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
  2980.         }
  2981.       return (strcmp (N0, N1) < 0);
  2982.     }
  2983. }

  2984. /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
  2985.    encoded names.  */

  2986. static void
  2987. sort_choices (struct ada_symbol_info syms[], int nsyms)
  2988. {
  2989.   int i;

  2990.   for (i = 1; i < nsyms; i += 1)
  2991.     {
  2992.       struct ada_symbol_info sym = syms[i];
  2993.       int j;

  2994.       for (j = i - 1; j >= 0; j -= 1)
  2995.         {
  2996.           if (encoded_ordered_before (SYMBOL_LINKAGE_NAME (syms[j].sym),
  2997.                                       SYMBOL_LINKAGE_NAME (sym.sym)))
  2998.             break;
  2999.           syms[j + 1] = syms[j];
  3000.         }
  3001.       syms[j + 1] = sym;
  3002.     }
  3003. }

  3004. /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
  3005.    by asking the user (if necessary), returning the number selected,
  3006.    and setting the first elements of SYMS items.  Error if no symbols
  3007.    selected.  */

  3008. /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
  3009.    to be re-integrated one of these days.  */

  3010. int
  3011. user_select_syms (struct ada_symbol_info *syms, int nsyms, int max_results)
  3012. {
  3013.   int i;
  3014.   int *chosen = (int *) alloca (sizeof (int) * nsyms);
  3015.   int n_chosen;
  3016.   int first_choice = (max_results == 1) ? 1 : 2;
  3017.   const char *select_mode = multiple_symbols_select_mode ();

  3018.   if (max_results < 1)
  3019.     error (_("Request to select 0 symbols!"));
  3020.   if (nsyms <= 1)
  3021.     return nsyms;

  3022.   if (select_mode == multiple_symbols_cancel)
  3023.     error (_("\
  3024. canceled because the command is ambiguous\n\
  3025. See set/show multiple-symbol."));

  3026.   /* If select_mode is "all", then return all possible symbols.
  3027.      Only do that if more than one symbol can be selected, of course.
  3028.      Otherwise, display the menu as usual.  */
  3029.   if (select_mode == multiple_symbols_all && max_results > 1)
  3030.     return nsyms;

  3031.   printf_unfiltered (_("[0] cancel\n"));
  3032.   if (max_results > 1)
  3033.     printf_unfiltered (_("[1] all\n"));

  3034.   sort_choices (syms, nsyms);

  3035.   for (i = 0; i < nsyms; i += 1)
  3036.     {
  3037.       if (syms[i].sym == NULL)
  3038.         continue;

  3039.       if (SYMBOL_CLASS (syms[i].sym) == LOC_BLOCK)
  3040.         {
  3041.           struct symtab_and_line sal =
  3042.             find_function_start_sal (syms[i].sym, 1);

  3043.           if (sal.symtab == NULL)
  3044.             printf_unfiltered (_("[%d] %s at <no source file available>:%d\n"),
  3045.                                i + first_choice,
  3046.                                SYMBOL_PRINT_NAME (syms[i].sym),
  3047.                                sal.line);
  3048.           else
  3049.             printf_unfiltered (_("[%d] %s at %s:%d\n"), i + first_choice,
  3050.                                SYMBOL_PRINT_NAME (syms[i].sym),
  3051.                                symtab_to_filename_for_display (sal.symtab),
  3052.                                sal.line);
  3053.           continue;
  3054.         }
  3055.       else
  3056.         {
  3057.           int is_enumeral =
  3058.             (SYMBOL_CLASS (syms[i].sym) == LOC_CONST
  3059.              && SYMBOL_TYPE (syms[i].sym) != NULL
  3060.              && TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) == TYPE_CODE_ENUM);
  3061.           struct symtab *symtab = NULL;

  3062.           if (SYMBOL_OBJFILE_OWNED (syms[i].sym))
  3063.             symtab = symbol_symtab (syms[i].sym);

  3064.           if (SYMBOL_LINE (syms[i].sym) != 0 && symtab != NULL)
  3065.             printf_unfiltered (_("[%d] %s at %s:%d\n"),
  3066.                                i + first_choice,
  3067.                                SYMBOL_PRINT_NAME (syms[i].sym),
  3068.                                symtab_to_filename_for_display (symtab),
  3069.                                SYMBOL_LINE (syms[i].sym));
  3070.           else if (is_enumeral
  3071.                    && TYPE_NAME (SYMBOL_TYPE (syms[i].sym)) != NULL)
  3072.             {
  3073.               printf_unfiltered (("[%d] "), i + first_choice);
  3074.               ada_print_type (SYMBOL_TYPE (syms[i].sym), NULL,
  3075.                               gdb_stdout, -1, 0, &type_print_raw_options);
  3076.               printf_unfiltered (_("'(%s) (enumeral)\n"),
  3077.                                  SYMBOL_PRINT_NAME (syms[i].sym));
  3078.             }
  3079.           else if (symtab != NULL)
  3080.             printf_unfiltered (is_enumeral
  3081.                                ? _("[%d] %s in %s (enumeral)\n")
  3082.                                : _("[%d] %s at %s:?\n"),
  3083.                                i + first_choice,
  3084.                                SYMBOL_PRINT_NAME (syms[i].sym),
  3085.                                symtab_to_filename_for_display (symtab));
  3086.           else
  3087.             printf_unfiltered (is_enumeral
  3088.                                ? _("[%d] %s (enumeral)\n")
  3089.                                : _("[%d] %s at ?\n"),
  3090.                                i + first_choice,
  3091.                                SYMBOL_PRINT_NAME (syms[i].sym));
  3092.         }
  3093.     }

  3094.   n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
  3095.                              "overload-choice");

  3096.   for (i = 0; i < n_chosen; i += 1)
  3097.     syms[i] = syms[chosen[i]];

  3098.   return n_chosen;
  3099. }

  3100. /* Read and validate a set of numeric choices from the user in the
  3101.    range 0 .. N_CHOICES-1.  Place the results in increasing
  3102.    order in CHOICES[0 .. N-1], and return N.

  3103.    The user types choices as a sequence of numbers on one line
  3104.    separated by blanks, encoding them as follows:

  3105.      + A choice of 0 means to cancel the selection, throwing an error.
  3106.      + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
  3107.      + The user chooses k by typing k+IS_ALL_CHOICE+1.

  3108.    The user is not allowed to choose more than MAX_RESULTS values.

  3109.    ANNOTATION_SUFFIX, if present, is used to annotate the input
  3110.    prompts (for use with the -f switch).  */

  3111. int
  3112. get_selections (int *choices, int n_choices, int max_results,
  3113.                 int is_all_choice, char *annotation_suffix)
  3114. {
  3115.   char *args;
  3116.   char *prompt;
  3117.   int n_chosen;
  3118.   int first_choice = is_all_choice ? 2 : 1;

  3119.   prompt = getenv ("PS2");
  3120.   if (prompt == NULL)
  3121.     prompt = "> ";

  3122.   args = command_line_input (prompt, 0, annotation_suffix);

  3123.   if (args == NULL)
  3124.     error_no_arg (_("one or more choice numbers"));

  3125.   n_chosen = 0;

  3126.   /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
  3127.      order, as given in args.  Choices are validated.  */
  3128.   while (1)
  3129.     {
  3130.       char *args2;
  3131.       int choice, j;

  3132.       args = skip_spaces (args);
  3133.       if (*args == '\0' && n_chosen == 0)
  3134.         error_no_arg (_("one or more choice numbers"));
  3135.       else if (*args == '\0')
  3136.         break;

  3137.       choice = strtol (args, &args2, 10);
  3138.       if (args == args2 || choice < 0
  3139.           || choice > n_choices + first_choice - 1)
  3140.         error (_("Argument must be choice number"));
  3141.       args = args2;

  3142.       if (choice == 0)
  3143.         error (_("cancelled"));

  3144.       if (choice < first_choice)
  3145.         {
  3146.           n_chosen = n_choices;
  3147.           for (j = 0; j < n_choices; j += 1)
  3148.             choices[j] = j;
  3149.           break;
  3150.         }
  3151.       choice -= first_choice;

  3152.       for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
  3153.         {
  3154.         }

  3155.       if (j < 0 || choice != choices[j])
  3156.         {
  3157.           int k;

  3158.           for (k = n_chosen - 1; k > j; k -= 1)
  3159.             choices[k + 1] = choices[k];
  3160.           choices[j + 1] = choice;
  3161.           n_chosen += 1;
  3162.         }
  3163.     }

  3164.   if (n_chosen > max_results)
  3165.     error (_("Select no more than %d of the above"), max_results);

  3166.   return n_chosen;
  3167. }

  3168. /* Replace the operator of length OPLEN at position PC in *EXPP with a call
  3169.    on the function identified by SYM and BLOCK, and taking NARGS
  3170.    arguments.  Update *EXPP as needed to hold more space.  */

  3171. static void
  3172. replace_operator_with_call (struct expression **expp, int pc, int nargs,
  3173.                             int oplen, struct symbol *sym,
  3174.                             const struct block *block)
  3175. {
  3176.   /* A new expression, with 6 more elements (3 for funcall, 4 for function
  3177.      symbol, -oplen for operator being replaced).  */
  3178.   struct expression *newexp = (struct expression *)
  3179.     xzalloc (sizeof (struct expression)
  3180.              + EXP_ELEM_TO_BYTES ((*expp)->nelts + 7 - oplen));
  3181.   struct expression *exp = *expp;

  3182.   newexp->nelts = exp->nelts + 7 - oplen;
  3183.   newexp->language_defn = exp->language_defn;
  3184.   newexp->gdbarch = exp->gdbarch;
  3185.   memcpy (newexp->elts, exp->elts, EXP_ELEM_TO_BYTES (pc));
  3186.   memcpy (newexp->elts + pc + 7, exp->elts + pc + oplen,
  3187.           EXP_ELEM_TO_BYTES (exp->nelts - pc - oplen));

  3188.   newexp->elts[pc].opcode = newexp->elts[pc + 2].opcode = OP_FUNCALL;
  3189.   newexp->elts[pc + 1].longconst = (LONGEST) nargs;

  3190.   newexp->elts[pc + 3].opcode = newexp->elts[pc + 6].opcode = OP_VAR_VALUE;
  3191.   newexp->elts[pc + 4].block = block;
  3192.   newexp->elts[pc + 5].symbol = sym;

  3193.   *expp = newexp;
  3194.   xfree (exp);
  3195. }

  3196. /* Type-class predicates */

  3197. /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
  3198.    or FLOAT).  */

  3199. static int
  3200. numeric_type_p (struct type *type)
  3201. {
  3202.   if (type == NULL)
  3203.     return 0;
  3204.   else
  3205.     {
  3206.       switch (TYPE_CODE (type))
  3207.         {
  3208.         case TYPE_CODE_INT:
  3209.         case TYPE_CODE_FLT:
  3210.           return 1;
  3211.         case TYPE_CODE_RANGE:
  3212.           return (type == TYPE_TARGET_TYPE (type)
  3213.                   || numeric_type_p (TYPE_TARGET_TYPE (type)));
  3214.         default:
  3215.           return 0;
  3216.         }
  3217.     }
  3218. }

  3219. /* True iff TYPE is integral (an INT or RANGE of INTs).  */

  3220. static int
  3221. integer_type_p (struct type *type)
  3222. {
  3223.   if (type == NULL)
  3224.     return 0;
  3225.   else
  3226.     {
  3227.       switch (TYPE_CODE (type))
  3228.         {
  3229.         case TYPE_CODE_INT:
  3230.           return 1;
  3231.         case TYPE_CODE_RANGE:
  3232.           return (type == TYPE_TARGET_TYPE (type)
  3233.                   || integer_type_p (TYPE_TARGET_TYPE (type)));
  3234.         default:
  3235.           return 0;
  3236.         }
  3237.     }
  3238. }

  3239. /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM).  */

  3240. static int
  3241. scalar_type_p (struct type *type)
  3242. {
  3243.   if (type == NULL)
  3244.     return 0;
  3245.   else
  3246.     {
  3247.       switch (TYPE_CODE (type))
  3248.         {
  3249.         case TYPE_CODE_INT:
  3250.         case TYPE_CODE_RANGE:
  3251.         case TYPE_CODE_ENUM:
  3252.         case TYPE_CODE_FLT:
  3253.           return 1;
  3254.         default:
  3255.           return 0;
  3256.         }
  3257.     }
  3258. }

  3259. /* True iff TYPE is discrete (INT, RANGE, ENUM).  */

  3260. static int
  3261. discrete_type_p (struct type *type)
  3262. {
  3263.   if (type == NULL)
  3264.     return 0;
  3265.   else
  3266.     {
  3267.       switch (TYPE_CODE (type))
  3268.         {
  3269.         case TYPE_CODE_INT:
  3270.         case TYPE_CODE_RANGE:
  3271.         case TYPE_CODE_ENUM:
  3272.         case TYPE_CODE_BOOL:
  3273.           return 1;
  3274.         default:
  3275.           return 0;
  3276.         }
  3277.     }
  3278. }

  3279. /* Returns non-zero if OP with operands in the vector ARGS could be
  3280.    a user-defined function.  Errs on the side of pre-defined operators
  3281.    (i.e., result 0).  */

  3282. static int
  3283. possible_user_operator_p (enum exp_opcode op, struct value *args[])
  3284. {
  3285.   struct type *type0 =
  3286.     (args[0] == NULL) ? NULL : ada_check_typedef (value_type (args[0]));
  3287.   struct type *type1 =
  3288.     (args[1] == NULL) ? NULL : ada_check_typedef (value_type (args[1]));

  3289.   if (type0 == NULL)
  3290.     return 0;

  3291.   switch (op)
  3292.     {
  3293.     default:
  3294.       return 0;

  3295.     case BINOP_ADD:
  3296.     case BINOP_SUB:
  3297.     case BINOP_MUL:
  3298.     case BINOP_DIV:
  3299.       return (!(numeric_type_p (type0) && numeric_type_p (type1)));

  3300.     case BINOP_REM:
  3301.     case BINOP_MOD:
  3302.     case BINOP_BITWISE_AND:
  3303.     case BINOP_BITWISE_IOR:
  3304.     case BINOP_BITWISE_XOR:
  3305.       return (!(integer_type_p (type0) && integer_type_p (type1)));

  3306.     case BINOP_EQUAL:
  3307.     case BINOP_NOTEQUAL:
  3308.     case BINOP_LESS:
  3309.     case BINOP_GTR:
  3310.     case BINOP_LEQ:
  3311.     case BINOP_GEQ:
  3312.       return (!(scalar_type_p (type0) && scalar_type_p (type1)));

  3313.     case BINOP_CONCAT:
  3314.       return !ada_is_array_type (type0) || !ada_is_array_type (type1);

  3315.     case BINOP_EXP:
  3316.       return (!(numeric_type_p (type0) && integer_type_p (type1)));

  3317.     case UNOP_NEG:
  3318.     case UNOP_PLUS:
  3319.     case UNOP_LOGICAL_NOT:
  3320.     case UNOP_ABS:
  3321.       return (!numeric_type_p (type0));

  3322.     }
  3323. }

  3324.                                 /* Renaming */

  3325. /* NOTES:

  3326.    1. In the following, we assume that a renaming type's name may
  3327.       have an ___XD suffix.  It would be nice if this went away at some
  3328.       point.
  3329.    2. We handle both the (old) purely type-based representation of
  3330.       renamings and the (new) variable-based encoding.  At some point,
  3331.       it is devoutly to be hoped that the former goes away
  3332.       (FIXME: hilfinger-2007-07-09).
  3333.    3. Subprogram renamings are not implemented, although the XRS
  3334.       suffix is recognized (FIXME: hilfinger-2007-07-09).  */

  3335. /* If SYM encodes a renaming,

  3336.        <renaming> renames <renamed entity>,

  3337.    sets *LEN to the length of the renamed entity's name,
  3338.    *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
  3339.    the string describing the subcomponent selected from the renamed
  3340.    entity.  Returns ADA_NOT_RENAMING if SYM does not encode a renaming
  3341.    (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
  3342.    are undefined).  Otherwise, returns a value indicating the category
  3343.    of entity renamed: an object (ADA_OBJECT_RENAMING), exception
  3344.    (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
  3345.    subprogram (ADA_SUBPROGRAM_RENAMING).  Does no allocation; the
  3346.    strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
  3347.    deallocated.  The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
  3348.    may be NULL, in which case they are not assigned.

  3349.    [Currently, however, GCC does not generate subprogram renamings.]  */

  3350. enum ada_renaming_category
  3351. ada_parse_renaming (struct symbol *sym,
  3352.                     const char **renamed_entity, int *len,
  3353.                     const char **renaming_expr)
  3354. {
  3355.   enum ada_renaming_category kind;
  3356.   const char *info;
  3357.   const char *suffix;

  3358.   if (sym == NULL)
  3359.     return ADA_NOT_RENAMING;
  3360.   switch (SYMBOL_CLASS (sym))
  3361.     {
  3362.     default:
  3363.       return ADA_NOT_RENAMING;
  3364.     case LOC_TYPEDEF:
  3365.       return parse_old_style_renaming (SYMBOL_TYPE (sym),
  3366.                                        renamed_entity, len, renaming_expr);
  3367.     case LOC_LOCAL:
  3368.     case LOC_STATIC:
  3369.     case LOC_COMPUTED:
  3370.     case LOC_OPTIMIZED_OUT:
  3371.       info = strstr (SYMBOL_LINKAGE_NAME (sym), "___XR");
  3372.       if (info == NULL)
  3373.         return ADA_NOT_RENAMING;
  3374.       switch (info[5])
  3375.         {
  3376.         case '_':
  3377.           kind = ADA_OBJECT_RENAMING;
  3378.           info += 6;
  3379.           break;
  3380.         case 'E':
  3381.           kind = ADA_EXCEPTION_RENAMING;
  3382.           info += 7;
  3383.           break;
  3384.         case 'P':
  3385.           kind = ADA_PACKAGE_RENAMING;
  3386.           info += 7;
  3387.           break;
  3388.         case 'S':
  3389.           kind = ADA_SUBPROGRAM_RENAMING;
  3390.           info += 7;
  3391.           break;
  3392.         default:
  3393.           return ADA_NOT_RENAMING;
  3394.         }
  3395.     }

  3396.   if (renamed_entity != NULL)
  3397.     *renamed_entity = info;
  3398.   suffix = strstr (info, "___XE");
  3399.   if (suffix == NULL || suffix == info)
  3400.     return ADA_NOT_RENAMING;
  3401.   if (len != NULL)
  3402.     *len = strlen (info) - strlen (suffix);
  3403.   suffix += 5;
  3404.   if (renaming_expr != NULL)
  3405.     *renaming_expr = suffix;
  3406.   return kind;
  3407. }

  3408. /* Assuming TYPE encodes a renaming according to the old encoding in
  3409.    exp_dbug.ads, returns details of that renaming in *RENAMED_ENTITY,
  3410.    *LEN, and *RENAMING_EXPR, as for ada_parse_renaming, above.  Returns
  3411.    ADA_NOT_RENAMING otherwise.  */
  3412. static enum ada_renaming_category
  3413. parse_old_style_renaming (struct type *type,
  3414.                           const char **renamed_entity, int *len,
  3415.                           const char **renaming_expr)
  3416. {
  3417.   enum ada_renaming_category kind;
  3418.   const char *name;
  3419.   const char *info;
  3420.   const char *suffix;

  3421.   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_ENUM
  3422.       || TYPE_NFIELDS (type) != 1)
  3423.     return ADA_NOT_RENAMING;

  3424.   name = type_name_no_tag (type);
  3425.   if (name == NULL)
  3426.     return ADA_NOT_RENAMING;

  3427.   name = strstr (name, "___XR");
  3428.   if (name == NULL)
  3429.     return ADA_NOT_RENAMING;
  3430.   switch (name[5])
  3431.     {
  3432.     case '\0':
  3433.     case '_':
  3434.       kind = ADA_OBJECT_RENAMING;
  3435.       break;
  3436.     case 'E':
  3437.       kind = ADA_EXCEPTION_RENAMING;
  3438.       break;
  3439.     case 'P':
  3440.       kind = ADA_PACKAGE_RENAMING;
  3441.       break;
  3442.     case 'S':
  3443.       kind = ADA_SUBPROGRAM_RENAMING;
  3444.       break;
  3445.     default:
  3446.       return ADA_NOT_RENAMING;
  3447.     }

  3448.   info = TYPE_FIELD_NAME (type, 0);
  3449.   if (info == NULL)
  3450.     return ADA_NOT_RENAMING;
  3451.   if (renamed_entity != NULL)
  3452.     *renamed_entity = info;
  3453.   suffix = strstr (info, "___XE");
  3454.   if (renaming_expr != NULL)
  3455.     *renaming_expr = suffix + 5;
  3456.   if (suffix == NULL || suffix == info)
  3457.     return ADA_NOT_RENAMING;
  3458.   if (len != NULL)
  3459.     *len = suffix - info;
  3460.   return kind;
  3461. }

  3462. /* Compute the value of the given RENAMING_SYM, which is expected to
  3463.    be a symbol encoding a renaming expression.  BLOCK is the block
  3464.    used to evaluate the renaming.  */

  3465. static struct value *
  3466. ada_read_renaming_var_value (struct symbol *renaming_sym,
  3467.                              const struct block *block)
  3468. {
  3469.   const char *sym_name;
  3470.   struct expression *expr;
  3471.   struct value *value;
  3472.   struct cleanup *old_chain = NULL;

  3473.   sym_name = SYMBOL_LINKAGE_NAME (renaming_sym);
  3474.   expr = parse_exp_1 (&sym_name, 0, block, 0);
  3475.   old_chain = make_cleanup (free_current_contents, &expr);
  3476.   value = evaluate_expression (expr);

  3477.   do_cleanups (old_chain);
  3478.   return value;
  3479. }


  3480.                                 /* Evaluation: Function Calls */

  3481. /* Return an lvalue containing the value VAL.  This is the identity on
  3482.    lvalues, and otherwise has the side-effect of allocating memory
  3483.    in the inferior where a copy of the value contents is copied.  */

  3484. static struct value *
  3485. ensure_lval (struct value *val)
  3486. {
  3487.   if (VALUE_LVAL (val) == not_lval
  3488.       || VALUE_LVAL (val) == lval_internalvar)
  3489.     {
  3490.       int len = TYPE_LENGTH (ada_check_typedef (value_type (val)));
  3491.       const CORE_ADDR addr =
  3492.         value_as_long (value_allocate_space_in_inferior (len));

  3493.       set_value_address (val, addr);
  3494.       VALUE_LVAL (val) = lval_memory;
  3495.       write_memory (addr, value_contents (val), len);
  3496.     }

  3497.   return val;
  3498. }

  3499. /* Return the value ACTUAL, converted to be an appropriate value for a
  3500.    formal of type FORMAL_TYPE.  Use *SP as a stack pointer for
  3501.    allocating any necessary descriptors (fat pointers), or copies of
  3502.    values not residing in memory, updating it as needed.  */

  3503. struct value *
  3504. ada_convert_actual (struct value *actual, struct type *formal_type0)
  3505. {
  3506.   struct type *actual_type = ada_check_typedef (value_type (actual));
  3507.   struct type *formal_type = ada_check_typedef (formal_type0);
  3508.   struct type *formal_target =
  3509.     TYPE_CODE (formal_type) == TYPE_CODE_PTR
  3510.     ? ada_check_typedef (TYPE_TARGET_TYPE (formal_type)) : formal_type;
  3511.   struct type *actual_target =
  3512.     TYPE_CODE (actual_type) == TYPE_CODE_PTR
  3513.     ? ada_check_typedef (TYPE_TARGET_TYPE (actual_type)) : actual_type;

  3514.   if (ada_is_array_descriptor_type (formal_target)
  3515.       && TYPE_CODE (actual_target) == TYPE_CODE_ARRAY)
  3516.     return make_array_descriptor (formal_type, actual);
  3517.   else if (TYPE_CODE (formal_type) == TYPE_CODE_PTR
  3518.            || TYPE_CODE (formal_type) == TYPE_CODE_REF)
  3519.     {
  3520.       struct value *result;

  3521.       if (TYPE_CODE (formal_target) == TYPE_CODE_ARRAY
  3522.           && ada_is_array_descriptor_type (actual_target))
  3523.         result = desc_data (actual);
  3524.       else if (TYPE_CODE (actual_type) != TYPE_CODE_PTR)
  3525.         {
  3526.           if (VALUE_LVAL (actual) != lval_memory)
  3527.             {
  3528.               struct value *val;

  3529.               actual_type = ada_check_typedef (value_type (actual));
  3530.               val = allocate_value (actual_type);
  3531.               memcpy ((char *) value_contents_raw (val),
  3532.                       (char *) value_contents (actual),
  3533.                       TYPE_LENGTH (actual_type));
  3534.               actual = ensure_lval (val);
  3535.             }
  3536.           result = value_addr (actual);
  3537.         }
  3538.       else
  3539.         return actual;
  3540.       return value_cast_pointers (formal_type, result, 0);
  3541.     }
  3542.   else if (TYPE_CODE (actual_type) == TYPE_CODE_PTR)
  3543.     return ada_value_ind (actual);

  3544.   return actual;
  3545. }

  3546. /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
  3547.    type TYPE.  This is usually an inefficient no-op except on some targets
  3548.    (such as AVR) where the representation of a pointer and an address
  3549.    differs.  */

  3550. static CORE_ADDR
  3551. value_pointer (struct value *value, struct type *type)
  3552. {
  3553.   struct gdbarch *gdbarch = get_type_arch (type);
  3554.   unsigned len = TYPE_LENGTH (type);
  3555.   gdb_byte *buf = alloca (len);
  3556.   CORE_ADDR addr;

  3557.   addr = value_address (value);
  3558.   gdbarch_address_to_pointer (gdbarch, type, buf, addr);
  3559.   addr = extract_unsigned_integer (buf, len, gdbarch_byte_order (gdbarch));
  3560.   return addr;
  3561. }


  3562. /* Push a descriptor of type TYPE for array value ARR on the stack at
  3563.    *SP, updating *SP to reflect the new descriptor.  Return either
  3564.    an lvalue representing the new descriptor, or (if TYPE is a pointer-
  3565.    to-descriptor type rather than a descriptor type), a struct value *
  3566.    representing a pointer to this descriptor.  */

  3567. static struct value *
  3568. make_array_descriptor (struct type *type, struct value *arr)
  3569. {
  3570.   struct type *bounds_type = desc_bounds_type (type);
  3571.   struct type *desc_type = desc_base_type (type);
  3572.   struct value *descriptor = allocate_value (desc_type);
  3573.   struct value *bounds = allocate_value (bounds_type);
  3574.   int i;

  3575.   for (i = ada_array_arity (ada_check_typedef (value_type (arr)));
  3576.        i > 0; i -= 1)
  3577.     {
  3578.       modify_field (value_type (bounds), value_contents_writeable (bounds),
  3579.                     ada_array_bound (arr, i, 0),
  3580.                     desc_bound_bitpos (bounds_type, i, 0),
  3581.                     desc_bound_bitsize (bounds_type, i, 0));
  3582.       modify_field (value_type (bounds), value_contents_writeable (bounds),
  3583.                     ada_array_bound (arr, i, 1),
  3584.                     desc_bound_bitpos (bounds_type, i, 1),
  3585.                     desc_bound_bitsize (bounds_type, i, 1));
  3586.     }

  3587.   bounds = ensure_lval (bounds);

  3588.   modify_field (value_type (descriptor),
  3589.                 value_contents_writeable (descriptor),
  3590.                 value_pointer (ensure_lval (arr),
  3591.                                TYPE_FIELD_TYPE (desc_type, 0)),
  3592.                 fat_pntr_data_bitpos (desc_type),
  3593.                 fat_pntr_data_bitsize (desc_type));

  3594.   modify_field (value_type (descriptor),
  3595.                 value_contents_writeable (descriptor),
  3596.                 value_pointer (bounds,
  3597.                                TYPE_FIELD_TYPE (desc_type, 1)),
  3598.                 fat_pntr_bounds_bitpos (desc_type),
  3599.                 fat_pntr_bounds_bitsize (desc_type));

  3600.   descriptor = ensure_lval (descriptor);

  3601.   if (TYPE_CODE (type) == TYPE_CODE_PTR)
  3602.     return value_addr (descriptor);
  3603.   else
  3604.     return descriptor;
  3605. }

  3606.                                 /* Symbol Cache Module */

  3607. /* Performance measurements made as of 2010-01-15 indicate that
  3608.    this cache does bring some noticeable improvements.  Depending
  3609.    on the type of entity being printed, the cache can make it as much
  3610.    as an order of magnitude faster than without it.

  3611.    The descriptive type DWARF extension has significantly reduced
  3612.    the need for this cache, at least when DWARF is being used.  However,
  3613.    even in this case, some expensive name-based symbol searches are still
  3614.    sometimes necessary - to find an XVZ variable, mostly.  */

  3615. /* Initialize the contents of SYM_CACHE.  */

  3616. static void
  3617. ada_init_symbol_cache (struct ada_symbol_cache *sym_cache)
  3618. {
  3619.   obstack_init (&sym_cache->cache_space);
  3620.   memset (sym_cache->root, '\000', sizeof (sym_cache->root));
  3621. }

  3622. /* Free the memory used by SYM_CACHE.  */

  3623. static void
  3624. ada_free_symbol_cache (struct ada_symbol_cache *sym_cache)
  3625. {
  3626.   obstack_free (&sym_cache->cache_space, NULL);
  3627.   xfree (sym_cache);
  3628. }

  3629. /* Return the symbol cache associated to the given program space PSPACE.
  3630.    If not allocated for this PSPACE yet, allocate and initialize one.  */

  3631. static struct ada_symbol_cache *
  3632. ada_get_symbol_cache (struct program_space *pspace)
  3633. {
  3634.   struct ada_pspace_data *pspace_data = get_ada_pspace_data (pspace);
  3635.   struct ada_symbol_cache *sym_cache = pspace_data->sym_cache;

  3636.   if (sym_cache == NULL)
  3637.     {
  3638.       sym_cache = XCNEW (struct ada_symbol_cache);
  3639.       ada_init_symbol_cache (sym_cache);
  3640.     }

  3641.   return sym_cache;
  3642. }

  3643. /* Clear all entries from the symbol cache.  */

  3644. static void
  3645. ada_clear_symbol_cache (void)
  3646. {
  3647.   struct ada_symbol_cache *sym_cache
  3648.     = ada_get_symbol_cache (current_program_space);

  3649.   obstack_free (&sym_cache->cache_space, NULL);
  3650.   ada_init_symbol_cache (sym_cache);
  3651. }

  3652. /* Search our cache for an entry matching NAME and NAMESPACE.
  3653.    Return it if found, or NULL otherwise.  */

  3654. static struct cache_entry **
  3655. find_entry (const char *name, domain_enum namespace)
  3656. {
  3657.   struct ada_symbol_cache *sym_cache
  3658.     = ada_get_symbol_cache (current_program_space);
  3659.   int h = msymbol_hash (name) % HASH_SIZE;
  3660.   struct cache_entry **e;

  3661.   for (e = &sym_cache->root[h]; *e != NULL; e = &(*e)->next)
  3662.     {
  3663.       if (namespace == (*e)->namespace && strcmp (name, (*e)->name) == 0)
  3664.         return e;
  3665.     }
  3666.   return NULL;
  3667. }

  3668. /* Search the symbol cache for an entry matching NAME and NAMESPACE.
  3669.    Return 1 if found, 0 otherwise.

  3670.    If an entry was found and SYM is not NULL, set *SYM to the entry's
  3671.    SYM.  Same principle for BLOCK if not NULL.  */

  3672. static int
  3673. lookup_cached_symbol (const char *name, domain_enum namespace,
  3674.                       struct symbol **sym, const struct block **block)
  3675. {
  3676.   struct cache_entry **e = find_entry (name, namespace);

  3677.   if (e == NULL)
  3678.     return 0;
  3679.   if (sym != NULL)
  3680.     *sym = (*e)->sym;
  3681.   if (block != NULL)
  3682.     *block = (*e)->block;
  3683.   return 1;
  3684. }

  3685. /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
  3686.    in domain NAMESPACE, save this result in our symbol cache.  */

  3687. static void
  3688. cache_symbol (const char *name, domain_enum namespace, struct symbol *sym,
  3689.               const struct block *block)
  3690. {
  3691.   struct ada_symbol_cache *sym_cache
  3692.     = ada_get_symbol_cache (current_program_space);
  3693.   int h;
  3694.   char *copy;
  3695.   struct cache_entry *e;

  3696.   /* Symbols for builtin types don't have a block.
  3697.      For now don't cache such symbols.  */
  3698.   if (sym != NULL && !SYMBOL_OBJFILE_OWNED (sym))
  3699.     return;

  3700.   /* If the symbol is a local symbol, then do not cache it, as a search
  3701.      for that symbol depends on the context.  To determine whether
  3702.      the symbol is local or not, we check the block where we found it
  3703.      against the global and static blocks of its associated symtab.  */
  3704.   if (sym
  3705.       && BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symbol_symtab (sym)),
  3706.                             GLOBAL_BLOCK) != block
  3707.       && BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symbol_symtab (sym)),
  3708.                             STATIC_BLOCK) != block)
  3709.     return;

  3710.   h = msymbol_hash (name) % HASH_SIZE;
  3711.   e = (struct cache_entry *) obstack_alloc (&sym_cache->cache_space,
  3712.                                             sizeof (*e));
  3713.   e->next = sym_cache->root[h];
  3714.   sym_cache->root[h] = e;
  3715.   e->name = copy = obstack_alloc (&sym_cache->cache_space, strlen (name) + 1);
  3716.   strcpy (copy, name);
  3717.   e->sym = sym;
  3718.   e->namespace = namespace;
  3719.   e->block = block;
  3720. }

  3721.                                 /* Symbol Lookup */

  3722. /* Return nonzero if wild matching should be used when searching for
  3723.    all symbols matching LOOKUP_NAME.

  3724.    LOOKUP_NAME is expected to be a symbol name after transformation
  3725.    for Ada lookups (see ada_name_for_lookup).  */

  3726. static int
  3727. should_use_wild_match (const char *lookup_name)
  3728. {
  3729.   return (strstr (lookup_name, "__") == NULL);
  3730. }

  3731. /* Return the result of a standard (literal, C-like) lookup of NAME in
  3732.    given DOMAIN, visible from lexical block BLOCK.  */

  3733. static struct symbol *
  3734. standard_lookup (const char *name, const struct block *block,
  3735.                  domain_enum domain)
  3736. {
  3737.   /* Initialize it just to avoid a GCC false warning.  */
  3738.   struct symbol *sym = NULL;

  3739.   if (lookup_cached_symbol (name, domain, &sym, NULL))
  3740.     return sym;
  3741.   sym = lookup_symbol_in_language (name, block, domain, language_c, 0);
  3742.   cache_symbol (name, domain, sym, block_found);
  3743.   return sym;
  3744. }


  3745. /* Non-zero iff there is at least one non-function/non-enumeral symbol
  3746.    in the symbol fields of SYMS[0..N-1].  We treat enumerals as functions,
  3747.    since they contend in overloading in the same way.  */
  3748. static int
  3749. is_nonfunction (struct ada_symbol_info syms[], int n)
  3750. {
  3751.   int i;

  3752.   for (i = 0; i < n; i += 1)
  3753.     if (TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) != TYPE_CODE_FUNC
  3754.         && (TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) != TYPE_CODE_ENUM
  3755.             || SYMBOL_CLASS (syms[i].sym) != LOC_CONST))
  3756.       return 1;

  3757.   return 0;
  3758. }

  3759. /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
  3760.    struct types.  Otherwise, they may not.  */

  3761. static int
  3762. equiv_types (struct type *type0, struct type *type1)
  3763. {
  3764.   if (type0 == type1)
  3765.     return 1;
  3766.   if (type0 == NULL || type1 == NULL
  3767.       || TYPE_CODE (type0) != TYPE_CODE (type1))
  3768.     return 0;
  3769.   if ((TYPE_CODE (type0) == TYPE_CODE_STRUCT
  3770.        || TYPE_CODE (type0) == TYPE_CODE_ENUM)
  3771.       && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
  3772.       && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
  3773.     return 1;

  3774.   return 0;
  3775. }

  3776. /* True iff SYM0 represents the same entity as SYM1, or one that is
  3777.    no more defined than that of SYM1.  */

  3778. static int
  3779. lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
  3780. {
  3781.   if (sym0 == sym1)
  3782.     return 1;
  3783.   if (SYMBOL_DOMAIN (sym0) != SYMBOL_DOMAIN (sym1)
  3784.       || SYMBOL_CLASS (sym0) != SYMBOL_CLASS (sym1))
  3785.     return 0;

  3786.   switch (SYMBOL_CLASS (sym0))
  3787.     {
  3788.     case LOC_UNDEF:
  3789.       return 1;
  3790.     case LOC_TYPEDEF:
  3791.       {
  3792.         struct type *type0 = SYMBOL_TYPE (sym0);
  3793.         struct type *type1 = SYMBOL_TYPE (sym1);
  3794.         const char *name0 = SYMBOL_LINKAGE_NAME (sym0);
  3795.         const char *name1 = SYMBOL_LINKAGE_NAME (sym1);
  3796.         int len0 = strlen (name0);

  3797.         return
  3798.           TYPE_CODE (type0) == TYPE_CODE (type1)
  3799.           && (equiv_types (type0, type1)
  3800.               || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
  3801.                   && strncmp (name1 + len0, "___XV", 5) == 0));
  3802.       }
  3803.     case LOC_CONST:
  3804.       return SYMBOL_VALUE (sym0) == SYMBOL_VALUE (sym1)
  3805.         && equiv_types (SYMBOL_TYPE (sym0), SYMBOL_TYPE (sym1));
  3806.     default:
  3807.       return 0;
  3808.     }
  3809. }

  3810. /* Append (SYM,BLOCK,SYMTAB) to the end of the array of struct ada_symbol_info
  3811.    records in OBSTACKP.  Do nothing if SYM is a duplicate.  */

  3812. static void
  3813. add_defn_to_vec (struct obstack *obstackp,
  3814.                  struct symbol *sym,
  3815.                  const struct block *block)
  3816. {
  3817.   int i;
  3818.   struct ada_symbol_info *prevDefns = defns_collected (obstackp, 0);

  3819.   /* Do not try to complete stub types, as the debugger is probably
  3820.      already scanning all symbols matching a certain name at the
  3821.      time when this function is called.  Trying to replace the stub
  3822.      type by its associated full type will cause us to restart a scan
  3823.      which may lead to an infinite recursion.  Instead, the client
  3824.      collecting the matching symbols will end up collecting several
  3825.      matches, with at least one of them complete.  It can then filter
  3826.      out the stub ones if needed.  */

  3827.   for (i = num_defns_collected (obstackp) - 1; i >= 0; i -= 1)
  3828.     {
  3829.       if (lesseq_defined_than (sym, prevDefns[i].sym))
  3830.         return;
  3831.       else if (lesseq_defined_than (prevDefns[i].sym, sym))
  3832.         {
  3833.           prevDefns[i].sym = sym;
  3834.           prevDefns[i].block = block;
  3835.           return;
  3836.         }
  3837.     }

  3838.   {
  3839.     struct ada_symbol_info info;

  3840.     info.sym = sym;
  3841.     info.block = block;
  3842.     obstack_grow (obstackp, &info, sizeof (struct ada_symbol_info));
  3843.   }
  3844. }

  3845. /* Number of ada_symbol_info structures currently collected in
  3846.    current vector in *OBSTACKP.  */

  3847. static int
  3848. num_defns_collected (struct obstack *obstackp)
  3849. {
  3850.   return obstack_object_size (obstackp) / sizeof (struct ada_symbol_info);
  3851. }

  3852. /* Vector of ada_symbol_info structures currently collected in current
  3853.    vector in *OBSTACKP.  If FINISH, close off the vector and return
  3854.    its final address.  */

  3855. static struct ada_symbol_info *
  3856. defns_collected (struct obstack *obstackp, int finish)
  3857. {
  3858.   if (finish)
  3859.     return obstack_finish (obstackp);
  3860.   else
  3861.     return (struct ada_symbol_info *) obstack_base (obstackp);
  3862. }

  3863. /* Return a bound minimal symbol matching NAME according to Ada
  3864.    decoding rules.  Returns an invalid symbol if there is no such
  3865.    minimal symbol.  Names prefixed with "standard__" are handled
  3866.    specially: "standard__" is first stripped off, and only static and
  3867.    global symbols are searched.  */

  3868. struct bound_minimal_symbol
  3869. ada_lookup_simple_minsym (const char *name)
  3870. {
  3871.   struct bound_minimal_symbol result;
  3872.   struct objfile *objfile;
  3873.   struct minimal_symbol *msymbol;
  3874.   const int wild_match_p = should_use_wild_match (name);

  3875.   memset (&result, 0, sizeof (result));

  3876.   /* Special case: If the user specifies a symbol name inside package
  3877.      Standard, do a non-wild matching of the symbol name without
  3878.      the "standard__" prefix.  This was primarily introduced in order
  3879.      to allow the user to specifically access the standard exceptions
  3880.      using, for instance, Standard.Constraint_Error when Constraint_Error
  3881.      is ambiguous (due to the user defining its own Constraint_Error
  3882.      entity inside its program).  */
  3883.   if (strncmp (name, "standard__", sizeof ("standard__") - 1) == 0)
  3884.     name += sizeof ("standard__") - 1;

  3885.   ALL_MSYMBOLS (objfile, msymbol)
  3886.   {
  3887.     if (match_name (MSYMBOL_LINKAGE_NAME (msymbol), name, wild_match_p)
  3888.         && MSYMBOL_TYPE (msymbol) != mst_solib_trampoline)
  3889.       {
  3890.         result.minsym = msymbol;
  3891.         result.objfile = objfile;
  3892.         break;
  3893.       }
  3894.   }

  3895.   return result;
  3896. }

  3897. /* For all subprograms that statically enclose the subprogram of the
  3898.    selected frame, add symbols matching identifier NAME in DOMAIN
  3899.    and their blocks to the list of data in OBSTACKP, as for
  3900.    ada_add_block_symbols (q.v.).   If WILD_MATCH_P, treat as NAME
  3901.    with a wildcard prefix.  */

  3902. static void
  3903. add_symbols_from_enclosing_procs (struct obstack *obstackp,
  3904.                                   const char *name, domain_enum namespace,
  3905.                                   int wild_match_p)
  3906. {
  3907. }

  3908. /* True if TYPE is definitely an artificial type supplied to a symbol
  3909.    for which no debugging information was given in the symbol file.  */

  3910. static int
  3911. is_nondebugging_type (struct type *type)
  3912. {
  3913.   const char *name = ada_type_name (type);

  3914.   return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
  3915. }

  3916. /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
  3917.    that are deemed "identical" for practical purposes.

  3918.    This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
  3919.    types and that their number of enumerals is identical (in other
  3920.    words, TYPE_NFIELDS (type1) == TYPE_NFIELDS (type2)).  */

  3921. static int
  3922. ada_identical_enum_types_p (struct type *type1, struct type *type2)
  3923. {
  3924.   int i;

  3925.   /* The heuristic we use here is fairly conservative.  We consider
  3926.      that 2 enumerate types are identical if they have the same
  3927.      number of enumerals and that all enumerals have the same
  3928.      underlying value and name.  */

  3929.   /* All enums in the type should have an identical underlying value.  */
  3930.   for (i = 0; i < TYPE_NFIELDS (type1); i++)
  3931.     if (TYPE_FIELD_ENUMVAL (type1, i) != TYPE_FIELD_ENUMVAL (type2, i))
  3932.       return 0;

  3933.   /* All enumerals should also have the same name (modulo any numerical
  3934.      suffix).  */
  3935.   for (i = 0; i < TYPE_NFIELDS (type1); i++)
  3936.     {
  3937.       const char *name_1 = TYPE_FIELD_NAME (type1, i);
  3938.       const char *name_2 = TYPE_FIELD_NAME (type2, i);
  3939.       int len_1 = strlen (name_1);
  3940.       int len_2 = strlen (name_2);

  3941.       ada_remove_trailing_digits (TYPE_FIELD_NAME (type1, i), &len_1);
  3942.       ada_remove_trailing_digits (TYPE_FIELD_NAME (type2, i), &len_2);
  3943.       if (len_1 != len_2
  3944.           || strncmp (TYPE_FIELD_NAME (type1, i),
  3945.                       TYPE_FIELD_NAME (type2, i),
  3946.                       len_1) != 0)
  3947.         return 0;
  3948.     }

  3949.   return 1;
  3950. }

  3951. /* Return nonzero if all the symbols in SYMS are all enumeral symbols
  3952.    that are deemed "identical" for practical purposes.  Sometimes,
  3953.    enumerals are not strictly identical, but their types are so similar
  3954.    that they can be considered identical.

  3955.    For instance, consider the following code:

  3956.       type Color is (Black, Red, Green, Blue, White);
  3957.       type RGB_Color is new Color range Red .. Blue;

  3958.    Type RGB_Color is a subrange of an implicit type which is a copy
  3959.    of type Color. If we call that implicit type RGB_ColorB ("B" is
  3960.    for "Base Type"), then type RGB_ColorB is a copy of type Color.
  3961.    As a result, when an expression references any of the enumeral
  3962.    by name (Eg. "print green"), the expression is technically
  3963.    ambiguous and the user should be asked to disambiguate. But
  3964.    doing so would only hinder the user, since it wouldn't matter
  3965.    what choice he makes, the outcome would always be the same.
  3966.    So, for practical purposes, we consider them as the same.  */

  3967. static int
  3968. symbols_are_identical_enums (struct ada_symbol_info *syms, int nsyms)
  3969. {
  3970.   int i;

  3971.   /* Before performing a thorough comparison check of each type,
  3972.      we perform a series of inexpensive checks.  We expect that these
  3973.      checks will quickly fail in the vast majority of cases, and thus
  3974.      help prevent the unnecessary use of a more expensive comparison.
  3975.      Said comparison also expects us to make some of these checks
  3976.      (see ada_identical_enum_types_p).  */

  3977.   /* Quick check: All symbols should have an enum type.  */
  3978.   for (i = 0; i < nsyms; i++)
  3979.     if (TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) != TYPE_CODE_ENUM)
  3980.       return 0;

  3981.   /* Quick check: They should all have the same value.  */
  3982.   for (i = 1; i < nsyms; i++)
  3983.     if (SYMBOL_VALUE (syms[i].sym) != SYMBOL_VALUE (syms[0].sym))
  3984.       return 0;

  3985.   /* Quick check: They should all have the same number of enumerals.  */
  3986.   for (i = 1; i < nsyms; i++)
  3987.     if (TYPE_NFIELDS (SYMBOL_TYPE (syms[i].sym))
  3988.         != TYPE_NFIELDS (SYMBOL_TYPE (syms[0].sym)))
  3989.       return 0;

  3990.   /* All the sanity checks passed, so we might have a set of
  3991.      identical enumeration types.  Perform a more complete
  3992.      comparison of the type of each symbol.  */
  3993.   for (i = 1; i < nsyms; i++)
  3994.     if (!ada_identical_enum_types_p (SYMBOL_TYPE (syms[i].sym),
  3995.                                      SYMBOL_TYPE (syms[0].sym)))
  3996.       return 0;

  3997.   return 1;
  3998. }

  3999. /* Remove any non-debugging symbols in SYMS[0 .. NSYMS-1] that definitely
  4000.    duplicate other symbols in the list (The only case I know of where
  4001.    this happens is when object files containing stabs-in-ecoff are
  4002.    linked with files containing ordinary ecoff debugging symbols (or no
  4003.    debugging symbols)).  Modifies SYMS to squeeze out deleted entries.
  4004.    Returns the number of items in the modified list.  */

  4005. static int
  4006. remove_extra_symbols (struct ada_symbol_info *syms, int nsyms)
  4007. {
  4008.   int i, j;

  4009.   /* We should never be called with less than 2 symbols, as there
  4010.      cannot be any extra symbol in that case.  But it's easy to
  4011.      handle, since we have nothing to do in that case.  */
  4012.   if (nsyms < 2)
  4013.     return nsyms;

  4014.   i = 0;
  4015.   while (i < nsyms)
  4016.     {
  4017.       int remove_p = 0;

  4018.       /* If two symbols have the same name and one of them is a stub type,
  4019.          the get rid of the stub.  */

  4020.       if (TYPE_STUB (SYMBOL_TYPE (syms[i].sym))
  4021.           && SYMBOL_LINKAGE_NAME (syms[i].sym) != NULL)
  4022.         {
  4023.           for (j = 0; j < nsyms; j++)
  4024.             {
  4025.               if (j != i
  4026.                   && !TYPE_STUB (SYMBOL_TYPE (syms[j].sym))
  4027.                   && SYMBOL_LINKAGE_NAME (syms[j].sym) != NULL
  4028.                   && strcmp (SYMBOL_LINKAGE_NAME (syms[i].sym),
  4029.                              SYMBOL_LINKAGE_NAME (syms[j].sym)) == 0)
  4030.                 remove_p = 1;
  4031.             }
  4032.         }

  4033.       /* Two symbols with the same name, same class and same address
  4034.          should be identical.  */

  4035.       else if (SYMBOL_LINKAGE_NAME (syms[i].sym) != NULL
  4036.           && SYMBOL_CLASS (syms[i].sym) == LOC_STATIC
  4037.           && is_nondebugging_type (SYMBOL_TYPE (syms[i].sym)))
  4038.         {
  4039.           for (j = 0; j < nsyms; j += 1)
  4040.             {
  4041.               if (i != j
  4042.                   && SYMBOL_LINKAGE_NAME (syms[j].sym) != NULL
  4043.                   && strcmp (SYMBOL_LINKAGE_NAME (syms[i].sym),
  4044.                              SYMBOL_LINKAGE_NAME (syms[j].sym)) == 0
  4045.                   && SYMBOL_CLASS (syms[i].sym) == SYMBOL_CLASS (syms[j].sym)
  4046.                   && SYMBOL_VALUE_ADDRESS (syms[i].sym)
  4047.                   == SYMBOL_VALUE_ADDRESS (syms[j].sym))
  4048.                 remove_p = 1;
  4049.             }
  4050.         }

  4051.       if (remove_p)
  4052.         {
  4053.           for (j = i + 1; j < nsyms; j += 1)
  4054.             syms[j - 1] = syms[j];
  4055.           nsyms -= 1;
  4056.         }

  4057.       i += 1;
  4058.     }

  4059.   /* If all the remaining symbols are identical enumerals, then
  4060.      just keep the first one and discard the rest.

  4061.      Unlike what we did previously, we do not discard any entry
  4062.      unless they are ALL identical.  This is because the symbol
  4063.      comparison is not a strict comparison, but rather a practical
  4064.      comparison.  If all symbols are considered identical, then
  4065.      we can just go ahead and use the first one and discard the rest.
  4066.      But if we cannot reduce the list to a single element, we have
  4067.      to ask the user to disambiguate anyways.  And if we have to
  4068.      present a multiple-choice menu, it's less confusing if the list
  4069.      isn't missing some choices that were identical and yet distinct.  */
  4070.   if (symbols_are_identical_enums (syms, nsyms))
  4071.     nsyms = 1;

  4072.   return nsyms;
  4073. }

  4074. /* Given a type that corresponds to a renaming entity, use the type name
  4075.    to extract the scope (package name or function name, fully qualified,
  4076.    and following the GNAT encoding convention) where this renaming has been
  4077.    defined.  The string returned needs to be deallocated after use.  */

  4078. static char *
  4079. xget_renaming_scope (struct type *renaming_type)
  4080. {
  4081.   /* The renaming types adhere to the following convention:
  4082.      <scope>__<rename>___<XR extension>.
  4083.      So, to extract the scope, we search for the "___XR" extension,
  4084.      and then backtrack until we find the first "__".  */

  4085.   const char *name = type_name_no_tag (renaming_type);
  4086.   char *suffix = strstr (name, "___XR");
  4087.   char *last;
  4088.   int scope_len;
  4089.   char *scope;

  4090.   /* Now, backtrack a bit until we find the first "__".  Start looking
  4091.      at suffix - 3, as the <rename> part is at least one character long.  */

  4092.   for (last = suffix - 3; last > name; last--)
  4093.     if (last[0] == '_' && last[1] == '_')
  4094.       break;

  4095.   /* Make a copy of scope and return it.  */

  4096.   scope_len = last - name;
  4097.   scope = (char *) xmalloc ((scope_len + 1) * sizeof (char));

  4098.   strncpy (scope, name, scope_len);
  4099.   scope[scope_len] = '\0';

  4100.   return scope;
  4101. }

  4102. /* Return nonzero if NAME corresponds to a package name.  */

  4103. static int
  4104. is_package_name (const char *name)
  4105. {
  4106.   /* Here, We take advantage of the fact that no symbols are generated
  4107.      for packages, while symbols are generated for each function.
  4108.      So the condition for NAME represent a package becomes equivalent
  4109.      to NAME not existing in our list of symbols.  There is only one
  4110.      small complication with library-level functions (see below).  */

  4111.   char *fun_name;

  4112.   /* If it is a function that has not been defined at library level,
  4113.      then we should be able to look it up in the symbols.  */
  4114.   if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
  4115.     return 0;

  4116.   /* Library-level function names start with "_ada_".  See if function
  4117.      "_ada_" followed by NAME can be found.  */

  4118.   /* Do a quick check that NAME does not contain "__", since library-level
  4119.      functions names cannot contain "__" in them.  */
  4120.   if (strstr (name, "__") != NULL)
  4121.     return 0;

  4122.   fun_name = xstrprintf ("_ada_%s", name);

  4123.   return (standard_lookup (fun_name, NULL, VAR_DOMAIN) == NULL);
  4124. }

  4125. /* Return nonzero if SYM corresponds to a renaming entity that is
  4126.    not visible from FUNCTION_NAME.  */

  4127. static int
  4128. old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
  4129. {
  4130.   char *scope;
  4131.   struct cleanup *old_chain;

  4132.   if (SYMBOL_CLASS (sym) != LOC_TYPEDEF)
  4133.     return 0;

  4134.   scope = xget_renaming_scope (SYMBOL_TYPE (sym));
  4135.   old_chain = make_cleanup (xfree, scope);

  4136.   /* If the rename has been defined in a package, then it is visible.  */
  4137.   if (is_package_name (scope))
  4138.     {
  4139.       do_cleanups (old_chain);
  4140.       return 0;
  4141.     }

  4142.   /* Check that the rename is in the current function scope by checking
  4143.      that its name starts with SCOPE.  */

  4144.   /* If the function name starts with "_ada_", it means that it is
  4145.      a library-level function.  Strip this prefix before doing the
  4146.      comparison, as the encoding for the renaming does not contain
  4147.      this prefix.  */
  4148.   if (strncmp (function_name, "_ada_", 5) == 0)
  4149.     function_name += 5;

  4150.   {
  4151.     int is_invisible = strncmp (function_name, scope, strlen (scope)) != 0;

  4152.     do_cleanups (old_chain);
  4153.     return is_invisible;
  4154.   }
  4155. }

  4156. /* Remove entries from SYMS that corresponds to a renaming entity that
  4157.    is not visible from the function associated with CURRENT_BLOCK or
  4158.    that is superfluous due to the presence of more specific renaming
  4159.    information.  Places surviving symbols in the initial entries of
  4160.    SYMS and returns the number of surviving symbols.

  4161.    Rationale:
  4162.    First, in cases where an object renaming is implemented as a
  4163.    reference variable, GNAT may produce both the actual reference
  4164.    variable and the renaming encoding.  In this case, we discard the
  4165.    latter.

  4166.    Second, GNAT emits a type following a specified encoding for each renaming
  4167.    entity.  Unfortunately, STABS currently does not support the definition
  4168.    of types that are local to a given lexical block, so all renamings types
  4169.    are emitted at library level.  As a consequence, if an application
  4170.    contains two renaming entities using the same name, and a user tries to
  4171.    print the value of one of these entities, the result of the ada symbol
  4172.    lookup will also contain the wrong renaming type.

  4173.    This function partially covers for this limitation by attempting to
  4174.    remove from the SYMS list renaming symbols that should be visible
  4175.    from CURRENT_BLOCK.  However, there does not seem be a 100% reliable
  4176.    method with the current information available.  The implementation
  4177.    below has a couple of limitations (FIXME: brobecker-2003-05-12):

  4178.       - When the user tries to print a rename in a function while there
  4179.         is another rename entity defined in a package:  Normally, the
  4180.         rename in the function has precedence over the rename in the
  4181.         package, so the latter should be removed from the list.  This is
  4182.         currently not the case.

  4183.       - This function will incorrectly remove valid renames if
  4184.         the CURRENT_BLOCK corresponds to a function which symbol name
  4185.         has been changed by an "Export" pragma.  As a consequence,
  4186.         the user will be unable to print such rename entities.  */

  4187. static int
  4188. remove_irrelevant_renamings (struct ada_symbol_info *syms,
  4189.                              int nsyms, const struct block *current_block)
  4190. {
  4191.   struct symbol *current_function;
  4192.   const char *current_function_name;
  4193.   int i;
  4194.   int is_new_style_renaming;

  4195.   /* If there is both a renaming foo___XR... encoded as a variable and
  4196.      a simple variable foo in the same block, discard the latter.
  4197.      First, zero out such symbols, then compress.  */
  4198.   is_new_style_renaming = 0;
  4199.   for (i = 0; i < nsyms; i += 1)
  4200.     {
  4201.       struct symbol *sym = syms[i].sym;
  4202.       const struct block *block = syms[i].block;
  4203.       const char *name;
  4204.       const char *suffix;

  4205.       if (sym == NULL || SYMBOL_CLASS (sym) == LOC_TYPEDEF)
  4206.         continue;
  4207.       name = SYMBOL_LINKAGE_NAME (sym);
  4208.       suffix = strstr (name, "___XR");

  4209.       if (suffix != NULL)
  4210.         {
  4211.           int name_len = suffix - name;
  4212.           int j;

  4213.           is_new_style_renaming = 1;
  4214.           for (j = 0; j < nsyms; j += 1)
  4215.             if (i != j && syms[j].sym != NULL
  4216.                 && strncmp (name, SYMBOL_LINKAGE_NAME (syms[j].sym),
  4217.                             name_len) == 0
  4218.                 && block == syms[j].block)
  4219.               syms[j].sym = NULL;
  4220.         }
  4221.     }
  4222.   if (is_new_style_renaming)
  4223.     {
  4224.       int j, k;

  4225.       for (j = k = 0; j < nsyms; j += 1)
  4226.         if (syms[j].sym != NULL)
  4227.             {
  4228.               syms[k] = syms[j];
  4229.               k += 1;
  4230.             }
  4231.       return k;
  4232.     }

  4233.   /* Extract the function name associated to CURRENT_BLOCK.
  4234.      Abort if unable to do so.  */

  4235.   if (current_block == NULL)
  4236.     return nsyms;

  4237.   current_function = block_linkage_function (current_block);
  4238.   if (current_function == NULL)
  4239.     return nsyms;

  4240.   current_function_name = SYMBOL_LINKAGE_NAME (current_function);
  4241.   if (current_function_name == NULL)
  4242.     return nsyms;

  4243.   /* Check each of the symbols, and remove it from the list if it is
  4244.      a type corresponding to a renaming that is out of the scope of
  4245.      the current block.  */

  4246.   i = 0;
  4247.   while (i < nsyms)
  4248.     {
  4249.       if (ada_parse_renaming (syms[i].sym, NULL, NULL, NULL)
  4250.           == ADA_OBJECT_RENAMING
  4251.           && old_renaming_is_invisible (syms[i].sym, current_function_name))
  4252.         {
  4253.           int j;

  4254.           for (j = i + 1; j < nsyms; j += 1)
  4255.             syms[j - 1] = syms[j];
  4256.           nsyms -= 1;
  4257.         }
  4258.       else
  4259.         i += 1;
  4260.     }

  4261.   return nsyms;
  4262. }

  4263. /* Add to OBSTACKP all symbols from BLOCK (and its super-blocks)
  4264.    whose name and domain match NAME and DOMAIN respectively.
  4265.    If no match was found, then extend the search to "enclosing"
  4266.    routines (in other words, if we're inside a nested function,
  4267.    search the symbols defined inside the enclosing functions).
  4268.    If WILD_MATCH_P is nonzero, perform the naming matching in
  4269.    "wild" mode (see function "wild_match" for more info).

  4270.    Note: This function assumes that OBSTACKP has 0 (zero) element in it.  */

  4271. static void
  4272. ada_add_local_symbols (struct obstack *obstackp, const char *name,
  4273.                        const struct block *block, domain_enum domain,
  4274.                        int wild_match_p)
  4275. {
  4276.   int block_depth = 0;

  4277.   while (block != NULL)
  4278.     {
  4279.       block_depth += 1;
  4280.       ada_add_block_symbols (obstackp, block, name, domain, NULL,
  4281.                              wild_match_p);

  4282.       /* If we found a non-function match, assume that's the one.  */
  4283.       if (is_nonfunction (defns_collected (obstackp, 0),
  4284.                           num_defns_collected (obstackp)))
  4285.         return;

  4286.       block = BLOCK_SUPERBLOCK (block);
  4287.     }

  4288.   /* If no luck so far, try to find NAME as a local symbol in some lexically
  4289.      enclosing subprogram.  */
  4290.   if (num_defns_collected (obstackp) == 0 && block_depth > 2)
  4291.     add_symbols_from_enclosing_procs (obstackp, name, domain, wild_match_p);
  4292. }

  4293. /* An object of this type is used as the user_data argument when
  4294.    calling the map_matching_symbols method.  */

  4295. struct match_data
  4296. {
  4297.   struct objfile *objfile;
  4298.   struct obstack *obstackp;
  4299.   struct symbol *arg_sym;
  4300.   int found_sym;
  4301. };

  4302. /* A callback for add_matching_symbols that adds SYM, found in BLOCK,
  4303.    to a list of symbols.  DATA0 is a pointer to a struct match_data *
  4304.    containing the obstack that collects the symbol list, the file that SYM
  4305.    must come from, a flag indicating whether a non-argument symbol has
  4306.    been found in the current block, and the last argument symbol
  4307.    passed in SYM within the current block (if any).  When SYM is null,
  4308.    marking the end of a block, the argument symbol is added if no
  4309.    other has been found.  */

  4310. static int
  4311. aux_add_nonlocal_symbols (struct block *block, struct symbol *sym, void *data0)
  4312. {
  4313.   struct match_data *data = (struct match_data *) data0;

  4314.   if (sym == NULL)
  4315.     {
  4316.       if (!data->found_sym && data->arg_sym != NULL)
  4317.         add_defn_to_vec (data->obstackp,
  4318.                          fixup_symbol_section (data->arg_sym, data->objfile),
  4319.                          block);
  4320.       data->found_sym = 0;
  4321.       data->arg_sym = NULL;
  4322.     }
  4323.   else
  4324.     {
  4325.       if (SYMBOL_CLASS (sym) == LOC_UNRESOLVED)
  4326.         return 0;
  4327.       else if (SYMBOL_IS_ARGUMENT (sym))
  4328.         data->arg_sym = sym;
  4329.       else
  4330.         {
  4331.           data->found_sym = 1;
  4332.           add_defn_to_vec (data->obstackp,
  4333.                            fixup_symbol_section (sym, data->objfile),
  4334.                            block);
  4335.         }
  4336.     }
  4337.   return 0;
  4338. }

  4339. /* Implements compare_names, but only applying the comparision using
  4340.    the given CASING.  */

  4341. static int
  4342. compare_names_with_case (const char *string1, const char *string2,
  4343.                          enum case_sensitivity casing)
  4344. {
  4345.   while (*string1 != '\0' && *string2 != '\0')
  4346.     {
  4347.       char c1, c2;

  4348.       if (isspace (*string1) || isspace (*string2))
  4349.         return strcmp_iw_ordered (string1, string2);

  4350.       if (casing == case_sensitive_off)
  4351.         {
  4352.           c1 = tolower (*string1);
  4353.           c2 = tolower (*string2);
  4354.         }
  4355.       else
  4356.         {
  4357.           c1 = *string1;
  4358.           c2 = *string2;
  4359.         }
  4360.       if (c1 != c2)
  4361.         break;

  4362.       string1 += 1;
  4363.       string2 += 1;
  4364.     }

  4365.   switch (*string1)
  4366.     {
  4367.     case '(':
  4368.       return strcmp_iw_ordered (string1, string2);
  4369.     case '_':
  4370.       if (*string2 == '\0')
  4371.         {
  4372.           if (is_name_suffix (string1))
  4373.             return 0;
  4374.           else
  4375.             return 1;
  4376.         }
  4377.       /* FALLTHROUGH */
  4378.     default:
  4379.       if (*string2 == '(')
  4380.         return strcmp_iw_ordered (string1, string2);
  4381.       else
  4382.         {
  4383.           if (casing == case_sensitive_off)
  4384.             return tolower (*string1) - tolower (*string2);
  4385.           else
  4386.             return *string1 - *string2;
  4387.         }
  4388.     }
  4389. }

  4390. /* Compare STRING1 to STRING2, with results as for strcmp.
  4391.    Compatible with strcmp_iw_ordered in that...

  4392.        strcmp_iw_ordered (STRING1, STRING2) <= 0

  4393.    ... implies...

  4394.        compare_names (STRING1, STRING2) <= 0

  4395.    (they may differ as to what symbols compare equal).  */

  4396. static int
  4397. compare_names (const char *string1, const char *string2)
  4398. {
  4399.   int result;

  4400.   /* Similar to what strcmp_iw_ordered does, we need to perform
  4401.      a case-insensitive comparison first, and only resort to
  4402.      a second, case-sensitive, comparison if the first one was
  4403.      not sufficient to differentiate the two strings.  */

  4404.   result = compare_names_with_case (string1, string2, case_sensitive_off);
  4405.   if (result == 0)
  4406.     result = compare_names_with_case (string1, string2, case_sensitive_on);

  4407.   return result;
  4408. }

  4409. /* Add to OBSTACKP all non-local symbols whose name and domain match
  4410.    NAME and DOMAIN respectively.  The search is performed on GLOBAL_BLOCK
  4411.    symbols if GLOBAL is non-zero, or on STATIC_BLOCK symbols otherwise.  */

  4412. static void
  4413. add_nonlocal_symbols (struct obstack *obstackp, const char *name,
  4414.                       domain_enum domain, int global,
  4415.                       int is_wild_match)
  4416. {
  4417.   struct objfile *objfile;
  4418.   struct match_data data;

  4419.   memset (&data, 0, sizeof data);
  4420.   data.obstackp = obstackp;

  4421.   ALL_OBJFILES (objfile)
  4422.     {
  4423.       data.objfile = objfile;

  4424.       if (is_wild_match)
  4425.         objfile->sf->qf->map_matching_symbols (objfile, name, domain, global,
  4426.                                                aux_add_nonlocal_symbols, &data,
  4427.                                                wild_match, NULL);
  4428.       else
  4429.         objfile->sf->qf->map_matching_symbols (objfile, name, domain, global,
  4430.                                                aux_add_nonlocal_symbols, &data,
  4431.                                                full_match, compare_names);
  4432.     }

  4433.   if (num_defns_collected (obstackp) == 0 && global && !is_wild_match)
  4434.     {
  4435.       ALL_OBJFILES (objfile)
  4436.         {
  4437.           char *name1 = alloca (strlen (name) + sizeof ("_ada_"));
  4438.           strcpy (name1, "_ada_");
  4439.           strcpy (name1 + sizeof ("_ada_") - 1, name);
  4440.           data.objfile = objfile;
  4441.           objfile->sf->qf->map_matching_symbols (objfile, name1, domain,
  4442.                                                  global,
  4443.                                                  aux_add_nonlocal_symbols,
  4444.                                                  &data,
  4445.                                                  full_match, compare_names);
  4446.         }
  4447.     }
  4448. }

  4449. /* Find symbols in DOMAIN matching NAME0, in BLOCK0 and, if full_search is
  4450.    non-zero, enclosing scope and in global scopes, returning the number of
  4451.    matches.
  4452.    Sets *RESULTS to point to a vector of (SYM,BLOCK) tuples,
  4453.    indicating the symbols found and the blocks and symbol tables (if
  4454.    any) in which they were found.  This vector is transient---good only to
  4455.    the next call of ada_lookup_symbol_list.

  4456.    When full_search is non-zero, any non-function/non-enumeral
  4457.    symbol match within the nest of blocks whose innermost member is BLOCK0,
  4458.    is the one match returned (no other matches in that or
  4459.    enclosing blocks is returned).  If there are any matches in or
  4460.    surrounding BLOCK0, then these alone are returned.

  4461.    Names prefixed with "standard__" are handled specially: "standard__"
  4462.    is first stripped off, and only static and global symbols are searched.  */

  4463. static int
  4464. ada_lookup_symbol_list_worker (const char *name0, const struct block *block0,
  4465.                                domain_enum namespace,
  4466.                                struct ada_symbol_info **results,
  4467.                                int full_search)
  4468. {
  4469.   struct symbol *sym;
  4470.   const struct block *block;
  4471.   const char *name;
  4472.   const int wild_match_p = should_use_wild_match (name0);
  4473.   int cacheIfUnique;
  4474.   int ndefns;

  4475.   obstack_free (&symbol_list_obstack, NULL);
  4476.   obstack_init (&symbol_list_obstack);

  4477.   cacheIfUnique = 0;

  4478.   /* Search specified block and its superiors.  */

  4479.   name = name0;
  4480.   block = block0;

  4481.   /* Special case: If the user specifies a symbol name inside package
  4482.      Standard, do a non-wild matching of the symbol name without
  4483.      the "standard__" prefix.  This was primarily introduced in order
  4484.      to allow the user to specifically access the standard exceptions
  4485.      using, for instance, Standard.Constraint_Error when Constraint_Error
  4486.      is ambiguous (due to the user defining its own Constraint_Error
  4487.      entity inside its program).  */
  4488.   if (strncmp (name0, "standard__", sizeof ("standard__") - 1) == 0)
  4489.     {
  4490.       block = NULL;
  4491.       name = name0 + sizeof ("standard__") - 1;
  4492.     }

  4493.   /* Check the non-global symbols.  If we have ANY match, then we're done.  */

  4494.   if (block != NULL)
  4495.     {
  4496.       if (full_search)
  4497.         {
  4498.           ada_add_local_symbols (&symbol_list_obstack, name, block,
  4499.                                  namespace, wild_match_p);
  4500.         }
  4501.       else
  4502.         {
  4503.           /* In the !full_search case we're are being called by
  4504.              ada_iterate_over_symbols, and we don't want to search
  4505.              superblocks.  */
  4506.           ada_add_block_symbols (&symbol_list_obstack, block, name,
  4507.                                  namespace, NULL, wild_match_p);
  4508.         }
  4509.       if (num_defns_collected (&symbol_list_obstack) > 0 || !full_search)
  4510.         goto done;
  4511.     }

  4512.   /* No non-global symbols found.  Check our cache to see if we have
  4513.      already performed this search before.  If we have, then return
  4514.      the same result.  */

  4515.   cacheIfUnique = 1;
  4516.   if (lookup_cached_symbol (name0, namespace, &sym, &block))
  4517.     {
  4518.       if (sym != NULL)
  4519.         add_defn_to_vec (&symbol_list_obstack, sym, block);
  4520.       goto done;
  4521.     }

  4522.   /* Search symbols from all global blocks.  */

  4523.   add_nonlocal_symbols (&symbol_list_obstack, name, namespace, 1,
  4524.                         wild_match_p);

  4525.   /* Now add symbols from all per-file blocks if we've gotten no hits
  4526.      (not strictly correct, but perhaps better than an error).  */

  4527.   if (num_defns_collected (&symbol_list_obstack) == 0)
  4528.     add_nonlocal_symbols (&symbol_list_obstack, name, namespace, 0,
  4529.                           wild_match_p);

  4530. done:
  4531.   ndefns = num_defns_collected (&symbol_list_obstack);
  4532.   *results = defns_collected (&symbol_list_obstack, 1);

  4533.   ndefns = remove_extra_symbols (*results, ndefns);

  4534.   if (ndefns == 0 && full_search)
  4535.     cache_symbol (name0, namespace, NULL, NULL);

  4536.   if (ndefns == 1 && full_search && cacheIfUnique)
  4537.     cache_symbol (name0, namespace, (*results)[0].sym, (*results)[0].block);

  4538.   ndefns = remove_irrelevant_renamings (*results, ndefns, block0);

  4539.   return ndefns;
  4540. }

  4541. /* Find symbols in DOMAIN matching NAME0, in BLOCK0 and enclosing scope and
  4542.    in global scopes, returning the number of matches, and setting *RESULTS
  4543.    to a vector of (SYM,BLOCK) tuples.
  4544.    See ada_lookup_symbol_list_worker for further details.  */

  4545. int
  4546. ada_lookup_symbol_list (const char *name0, const struct block *block0,
  4547.                         domain_enum domain, struct ada_symbol_info **results)
  4548. {
  4549.   return ada_lookup_symbol_list_worker (name0, block0, domain, results, 1);
  4550. }

  4551. /* Implementation of the la_iterate_over_symbols method.  */

  4552. static void
  4553. ada_iterate_over_symbols (const struct block *block,
  4554.                           const char *name, domain_enum domain,
  4555.                           symbol_found_callback_ftype *callback,
  4556.                           void *data)
  4557. {
  4558.   int ndefs, i;
  4559.   struct ada_symbol_info *results;

  4560.   ndefs = ada_lookup_symbol_list_worker (name, block, domain, &results, 0);
  4561.   for (i = 0; i < ndefs; ++i)
  4562.     {
  4563.       if (! (*callback) (results[i].sym, data))
  4564.         break;
  4565.     }
  4566. }

  4567. /* If NAME is the name of an entity, return a string that should
  4568.    be used to look that entity up in Ada units.  This string should
  4569.    be deallocated after use using xfree.

  4570.    NAME can have any form that the "break" or "print" commands might
  4571.    recognize.  In other words, it does not have to be the "natural"
  4572.    name, or the "encoded" name.  */

  4573. char *
  4574. ada_name_for_lookup (const char *name)
  4575. {
  4576.   char *canon;
  4577.   int nlen = strlen (name);

  4578.   if (name[0] == '<' && name[nlen - 1] == '>')
  4579.     {
  4580.       canon = xmalloc (nlen - 1);
  4581.       memcpy (canon, name + 1, nlen - 2);
  4582.       canon[nlen - 2] = '\0';
  4583.     }
  4584.   else
  4585.     canon = xstrdup (ada_encode (ada_fold_name (name)));
  4586.   return canon;
  4587. }

  4588. /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
  4589.    to 1, but choosing the first symbol found if there are multiple
  4590.    choices.

  4591.    The result is stored in *INFO, which must be non-NULL.
  4592.    If no match is found, INFO->SYM is set to NULL.  */

  4593. void
  4594. ada_lookup_encoded_symbol (const char *name, const struct block *block,
  4595.                            domain_enum namespace,
  4596.                            struct ada_symbol_info *info)
  4597. {
  4598.   struct ada_symbol_info *candidates;
  4599.   int n_candidates;

  4600.   gdb_assert (info != NULL);
  4601.   memset (info, 0, sizeof (struct ada_symbol_info));

  4602.   n_candidates = ada_lookup_symbol_list (name, block, namespace, &candidates);
  4603.   if (n_candidates == 0)
  4604.     return;

  4605.   *info = candidates[0];
  4606.   info->sym = fixup_symbol_section (info->sym, NULL);
  4607. }

  4608. /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
  4609.    scope and in global scopes, or NULL if none.  NAME is folded and
  4610.    encoded first.  Otherwise, the result is as for ada_lookup_symbol_list,
  4611.    choosing the first symbol if there are multiple choices.
  4612.    If IS_A_FIELD_OF_THIS is not NULL, it is set to zero.  */

  4613. struct symbol *
  4614. ada_lookup_symbol (const char *name, const struct block *block0,
  4615.                    domain_enum namespace, int *is_a_field_of_this)
  4616. {
  4617.   struct ada_symbol_info info;

  4618.   if (is_a_field_of_this != NULL)
  4619.     *is_a_field_of_this = 0;

  4620.   ada_lookup_encoded_symbol (ada_encode (ada_fold_name (name)),
  4621.                              block0, namespace, &info);
  4622.   return info.sym;
  4623. }

  4624. static struct symbol *
  4625. ada_lookup_symbol_nonlocal (const struct language_defn *langdef,
  4626.                             const char *name,
  4627.                             const struct block *block,
  4628.                             const domain_enum domain)
  4629. {
  4630.   return ada_lookup_symbol (name, block_static_block (block), domain, NULL);
  4631. }


  4632. /* True iff STR is a possible encoded suffix of a normal Ada name
  4633.    that is to be ignored for matching purposes.  Suffixes of parallel
  4634.    names (e.g., XVE) are not included here.  Currently, the possible suffixes
  4635.    are given by any of the regular expressions:

  4636.    [.$][0-9]+       [nested subprogram suffix, on platforms such as GNU/Linux]
  4637.    ___[0-9]+        [nested subprogram suffix, on platforms such as HP/UX]
  4638.    TKB              [subprogram suffix for task bodies]
  4639.    _E[0-9]+[bs]$    [protected object entry suffixes]
  4640.    (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$

  4641.    Also, any leading "__[0-9]+" sequence is skipped before the suffix
  4642.    match is performed.  This sequence is used to differentiate homonyms,
  4643.    is an optional part of a valid name suffix.  */

  4644. static int
  4645. is_name_suffix (const char *str)
  4646. {
  4647.   int k;
  4648.   const char *matching;
  4649.   const int len = strlen (str);

  4650.   /* Skip optional leading __[0-9]+.  */

  4651.   if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
  4652.     {
  4653.       str += 3;
  4654.       while (isdigit (str[0]))
  4655.         str += 1;
  4656.     }

  4657.   /* [.$][0-9]+ */

  4658.   if (str[0] == '.' || str[0] == '$')
  4659.     {
  4660.       matching = str + 1;
  4661.       while (isdigit (matching[0]))
  4662.         matching += 1;
  4663.       if (matching[0] == '\0')
  4664.         return 1;
  4665.     }

  4666.   /* ___[0-9]+ */

  4667.   if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
  4668.     {
  4669.       matching = str + 3;
  4670.       while (isdigit (matching[0]))
  4671.         matching += 1;
  4672.       if (matching[0] == '\0')
  4673.         return 1;
  4674.     }

  4675.   /* "TKB" suffixes are used for subprograms implementing task bodies.  */

  4676.   if (strcmp (str, "TKB") == 0)
  4677.     return 1;

  4678. #if 0
  4679.   /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
  4680.      with a N at the end.  Unfortunately, the compiler uses the same
  4681.      convention for other internal types it creates.  So treating
  4682.      all entity names that end with an "N" as a name suffix causes
  4683.      some regressions.  For instance, consider the case of an enumerated
  4684.      type.  To support the 'Image attribute, it creates an array whose
  4685.      name ends with N.
  4686.      Having a single character like this as a suffix carrying some
  4687.      information is a bit risky.  Perhaps we should change the encoding
  4688.      to be something like "_N" instead.  In the meantime, do not do
  4689.      the following check.  */
  4690.   /* Protected Object Subprograms */
  4691.   if (len == 1 && str [0] == 'N')
  4692.     return 1;
  4693. #endif

  4694.   /* _E[0-9]+[bs]$ */
  4695.   if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
  4696.     {
  4697.       matching = str + 3;
  4698.       while (isdigit (matching[0]))
  4699.         matching += 1;
  4700.       if ((matching[0] == 'b' || matching[0] == 's')
  4701.           && matching [1] == '\0')
  4702.         return 1;
  4703.     }

  4704.   /* ??? We should not modify STR directly, as we are doing below.  This
  4705.      is fine in this case, but may become problematic later if we find
  4706.      that this alternative did not work, and want to try matching
  4707.      another one from the begining of STR.  Since we modified it, we
  4708.      won't be able to find the begining of the string anymore!  */
  4709.   if (str[0] == 'X')
  4710.     {
  4711.       str += 1;
  4712.       while (str[0] != '_' && str[0] != '\0')
  4713.         {
  4714.           if (str[0] != 'n' && str[0] != 'b')
  4715.             return 0;
  4716.           str += 1;
  4717.         }
  4718.     }

  4719.   if (str[0] == '\000')
  4720.     return 1;

  4721.   if (str[0] == '_')
  4722.     {
  4723.       if (str[1] != '_' || str[2] == '\000')
  4724.         return 0;
  4725.       if (str[2] == '_')
  4726.         {
  4727.           if (strcmp (str + 3, "JM") == 0)
  4728.             return 1;
  4729.           /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
  4730.              the LJM suffix in favor of the JM one.  But we will
  4731.              still accept LJM as a valid suffix for a reasonable
  4732.              amount of time, just to allow ourselves to debug programs
  4733.              compiled using an older version of GNAT.  */
  4734.           if (strcmp (str + 3, "LJM") == 0)
  4735.             return 1;
  4736.           if (str[3] != 'X')
  4737.             return 0;
  4738.           if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
  4739.               || str[4] == 'U' || str[4] == 'P')
  4740.             return 1;
  4741.           if (str[4] == 'R' && str[5] != 'T')
  4742.             return 1;
  4743.           return 0;
  4744.         }
  4745.       if (!isdigit (str[2]))
  4746.         return 0;
  4747.       for (k = 3; str[k] != '\0'; k += 1)
  4748.         if (!isdigit (str[k]) && str[k] != '_')
  4749.           return 0;
  4750.       return 1;
  4751.     }
  4752.   if (str[0] == '$' && isdigit (str[1]))
  4753.     {
  4754.       for (k = 2; str[k] != '\0'; k += 1)
  4755.         if (!isdigit (str[k]) && str[k] != '_')
  4756.           return 0;
  4757.       return 1;
  4758.     }
  4759.   return 0;
  4760. }

  4761. /* Return non-zero if the string starting at NAME and ending before
  4762.    NAME_END contains no capital letters.  */

  4763. static int
  4764. is_valid_name_for_wild_match (const char *name0)
  4765. {
  4766.   const char *decoded_name = ada_decode (name0);
  4767.   int i;

  4768.   /* If the decoded name starts with an angle bracket, it means that
  4769.      NAME0 does not follow the GNAT encoding format.  It should then
  4770.      not be allowed as a possible wild match.  */
  4771.   if (decoded_name[0] == '<')
  4772.     return 0;

  4773.   for (i=0; decoded_name[i] != '\0'; i++)
  4774.     if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
  4775.       return 0;

  4776.   return 1;
  4777. }

  4778. /* Advance *NAMEP to next occurrence of TARGET0 in the string NAME0
  4779.    that could start a simple name.  Assumes that *NAMEP points into
  4780.    the string beginning at NAME0.  */

  4781. static int
  4782. advance_wild_match (const char **namep, const char *name0, int target0)
  4783. {
  4784.   const char *name = *namep;

  4785.   while (1)
  4786.     {
  4787.       int t0, t1;

  4788.       t0 = *name;
  4789.       if (t0 == '_')
  4790.         {
  4791.           t1 = name[1];
  4792.           if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
  4793.             {
  4794.               name += 1;
  4795.               if (name == name0 + 5 && strncmp (name0, "_ada", 4) == 0)
  4796.                 break;
  4797.               else
  4798.                 name += 1;
  4799.             }
  4800.           else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
  4801.                                  || name[2] == target0))
  4802.             {
  4803.               name += 2;
  4804.               break;
  4805.             }
  4806.           else
  4807.             return 0;
  4808.         }
  4809.       else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
  4810.         name += 1;
  4811.       else
  4812.         return 0;
  4813.     }

  4814.   *namep = name;
  4815.   return 1;
  4816. }

  4817. /* Return 0 iff NAME encodes a name of the form prefix.PATN.  Ignores any
  4818.    informational suffixes of NAME (i.e., for which is_name_suffix is
  4819.    true).  Assumes that PATN is a lower-cased Ada simple name.  */

  4820. static int
  4821. wild_match (const char *name, const char *patn)
  4822. {
  4823.   const char *p;
  4824.   const char *name0 = name;

  4825.   while (1)
  4826.     {
  4827.       const char *match = name;

  4828.       if (*name == *patn)
  4829.         {
  4830.           for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
  4831.             if (*p != *name)
  4832.               break;
  4833.           if (*p == '\0' && is_name_suffix (name))
  4834.             return match != name0 && !is_valid_name_for_wild_match (name0);

  4835.           if (name[-1] == '_')
  4836.             name -= 1;
  4837.         }
  4838.       if (!advance_wild_match (&name, name0, *patn))
  4839.         return 1;
  4840.     }
  4841. }

  4842. /* Returns 0 iff symbol name SYM_NAME matches SEARCH_NAME, apart from
  4843.    informational suffix.  */

  4844. static int
  4845. full_match (const char *sym_name, const char *search_name)
  4846. {
  4847.   return !match_name (sym_name, search_name, 0);
  4848. }


  4849. /* Add symbols from BLOCK matching identifier NAME in DOMAIN to
  4850.    vector *defn_symbols, updating the list of symbols in OBSTACKP
  4851.    (if necessary).  If WILD, treat as NAME with a wildcard prefix.
  4852.    OBJFILE is the section containing BLOCK.  */

  4853. static void
  4854. ada_add_block_symbols (struct obstack *obstackp,
  4855.                        const struct block *block, const char *name,
  4856.                        domain_enum domain, struct objfile *objfile,
  4857.                        int wild)
  4858. {
  4859.   struct block_iterator iter;
  4860.   int name_len = strlen (name);
  4861.   /* A matching argument symbol, if any.  */
  4862.   struct symbol *arg_sym;
  4863.   /* Set true when we find a matching non-argument symbol.  */
  4864.   int found_sym;
  4865.   struct symbol *sym;

  4866.   arg_sym = NULL;
  4867.   found_sym = 0;
  4868.   if (wild)
  4869.     {
  4870.       for (sym = block_iter_match_first (block, name, wild_match, &iter);
  4871.            sym != NULL; sym = block_iter_match_next (name, wild_match, &iter))
  4872.       {
  4873.         if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
  4874.                                    SYMBOL_DOMAIN (sym), domain)
  4875.             && wild_match (SYMBOL_LINKAGE_NAME (sym), name) == 0)
  4876.           {
  4877.             if (SYMBOL_CLASS (sym) == LOC_UNRESOLVED)
  4878.               continue;
  4879.             else if (SYMBOL_IS_ARGUMENT (sym))
  4880.               arg_sym = sym;
  4881.             else
  4882.               {
  4883.                 found_sym = 1;
  4884.                 add_defn_to_vec (obstackp,
  4885.                                  fixup_symbol_section (sym, objfile),
  4886.                                  block);
  4887.               }
  4888.           }
  4889.       }
  4890.     }
  4891.   else
  4892.     {
  4893.      for (sym = block_iter_match_first (block, name, full_match, &iter);
  4894.           sym != NULL; sym = block_iter_match_next (name, full_match, &iter))
  4895.       {
  4896.         if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
  4897.                                    SYMBOL_DOMAIN (sym), domain))
  4898.           {
  4899.             if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
  4900.               {
  4901.                 if (SYMBOL_IS_ARGUMENT (sym))
  4902.                   arg_sym = sym;
  4903.                 else
  4904.                   {
  4905.                     found_sym = 1;
  4906.                     add_defn_to_vec (obstackp,
  4907.                                      fixup_symbol_section (sym, objfile),
  4908.                                      block);
  4909.                   }
  4910.               }
  4911.           }
  4912.       }
  4913.     }

  4914.   if (!found_sym && arg_sym != NULL)
  4915.     {
  4916.       add_defn_to_vec (obstackp,
  4917.                        fixup_symbol_section (arg_sym, objfile),
  4918.                        block);
  4919.     }

  4920.   if (!wild)
  4921.     {
  4922.       arg_sym = NULL;
  4923.       found_sym = 0;

  4924.       ALL_BLOCK_SYMBOLS (block, iter, sym)
  4925.       {
  4926.         if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
  4927.                                    SYMBOL_DOMAIN (sym), domain))
  4928.           {
  4929.             int cmp;

  4930.             cmp = (int) '_' - (int) SYMBOL_LINKAGE_NAME (sym)[0];
  4931.             if (cmp == 0)
  4932.               {
  4933.                 cmp = strncmp ("_ada_", SYMBOL_LINKAGE_NAME (sym), 5);
  4934.                 if (cmp == 0)
  4935.                   cmp = strncmp (name, SYMBOL_LINKAGE_NAME (sym) + 5,
  4936.                                  name_len);
  4937.               }

  4938.             if (cmp == 0
  4939.                 && is_name_suffix (SYMBOL_LINKAGE_NAME (sym) + name_len + 5))
  4940.               {
  4941.                 if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
  4942.                   {
  4943.                     if (SYMBOL_IS_ARGUMENT (sym))
  4944.                       arg_sym = sym;
  4945.                     else
  4946.                       {
  4947.                         found_sym = 1;
  4948.                         add_defn_to_vec (obstackp,
  4949.                                          fixup_symbol_section (sym, objfile),
  4950.                                          block);
  4951.                       }
  4952.                   }
  4953.               }
  4954.           }
  4955.       }

  4956.       /* NOTE: This really shouldn't be needed for _ada_ symbols.
  4957.          They aren't parameters, right?  */
  4958.       if (!found_sym && arg_sym != NULL)
  4959.         {
  4960.           add_defn_to_vec (obstackp,
  4961.                            fixup_symbol_section (arg_sym, objfile),
  4962.                            block);
  4963.         }
  4964.     }
  4965. }


  4966.                                 /* Symbol Completion */

  4967. /* If SYM_NAME is a completion candidate for TEXT, return this symbol
  4968.    name in a form that's appropriate for the completion.  The result
  4969.    does not need to be deallocated, but is only good until the next call.

  4970.    TEXT_LEN is equal to the length of TEXT.
  4971.    Perform a wild match if WILD_MATCH_P is set.
  4972.    ENCODED_P should be set if TEXT represents the start of a symbol name
  4973.    in its encoded form.  */

  4974. static const char *
  4975. symbol_completion_match (const char *sym_name,
  4976.                          const char *text, int text_len,
  4977.                          int wild_match_p, int encoded_p)
  4978. {
  4979.   const int verbatim_match = (text[0] == '<');
  4980.   int match = 0;

  4981.   if (verbatim_match)
  4982.     {
  4983.       /* Strip the leading angle bracket.  */
  4984.       text = text + 1;
  4985.       text_len--;
  4986.     }

  4987.   /* First, test against the fully qualified name of the symbol.  */

  4988.   if (strncmp (sym_name, text, text_len) == 0)
  4989.     match = 1;

  4990.   if (match && !encoded_p)
  4991.     {
  4992.       /* One needed check before declaring a positive match is to verify
  4993.          that iff we are doing a verbatim match, the decoded version
  4994.          of the symbol name starts with '<'.  Otherwise, this symbol name
  4995.          is not a suitable completion.  */
  4996.       const char *sym_name_copy = sym_name;
  4997.       int has_angle_bracket;

  4998.       sym_name = ada_decode (sym_name);
  4999.       has_angle_bracket = (sym_name[0] == '<');
  5000.       match = (has_angle_bracket == verbatim_match);
  5001.       sym_name = sym_name_copy;
  5002.     }

  5003.   if (match && !verbatim_match)
  5004.     {
  5005.       /* When doing non-verbatim match, another check that needs to
  5006.          be done is to verify that the potentially matching symbol name
  5007.          does not include capital letters, because the ada-mode would
  5008.          not be able to understand these symbol names without the
  5009.          angle bracket notation.  */
  5010.       const char *tmp;

  5011.       for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
  5012.       if (*tmp != '\0')
  5013.         match = 0;
  5014.     }

  5015.   /* Second: Try wild matching...  */

  5016.   if (!match && wild_match_p)
  5017.     {
  5018.       /* Since we are doing wild matching, this means that TEXT
  5019.          may represent an unqualified symbol name.  We therefore must
  5020.          also compare TEXT against the unqualified name of the symbol.  */
  5021.       sym_name = ada_unqualified_name (ada_decode (sym_name));

  5022.       if (strncmp (sym_name, text, text_len) == 0)
  5023.         match = 1;
  5024.     }

  5025.   /* Finally: If we found a mach, prepare the result to return.  */

  5026.   if (!match)
  5027.     return NULL;

  5028.   if (verbatim_match)
  5029.     sym_name = add_angle_brackets (sym_name);

  5030.   if (!encoded_p)
  5031.     sym_name = ada_decode (sym_name);

  5032.   return sym_name;
  5033. }

  5034. /* A companion function to ada_make_symbol_completion_list().
  5035.    Check if SYM_NAME represents a symbol which name would be suitable
  5036.    to complete TEXT (TEXT_LEN is the length of TEXT), in which case
  5037.    it is appended at the end of the given string vector SV.

  5038.    ORIG_TEXT is the string original string from the user command
  5039.    that needs to be completed.  WORD is the entire command on which
  5040.    completion should be performed.  These two parameters are used to
  5041.    determine which part of the symbol name should be added to the
  5042.    completion vector.
  5043.    if WILD_MATCH_P is set, then wild matching is performed.
  5044.    ENCODED_P should be set if TEXT represents a symbol name in its
  5045.    encoded formed (in which case the completion should also be
  5046.    encoded).  */

  5047. static void
  5048. symbol_completion_add (VEC(char_ptr) **sv,
  5049.                        const char *sym_name,
  5050.                        const char *text, int text_len,
  5051.                        const char *orig_text, const char *word,
  5052.                        int wild_match_p, int encoded_p)
  5053. {
  5054.   const char *match = symbol_completion_match (sym_name, text, text_len,
  5055.                                                wild_match_p, encoded_p);
  5056.   char *completion;

  5057.   if (match == NULL)
  5058.     return;

  5059.   /* We found a match, so add the appropriate completion to the given
  5060.      string vector.  */

  5061.   if (word == orig_text)
  5062.     {
  5063.       completion = xmalloc (strlen (match) + 5);
  5064.       strcpy (completion, match);
  5065.     }
  5066.   else if (word > orig_text)
  5067.     {
  5068.       /* Return some portion of sym_name.  */
  5069.       completion = xmalloc (strlen (match) + 5);
  5070.       strcpy (completion, match + (word - orig_text));
  5071.     }
  5072.   else
  5073.     {
  5074.       /* Return some of ORIG_TEXT plus sym_name.  */
  5075.       completion = xmalloc (strlen (match) + (orig_text - word) + 5);
  5076.       strncpy (completion, word, orig_text - word);
  5077.       completion[orig_text - word] = '\0';
  5078.       strcat (completion, match);
  5079.     }

  5080.   VEC_safe_push (char_ptr, *sv, completion);
  5081. }

  5082. /* An object of this type is passed as the user_data argument to the
  5083.    expand_symtabs_matching method.  */
  5084. struct add_partial_datum
  5085. {
  5086.   VEC(char_ptr) **completions;
  5087.   const char *text;
  5088.   int text_len;
  5089.   const char *text0;
  5090.   const char *word;
  5091.   int wild_match;
  5092.   int encoded;
  5093. };

  5094. /* A callback for expand_symtabs_matching.  */

  5095. static int
  5096. ada_complete_symbol_matcher (const char *name, void *user_data)
  5097. {
  5098.   struct add_partial_datum *data = user_data;

  5099.   return symbol_completion_match (name, data->text, data->text_len,
  5100.                                   data->wild_match, data->encoded) != NULL;
  5101. }

  5102. /* Return a list of possible symbol names completing TEXT0.  WORD is
  5103.    the entire command on which completion is made.  */

  5104. static VEC (char_ptr) *
  5105. ada_make_symbol_completion_list (const char *text0, const char *word,
  5106.                                  enum type_code code)
  5107. {
  5108.   char *text;
  5109.   int text_len;
  5110.   int wild_match_p;
  5111.   int encoded_p;
  5112.   VEC(char_ptr) *completions = VEC_alloc (char_ptr, 128);
  5113.   struct symbol *sym;
  5114.   struct compunit_symtab *s;
  5115.   struct minimal_symbol *msymbol;
  5116.   struct objfile *objfile;
  5117.   const struct block *b, *surrounding_static_block = 0;
  5118.   int i;
  5119.   struct block_iterator iter;
  5120.   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);

  5121.   gdb_assert (code == TYPE_CODE_UNDEF);

  5122.   if (text0[0] == '<')
  5123.     {
  5124.       text = xstrdup (text0);
  5125.       make_cleanup (xfree, text);
  5126.       text_len = strlen (text);
  5127.       wild_match_p = 0;
  5128.       encoded_p = 1;
  5129.     }
  5130.   else
  5131.     {
  5132.       text = xstrdup (ada_encode (text0));
  5133.       make_cleanup (xfree, text);
  5134.       text_len = strlen (text);
  5135.       for (i = 0; i < text_len; i++)
  5136.         text[i] = tolower (text[i]);

  5137.       encoded_p = (strstr (text0, "__") != NULL);
  5138.       /* If the name contains a ".", then the user is entering a fully
  5139.          qualified entity name, and the match must not be done in wild
  5140.          mode.  Similarly, if the user wants to complete what looks like
  5141.          an encoded name, the match must not be done in wild mode.  */
  5142.       wild_match_p = (strchr (text0, '.') == NULL && !encoded_p);
  5143.     }

  5144.   /* First, look at the partial symtab symbols.  */
  5145.   {
  5146.     struct add_partial_datum data;

  5147.     data.completions = &completions;
  5148.     data.text = text;
  5149.     data.text_len = text_len;
  5150.     data.text0 = text0;
  5151.     data.word = word;
  5152.     data.wild_match = wild_match_p;
  5153.     data.encoded = encoded_p;
  5154.     expand_symtabs_matching (NULL, ada_complete_symbol_matcher, ALL_DOMAIN,
  5155.                              &data);
  5156.   }

  5157.   /* At this point scan through the misc symbol vectors and add each
  5158.      symbol you find to the list.  Eventually we want to ignore
  5159.      anything that isn't a text symbol (everything else will be
  5160.      handled by the psymtab code above).  */

  5161.   ALL_MSYMBOLS (objfile, msymbol)
  5162.   {
  5163.     QUIT;
  5164.     symbol_completion_add (&completions, MSYMBOL_LINKAGE_NAME (msymbol),
  5165.                            text, text_len, text0, word, wild_match_p,
  5166.                            encoded_p);
  5167.   }

  5168.   /* Search upwards from currently selected frame (so that we can
  5169.      complete on local vars.  */

  5170.   for (b = get_selected_block (0); b != NULL; b = BLOCK_SUPERBLOCK (b))
  5171.     {
  5172.       if (!BLOCK_SUPERBLOCK (b))
  5173.         surrounding_static_block = b;   /* For elmin of dups */

  5174.       ALL_BLOCK_SYMBOLS (b, iter, sym)
  5175.       {
  5176.         symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (sym),
  5177.                                text, text_len, text0, word,
  5178.                                wild_match_p, encoded_p);
  5179.       }
  5180.     }

  5181.   /* Go through the symtabs and check the externs and statics for
  5182.      symbols which match.  */

  5183.   ALL_COMPUNITS (objfile, s)
  5184.   {
  5185.     QUIT;
  5186.     b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (s), GLOBAL_BLOCK);
  5187.     ALL_BLOCK_SYMBOLS (b, iter, sym)
  5188.     {
  5189.       symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (sym),
  5190.                              text, text_len, text0, word,
  5191.                              wild_match_p, encoded_p);
  5192.     }
  5193.   }

  5194.   ALL_COMPUNITS (objfile, s)
  5195.   {
  5196.     QUIT;
  5197.     b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (s), STATIC_BLOCK);
  5198.     /* Don't do this block twice.  */
  5199.     if (b == surrounding_static_block)
  5200.       continue;
  5201.     ALL_BLOCK_SYMBOLS (b, iter, sym)
  5202.     {
  5203.       symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (sym),
  5204.                              text, text_len, text0, word,
  5205.                              wild_match_p, encoded_p);
  5206.     }
  5207.   }

  5208.   do_cleanups (old_chain);
  5209.   return completions;
  5210. }

  5211.                                 /* Field Access */

  5212. /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
  5213.    for tagged types.  */

  5214. static int
  5215. ada_is_dispatch_table_ptr_type (struct type *type)
  5216. {
  5217.   const char *name;

  5218.   if (TYPE_CODE (type) != TYPE_CODE_PTR)
  5219.     return 0;

  5220.   name = TYPE_NAME (TYPE_TARGET_TYPE (type));
  5221.   if (name == NULL)
  5222.     return 0;

  5223.   return (strcmp (name, "ada__tags__dispatch_table") == 0);
  5224. }

  5225. /* Return non-zero if TYPE is an interface tag.  */

  5226. static int
  5227. ada_is_interface_tag (struct type *type)
  5228. {
  5229.   const char *name = TYPE_NAME (type);

  5230.   if (name == NULL)
  5231.     return 0;

  5232.   return (strcmp (name, "ada__tags__interface_tag") == 0);
  5233. }

  5234. /* True if field number FIELD_NUM in struct or union type TYPE is supposed
  5235.    to be invisible to users.  */

  5236. int
  5237. ada_is_ignored_field (struct type *type, int field_num)
  5238. {
  5239.   if (field_num < 0 || field_num > TYPE_NFIELDS (type))
  5240.     return 1;

  5241.   /* Check the name of that field.  */
  5242.   {
  5243.     const char *name = TYPE_FIELD_NAME (type, field_num);

  5244.     /* Anonymous field names should not be printed.
  5245.        brobecker/2007-02-20: I don't think this can actually happen
  5246.        but we don't want to print the value of annonymous fields anyway.  */
  5247.     if (name == NULL)
  5248.       return 1;

  5249.     /* Normally, fields whose name start with an underscore ("_")
  5250.        are fields that have been internally generated by the compiler,
  5251.        and thus should not be printed.  The "_parent" field is special,
  5252.        however: This is a field internally generated by the compiler
  5253.        for tagged types, and it contains the components inherited from
  5254.        the parent type.  This field should not be printed as is, but
  5255.        should not be ignored either.  */
  5256.     if (name[0] == '_' && strncmp (name, "_parent", 7) != 0)
  5257.       return 1;
  5258.   }

  5259.   /* If this is the dispatch table of a tagged type or an interface tag,
  5260.      then ignore.  */
  5261.   if (ada_is_tagged_type (type, 1)
  5262.       && (ada_is_dispatch_table_ptr_type (TYPE_FIELD_TYPE (type, field_num))
  5263.           || ada_is_interface_tag (TYPE_FIELD_TYPE (type, field_num))))
  5264.     return 1;

  5265.   /* Not a special field, so it should not be ignored.  */
  5266.   return 0;
  5267. }

  5268. /* True iff TYPE has a tag field.  If REFOK, then TYPE may also be a
  5269.    pointer or reference type whose ultimate target has a tag field.  */

  5270. int
  5271. ada_is_tagged_type (struct type *type, int refok)
  5272. {
  5273.   return (ada_lookup_struct_elt_type (type, "_tag", refok, 1, NULL) != NULL);
  5274. }

  5275. /* True iff TYPE represents the type of X'Tag */

  5276. int
  5277. ada_is_tag_type (struct type *type)
  5278. {
  5279.   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_PTR)
  5280.     return 0;
  5281.   else
  5282.     {
  5283.       const char *name = ada_type_name (TYPE_TARGET_TYPE (type));

  5284.       return (name != NULL
  5285.               && strcmp (name, "ada__tags__dispatch_table") == 0);
  5286.     }
  5287. }

  5288. /* The type of the tag on VAL.  */

  5289. struct type *
  5290. ada_tag_type (struct value *val)
  5291. {
  5292.   return ada_lookup_struct_elt_type (value_type (val), "_tag", 1, 0, NULL);
  5293. }

  5294. /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
  5295.    retired at Ada 05).  */

  5296. static int
  5297. is_ada95_tag (struct value *tag)
  5298. {
  5299.   return ada_value_struct_elt (tag, "tsd", 1) != NULL;
  5300. }

  5301. /* The value of the tag on VAL.  */

  5302. struct value *
  5303. ada_value_tag (struct value *val)
  5304. {
  5305.   return ada_value_struct_elt (val, "_tag", 0);
  5306. }

  5307. /* The value of the tag on the object of type TYPE whose contents are
  5308.    saved at VALADDR, if it is non-null, or is at memory address
  5309.    ADDRESS.  */

  5310. static struct value *
  5311. value_tag_from_contents_and_address (struct type *type,
  5312.                                      const gdb_byte *valaddr,
  5313.                                      CORE_ADDR address)
  5314. {
  5315.   int tag_byte_offset;
  5316.   struct type *tag_type;

  5317.   if (find_struct_field ("_tag", type, 0, &tag_type, &tag_byte_offset,
  5318.                          NULL, NULL, NULL))
  5319.     {
  5320.       const gdb_byte *valaddr1 = ((valaddr == NULL)
  5321.                                   ? NULL
  5322.                                   : valaddr + tag_byte_offset);
  5323.       CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;

  5324.       return value_from_contents_and_address (tag_type, valaddr1, address1);
  5325.     }
  5326.   return NULL;
  5327. }

  5328. static struct type *
  5329. type_from_tag (struct value *tag)
  5330. {
  5331.   const char *type_name = ada_tag_name (tag);

  5332.   if (type_name != NULL)
  5333.     return ada_find_any_type (ada_encode (type_name));
  5334.   return NULL;
  5335. }

  5336. /* Given a value OBJ of a tagged type, return a value of this
  5337.    type at the base address of the object.  The base address, as
  5338.    defined in Ada.Tags, it is the address of the primary tag of
  5339.    the object, and therefore where the field values of its full
  5340.    view can be fetched.  */

  5341. struct value *
  5342. ada_tag_value_at_base_address (struct value *obj)
  5343. {
  5344.   volatile struct gdb_exception e;
  5345.   struct value *val;
  5346.   LONGEST offset_to_top = 0;
  5347.   struct type *ptr_type, *obj_type;
  5348.   struct value *tag;
  5349.   CORE_ADDR base_address;

  5350.   obj_type = value_type (obj);

  5351.   /* It is the responsability of the caller to deref pointers.  */

  5352.   if (TYPE_CODE (obj_type) == TYPE_CODE_PTR
  5353.       || TYPE_CODE (obj_type) == TYPE_CODE_REF)
  5354.     return obj;

  5355.   tag = ada_value_tag (obj);
  5356.   if (!tag)
  5357.     return obj;

  5358.   /* Base addresses only appeared with Ada 05 and multiple inheritance.  */

  5359.   if (is_ada95_tag (tag))
  5360.     return obj;

  5361.   ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;
  5362.   ptr_type = lookup_pointer_type (ptr_type);
  5363.   val = value_cast (ptr_type, tag);
  5364.   if (!val)
  5365.     return obj;

  5366.   /* It is perfectly possible that an exception be raised while
  5367.      trying to determine the base address, just like for the tag;
  5368.      see ada_tag_name for more details.  We do not print the error
  5369.      message for the same reason.  */

  5370.   TRY_CATCH (e, RETURN_MASK_ERROR)
  5371.     {
  5372.       offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
  5373.     }

  5374.   if (e.reason < 0)
  5375.     return obj;

  5376.   /* If offset is null, nothing to do.  */

  5377.   if (offset_to_top == 0)
  5378.     return obj;

  5379.   /* -1 is a special case in Ada.Tags; however, what should be done
  5380.      is not quite clear from the documentation.  So do nothing for
  5381.      now.  */

  5382.   if (offset_to_top == -1)
  5383.     return obj;

  5384.   base_address = value_address (obj) - offset_to_top;
  5385.   tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);

  5386.   /* Make sure that we have a proper tag at the new address.
  5387.      Otherwise, offset_to_top is bogus (which can happen when
  5388.      the object is not initialized yet).  */

  5389.   if (!tag)
  5390.     return obj;

  5391.   obj_type = type_from_tag (tag);

  5392.   if (!obj_type)
  5393.     return obj;

  5394.   return value_from_contents_and_address (obj_type, NULL, base_address);
  5395. }

  5396. /* Return the "ada__tags__type_specific_data" type.  */

  5397. static struct type *
  5398. ada_get_tsd_type (struct inferior *inf)
  5399. {
  5400.   struct ada_inferior_data *data = get_ada_inferior_data (inf);

  5401.   if (data->tsd_type == 0)
  5402.     data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
  5403.   return data->tsd_type;
  5404. }

  5405. /* Return the TSD (type-specific data) associated to the given TAG.
  5406.    TAG is assumed to be the tag of a tagged-type entity.

  5407.    May return NULL if we are unable to get the TSD.  */

  5408. static struct value *
  5409. ada_get_tsd_from_tag (struct value *tag)
  5410. {
  5411.   struct value *val;
  5412.   struct type *type;

  5413.   /* First option: The TSD is simply stored as a field of our TAG.
  5414.      Only older versions of GNAT would use this format, but we have
  5415.      to test it first, because there are no visible markers for
  5416.      the current approach except the absence of that field.  */

  5417.   val = ada_value_struct_elt (tag, "tsd", 1);
  5418.   if (val)
  5419.     return val;

  5420.   /* Try the second representation for the dispatch table (in which
  5421.      there is no explicit 'tsd' field in the referent of the tag pointer,
  5422.      and instead the tsd pointer is stored just before the dispatch
  5423.      table.  */

  5424.   type = ada_get_tsd_type (current_inferior());
  5425.   if (type == NULL)
  5426.     return NULL;
  5427.   type = lookup_pointer_type (lookup_pointer_type (type));
  5428.   val = value_cast (type, tag);
  5429.   if (val == NULL)
  5430.     return NULL;
  5431.   return value_ind (value_ptradd (val, -1));
  5432. }

  5433. /* Given the TSD of a tag (type-specific data), return a string
  5434.    containing the name of the associated type.

  5435.    The returned value is good until the next call.  May return NULL
  5436.    if we are unable to determine the tag name.  */

  5437. static char *
  5438. ada_tag_name_from_tsd (struct value *tsd)
  5439. {
  5440.   static char name[1024];
  5441.   char *p;
  5442.   struct value *val;

  5443.   val = ada_value_struct_elt (tsd, "expanded_name", 1);
  5444.   if (val == NULL)
  5445.     return NULL;
  5446.   read_memory_string (value_as_address (val), name, sizeof (name) - 1);
  5447.   for (p = name; *p != '\0'; p += 1)
  5448.     if (isalpha (*p))
  5449.       *p = tolower (*p);
  5450.   return name;
  5451. }

  5452. /* The type name of the dynamic type denoted by the 'tag value TAG, as
  5453.    a C string.

  5454.    Return NULL if the TAG is not an Ada tag, or if we were unable to
  5455.    determine the name of that tag.  The result is good until the next
  5456.    call.  */

  5457. const char *
  5458. ada_tag_name (struct value *tag)
  5459. {
  5460.   volatile struct gdb_exception e;
  5461.   char *name = NULL;

  5462.   if (!ada_is_tag_type (value_type (tag)))
  5463.     return NULL;

  5464.   /* It is perfectly possible that an exception be raised while trying
  5465.      to determine the TAG's name, even under normal circumstances:
  5466.      The associated variable may be uninitialized or corrupted, for
  5467.      instance. We do not let any exception propagate past this point.
  5468.      instead we return NULL.

  5469.      We also do not print the error message either (which often is very
  5470.      low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
  5471.      the caller print a more meaningful message if necessary.  */
  5472.   TRY_CATCH (e, RETURN_MASK_ERROR)
  5473.     {
  5474.       struct value *tsd = ada_get_tsd_from_tag (tag);

  5475.       if (tsd != NULL)
  5476.         name = ada_tag_name_from_tsd (tsd);
  5477.     }

  5478.   return name;
  5479. }

  5480. /* The parent type of TYPE, or NULL if none.  */

  5481. struct type *
  5482. ada_parent_type (struct type *type)
  5483. {
  5484.   int i;

  5485.   type = ada_check_typedef (type);

  5486.   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
  5487.     return NULL;

  5488.   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
  5489.     if (ada_is_parent_field (type, i))
  5490.       {
  5491.         struct type *parent_type = TYPE_FIELD_TYPE (type, i);

  5492.         /* If the _parent field is a pointer, then dereference it.  */
  5493.         if (TYPE_CODE (parent_type) == TYPE_CODE_PTR)
  5494.           parent_type = TYPE_TARGET_TYPE (parent_type);
  5495.         /* If there is a parallel XVS type, get the actual base type.  */
  5496.         parent_type = ada_get_base_type (parent_type);

  5497.         return ada_check_typedef (parent_type);
  5498.       }

  5499.   return NULL;
  5500. }

  5501. /* True iff field number FIELD_NUM of structure type TYPE contains the
  5502.    parent-type (inherited) fields of a derived type.  Assumes TYPE is
  5503.    a structure type with at least FIELD_NUM+1 fields.  */

  5504. int
  5505. ada_is_parent_field (struct type *type, int field_num)
  5506. {
  5507.   const char *name = TYPE_FIELD_NAME (ada_check_typedef (type), field_num);

  5508.   return (name != NULL
  5509.           && (strncmp (name, "PARENT", 6) == 0
  5510.               || strncmp (name, "_parent", 7) == 0));
  5511. }

  5512. /* True iff field number FIELD_NUM of structure type TYPE is a
  5513.    transparent wrapper field (which should be silently traversed when doing
  5514.    field selection and flattened when printing).  Assumes TYPE is a
  5515.    structure type with at least FIELD_NUM+1 fields.  Such fields are always
  5516.    structures.  */

  5517. int
  5518. ada_is_wrapper_field (struct type *type, int field_num)
  5519. {
  5520.   const char *name = TYPE_FIELD_NAME (type, field_num);

  5521.   return (name != NULL
  5522.           && (strncmp (name, "PARENT", 6) == 0
  5523.               || strcmp (name, "REP") == 0
  5524.               || strncmp (name, "_parent", 7) == 0
  5525.               || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
  5526. }

  5527. /* True iff field number FIELD_NUM of structure or union type TYPE
  5528.    is a variant wrapper.  Assumes TYPE is a structure type with at least
  5529.    FIELD_NUM+1 fields.  */

  5530. int
  5531. ada_is_variant_part (struct type *type, int field_num)
  5532. {
  5533.   struct type *field_type = TYPE_FIELD_TYPE (type, field_num);

  5534.   return (TYPE_CODE (field_type) == TYPE_CODE_UNION
  5535.           || (is_dynamic_field (type, field_num)
  5536.               && (TYPE_CODE (TYPE_TARGET_TYPE (field_type))
  5537.                   == TYPE_CODE_UNION)));
  5538. }

  5539. /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
  5540.    whose discriminants are contained in the record type OUTER_TYPE,
  5541.    returns the type of the controlling discriminant for the variant.
  5542.    May return NULL if the type could not be found.  */

  5543. struct type *
  5544. ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
  5545. {
  5546.   char *name = ada_variant_discrim_name (var_type);

  5547.   return ada_lookup_struct_elt_type (outer_type, name, 1, 1, NULL);
  5548. }

  5549. /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
  5550.    valid field number within it, returns 1 iff field FIELD_NUM of TYPE
  5551.    represents a 'when others' clause; otherwise 0.  */

  5552. int
  5553. ada_is_others_clause (struct type *type, int field_num)
  5554. {
  5555.   const char *name = TYPE_FIELD_NAME (type, field_num);

  5556.   return (name != NULL && name[0] == 'O');
  5557. }

  5558. /* Assuming that TYPE0 is the type of the variant part of a record,
  5559.    returns the name of the discriminant controlling the variant.
  5560.    The value is valid until the next call to ada_variant_discrim_name.  */

  5561. char *
  5562. ada_variant_discrim_name (struct type *type0)
  5563. {
  5564.   static char *result = NULL;
  5565.   static size_t result_len = 0;
  5566.   struct type *type;
  5567.   const char *name;
  5568.   const char *discrim_end;
  5569.   const char *discrim_start;

  5570.   if (TYPE_CODE (type0) == TYPE_CODE_PTR)
  5571.     type = TYPE_TARGET_TYPE (type0);
  5572.   else
  5573.     type = type0;

  5574.   name = ada_type_name (type);

  5575.   if (name == NULL || name[0] == '\000')
  5576.     return "";

  5577.   for (discrim_end = name + strlen (name) - 6; discrim_end != name;
  5578.        discrim_end -= 1)
  5579.     {
  5580.       if (strncmp (discrim_end, "___XVN", 6) == 0)
  5581.         break;
  5582.     }
  5583.   if (discrim_end == name)
  5584.     return "";

  5585.   for (discrim_start = discrim_end; discrim_start != name + 3;
  5586.        discrim_start -= 1)
  5587.     {
  5588.       if (discrim_start == name + 1)
  5589.         return "";
  5590.       if ((discrim_start > name + 3
  5591.            && strncmp (discrim_start - 3, "___", 3) == 0)
  5592.           || discrim_start[-1] == '.')
  5593.         break;
  5594.     }

  5595.   GROW_VECT (result, result_len, discrim_end - discrim_start + 1);
  5596.   strncpy (result, discrim_start, discrim_end - discrim_start);
  5597.   result[discrim_end - discrim_start] = '\0';
  5598.   return result;
  5599. }

  5600. /* Scan STR for a subtype-encoded number, beginning at position K.
  5601.    Put the position of the character just past the number scanned in
  5602.    *NEW_K, if NEW_K!=NULL.  Put the scanned number in *R, if R!=NULL.
  5603.    Return 1 if there was a valid number at the given position, and 0
  5604.    otherwise.  A "subtype-encoded" number consists of the absolute value
  5605.    in decimal, followed by the letter 'm' to indicate a negative number.
  5606.    Assumes 0m does not occur.  */

  5607. int
  5608. ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
  5609. {
  5610.   ULONGEST RU;

  5611.   if (!isdigit (str[k]))
  5612.     return 0;

  5613.   /* Do it the hard way so as not to make any assumption about
  5614.      the relationship of unsigned long (%lu scan format code) and
  5615.      LONGEST.  */
  5616.   RU = 0;
  5617.   while (isdigit (str[k]))
  5618.     {
  5619.       RU = RU * 10 + (str[k] - '0');
  5620.       k += 1;
  5621.     }

  5622.   if (str[k] == 'm')
  5623.     {
  5624.       if (R != NULL)
  5625.         *R = (-(LONGEST) (RU - 1)) - 1;
  5626.       k += 1;
  5627.     }
  5628.   else if (R != NULL)
  5629.     *R = (LONGEST) RU;

  5630.   /* NOTE on the above: Technically, C does not say what the results of
  5631.      - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
  5632.      number representable as a LONGEST (although either would probably work
  5633.      in most implementations).  When RU>0, the locution in the then branch
  5634.      above is always equivalent to the negative of RU.  */

  5635.   if (new_k != NULL)
  5636.     *new_k = k;
  5637.   return 1;
  5638. }

  5639. /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
  5640.    and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
  5641.    in the range encoded by field FIELD_NUM of TYPE; otherwise 0.  */

  5642. int
  5643. ada_in_variant (LONGEST val, struct type *type, int field_num)
  5644. {
  5645.   const char *name = TYPE_FIELD_NAME (type, field_num);
  5646.   int p;

  5647.   p = 0;
  5648.   while (1)
  5649.     {
  5650.       switch (name[p])
  5651.         {
  5652.         case '\0':
  5653.           return 0;
  5654.         case 'S':
  5655.           {
  5656.             LONGEST W;

  5657.             if (!ada_scan_number (name, p + 1, &W, &p))
  5658.               return 0;
  5659.             if (val == W)
  5660.               return 1;
  5661.             break;
  5662.           }
  5663.         case 'R':
  5664.           {
  5665.             LONGEST L, U;

  5666.             if (!ada_scan_number (name, p + 1, &L, &p)
  5667.                 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
  5668.               return 0;
  5669.             if (val >= L && val <= U)
  5670.               return 1;
  5671.             break;
  5672.           }
  5673.         case 'O':
  5674.           return 1;
  5675.         default:
  5676.           return 0;
  5677.         }
  5678.     }
  5679. }

  5680. /* FIXME: Lots of redundancy below.  Try to consolidate.  */

  5681. /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
  5682.    ARG_TYPE, extract and return the value of one of its (non-static)
  5683.    fields.  FIELDNO says which field.   Differs from value_primitive_field
  5684.    only in that it can handle packed values of arbitrary type.  */

  5685. static struct value *
  5686. ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
  5687.                            struct type *arg_type)
  5688. {
  5689.   struct type *type;

  5690.   arg_type = ada_check_typedef (arg_type);
  5691.   type = TYPE_FIELD_TYPE (arg_type, fieldno);

  5692.   /* Handle packed fields.  */

  5693.   if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0)
  5694.     {
  5695.       int bit_pos = TYPE_FIELD_BITPOS (arg_type, fieldno);
  5696.       int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);

  5697.       return ada_value_primitive_packed_val (arg1, value_contents (arg1),
  5698.                                              offset + bit_pos / 8,
  5699.                                              bit_pos % 8, bit_size, type);
  5700.     }
  5701.   else
  5702.     return value_primitive_field (arg1, offset, fieldno, arg_type);
  5703. }

  5704. /* Find field with name NAME in object of type TYPE.  If found,
  5705.    set the following for each argument that is non-null:
  5706.     - *FIELD_TYPE_P to the field's type;
  5707.     - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
  5708.       an object of that type;
  5709.     - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
  5710.     - *BIT_SIZE_P to its size in bits if the field is packed, and
  5711.       0 otherwise;
  5712.    If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
  5713.    fields up to but not including the desired field, or by the total
  5714.    number of fields if not found.   A NULL value of NAME never
  5715.    matches; the function just counts visible fields in this case.

  5716.    Returns 1 if found, 0 otherwise.  */

  5717. static int
  5718. find_struct_field (const char *name, struct type *type, int offset,
  5719.                    struct type **field_type_p,
  5720.                    int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
  5721.                    int *index_p)
  5722. {
  5723.   int i;

  5724.   type = ada_check_typedef (type);

  5725.   if (field_type_p != NULL)
  5726.     *field_type_p = NULL;
  5727.   if (byte_offset_p != NULL)
  5728.     *byte_offset_p = 0;
  5729.   if (bit_offset_p != NULL)
  5730.     *bit_offset_p = 0;
  5731.   if (bit_size_p != NULL)
  5732.     *bit_size_p = 0;

  5733.   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
  5734.     {
  5735.       int bit_pos = TYPE_FIELD_BITPOS (type, i);
  5736.       int fld_offset = offset + bit_pos / 8;
  5737.       const char *t_field_name = TYPE_FIELD_NAME (type, i);

  5738.       if (t_field_name == NULL)
  5739.         continue;

  5740.       else if (name != NULL && field_name_match (t_field_name, name))
  5741.         {
  5742.           int bit_size = TYPE_FIELD_BITSIZE (type, i);

  5743.           if (field_type_p != NULL)
  5744.             *field_type_p = TYPE_FIELD_TYPE (type, i);
  5745.           if (byte_offset_p != NULL)
  5746.             *byte_offset_p = fld_offset;
  5747.           if (bit_offset_p != NULL)
  5748.             *bit_offset_p = bit_pos % 8;
  5749.           if (bit_size_p != NULL)
  5750.             *bit_size_p = bit_size;
  5751.           return 1;
  5752.         }
  5753.       else if (ada_is_wrapper_field (type, i))
  5754.         {
  5755.           if (find_struct_field (name, TYPE_FIELD_TYPE (type, i), fld_offset,
  5756.                                  field_type_p, byte_offset_p, bit_offset_p,
  5757.                                  bit_size_p, index_p))
  5758.             return 1;
  5759.         }
  5760.       else if (ada_is_variant_part (type, i))
  5761.         {
  5762.           /* PNH: Wait.  Do we ever execute this section, or is ARG always of
  5763.              fixed type?? */
  5764.           int j;
  5765.           struct type *field_type
  5766.             = ada_check_typedef (TYPE_FIELD_TYPE (type, i));

  5767.           for (j = 0; j < TYPE_NFIELDS (field_type); j += 1)
  5768.             {
  5769.               if (find_struct_field (name, TYPE_FIELD_TYPE (field_type, j),
  5770.                                      fld_offset
  5771.                                      + TYPE_FIELD_BITPOS (field_type, j) / 8,
  5772.                                      field_type_p, byte_offset_p,
  5773.                                      bit_offset_p, bit_size_p, index_p))
  5774.                 return 1;
  5775.             }
  5776.         }
  5777.       else if (index_p != NULL)
  5778.         *index_p += 1;
  5779.     }
  5780.   return 0;
  5781. }

  5782. /* Number of user-visible fields in record type TYPE.  */

  5783. static int
  5784. num_visible_fields (struct type *type)
  5785. {
  5786.   int n;

  5787.   n = 0;
  5788.   find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
  5789.   return n;
  5790. }

  5791. /* Look for a field NAME in ARG.  Adjust the address of ARG by OFFSET bytes,
  5792.    and search in it assuming it has (class) type TYPE.
  5793.    If found, return value, else return NULL.

  5794.    Searches recursively through wrapper fields (e.g., '_parent').  */

  5795. static struct value *
  5796. ada_search_struct_field (char *name, struct value *arg, int offset,
  5797.                          struct type *type)
  5798. {
  5799.   int i;

  5800.   type = ada_check_typedef (type);
  5801.   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
  5802.     {
  5803.       const char *t_field_name = TYPE_FIELD_NAME (type, i);

  5804.       if (t_field_name == NULL)
  5805.         continue;

  5806.       else if (field_name_match (t_field_name, name))
  5807.         return ada_value_primitive_field (arg, offset, i, type);

  5808.       else if (ada_is_wrapper_field (type, i))
  5809.         {
  5810.           struct value *v =     /* Do not let indent join lines here.  */
  5811.             ada_search_struct_field (name, arg,
  5812.                                      offset + TYPE_FIELD_BITPOS (type, i) / 8,
  5813.                                      TYPE_FIELD_TYPE (type, i));

  5814.           if (v != NULL)
  5815.             return v;
  5816.         }

  5817.       else if (ada_is_variant_part (type, i))
  5818.         {
  5819.           /* PNH: Do we ever get here?  See find_struct_field.  */
  5820.           int j;
  5821.           struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type,
  5822.                                                                         i));
  5823.           int var_offset = offset + TYPE_FIELD_BITPOS (type, i) / 8;

  5824.           for (j = 0; j < TYPE_NFIELDS (field_type); j += 1)
  5825.             {
  5826.               struct value *v = ada_search_struct_field /* Force line
  5827.                                                            break.  */
  5828.                 (name, arg,
  5829.                  var_offset + TYPE_FIELD_BITPOS (field_type, j) / 8,
  5830.                  TYPE_FIELD_TYPE (field_type, j));

  5831.               if (v != NULL)
  5832.                 return v;
  5833.             }
  5834.         }
  5835.     }
  5836.   return NULL;
  5837. }

  5838. static struct value *ada_index_struct_field_1 (int *, struct value *,
  5839.                                                int, struct type *);


  5840. /* Return field #INDEX in ARG, where the index is that returned by
  5841. * find_struct_field through its INDEX_P argument.  Adjust the address
  5842. * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
  5843. * If found, return value, else return NULL.  */

  5844. static struct value *
  5845. ada_index_struct_field (int index, struct value *arg, int offset,
  5846.                         struct type *type)
  5847. {
  5848.   return ada_index_struct_field_1 (&index, arg, offset, type);
  5849. }


  5850. /* Auxiliary function for ada_index_struct_field.  Like
  5851. * ada_index_struct_field, but takes index from *INDEX_P and modifies
  5852. * *INDEX_P.  */

  5853. static struct value *
  5854. ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
  5855.                           struct type *type)
  5856. {
  5857.   int i;
  5858.   type = ada_check_typedef (type);

  5859.   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
  5860.     {
  5861.       if (TYPE_FIELD_NAME (type, i) == NULL)
  5862.         continue;
  5863.       else if (ada_is_wrapper_field (type, i))
  5864.         {
  5865.           struct value *v =     /* Do not let indent join lines here.  */
  5866.             ada_index_struct_field_1 (index_p, arg,
  5867.                                       offset + TYPE_FIELD_BITPOS (type, i) / 8,
  5868.                                       TYPE_FIELD_TYPE (type, i));

  5869.           if (v != NULL)
  5870.             return v;
  5871.         }

  5872.       else if (ada_is_variant_part (type, i))
  5873.         {
  5874.           /* PNH: Do we ever get here?  See ada_search_struct_field,
  5875.              find_struct_field.  */
  5876.           error (_("Cannot assign this kind of variant record"));
  5877.         }
  5878.       else if (*index_p == 0)
  5879.         return ada_value_primitive_field (arg, offset, i, type);
  5880.       else
  5881.         *index_p -= 1;
  5882.     }
  5883.   return NULL;
  5884. }

  5885. /* Given ARG, a value of type (pointer or reference to a)*
  5886.    structure/union, extract the component named NAME from the ultimate
  5887.    target structure/union and return it as a value with its
  5888.    appropriate type.

  5889.    The routine searches for NAME among all members of the structure itself
  5890.    and (recursively) among all members of any wrapper members
  5891.    (e.g., '_parent').

  5892.    If NO_ERR, then simply return NULL in case of error, rather than
  5893.    calling error.  */

  5894. struct value *
  5895. ada_value_struct_elt (struct value *arg, char *name, int no_err)
  5896. {
  5897.   struct type *t, *t1;
  5898.   struct value *v;

  5899.   v = NULL;
  5900.   t1 = t = ada_check_typedef (value_type (arg));
  5901.   if (TYPE_CODE (t) == TYPE_CODE_REF)
  5902.     {
  5903.       t1 = TYPE_TARGET_TYPE (t);
  5904.       if (t1 == NULL)
  5905.         goto BadValue;
  5906.       t1 = ada_check_typedef (t1);
  5907.       if (TYPE_CODE (t1) == TYPE_CODE_PTR)
  5908.         {
  5909.           arg = coerce_ref (arg);
  5910.           t = t1;
  5911.         }
  5912.     }

  5913.   while (TYPE_CODE (t) == TYPE_CODE_PTR)
  5914.     {
  5915.       t1 = TYPE_TARGET_TYPE (t);
  5916.       if (t1 == NULL)
  5917.         goto BadValue;
  5918.       t1 = ada_check_typedef (t1);
  5919.       if (TYPE_CODE (t1) == TYPE_CODE_PTR)
  5920.         {
  5921.           arg = value_ind (arg);
  5922.           t = t1;
  5923.         }
  5924.       else
  5925.         break;
  5926.     }

  5927.   if (TYPE_CODE (t1) != TYPE_CODE_STRUCT && TYPE_CODE (t1) != TYPE_CODE_UNION)
  5928.     goto BadValue;

  5929.   if (t1 == t)
  5930.     v = ada_search_struct_field (name, arg, 0, t);
  5931.   else
  5932.     {
  5933.       int bit_offset, bit_size, byte_offset;
  5934.       struct type *field_type;
  5935.       CORE_ADDR address;

  5936.       if (TYPE_CODE (t) == TYPE_CODE_PTR)
  5937.         address = value_address (ada_value_ind (arg));
  5938.       else
  5939.         address = value_address (ada_coerce_ref (arg));

  5940.       t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL, address, NULL, 1);
  5941.       if (find_struct_field (name, t1, 0,
  5942.                              &field_type, &byte_offset, &bit_offset,
  5943.                              &bit_size, NULL))
  5944.         {
  5945.           if (bit_size != 0)
  5946.             {
  5947.               if (TYPE_CODE (t) == TYPE_CODE_REF)
  5948.                 arg = ada_coerce_ref (arg);
  5949.               else
  5950.                 arg = ada_value_ind (arg);
  5951.               v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
  5952.                                                   bit_offset, bit_size,
  5953.                                                   field_type);
  5954.             }
  5955.           else
  5956.             v = value_at_lazy (field_type, address + byte_offset);
  5957.         }
  5958.     }

  5959.   if (v != NULL || no_err)
  5960.     return v;
  5961.   else
  5962.     error (_("There is no member named %s."), name);

  5963. BadValue:
  5964.   if (no_err)
  5965.     return NULL;
  5966.   else
  5967.     error (_("Attempt to extract a component of "
  5968.              "a value that is not a record."));
  5969. }

  5970. /* Given a type TYPE, look up the type of the component of type named NAME.
  5971.    If DISPP is non-null, add its byte displacement from the beginning of a
  5972.    structure (pointed to by a value) of type TYPE to *DISPP (does not
  5973.    work for packed fields).

  5974.    Matches any field whose name has NAME as a prefix, possibly
  5975.    followed by "___".

  5976.    TYPE can be either a struct or union.  If REFOK, TYPE may also
  5977.    be a (pointer or reference)+ to a struct or union, and the
  5978.    ultimate target type will be searched.

  5979.    Looks recursively into variant clauses and parent types.

  5980.    If NOERR is nonzero, return NULL if NAME is not suitably defined or
  5981.    TYPE is not a type of the right kind.  */

  5982. static struct type *
  5983. ada_lookup_struct_elt_type (struct type *type, char *name, int refok,
  5984.                             int noerr, int *dispp)
  5985. {
  5986.   int i;

  5987.   if (name == NULL)
  5988.     goto BadName;

  5989.   if (refok && type != NULL)
  5990.     while (1)
  5991.       {
  5992.         type = ada_check_typedef (type);
  5993.         if (TYPE_CODE (type) != TYPE_CODE_PTR
  5994.             && TYPE_CODE (type) != TYPE_CODE_REF)
  5995.           break;
  5996.         type = TYPE_TARGET_TYPE (type);
  5997.       }

  5998.   if (type == NULL
  5999.       || (TYPE_CODE (type) != TYPE_CODE_STRUCT
  6000.           && TYPE_CODE (type) != TYPE_CODE_UNION))
  6001.     {
  6002.       if (noerr)
  6003.         return NULL;
  6004.       else
  6005.         {
  6006.           target_terminal_ours ();
  6007.           gdb_flush (gdb_stdout);
  6008.           if (type == NULL)
  6009.             error (_("Type (null) is not a structure or union type"));
  6010.           else
  6011.             {
  6012.               /* XXX: type_sprint */
  6013.               fprintf_unfiltered (gdb_stderr, _("Type "));
  6014.               type_print (type, "", gdb_stderr, -1);
  6015.               error (_(" is not a structure or union type"));
  6016.             }
  6017.         }
  6018.     }

  6019.   type = to_static_fixed_type (type);

  6020.   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
  6021.     {
  6022.       const char *t_field_name = TYPE_FIELD_NAME (type, i);
  6023.       struct type *t;
  6024.       int disp;

  6025.       if (t_field_name == NULL)
  6026.         continue;

  6027.       else if (field_name_match (t_field_name, name))
  6028.         {
  6029.           if (dispp != NULL)
  6030.             *dispp += TYPE_FIELD_BITPOS (type, i) / 8;
  6031.           return ada_check_typedef (TYPE_FIELD_TYPE (type, i));
  6032.         }

  6033.       else if (ada_is_wrapper_field (type, i))
  6034.         {
  6035.           disp = 0;
  6036.           t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (type, i), name,
  6037.                                           0, 1, &disp);
  6038.           if (t != NULL)
  6039.             {
  6040.               if (dispp != NULL)
  6041.                 *dispp += disp + TYPE_FIELD_BITPOS (type, i) / 8;
  6042.               return t;
  6043.             }
  6044.         }

  6045.       else if (ada_is_variant_part (type, i))
  6046.         {
  6047.           int j;
  6048.           struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type,
  6049.                                                                         i));

  6050.           for (j = TYPE_NFIELDS (field_type) - 1; j >= 0; j -= 1)
  6051.             {
  6052.               /* FIXME pnh 2008/01/26: We check for a field that is
  6053.                  NOT wrapped in a struct, since the compiler sometimes
  6054.                  generates these for unchecked variant types.  Revisit
  6055.                  if the compiler changes this practice.  */
  6056.               const char *v_field_name = TYPE_FIELD_NAME (field_type, j);
  6057.               disp = 0;
  6058.               if (v_field_name != NULL
  6059.                   && field_name_match (v_field_name, name))
  6060.                 t = ada_check_typedef (TYPE_FIELD_TYPE (field_type, j));
  6061.               else
  6062.                 t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (field_type,
  6063.                                                                  j),
  6064.                                                 name, 0, 1, &disp);

  6065.               if (t != NULL)
  6066.                 {
  6067.                   if (dispp != NULL)
  6068.                     *dispp += disp + TYPE_FIELD_BITPOS (type, i) / 8;
  6069.                   return t;
  6070.                 }
  6071.             }
  6072.         }

  6073.     }

  6074. BadName:
  6075.   if (!noerr)
  6076.     {
  6077.       target_terminal_ours ();
  6078.       gdb_flush (gdb_stdout);
  6079.       if (name == NULL)
  6080.         {
  6081.           /* XXX: type_sprint */
  6082.           fprintf_unfiltered (gdb_stderr, _("Type "));
  6083.           type_print (type, "", gdb_stderr, -1);
  6084.           error (_(" has no component named <null>"));
  6085.         }
  6086.       else
  6087.         {
  6088.           /* XXX: type_sprint */
  6089.           fprintf_unfiltered (gdb_stderr, _("Type "));
  6090.           type_print (type, "", gdb_stderr, -1);
  6091.           error (_(" has no component named %s"), name);
  6092.         }
  6093.     }

  6094.   return NULL;
  6095. }

  6096. /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
  6097.    within a value of type OUTER_TYPE, return true iff VAR_TYPE
  6098.    represents an unchecked union (that is, the variant part of a
  6099.    record that is named in an Unchecked_Union pragma).  */

  6100. static int
  6101. is_unchecked_variant (struct type *var_type, struct type *outer_type)
  6102. {
  6103.   char *discrim_name = ada_variant_discrim_name (var_type);

  6104.   return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1, NULL)
  6105.           == NULL);
  6106. }


  6107. /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
  6108.    within a value of type OUTER_TYPE that is stored in GDB at
  6109.    OUTER_VALADDR, determine which variant clause (field number in VAR_TYPE,
  6110.    numbering from 0) is applicable.  Returns -1 if none are.  */

  6111. int
  6112. ada_which_variant_applies (struct type *var_type, struct type *outer_type,
  6113.                            const gdb_byte *outer_valaddr)
  6114. {
  6115.   int others_clause;
  6116.   int i;
  6117.   char *discrim_name = ada_variant_discrim_name (var_type);
  6118.   struct value *outer;
  6119.   struct value *discrim;
  6120.   LONGEST discrim_val;

  6121.   /* Using plain value_from_contents_and_address here causes problems
  6122.      because we will end up trying to resolve a type that is currently
  6123.      being constructed.  */
  6124.   outer = value_from_contents_and_address_unresolved (outer_type,
  6125.                                                       outer_valaddr, 0);
  6126.   discrim = ada_value_struct_elt (outer, discrim_name, 1);
  6127.   if (discrim == NULL)
  6128.     return -1;
  6129.   discrim_val = value_as_long (discrim);

  6130.   others_clause = -1;
  6131.   for (i = 0; i < TYPE_NFIELDS (var_type); i += 1)
  6132.     {
  6133.       if (ada_is_others_clause (var_type, i))
  6134.         others_clause = i;
  6135.       else if (ada_in_variant (discrim_val, var_type, i))
  6136.         return i;
  6137.     }

  6138.   return others_clause;
  6139. }



  6140.                                 /* Dynamic-Sized Records */

  6141. /* Strategy: The type ostensibly attached to a value with dynamic size
  6142.    (i.e., a size that is not statically recorded in the debugging
  6143.    data) does not accurately reflect the size or layout of the value.
  6144.    Our strategy is to convert these values to values with accurate,
  6145.    conventional types that are constructed on the fly.  */

  6146. /* There is a subtle and tricky problem here.  In general, we cannot
  6147.    determine the size of dynamic records without its data.  However,
  6148.    the 'struct value' data structure, which GDB uses to represent
  6149.    quantities in the inferior process (the target), requires the size
  6150.    of the type at the time of its allocation in order to reserve space
  6151.    for GDB's internal copy of the data.  That's why the
  6152.    'to_fixed_xxx_type' routines take (target) addresses as parameters,
  6153.    rather than struct value*s.

  6154.    However, GDB's internal history variables ($1, $2, etc.) are
  6155.    struct value*s containing internal copies of the data that are not, in
  6156.    general, the same as the data at their corresponding addresses in
  6157.    the target.  Fortunately, the types we give to these values are all
  6158.    conventional, fixed-size types (as per the strategy described
  6159.    above), so that we don't usually have to perform the
  6160.    'to_fixed_xxx_type' conversions to look at their values.
  6161.    Unfortunately, there is one exception: if one of the internal
  6162.    history variables is an array whose elements are unconstrained
  6163.    records, then we will need to create distinct fixed types for each
  6164.    element selected.  */

  6165. /* The upshot of all of this is that many routines take a (type, host
  6166.    address, target address) triple as arguments to represent a value.
  6167.    The host address, if non-null, is supposed to contain an internal
  6168.    copy of the relevant data; otherwise, the program is to consult the
  6169.    target at the target address.  */

  6170. /* Assuming that VAL0 represents a pointer value, the result of
  6171.    dereferencing it.  Differs from value_ind in its treatment of
  6172.    dynamic-sized types.  */

  6173. struct value *
  6174. ada_value_ind (struct value *val0)
  6175. {
  6176.   struct value *val = value_ind (val0);

  6177.   if (ada_is_tagged_type (value_type (val), 0))
  6178.     val = ada_tag_value_at_base_address (val);

  6179.   return ada_to_fixed_value (val);
  6180. }

  6181. /* The value resulting from dereferencing any "reference to"
  6182.    qualifiers on VAL0.  */

  6183. static struct value *
  6184. ada_coerce_ref (struct value *val0)
  6185. {
  6186.   if (TYPE_CODE (value_type (val0)) == TYPE_CODE_REF)
  6187.     {
  6188.       struct value *val = val0;

  6189.       val = coerce_ref (val);

  6190.       if (ada_is_tagged_type (value_type (val), 0))
  6191.         val = ada_tag_value_at_base_address (val);

  6192.       return ada_to_fixed_value (val);
  6193.     }
  6194.   else
  6195.     return val0;
  6196. }

  6197. /* Return OFF rounded upward if necessary to a multiple of
  6198.    ALIGNMENT (a power of 2).  */

  6199. static unsigned int
  6200. align_value (unsigned int off, unsigned int alignment)
  6201. {
  6202.   return (off + alignment - 1) & ~(alignment - 1);
  6203. }

  6204. /* Return the bit alignment required for field #F of template type TYPE.  */

  6205. static unsigned int
  6206. field_alignment (struct type *type, int f)
  6207. {
  6208.   const char *name = TYPE_FIELD_NAME (type, f);
  6209.   int len;
  6210.   int align_offset;

  6211.   /* The field name should never be null, unless the debugging information
  6212.      is somehow malformed.  In this case, we assume the field does not
  6213.      require any alignment.  */
  6214.   if (name == NULL)
  6215.     return 1;

  6216.   len = strlen (name);

  6217.   if (!isdigit (name[len - 1]))
  6218.     return 1;

  6219.   if (isdigit (name[len - 2]))
  6220.     align_offset = len - 2;
  6221.   else
  6222.     align_offset = len - 1;

  6223.   if (align_offset < 7 || strncmp ("___XV", name + align_offset - 6, 5) != 0)
  6224.     return TARGET_CHAR_BIT;

  6225.   return atoi (name + align_offset) * TARGET_CHAR_BIT;
  6226. }

  6227. /* Find a typedef or tag symbol named NAME.  Ignores ambiguity.  */

  6228. static struct symbol *
  6229. ada_find_any_type_symbol (const char *name)
  6230. {
  6231.   struct symbol *sym;

  6232.   sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
  6233.   if (sym != NULL && SYMBOL_CLASS (sym) == LOC_TYPEDEF)
  6234.     return sym;

  6235.   sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
  6236.   return sym;
  6237. }

  6238. /* Find a type named NAME.  Ignores ambiguity.  This routine will look
  6239.    solely for types defined by debug info, it will not search the GDB
  6240.    primitive types.  */

  6241. static struct type *
  6242. ada_find_any_type (const char *name)
  6243. {
  6244.   struct symbol *sym = ada_find_any_type_symbol (name);

  6245.   if (sym != NULL)
  6246.     return SYMBOL_TYPE (sym);

  6247.   return NULL;
  6248. }

  6249. /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
  6250.    associated with NAME_SYM's name.  NAME_SYM may itself be a renaming
  6251.    symbol, in which case it is returned.  Otherwise, this looks for
  6252.    symbols whose name is that of NAME_SYM suffixed with  "___XR".
  6253.    Return symbol if found, and NULL otherwise.  */

  6254. struct symbol *
  6255. ada_find_renaming_symbol (struct symbol *name_sym, const struct block *block)
  6256. {
  6257.   const char *name = SYMBOL_LINKAGE_NAME (name_sym);
  6258.   struct symbol *sym;

  6259.   if (strstr (name, "___XR") != NULL)
  6260.      return name_sym;

  6261.   sym = find_old_style_renaming_symbol (name, block);

  6262.   if (sym != NULL)
  6263.     return sym;

  6264.   /* Not right yet.  FIXME pnh 7/20/2007.  */
  6265.   sym = ada_find_any_type_symbol (name);
  6266.   if (sym != NULL && strstr (SYMBOL_LINKAGE_NAME (sym), "___XR") != NULL)
  6267.     return sym;
  6268.   else
  6269.     return NULL;
  6270. }

  6271. static struct symbol *
  6272. find_old_style_renaming_symbol (const char *name, const struct block *block)
  6273. {
  6274.   const struct symbol *function_sym = block_linkage_function (block);
  6275.   char *rename;

  6276.   if (function_sym != NULL)
  6277.     {
  6278.       /* If the symbol is defined inside a function, NAME is not fully
  6279.          qualified.  This means we need to prepend the function name
  6280.          as well as adding the ``___XR'' suffix to build the name of
  6281.          the associated renaming symbol.  */
  6282.       const char *function_name = SYMBOL_LINKAGE_NAME (function_sym);
  6283.       /* Function names sometimes contain suffixes used
  6284.          for instance to qualify nested subprograms.  When building
  6285.          the XR type name, we need to make sure that this suffix is
  6286.          not included.  So do not include any suffix in the function
  6287.          name length below.  */
  6288.       int function_name_len = ada_name_prefix_len (function_name);
  6289.       const int rename_len = function_name_len + 2      /*  "__" */
  6290.         + strlen (name) + 6 /* "___XR\0" */ ;

  6291.       /* Strip the suffix if necessary.  */
  6292.       ada_remove_trailing_digits (function_name, &function_name_len);
  6293.       ada_remove_po_subprogram_suffix (function_name, &function_name_len);
  6294.       ada_remove_Xbn_suffix (function_name, &function_name_len);

  6295.       /* Library-level functions are a special case, as GNAT adds
  6296.          a ``_ada_'' prefix to the function name to avoid namespace
  6297.          pollution.  However, the renaming symbols themselves do not
  6298.          have this prefix, so we need to skip this prefix if present.  */
  6299.       if (function_name_len > 5 /* "_ada_" */
  6300.           && strstr (function_name, "_ada_") == function_name)
  6301.         {
  6302.           function_name += 5;
  6303.           function_name_len -= 5;
  6304.         }

  6305.       rename = (char *) alloca (rename_len * sizeof (char));
  6306.       strncpy (rename, function_name, function_name_len);
  6307.       xsnprintf (rename + function_name_len, rename_len - function_name_len,
  6308.                  "__%s___XR", name);
  6309.     }
  6310.   else
  6311.     {
  6312.       const int rename_len = strlen (name) + 6;

  6313.       rename = (char *) alloca (rename_len * sizeof (char));
  6314.       xsnprintf (rename, rename_len * sizeof (char), "%s___XR", name);
  6315.     }

  6316.   return ada_find_any_type_symbol (rename);
  6317. }

  6318. /* Because of GNAT encoding conventions, several GDB symbols may match a
  6319.    given type name.  If the type denoted by TYPE0 is to be preferred to
  6320.    that of TYPE1 for purposes of type printing, return non-zero;
  6321.    otherwise return 0.  */

  6322. int
  6323. ada_prefer_type (struct type *type0, struct type *type1)
  6324. {
  6325.   if (type1 == NULL)
  6326.     return 1;
  6327.   else if (type0 == NULL)
  6328.     return 0;
  6329.   else if (TYPE_CODE (type1) == TYPE_CODE_VOID)
  6330.     return 1;
  6331.   else if (TYPE_CODE (type0) == TYPE_CODE_VOID)
  6332.     return 0;
  6333.   else if (TYPE_NAME (type1) == NULL && TYPE_NAME (type0) != NULL)
  6334.     return 1;
  6335.   else if (ada_is_constrained_packed_array_type (type0))
  6336.     return 1;
  6337.   else if (ada_is_array_descriptor_type (type0)
  6338.            && !ada_is_array_descriptor_type (type1))
  6339.     return 1;
  6340.   else
  6341.     {
  6342.       const char *type0_name = type_name_no_tag (type0);
  6343.       const char *type1_name = type_name_no_tag (type1);

  6344.       if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
  6345.           && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
  6346.         return 1;
  6347.     }
  6348.   return 0;
  6349. }

  6350. /* The name of TYPE, which is either its TYPE_NAME, or, if that is
  6351.    null, its TYPE_TAG_NAME.  Null if TYPE is null.  */

  6352. const char *
  6353. ada_type_name (struct type *type)
  6354. {
  6355.   if (type == NULL)
  6356.     return NULL;
  6357.   else if (TYPE_NAME (type) != NULL)
  6358.     return TYPE_NAME (type);
  6359.   else
  6360.     return TYPE_TAG_NAME (type);
  6361. }

  6362. /* Search the list of "descriptive" types associated to TYPE for a type
  6363.    whose name is NAME.  */

  6364. static struct type *
  6365. find_parallel_type_by_descriptive_type (struct type *type, const char *name)
  6366. {
  6367.   struct type *result;

  6368.   if (ada_ignore_descriptive_types_p)
  6369.     return NULL;

  6370.   /* If there no descriptive-type info, then there is no parallel type
  6371.      to be found.  */
  6372.   if (!HAVE_GNAT_AUX_INFO (type))
  6373.     return NULL;

  6374.   result = TYPE_DESCRIPTIVE_TYPE (type);
  6375.   while (result != NULL)
  6376.     {
  6377.       const char *result_name = ada_type_name (result);

  6378.       if (result_name == NULL)
  6379.         {
  6380.           warning (_("unexpected null name on descriptive type"));
  6381.           return NULL;
  6382.         }

  6383.       /* If the names match, stop.  */
  6384.       if (strcmp (result_name, name) == 0)
  6385.         break;

  6386.       /* Otherwise, look at the next item on the list, if any.  */
  6387.       if (HAVE_GNAT_AUX_INFO (result))
  6388.         result = TYPE_DESCRIPTIVE_TYPE (result);
  6389.       else
  6390.         result = NULL;
  6391.     }

  6392.   /* If we didn't find a match, see whether this is a packed array.  With
  6393.      older compilers, the descriptive type information is either absent or
  6394.      irrelevant when it comes to packed arrays so the above lookup fails.
  6395.      Fall back to using a parallel lookup by name in this case.  */
  6396.   if (result == NULL && ada_is_constrained_packed_array_type (type))
  6397.     return ada_find_any_type (name);

  6398.   return result;
  6399. }

  6400. /* Find a parallel type to TYPE with the specified NAME, using the
  6401.    descriptive type taken from the debugging information, if available,
  6402.    and otherwise using the (slower) name-based method.  */

  6403. static struct type *
  6404. ada_find_parallel_type_with_name (struct type *type, const char *name)
  6405. {
  6406.   struct type *result = NULL;

  6407.   if (HAVE_GNAT_AUX_INFO (type))
  6408.     result = find_parallel_type_by_descriptive_type (type, name);
  6409.   else
  6410.     result = ada_find_any_type (name);

  6411.   return result;
  6412. }

  6413. /* Same as above, but specify the name of the parallel type by appending
  6414.    SUFFIX to the name of TYPE.  */

  6415. struct type *
  6416. ada_find_parallel_type (struct type *type, const char *suffix)
  6417. {
  6418.   char *name;
  6419.   const char *typename = ada_type_name (type);
  6420.   int len;

  6421.   if (typename == NULL)
  6422.     return NULL;

  6423.   len = strlen (typename);

  6424.   name = (char *) alloca (len + strlen (suffix) + 1);

  6425.   strcpy (name, typename);
  6426.   strcpy (name + len, suffix);

  6427.   return ada_find_parallel_type_with_name (type, name);
  6428. }

  6429. /* If TYPE is a variable-size record type, return the corresponding template
  6430.    type describing its fields.  Otherwise, return NULL.  */

  6431. static struct type *
  6432. dynamic_template_type (struct type *type)
  6433. {
  6434.   type = ada_check_typedef (type);

  6435.   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT
  6436.       || ada_type_name (type) == NULL)
  6437.     return NULL;
  6438.   else
  6439.     {
  6440.       int len = strlen (ada_type_name (type));

  6441.       if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
  6442.         return type;
  6443.       else
  6444.         return ada_find_parallel_type (type, "___XVE");
  6445.     }
  6446. }

  6447. /* Assuming that TEMPL_TYPE is a union or struct type, returns
  6448.    non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size.  */

  6449. static int
  6450. is_dynamic_field (struct type *templ_type, int field_num)
  6451. {
  6452.   const char *name = TYPE_FIELD_NAME (templ_type, field_num);

  6453.   return name != NULL
  6454.     && TYPE_CODE (TYPE_FIELD_TYPE (templ_type, field_num)) == TYPE_CODE_PTR
  6455.     && strstr (name, "___XVL") != NULL;
  6456. }

  6457. /* The index of the variant field of TYPE, or -1 if TYPE does not
  6458.    represent a variant record type.  */

  6459. static int
  6460. variant_field_index (struct type *type)
  6461. {
  6462.   int f;

  6463.   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
  6464.     return -1;

  6465.   for (f = 0; f < TYPE_NFIELDS (type); f += 1)
  6466.     {
  6467.       if (ada_is_variant_part (type, f))
  6468.         return f;
  6469.     }
  6470.   return -1;
  6471. }

  6472. /* A record type with no fields.  */

  6473. static struct type *
  6474. empty_record (struct type *template)
  6475. {
  6476.   struct type *type = alloc_type_copy (template);

  6477.   TYPE_CODE (type) = TYPE_CODE_STRUCT;
  6478.   TYPE_NFIELDS (type) = 0;
  6479.   TYPE_FIELDS (type) = NULL;
  6480.   INIT_CPLUS_SPECIFIC (type);
  6481.   TYPE_NAME (type) = "<empty>";
  6482.   TYPE_TAG_NAME (type) = NULL;
  6483.   TYPE_LENGTH (type) = 0;
  6484.   return type;
  6485. }

  6486. /* An ordinary record type (with fixed-length fields) that describes
  6487.    the value of type TYPE at VALADDR or ADDRESS (see comments at
  6488.    the beginning of this section) VAL according to GNAT conventions.
  6489.    DVAL0 should describe the (portion of a) record that contains any
  6490.    necessary discriminants.  It should be NULL if value_type (VAL) is
  6491.    an outer-level type (i.e., as opposed to a branch of a variant.)  A
  6492.    variant field (unless unchecked) is replaced by a particular branch
  6493.    of the variant.

  6494.    If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
  6495.    length are not statically known are discarded.  As a consequence,
  6496.    VALADDR, ADDRESS and DVAL0 are ignored.

  6497.    NOTE: Limitations: For now, we assume that dynamic fields and
  6498.    variants occupy whole numbers of bytes.  However, they need not be
  6499.    byte-aligned.  */

  6500. struct type *
  6501. ada_template_to_fixed_record_type_1 (struct type *type,
  6502.                                      const gdb_byte *valaddr,
  6503.                                      CORE_ADDR address, struct value *dval0,
  6504.                                      int keep_dynamic_fields)
  6505. {
  6506.   struct value *mark = value_mark ();
  6507.   struct value *dval;
  6508.   struct type *rtype;
  6509.   int nfields, bit_len;
  6510.   int variant_field;
  6511.   long off;
  6512.   int fld_bit_len;
  6513.   int f;

  6514.   /* Compute the number of fields in this record type that are going
  6515.      to be processed: unless keep_dynamic_fields, this includes only
  6516.      fields whose position and length are static will be processed.  */
  6517.   if (keep_dynamic_fields)
  6518.     nfields = TYPE_NFIELDS (type);
  6519.   else
  6520.     {
  6521.       nfields = 0;
  6522.       while (nfields < TYPE_NFIELDS (type)
  6523.              && !ada_is_variant_part (type, nfields)
  6524.              && !is_dynamic_field (type, nfields))
  6525.         nfields++;
  6526.     }

  6527.   rtype = alloc_type_copy (type);
  6528.   TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
  6529.   INIT_CPLUS_SPECIFIC (rtype);
  6530.   TYPE_NFIELDS (rtype) = nfields;
  6531.   TYPE_FIELDS (rtype) = (struct field *)
  6532.     TYPE_ALLOC (rtype, nfields * sizeof (struct field));
  6533.   memset (TYPE_FIELDS (rtype), 0, sizeof (struct field) * nfields);
  6534.   TYPE_NAME (rtype) = ada_type_name (type);
  6535.   TYPE_TAG_NAME (rtype) = NULL;
  6536.   TYPE_FIXED_INSTANCE (rtype) = 1;

  6537.   off = 0;
  6538.   bit_len = 0;
  6539.   variant_field = -1;

  6540.   for (f = 0; f < nfields; f += 1)
  6541.     {
  6542.       off = align_value (off, field_alignment (type, f))
  6543.         + TYPE_FIELD_BITPOS (type, f);
  6544.       SET_FIELD_BITPOS (TYPE_FIELD (rtype, f), off);
  6545.       TYPE_FIELD_BITSIZE (rtype, f) = 0;

  6546.       if (ada_is_variant_part (type, f))
  6547.         {
  6548.           variant_field = f;
  6549.           fld_bit_len = 0;
  6550.         }
  6551.       else if (is_dynamic_field (type, f))
  6552.         {
  6553.           const gdb_byte *field_valaddr = valaddr;
  6554.           CORE_ADDR field_address = address;
  6555.           struct type *field_type =
  6556.             TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type, f));

  6557.           if (dval0 == NULL)
  6558.             {
  6559.               /* rtype's length is computed based on the run-time
  6560.                  value of discriminants.  If the discriminants are not
  6561.                  initialized, the type size may be completely bogus and
  6562.                  GDB may fail to allocate a value for it.  So check the
  6563.                  size first before creating the value.  */
  6564.               ada_ensure_varsize_limit (rtype);
  6565.               /* Using plain value_from_contents_and_address here
  6566.                  causes problems because we will end up trying to
  6567.                  resolve a type that is currently being
  6568.                  constructed.  */
  6569.               dval = value_from_contents_and_address_unresolved (rtype,
  6570.                                                                  valaddr,
  6571.                                                                  address);
  6572.               rtype = value_type (dval);
  6573.             }
  6574.           else
  6575.             dval = dval0;

  6576.           /* If the type referenced by this field is an aligner type, we need
  6577.              to unwrap that aligner type, because its size might not be set.
  6578.              Keeping the aligner type would cause us to compute the wrong
  6579.              size for this field, impacting the offset of the all the fields
  6580.              that follow this one.  */
  6581.           if (ada_is_aligner_type (field_type))
  6582.             {
  6583.               long field_offset = TYPE_FIELD_BITPOS (field_type, f);

  6584.               field_valaddr = cond_offset_host (field_valaddr, field_offset);
  6585.               field_address = cond_offset_target (field_address, field_offset);
  6586.               field_type = ada_aligned_type (field_type);
  6587.             }

  6588.           field_valaddr = cond_offset_host (field_valaddr,
  6589.                                             off / TARGET_CHAR_BIT);
  6590.           field_address = cond_offset_target (field_address,
  6591.                                               off / TARGET_CHAR_BIT);

  6592.           /* Get the fixed type of the field.  Note that, in this case,
  6593.              we do not want to get the real type out of the tag: if
  6594.              the current field is the parent part of a tagged record,
  6595.              we will get the tag of the object.  Clearly wrong: the real
  6596.              type of the parent is not the real type of the child.  We
  6597.              would end up in an infinite loop.        */
  6598.           field_type = ada_get_base_type (field_type);
  6599.           field_type = ada_to_fixed_type (field_type, field_valaddr,
  6600.                                           field_address, dval, 0);
  6601.           /* If the field size is already larger than the maximum
  6602.              object size, then the record itself will necessarily
  6603.              be larger than the maximum object size.  We need to make
  6604.              this check now, because the size might be so ridiculously
  6605.              large (due to an uninitialized variable in the inferior)
  6606.              that it would cause an overflow when adding it to the
  6607.              record size.  */
  6608.           ada_ensure_varsize_limit (field_type);

  6609.           TYPE_FIELD_TYPE (rtype, f) = field_type;
  6610.           TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
  6611.           /* The multiplication can potentially overflow.  But because
  6612.              the field length has been size-checked just above, and
  6613.              assuming that the maximum size is a reasonable value,
  6614.              an overflow should not happen in practice.  So rather than
  6615.              adding overflow recovery code to this already complex code,
  6616.              we just assume that it's not going to happen.  */
  6617.           fld_bit_len =
  6618.             TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, f)) * TARGET_CHAR_BIT;
  6619.         }
  6620.       else
  6621.         {
  6622.           /* Note: If this field's type is a typedef, it is important
  6623.              to preserve the typedef layer.

  6624.              Otherwise, we might be transforming a typedef to a fat
  6625.              pointer (encoding a pointer to an unconstrained array),
  6626.              into a basic fat pointer (encoding an unconstrained
  6627.              array).  As both types are implemented using the same
  6628.              structure, the typedef is the only clue which allows us
  6629.              to distinguish between the two options.  Stripping it
  6630.              would prevent us from printing this field appropriately.  */
  6631.           TYPE_FIELD_TYPE (rtype, f) = TYPE_FIELD_TYPE (type, f);
  6632.           TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
  6633.           if (TYPE_FIELD_BITSIZE (type, f) > 0)
  6634.             fld_bit_len =
  6635.               TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
  6636.           else
  6637.             {
  6638.               struct type *field_type = TYPE_FIELD_TYPE (type, f);

  6639.               /* We need to be careful of typedefs when computing
  6640.                  the length of our field.  If this is a typedef,
  6641.                  get the length of the target type, not the length
  6642.                  of the typedef.  */
  6643.               if (TYPE_CODE (field_type) == TYPE_CODE_TYPEDEF)
  6644.                 field_type = ada_typedef_target_type (field_type);

  6645.               fld_bit_len =
  6646.                 TYPE_LENGTH (ada_check_typedef (field_type)) * TARGET_CHAR_BIT;
  6647.             }
  6648.         }
  6649.       if (off + fld_bit_len > bit_len)
  6650.         bit_len = off + fld_bit_len;
  6651.       off += fld_bit_len;
  6652.       TYPE_LENGTH (rtype) =
  6653.         align_value (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
  6654.     }

  6655.   /* We handle the variant part, if any, at the end because of certain
  6656.      odd cases in which it is re-ordered so as NOT to be the last field of
  6657.      the record.  This can happen in the presence of representation
  6658.      clauses.  */
  6659.   if (variant_field >= 0)
  6660.     {
  6661.       struct type *branch_type;

  6662.       off = TYPE_FIELD_BITPOS (rtype, variant_field);

  6663.       if (dval0 == NULL)
  6664.         {
  6665.           /* Using plain value_from_contents_and_address here causes
  6666.              problems because we will end up trying to resolve a type
  6667.              that is currently being constructed.  */
  6668.           dval = value_from_contents_and_address_unresolved (rtype, valaddr,
  6669.                                                              address);
  6670.           rtype = value_type (dval);
  6671.         }
  6672.       else
  6673.         dval = dval0;

  6674.       branch_type =
  6675.         to_fixed_variant_branch_type
  6676.         (TYPE_FIELD_TYPE (type, variant_field),
  6677.          cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
  6678.          cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
  6679.       if (branch_type == NULL)
  6680.         {
  6681.           for (f = variant_field + 1; f < TYPE_NFIELDS (rtype); f += 1)
  6682.             TYPE_FIELDS (rtype)[f - 1] = TYPE_FIELDS (rtype)[f];
  6683.           TYPE_NFIELDS (rtype) -= 1;
  6684.         }
  6685.       else
  6686.         {
  6687.           TYPE_FIELD_TYPE (rtype, variant_field) = branch_type;
  6688.           TYPE_FIELD_NAME (rtype, variant_field) = "S";
  6689.           fld_bit_len =
  6690.             TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, variant_field)) *
  6691.             TARGET_CHAR_BIT;
  6692.           if (off + fld_bit_len > bit_len)
  6693.             bit_len = off + fld_bit_len;
  6694.           TYPE_LENGTH (rtype) =
  6695.             align_value (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
  6696.         }
  6697.     }

  6698.   /* According to exp_dbug.ads, the size of TYPE for variable-size records
  6699.      should contain the alignment of that record, which should be a strictly
  6700.      positive value.  If null or negative, then something is wrong, most
  6701.      probably in the debug info.  In that case, we don't round up the size
  6702.      of the resulting type.  If this record is not part of another structure,
  6703.      the current RTYPE length might be good enough for our purposes.  */
  6704.   if (TYPE_LENGTH (type) <= 0)
  6705.     {
  6706.       if (TYPE_NAME (rtype))
  6707.         warning (_("Invalid type size for `%s' detected: %d."),
  6708.                  TYPE_NAME (rtype), TYPE_LENGTH (type));
  6709.       else
  6710.         warning (_("Invalid type size for <unnamed> detected: %d."),
  6711.                  TYPE_LENGTH (type));
  6712.     }
  6713.   else
  6714.     {
  6715.       TYPE_LENGTH (rtype) = align_value (TYPE_LENGTH (rtype),
  6716.                                          TYPE_LENGTH (type));
  6717.     }

  6718.   value_free_to_mark (mark);
  6719.   if (TYPE_LENGTH (rtype) > varsize_limit)
  6720.     error (_("record type with dynamic size is larger than varsize-limit"));
  6721.   return rtype;
  6722. }

  6723. /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
  6724.    of 1.  */

  6725. static struct type *
  6726. template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
  6727.                                CORE_ADDR address, struct value *dval0)
  6728. {
  6729.   return ada_template_to_fixed_record_type_1 (type, valaddr,
  6730.                                               address, dval0, 1);
  6731. }

  6732. /* An ordinary record type in which ___XVL-convention fields and
  6733.    ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
  6734.    static approximations, containing all possible fields.  Uses
  6735.    no runtime values.  Useless for use in values, but that's OK,
  6736.    since the results are used only for type determinations.   Works on both
  6737.    structs and unions.  Representation note: to save space, we memorize
  6738.    the result of this function in the TYPE_TARGET_TYPE of the
  6739.    template type.  */

  6740. static struct type *
  6741. template_to_static_fixed_type (struct type *type0)
  6742. {
  6743.   struct type *type;
  6744.   int nfields;
  6745.   int f;

  6746.   if (TYPE_TARGET_TYPE (type0) != NULL)
  6747.     return TYPE_TARGET_TYPE (type0);

  6748.   nfields = TYPE_NFIELDS (type0);
  6749.   type = type0;

  6750.   for (f = 0; f < nfields; f += 1)
  6751.     {
  6752.       struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type0, f));
  6753.       struct type *new_type;

  6754.       if (is_dynamic_field (type0, f))
  6755.         new_type = to_static_fixed_type (TYPE_TARGET_TYPE (field_type));
  6756.       else
  6757.         new_type = static_unwrap_type (field_type);
  6758.       if (type == type0 && new_type != field_type)
  6759.         {
  6760.           TYPE_TARGET_TYPE (type0) = type = alloc_type_copy (type0);
  6761.           TYPE_CODE (type) = TYPE_CODE (type0);
  6762.           INIT_CPLUS_SPECIFIC (type);
  6763.           TYPE_NFIELDS (type) = nfields;
  6764.           TYPE_FIELDS (type) = (struct field *)
  6765.             TYPE_ALLOC (type, nfields * sizeof (struct field));
  6766.           memcpy (TYPE_FIELDS (type), TYPE_FIELDS (type0),
  6767.                   sizeof (struct field) * nfields);
  6768.           TYPE_NAME (type) = ada_type_name (type0);
  6769.           TYPE_TAG_NAME (type) = NULL;
  6770.           TYPE_FIXED_INSTANCE (type) = 1;
  6771.           TYPE_LENGTH (type) = 0;
  6772.         }
  6773.       TYPE_FIELD_TYPE (type, f) = new_type;
  6774.       TYPE_FIELD_NAME (type, f) = TYPE_FIELD_NAME (type0, f);
  6775.     }
  6776.   return type;
  6777. }

  6778. /* Given an object of type TYPE whose contents are at VALADDR and
  6779.    whose address in memory is ADDRESS, returns a revision of TYPE,
  6780.    which should be a non-dynamic-sized record, in which the variant
  6781.    part, if any, is replaced with the appropriate branch.  Looks
  6782.    for discriminant values in DVAL0, which can be NULL if the record
  6783.    contains the necessary discriminant values.  */

  6784. static struct type *
  6785. to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
  6786.                                    CORE_ADDR address, struct value *dval0)
  6787. {
  6788.   struct value *mark = value_mark ();
  6789.   struct value *dval;
  6790.   struct type *rtype;
  6791.   struct type *branch_type;
  6792.   int nfields = TYPE_NFIELDS (type);
  6793.   int variant_field = variant_field_index (type);

  6794.   if (variant_field == -1)
  6795.     return type;

  6796.   if (dval0 == NULL)
  6797.     {
  6798.       dval = value_from_contents_and_address (type, valaddr, address);
  6799.       type = value_type (dval);
  6800.     }
  6801.   else
  6802.     dval = dval0;

  6803.   rtype = alloc_type_copy (type);
  6804.   TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
  6805.   INIT_CPLUS_SPECIFIC (rtype);
  6806.   TYPE_NFIELDS (rtype) = nfields;
  6807.   TYPE_FIELDS (rtype) =
  6808.     (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
  6809.   memcpy (TYPE_FIELDS (rtype), TYPE_FIELDS (type),
  6810.           sizeof (struct field) * nfields);
  6811.   TYPE_NAME (rtype) = ada_type_name (type);
  6812.   TYPE_TAG_NAME (rtype) = NULL;
  6813.   TYPE_FIXED_INSTANCE (rtype) = 1;
  6814.   TYPE_LENGTH (rtype) = TYPE_LENGTH (type);

  6815.   branch_type = to_fixed_variant_branch_type
  6816.     (TYPE_FIELD_TYPE (type, variant_field),
  6817.      cond_offset_host (valaddr,
  6818.                        TYPE_FIELD_BITPOS (type, variant_field)
  6819.                        / TARGET_CHAR_BIT),
  6820.      cond_offset_target (address,
  6821.                          TYPE_FIELD_BITPOS (type, variant_field)
  6822.                          / TARGET_CHAR_BIT), dval);
  6823.   if (branch_type == NULL)
  6824.     {
  6825.       int f;

  6826.       for (f = variant_field + 1; f < nfields; f += 1)
  6827.         TYPE_FIELDS (rtype)[f - 1] = TYPE_FIELDS (rtype)[f];
  6828.       TYPE_NFIELDS (rtype) -= 1;
  6829.     }
  6830.   else
  6831.     {
  6832.       TYPE_FIELD_TYPE (rtype, variant_field) = branch_type;
  6833.       TYPE_FIELD_NAME (rtype, variant_field) = "S";
  6834.       TYPE_FIELD_BITSIZE (rtype, variant_field) = 0;
  6835.       TYPE_LENGTH (rtype) += TYPE_LENGTH (branch_type);
  6836.     }
  6837.   TYPE_LENGTH (rtype) -= TYPE_LENGTH (TYPE_FIELD_TYPE (type, variant_field));

  6838.   value_free_to_mark (mark);
  6839.   return rtype;
  6840. }

  6841. /* An ordinary record type (with fixed-length fields) that describes
  6842.    the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
  6843.    beginning of this section].   Any necessary discriminants' values
  6844.    should be in DVAL, a record value; it may be NULL if the object
  6845.    at ADDR itself contains any necessary discriminant values.
  6846.    Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
  6847.    values from the record are needed.  Except in the case that DVAL,
  6848.    VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
  6849.    unchecked) is replaced by a particular branch of the variant.

  6850.    NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
  6851.    is questionable and may be removed.  It can arise during the
  6852.    processing of an unconstrained-array-of-record type where all the
  6853.    variant branches have exactly the same size.  This is because in
  6854.    such cases, the compiler does not bother to use the XVS convention
  6855.    when encoding the record.  I am currently dubious of this
  6856.    shortcut and suspect the compiler should be altered.  FIXME.  */

  6857. static struct type *
  6858. to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
  6859.                       CORE_ADDR address, struct value *dval)
  6860. {
  6861.   struct type *templ_type;

  6862.   if (TYPE_FIXED_INSTANCE (type0))
  6863.     return type0;

  6864.   templ_type = dynamic_template_type (type0);

  6865.   if (templ_type != NULL)
  6866.     return template_to_fixed_record_type (templ_type, valaddr, address, dval);
  6867.   else if (variant_field_index (type0) >= 0)
  6868.     {
  6869.       if (dval == NULL && valaddr == NULL && address == 0)
  6870.         return type0;
  6871.       return to_record_with_fixed_variant_part (type0, valaddr, address,
  6872.                                                 dval);
  6873.     }
  6874.   else
  6875.     {
  6876.       TYPE_FIXED_INSTANCE (type0) = 1;
  6877.       return type0;
  6878.     }

  6879. }

  6880. /* An ordinary record type (with fixed-length fields) that describes
  6881.    the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
  6882.    union type.  Any necessary discriminants' values should be in DVAL,
  6883.    a record value.  That is, this routine selects the appropriate
  6884.    branch of the union at ADDR according to the discriminant value
  6885.    indicated in the union's type name.  Returns VAR_TYPE0 itself if
  6886.    it represents a variant subject to a pragma Unchecked_Union.  */

  6887. static struct type *
  6888. to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
  6889.                               CORE_ADDR address, struct value *dval)
  6890. {
  6891.   int which;
  6892.   struct type *templ_type;
  6893.   struct type *var_type;

  6894.   if (TYPE_CODE (var_type0) == TYPE_CODE_PTR)
  6895.     var_type = TYPE_TARGET_TYPE (var_type0);
  6896.   else
  6897.     var_type = var_type0;

  6898.   templ_type = ada_find_parallel_type (var_type, "___XVU");

  6899.   if (templ_type != NULL)
  6900.     var_type = templ_type;

  6901.   if (is_unchecked_variant (var_type, value_type (dval)))
  6902.       return var_type0;
  6903.   which =
  6904.     ada_which_variant_applies (var_type,
  6905.                                value_type (dval), value_contents (dval));

  6906.   if (which < 0)
  6907.     return empty_record (var_type);
  6908.   else if (is_dynamic_field (var_type, which))
  6909.     return to_fixed_record_type
  6910.       (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (var_type, which)),
  6911.        valaddr, address, dval);
  6912.   else if (variant_field_index (TYPE_FIELD_TYPE (var_type, which)) >= 0)
  6913.     return
  6914.       to_fixed_record_type
  6915.       (TYPE_FIELD_TYPE (var_type, which), valaddr, address, dval);
  6916.   else
  6917.     return TYPE_FIELD_TYPE (var_type, which);
  6918. }

  6919. /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
  6920.    ENCODING_TYPE, a type following the GNAT conventions for discrete
  6921.    type encodings, only carries redundant information.  */

  6922. static int
  6923. ada_is_redundant_range_encoding (struct type *range_type,
  6924.                                  struct type *encoding_type)
  6925. {
  6926.   struct type *fixed_range_type;
  6927.   char *bounds_str;
  6928.   int n;
  6929.   LONGEST lo, hi;

  6930.   gdb_assert (TYPE_CODE (range_type) == TYPE_CODE_RANGE);

  6931.   if (TYPE_CODE (get_base_type (range_type))
  6932.       != TYPE_CODE (get_base_type (encoding_type)))
  6933.     {
  6934.       /* The compiler probably used a simple base type to describe
  6935.          the range type instead of the range's actual base type,
  6936.          expecting us to get the real base type from the encoding
  6937.          anyway.  In this situation, the encoding cannot be ignored
  6938.          as redundant.  */
  6939.       return 0;
  6940.     }

  6941.   if (is_dynamic_type (range_type))
  6942.     return 0;

  6943.   if (TYPE_NAME (encoding_type) == NULL)
  6944.     return 0;

  6945.   bounds_str = strstr (TYPE_NAME (encoding_type), "___XDLU_");
  6946.   if (bounds_str == NULL)
  6947.     return 0;

  6948.   n = 8; /* Skip "___XDLU_".  */
  6949.   if (!ada_scan_number (bounds_str, n, &lo, &n))
  6950.     return 0;
  6951.   if (TYPE_LOW_BOUND (range_type) != lo)
  6952.     return 0;

  6953.   n += 2; /* Skip the "__" separator between the two bounds.  */
  6954.   if (!ada_scan_number (bounds_str, n, &hi, &n))
  6955.     return 0;
  6956.   if (TYPE_HIGH_BOUND (range_type) != hi)
  6957.     return 0;

  6958.   return 1;
  6959. }

  6960. /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
  6961.    a type following the GNAT encoding for describing array type
  6962.    indices, only carries redundant information.  */

  6963. static int
  6964. ada_is_redundant_index_type_desc (struct type *array_type,
  6965.                                   struct type *desc_type)
  6966. {
  6967.   struct type *this_layer = check_typedef (array_type);
  6968.   int i;

  6969.   for (i = 0; i < TYPE_NFIELDS (desc_type); i++)
  6970.     {
  6971.       if (!ada_is_redundant_range_encoding (TYPE_INDEX_TYPE (this_layer),
  6972.                                             TYPE_FIELD_TYPE (desc_type, i)))
  6973.         return 0;
  6974.       this_layer = check_typedef (TYPE_TARGET_TYPE (this_layer));
  6975.     }

  6976.   return 1;
  6977. }

  6978. /* Assuming that TYPE0 is an array type describing the type of a value
  6979.    at ADDR, and that DVAL describes a record containing any
  6980.    discriminants used in TYPE0, returns a type for the value that
  6981.    contains no dynamic components (that is, no components whose sizes
  6982.    are determined by run-time quantities).  Unless IGNORE_TOO_BIG is
  6983.    true, gives an error message if the resulting type's size is over
  6984.    varsize_limit.  */

  6985. static struct type *
  6986. to_fixed_array_type (struct type *type0, struct value *dval,
  6987.                      int ignore_too_big)
  6988. {
  6989.   struct type *index_type_desc;
  6990.   struct type *result;
  6991.   int constrained_packed_array_p;

  6992.   type0 = ada_check_typedef (type0);
  6993.   if (TYPE_FIXED_INSTANCE (type0))
  6994.     return type0;

  6995.   constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
  6996.   if (constrained_packed_array_p)
  6997.     type0 = decode_constrained_packed_array_type (type0);

  6998.   index_type_desc = ada_find_parallel_type (type0, "___XA");
  6999.   ada_fixup_array_indexes_type (index_type_desc);
  7000.   if (index_type_desc != NULL
  7001.       && ada_is_redundant_index_type_desc (type0, index_type_desc))
  7002.     {
  7003.       /* Ignore this ___XA parallel type, as it does not bring any
  7004.          useful information.  This allows us to avoid creating fixed
  7005.          versions of the array's index types, which would be identical
  7006.          to the original ones.  This, in turn, can also help avoid
  7007.          the creation of fixed versions of the array itself.  */
  7008.       index_type_desc = NULL;
  7009.     }

  7010.   if (index_type_desc == NULL)
  7011.     {
  7012.       struct type *elt_type0 = ada_check_typedef (TYPE_TARGET_TYPE (type0));

  7013.       /* NOTE: elt_type---the fixed version of elt_type0---should never
  7014.          depend on the contents of the array in properly constructed
  7015.          debugging data.  */
  7016.       /* Create a fixed version of the array element type.
  7017.          We're not providing the address of an element here,
  7018.          and thus the actual object value cannot be inspected to do
  7019.          the conversion.  This should not be a problem, since arrays of
  7020.          unconstrained objects are not allowed.  In particular, all
  7021.          the elements of an array of a tagged type should all be of
  7022.          the same type specified in the debugging info.  No need to
  7023.          consult the object tag.  */
  7024.       struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);

  7025.       /* Make sure we always create a new array type when dealing with
  7026.          packed array types, since we're going to fix-up the array
  7027.          type length and element bitsize a little further down.  */
  7028.       if (elt_type0 == elt_type && !constrained_packed_array_p)
  7029.         result = type0;
  7030.       else
  7031.         result = create_array_type (alloc_type_copy (type0),
  7032.                                     elt_type, TYPE_INDEX_TYPE (type0));
  7033.     }
  7034.   else
  7035.     {
  7036.       int i;
  7037.       struct type *elt_type0;

  7038.       elt_type0 = type0;
  7039.       for (i = TYPE_NFIELDS (index_type_desc); i > 0; i -= 1)
  7040.         elt_type0 = TYPE_TARGET_TYPE (elt_type0);

  7041.       /* NOTE: result---the fixed version of elt_type0---should never
  7042.          depend on the contents of the array in properly constructed
  7043.          debugging data.  */
  7044.       /* Create a fixed version of the array element type.
  7045.          We're not providing the address of an element here,
  7046.          and thus the actual object value cannot be inspected to do
  7047.          the conversion.  This should not be a problem, since arrays of
  7048.          unconstrained objects are not allowed.  In particular, all
  7049.          the elements of an array of a tagged type should all be of
  7050.          the same type specified in the debugging info.  No need to
  7051.          consult the object tag.  */
  7052.       result =
  7053.         ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);

  7054.       elt_type0 = type0;
  7055.       for (i = TYPE_NFIELDS (index_type_desc) - 1; i >= 0; i -= 1)
  7056.         {
  7057.           struct type *range_type =
  7058.             to_fixed_range_type (TYPE_FIELD_TYPE (index_type_desc, i), dval);

  7059.           result = create_array_type (alloc_type_copy (elt_type0),
  7060.                                       result, range_type);
  7061.           elt_type0 = TYPE_TARGET_TYPE (elt_type0);
  7062.         }
  7063.       if (!ignore_too_big && TYPE_LENGTH (result) > varsize_limit)
  7064.         error (_("array type with dynamic size is larger than varsize-limit"));
  7065.     }

  7066.   /* We want to preserve the type name.  This can be useful when
  7067.      trying to get the type name of a value that has already been
  7068.      printed (for instance, if the user did "print VAR; whatis $".  */
  7069.   TYPE_NAME (result) = TYPE_NAME (type0);

  7070.   if (constrained_packed_array_p)
  7071.     {
  7072.       /* So far, the resulting type has been created as if the original
  7073.          type was a regular (non-packed) array type.  As a result, the
  7074.          bitsize of the array elements needs to be set again, and the array
  7075.          length needs to be recomputed based on that bitsize.  */
  7076.       int len = TYPE_LENGTH (result) / TYPE_LENGTH (TYPE_TARGET_TYPE (result));
  7077.       int elt_bitsize = TYPE_FIELD_BITSIZE (type0, 0);

  7078.       TYPE_FIELD_BITSIZE (result, 0) = TYPE_FIELD_BITSIZE (type0, 0);
  7079.       TYPE_LENGTH (result) = len * elt_bitsize / HOST_CHAR_BIT;
  7080.       if (TYPE_LENGTH (result) * HOST_CHAR_BIT < len * elt_bitsize)
  7081.         TYPE_LENGTH (result)++;
  7082.     }

  7083.   TYPE_FIXED_INSTANCE (result) = 1;
  7084.   return result;
  7085. }


  7086. /* A standard type (containing no dynamically sized components)
  7087.    corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
  7088.    DVAL describes a record containing any discriminants used in TYPE0,
  7089.    and may be NULL if there are none, or if the object of type TYPE at
  7090.    ADDRESS or in VALADDR contains these discriminants.

  7091.    If CHECK_TAG is not null, in the case of tagged types, this function
  7092.    attempts to locate the object's tag and use it to compute the actual
  7093.    type.  However, when ADDRESS is null, we cannot use it to determine the
  7094.    location of the tag, and therefore compute the tagged type's actual type.
  7095.    So we return the tagged type without consulting the tag.  */

  7096. static struct type *
  7097. ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
  7098.                    CORE_ADDR address, struct value *dval, int check_tag)
  7099. {
  7100.   type = ada_check_typedef (type);
  7101.   switch (TYPE_CODE (type))
  7102.     {
  7103.     default:
  7104.       return type;
  7105.     case TYPE_CODE_STRUCT:
  7106.       {
  7107.         struct type *static_type = to_static_fixed_type (type);
  7108.         struct type *fixed_record_type =
  7109.           to_fixed_record_type (type, valaddr, address, NULL);

  7110.         /* If STATIC_TYPE is a tagged type and we know the object's address,
  7111.            then we can determine its tag, and compute the object's actual
  7112.            type from there.  Note that we have to use the fixed record
  7113.            type (the parent part of the record may have dynamic fields
  7114.            and the way the location of _tag is expressed may depend on
  7115.            them).  */

  7116.         if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
  7117.           {
  7118.             struct value *tag =
  7119.               value_tag_from_contents_and_address
  7120.               (fixed_record_type,
  7121.                valaddr,
  7122.                address);
  7123.             struct type *real_type = type_from_tag (tag);
  7124.             struct value *obj =
  7125.               value_from_contents_and_address (fixed_record_type,
  7126.                                                valaddr,
  7127.                                                address);
  7128.             fixed_record_type = value_type (obj);
  7129.             if (real_type != NULL)
  7130.               return to_fixed_record_type
  7131.                 (real_type, NULL,
  7132.                  value_address (ada_tag_value_at_base_address (obj)), NULL);
  7133.           }

  7134.         /* Check to see if there is a parallel ___XVZ variable.
  7135.            If there is, then it provides the actual size of our type.  */
  7136.         else if (ada_type_name (fixed_record_type) != NULL)
  7137.           {
  7138.             const char *name = ada_type_name (fixed_record_type);
  7139.             char *xvz_name = alloca (strlen (name) + 7 /* "___XVZ\0" */);
  7140.             int xvz_found = 0;
  7141.             LONGEST size;

  7142.             xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
  7143.             size = get_int_var_value (xvz_name, &xvz_found);
  7144.             if (xvz_found && TYPE_LENGTH (fixed_record_type) != size)
  7145.               {
  7146.                 fixed_record_type = copy_type (fixed_record_type);
  7147.                 TYPE_LENGTH (fixed_record_type) = size;

  7148.                 /* The FIXED_RECORD_TYPE may have be a stub.  We have
  7149.                    observed this when the debugging info is STABS, and
  7150.                    apparently it is something that is hard to fix.

  7151.                    In practice, we don't need the actual type definition
  7152.                    at all, because the presence of the XVZ variable allows us
  7153.                    to assume that there must be a XVS type as well, which we
  7154.                    should be able to use later, when we need the actual type
  7155.                    definition.

  7156.                    In the meantime, pretend that the "fixed" type we are
  7157.                    returning is NOT a stub, because this can cause trouble
  7158.                    when using this type to create new types targeting it.
  7159.                    Indeed, the associated creation routines often check
  7160.                    whether the target type is a stub and will try to replace
  7161.                    it, thus using a type with the wrong size.  This, in turn,
  7162.                    might cause the new type to have the wrong size too.
  7163.                    Consider the case of an array, for instance, where the size
  7164.                    of the array is computed from the number of elements in
  7165.                    our array multiplied by the size of its element.  */
  7166.                 TYPE_STUB (fixed_record_type) = 0;
  7167.               }
  7168.           }
  7169.         return fixed_record_type;
  7170.       }
  7171.     case TYPE_CODE_ARRAY:
  7172.       return to_fixed_array_type (type, dval, 1);
  7173.     case TYPE_CODE_UNION:
  7174.       if (dval == NULL)
  7175.         return type;
  7176.       else
  7177.         return to_fixed_variant_branch_type (type, valaddr, address, dval);
  7178.     }
  7179. }

  7180. /* The same as ada_to_fixed_type_1, except that it preserves the type
  7181.    if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.

  7182.    The typedef layer needs be preserved in order to differentiate between
  7183.    arrays and array pointers when both types are implemented using the same
  7184.    fat pointer.  In the array pointer case, the pointer is encoded as
  7185.    a typedef of the pointer type.  For instance, considering:

  7186.           type String_Access is access String;
  7187.           S1 : String_Access := null;

  7188.    To the debugger, S1 is defined as a typedef of type String.  But
  7189.    to the user, it is a pointer.  So if the user tries to print S1,
  7190.    we should not dereference the array, but print the array address
  7191.    instead.

  7192.    If we didn't preserve the typedef layer, we would lose the fact that
  7193.    the type is to be presented as a pointer (needs de-reference before
  7194.    being printed).  And we would also use the source-level type name.  */

  7195. struct type *
  7196. ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
  7197.                    CORE_ADDR address, struct value *dval, int check_tag)

  7198. {
  7199.   struct type *fixed_type =
  7200.     ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);

  7201.   /*  If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
  7202.       then preserve the typedef layer.

  7203.       Implementation note: We can only check the main-type portion of
  7204.       the TYPE and FIXED_TYPE, because eliminating the typedef layer
  7205.       from TYPE now returns a type that has the same instance flags
  7206.       as TYPE.  For instance, if TYPE is a "typedef const", and its
  7207.       target type is a "struct", then the typedef elimination will return
  7208.       a "const" version of the target type.  See check_typedef for more
  7209.       details about how the typedef layer elimination is done.

  7210.       brobecker/2010-11-19: It seems to me that the only case where it is
  7211.       useful to preserve the typedef layer is when dealing with fat pointers.
  7212.       Perhaps, we could add a check for that and preserve the typedef layer
  7213.       only in that situation.  But this seems unecessary so far, probably
  7214.       because we call check_typedef/ada_check_typedef pretty much everywhere.
  7215.       */
  7216.   if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF
  7217.       && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
  7218.           == TYPE_MAIN_TYPE (fixed_type)))
  7219.     return type;

  7220.   return fixed_type;
  7221. }

  7222. /* A standard (static-sized) type corresponding as well as possible to
  7223.    TYPE0, but based on no runtime data.  */

  7224. static struct type *
  7225. to_static_fixed_type (struct type *type0)
  7226. {
  7227.   struct type *type;

  7228.   if (type0 == NULL)
  7229.     return NULL;

  7230.   if (TYPE_FIXED_INSTANCE (type0))
  7231.     return type0;

  7232.   type0 = ada_check_typedef (type0);

  7233.   switch (TYPE_CODE (type0))
  7234.     {
  7235.     default:
  7236.       return type0;
  7237.     case TYPE_CODE_STRUCT:
  7238.       type = dynamic_template_type (type0);
  7239.       if (type != NULL)
  7240.         return template_to_static_fixed_type (type);
  7241.       else
  7242.         return template_to_static_fixed_type (type0);
  7243.     case TYPE_CODE_UNION:
  7244.       type = ada_find_parallel_type (type0, "___XVU");
  7245.       if (type != NULL)
  7246.         return template_to_static_fixed_type (type);
  7247.       else
  7248.         return template_to_static_fixed_type (type0);
  7249.     }
  7250. }

  7251. /* A static approximation of TYPE with all type wrappers removed.  */

  7252. static struct type *
  7253. static_unwrap_type (struct type *type)
  7254. {
  7255.   if (ada_is_aligner_type (type))
  7256.     {
  7257.       struct type *type1 = TYPE_FIELD_TYPE (ada_check_typedef (type), 0);
  7258.       if (ada_type_name (type1) == NULL)
  7259.         TYPE_NAME (type1) = ada_type_name (type);

  7260.       return static_unwrap_type (type1);
  7261.     }
  7262.   else
  7263.     {
  7264.       struct type *raw_real_type = ada_get_base_type (type);

  7265.       if (raw_real_type == type)
  7266.         return type;
  7267.       else
  7268.         return to_static_fixed_type (raw_real_type);
  7269.     }
  7270. }

  7271. /* In some cases, incomplete and private types require
  7272.    cross-references that are not resolved as records (for example,
  7273.       type Foo;
  7274.       type FooP is access Foo;
  7275.       V: FooP;
  7276.       type Foo is array ...;
  7277.    ).  In these cases, since there is no mechanism for producing
  7278.    cross-references to such types, we instead substitute for FooP a
  7279.    stub enumeration type that is nowhere resolved, and whose tag is
  7280.    the name of the actual type.  Call these types "non-record stubs".  */

  7281. /* A type equivalent to TYPE that is not a non-record stub, if one
  7282.    exists, otherwise TYPE.  */

  7283. struct type *
  7284. ada_check_typedef (struct type *type)
  7285. {
  7286.   if (type == NULL)
  7287.     return NULL;

  7288.   /* If our type is a typedef type of a fat pointer, then we're done.
  7289.      We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
  7290.      what allows us to distinguish between fat pointers that represent
  7291.      array types, and fat pointers that represent array access types
  7292.      (in both cases, the compiler implements them as fat pointers).  */
  7293.   if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF
  7294.       && is_thick_pntr (ada_typedef_target_type (type)))
  7295.     return type;

  7296.   CHECK_TYPEDEF (type);
  7297.   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_ENUM
  7298.       || !TYPE_STUB (type)
  7299.       || TYPE_TAG_NAME (type) == NULL)
  7300.     return type;
  7301.   else
  7302.     {
  7303.       const char *name = TYPE_TAG_NAME (type);
  7304.       struct type *type1 = ada_find_any_type (name);

  7305.       if (type1 == NULL)
  7306.         return type;

  7307.       /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
  7308.          stubs pointing to arrays, as we don't create symbols for array
  7309.          types, only for the typedef-to-array types).  If that's the case,
  7310.          strip the typedef layer.  */
  7311.       if (TYPE_CODE (type1) == TYPE_CODE_TYPEDEF)
  7312.         type1 = ada_check_typedef (type1);

  7313.       return type1;
  7314.     }
  7315. }

  7316. /* A value representing the data at VALADDR/ADDRESS as described by
  7317.    type TYPE0, but with a standard (static-sized) type that correctly
  7318.    describes it.  If VAL0 is not NULL and TYPE0 already is a standard
  7319.    type, then return VAL0 [this feature is simply to avoid redundant
  7320.    creation of struct values].  */

  7321. static struct value *
  7322. ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
  7323.                            struct value *val0)
  7324. {
  7325.   struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);

  7326.   if (type == type0 && val0 != NULL)
  7327.     return val0;
  7328.   else
  7329.     return value_from_contents_and_address (type, 0, address);
  7330. }

  7331. /* A value representing VAL, but with a standard (static-sized) type
  7332.    that correctly describes it.  Does not necessarily create a new
  7333.    value.  */

  7334. struct value *
  7335. ada_to_fixed_value (struct value *val)
  7336. {
  7337.   val = unwrap_value (val);
  7338.   val = ada_to_fixed_value_create (value_type (val),
  7339.                                       value_address (val),
  7340.                                       val);
  7341.   return val;
  7342. }


  7343. /* Attributes */

  7344. /* Table mapping attribute numbers to names.
  7345.    NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h.  */

  7346. static const char *attribute_names[] = {
  7347.   "<?>",

  7348.   "first",
  7349.   "last",
  7350.   "length",
  7351.   "image",
  7352.   "max",
  7353.   "min",
  7354.   "modulus",
  7355.   "pos",
  7356.   "size",
  7357.   "tag",
  7358.   "val",
  7359.   0
  7360. };

  7361. const char *
  7362. ada_attribute_name (enum exp_opcode n)
  7363. {
  7364.   if (n >= OP_ATR_FIRST && n <= (int) OP_ATR_VAL)
  7365.     return attribute_names[n - OP_ATR_FIRST + 1];
  7366.   else
  7367.     return attribute_names[0];
  7368. }

  7369. /* Evaluate the 'POS attribute applied to ARG.  */

  7370. static LONGEST
  7371. pos_atr (struct value *arg)
  7372. {
  7373.   struct value *val = coerce_ref (arg);
  7374.   struct type *type = value_type (val);

  7375.   if (!discrete_type_p (type))
  7376.     error (_("'POS only defined on discrete types"));

  7377.   if (TYPE_CODE (type) == TYPE_CODE_ENUM)
  7378.     {
  7379.       int i;
  7380.       LONGEST v = value_as_long (val);

  7381.       for (i = 0; i < TYPE_NFIELDS (type); i += 1)
  7382.         {
  7383.           if (v == TYPE_FIELD_ENUMVAL (type, i))
  7384.             return i;
  7385.         }
  7386.       error (_("enumeration value is invalid: can't find 'POS"));
  7387.     }
  7388.   else
  7389.     return value_as_long (val);
  7390. }

  7391. static struct value *
  7392. value_pos_atr (struct type *type, struct value *arg)
  7393. {
  7394.   return value_from_longest (type, pos_atr (arg));
  7395. }

  7396. /* Evaluate the TYPE'VAL attribute applied to ARG.  */

  7397. static struct value *
  7398. value_val_atr (struct type *type, struct value *arg)
  7399. {
  7400.   if (!discrete_type_p (type))
  7401.     error (_("'VAL only defined on discrete types"));
  7402.   if (!integer_type_p (value_type (arg)))
  7403.     error (_("'VAL requires integral argument"));

  7404.   if (TYPE_CODE (type) == TYPE_CODE_ENUM)
  7405.     {
  7406.       long pos = value_as_long (arg);

  7407.       if (pos < 0 || pos >= TYPE_NFIELDS (type))
  7408.         error (_("argument to 'VAL out of range"));
  7409.       return value_from_longest (type, TYPE_FIELD_ENUMVAL (type, pos));
  7410.     }
  7411.   else
  7412.     return value_from_longest (type, value_as_long (arg));
  7413. }


  7414.                                 /* Evaluation */

  7415. /* True if TYPE appears to be an Ada character type.
  7416.    [At the moment, this is true only for Character and Wide_Character;
  7417.    It is a heuristic test that could stand improvement].  */

  7418. int
  7419. ada_is_character_type (struct type *type)
  7420. {
  7421.   const char *name;

  7422.   /* If the type code says it's a character, then assume it really is,
  7423.      and don't check any further.  */
  7424.   if (TYPE_CODE (type) == TYPE_CODE_CHAR)
  7425.     return 1;

  7426.   /* Otherwise, assume it's a character type iff it is a discrete type
  7427.      with a known character type name.  */
  7428.   name = ada_type_name (type);
  7429.   return (name != NULL
  7430.           && (TYPE_CODE (type) == TYPE_CODE_INT
  7431.               || TYPE_CODE (type) == TYPE_CODE_RANGE)
  7432.           && (strcmp (name, "character") == 0
  7433.               || strcmp (name, "wide_character") == 0
  7434.               || strcmp (name, "wide_wide_character") == 0
  7435.               || strcmp (name, "unsigned char") == 0));
  7436. }

  7437. /* True if TYPE appears to be an Ada string type.  */

  7438. int
  7439. ada_is_string_type (struct type *type)
  7440. {
  7441.   type = ada_check_typedef (type);
  7442.   if (type != NULL
  7443.       && TYPE_CODE (type) != TYPE_CODE_PTR
  7444.       && (ada_is_simple_array_type (type)
  7445.           || ada_is_array_descriptor_type (type))
  7446.       && ada_array_arity (type) == 1)
  7447.     {
  7448.       struct type *elttype = ada_array_element_type (type, 1);

  7449.       return ada_is_character_type (elttype);
  7450.     }
  7451.   else
  7452.     return 0;
  7453. }

  7454. /* The compiler sometimes provides a parallel XVS type for a given
  7455.    PAD type.  Normally, it is safe to follow the PAD type directly,
  7456.    but older versions of the compiler have a bug that causes the offset
  7457.    of its "F" field to be wrong.  Following that field in that case
  7458.    would lead to incorrect results, but this can be worked around
  7459.    by ignoring the PAD type and using the associated XVS type instead.

  7460.    Set to True if the debugger should trust the contents of PAD types.
  7461.    Otherwise, ignore the PAD type if there is a parallel XVS type.  */
  7462. static int trust_pad_over_xvs = 1;

  7463. /* True if TYPE is a struct type introduced by the compiler to force the
  7464.    alignment of a value.  Such types have a single field with a
  7465.    distinctive name.  */

  7466. int
  7467. ada_is_aligner_type (struct type *type)
  7468. {
  7469.   type = ada_check_typedef (type);

  7470.   if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
  7471.     return 0;

  7472.   return (TYPE_CODE (type) == TYPE_CODE_STRUCT
  7473.           && TYPE_NFIELDS (type) == 1
  7474.           && strcmp (TYPE_FIELD_NAME (type, 0), "F") == 0);
  7475. }

  7476. /* If there is an ___XVS-convention type parallel to SUBTYPE, return
  7477.    the parallel type.  */

  7478. struct type *
  7479. ada_get_base_type (struct type *raw_type)
  7480. {
  7481.   struct type *real_type_namer;
  7482.   struct type *raw_real_type;

  7483.   if (raw_type == NULL || TYPE_CODE (raw_type) != TYPE_CODE_STRUCT)
  7484.     return raw_type;

  7485.   if (ada_is_aligner_type (raw_type))
  7486.     /* The encoding specifies that we should always use the aligner type.
  7487.        So, even if this aligner type has an associated XVS type, we should
  7488.        simply ignore it.

  7489.        According to the compiler gurus, an XVS type parallel to an aligner
  7490.        type may exist because of a stabs limitation.  In stabs, aligner
  7491.        types are empty because the field has a variable-sized type, and
  7492.        thus cannot actually be used as an aligner type.  As a result,
  7493.        we need the associated parallel XVS type to decode the type.
  7494.        Since the policy in the compiler is to not change the internal
  7495.        representation based on the debugging info format, we sometimes
  7496.        end up having a redundant XVS type parallel to the aligner type.  */
  7497.     return raw_type;

  7498.   real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
  7499.   if (real_type_namer == NULL
  7500.       || TYPE_CODE (real_type_namer) != TYPE_CODE_STRUCT
  7501.       || TYPE_NFIELDS (real_type_namer) != 1)
  7502.     return raw_type;

  7503.   if (TYPE_CODE (TYPE_FIELD_TYPE (real_type_namer, 0)) != TYPE_CODE_REF)
  7504.     {
  7505.       /* This is an older encoding form where the base type needs to be
  7506.          looked up by name.  We prefer the newer enconding because it is
  7507.          more efficient.  */
  7508.       raw_real_type = ada_find_any_type (TYPE_FIELD_NAME (real_type_namer, 0));
  7509.       if (raw_real_type == NULL)
  7510.         return raw_type;
  7511.       else
  7512.         return raw_real_type;
  7513.     }

  7514.   /* The field in our XVS type is a reference to the base type.  */
  7515.   return TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (real_type_namer, 0));
  7516. }

  7517. /* The type of value designated by TYPE, with all aligners removed.  */

  7518. struct type *
  7519. ada_aligned_type (struct type *type)
  7520. {
  7521.   if (ada_is_aligner_type (type))
  7522.     return ada_aligned_type (TYPE_FIELD_TYPE (type, 0));
  7523.   else
  7524.     return ada_get_base_type (type);
  7525. }


  7526. /* The address of the aligned value in an object at address VALADDR
  7527.    having type TYPE.  Assumes ada_is_aligner_type (TYPE).  */

  7528. const gdb_byte *
  7529. ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
  7530. {
  7531.   if (ada_is_aligner_type (type))
  7532.     return ada_aligned_value_addr (TYPE_FIELD_TYPE (type, 0),
  7533.                                    valaddr +
  7534.                                    TYPE_FIELD_BITPOS (type,
  7535.                                                       0) / TARGET_CHAR_BIT);
  7536.   else
  7537.     return valaddr;
  7538. }



  7539. /* The printed representation of an enumeration literal with encoded
  7540.    name NAME.  The value is good to the next call of ada_enum_name.  */
  7541. const char *
  7542. ada_enum_name (const char *name)
  7543. {
  7544.   static char *result;
  7545.   static size_t result_len = 0;
  7546.   char *tmp;

  7547.   /* First, unqualify the enumeration name:
  7548.      1. Search for the last '.' character.  If we find one, then skip
  7549.      all the preceding characters, the unqualified name starts
  7550.      right after that dot.
  7551.      2. Otherwise, we may be debugging on a target where the compiler
  7552.      translates dots into "__".  Search forward for double underscores,
  7553.      but stop searching when we hit an overloading suffix, which is
  7554.      of the form "__" followed by digits.  */

  7555.   tmp = strrchr (name, '.');
  7556.   if (tmp != NULL)
  7557.     name = tmp + 1;
  7558.   else
  7559.     {
  7560.       while ((tmp = strstr (name, "__")) != NULL)
  7561.         {
  7562.           if (isdigit (tmp[2]))
  7563.             break;
  7564.           else
  7565.             name = tmp + 2;
  7566.         }
  7567.     }

  7568.   if (name[0] == 'Q')
  7569.     {
  7570.       int v;

  7571.       if (name[1] == 'U' || name[1] == 'W')
  7572.         {
  7573.           if (sscanf (name + 2, "%x", &v) != 1)
  7574.             return name;
  7575.         }
  7576.       else
  7577.         return name;

  7578.       GROW_VECT (result, result_len, 16);
  7579.       if (isascii (v) && isprint (v))
  7580.         xsnprintf (result, result_len, "'%c'", v);
  7581.       else if (name[1] == 'U')
  7582.         xsnprintf (result, result_len, "[\"%02x\"]", v);
  7583.       else
  7584.         xsnprintf (result, result_len, "[\"%04x\"]", v);

  7585.       return result;
  7586.     }
  7587.   else
  7588.     {
  7589.       tmp = strstr (name, "__");
  7590.       if (tmp == NULL)
  7591.         tmp = strstr (name, "$");
  7592.       if (tmp != NULL)
  7593.         {
  7594.           GROW_VECT (result, result_len, tmp - name + 1);
  7595.           strncpy (result, name, tmp - name);
  7596.           result[tmp - name] = '\0';
  7597.           return result;
  7598.         }

  7599.       return name;
  7600.     }
  7601. }

  7602. /* Evaluate the subexpression of EXP starting at *POS as for
  7603.    evaluate_type, updating *POS to point just past the evaluated
  7604.    expression.  */

  7605. static struct value *
  7606. evaluate_subexp_type (struct expression *exp, int *pos)
  7607. {
  7608.   return evaluate_subexp (NULL_TYPE, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
  7609. }

  7610. /* If VAL is wrapped in an aligner or subtype wrapper, return the
  7611.    value it wraps.  */

  7612. static struct value *
  7613. unwrap_value (struct value *val)
  7614. {
  7615.   struct type *type = ada_check_typedef (value_type (val));

  7616.   if (ada_is_aligner_type (type))
  7617.     {
  7618.       struct value *v = ada_value_struct_elt (val, "F", 0);
  7619.       struct type *val_type = ada_check_typedef (value_type (v));

  7620.       if (ada_type_name (val_type) == NULL)
  7621.         TYPE_NAME (val_type) = ada_type_name (type);

  7622.       return unwrap_value (v);
  7623.     }
  7624.   else
  7625.     {
  7626.       struct type *raw_real_type =
  7627.         ada_check_typedef (ada_get_base_type (type));

  7628.       /* If there is no parallel XVS or XVE type, then the value is
  7629.          already unwrapped.  Return it without further modification.  */
  7630.       if ((type == raw_real_type)
  7631.           && ada_find_parallel_type (type, "___XVE") == NULL)
  7632.         return val;

  7633.       return
  7634.         coerce_unspec_val_to_type
  7635.         (val, ada_to_fixed_type (raw_real_type, 0,
  7636.                                  value_address (val),
  7637.                                  NULL, 1));
  7638.     }
  7639. }

  7640. static struct value *
  7641. cast_to_fixed (struct type *type, struct value *arg)
  7642. {
  7643.   LONGEST val;

  7644.   if (type == value_type (arg))
  7645.     return arg;
  7646.   else if (ada_is_fixed_point_type (value_type (arg)))
  7647.     val = ada_float_to_fixed (type,
  7648.                               ada_fixed_to_float (value_type (arg),
  7649.                                                   value_as_long (arg)));
  7650.   else
  7651.     {
  7652.       DOUBLEST argd = value_as_double (arg);

  7653.       val = ada_float_to_fixed (type, argd);
  7654.     }

  7655.   return value_from_longest (type, val);
  7656. }

  7657. static struct value *
  7658. cast_from_fixed (struct type *type, struct value *arg)
  7659. {
  7660.   DOUBLEST val = ada_fixed_to_float (value_type (arg),
  7661.                                      value_as_long (arg));

  7662.   return value_from_double (type, val);
  7663. }

  7664. /* Given two array types T1 and T2, return nonzero iff both arrays
  7665.    contain the same number of elements.  */

  7666. static int
  7667. ada_same_array_size_p (struct type *t1, struct type *t2)
  7668. {
  7669.   LONGEST lo1, hi1, lo2, hi2;

  7670.   /* Get the array bounds in order to verify that the size of
  7671.      the two arrays match.  */
  7672.   if (!get_array_bounds (t1, &lo1, &hi1)
  7673.       || !get_array_bounds (t2, &lo2, &hi2))
  7674.     error (_("unable to determine array bounds"));

  7675.   /* To make things easier for size comparison, normalize a bit
  7676.      the case of empty arrays by making sure that the difference
  7677.      between upper bound and lower bound is always -1.  */
  7678.   if (lo1 > hi1)
  7679.     hi1 = lo1 - 1;
  7680.   if (lo2 > hi2)
  7681.     hi2 = lo2 - 1;

  7682.   return (hi1 - lo1 == hi2 - lo2);
  7683. }

  7684. /* Assuming that VAL is an array of integrals, and TYPE represents
  7685.    an array with the same number of elements, but with wider integral
  7686.    elements, return an array "casted" to TYPE.  In practice, this
  7687.    means that the returned array is built by casting each element
  7688.    of the original array into TYPE's (wider) element type.  */

  7689. static struct value *
  7690. ada_promote_array_of_integrals (struct type *type, struct value *val)
  7691. {
  7692.   struct type *elt_type = TYPE_TARGET_TYPE (type);
  7693.   LONGEST lo, hi;
  7694.   struct value *res;
  7695.   LONGEST i;

  7696.   /* Verify that both val and type are arrays of scalars, and
  7697.      that the size of val's elements is smaller than the size
  7698.      of type's element.  */
  7699.   gdb_assert (TYPE_CODE (type) == TYPE_CODE_ARRAY);
  7700.   gdb_assert (is_integral_type (TYPE_TARGET_TYPE (type)));
  7701.   gdb_assert (TYPE_CODE (value_type (val)) == TYPE_CODE_ARRAY);
  7702.   gdb_assert (is_integral_type (TYPE_TARGET_TYPE (value_type (val))));
  7703.   gdb_assert (TYPE_LENGTH (TYPE_TARGET_TYPE (type))
  7704.               > TYPE_LENGTH (TYPE_TARGET_TYPE (value_type (val))));

  7705.   if (!get_array_bounds (type, &lo, &hi))
  7706.     error (_("unable to determine array bounds"));

  7707.   res = allocate_value (type);

  7708.   /* Promote each array element.  */
  7709.   for (i = 0; i < hi - lo + 1; i++)
  7710.     {
  7711.       struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));

  7712.       memcpy (value_contents_writeable (res) + (i * TYPE_LENGTH (elt_type)),
  7713.               value_contents_all (elt), TYPE_LENGTH (elt_type));
  7714.     }

  7715.   return res;
  7716. }

  7717. /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
  7718.    return the converted value.  */

  7719. static struct value *
  7720. coerce_for_assign (struct type *type, struct value *val)
  7721. {
  7722.   struct type *type2 = value_type (val);

  7723.   if (type == type2)
  7724.     return val;

  7725.   type2 = ada_check_typedef (type2);
  7726.   type = ada_check_typedef (type);

  7727.   if (TYPE_CODE (type2) == TYPE_CODE_PTR
  7728.       && TYPE_CODE (type) == TYPE_CODE_ARRAY)
  7729.     {
  7730.       val = ada_value_ind (val);
  7731.       type2 = value_type (val);
  7732.     }

  7733.   if (TYPE_CODE (type2) == TYPE_CODE_ARRAY
  7734.       && TYPE_CODE (type) == TYPE_CODE_ARRAY)
  7735.     {
  7736.       if (!ada_same_array_size_p (type, type2))
  7737.         error (_("cannot assign arrays of different length"));

  7738.       if (is_integral_type (TYPE_TARGET_TYPE (type))
  7739.           && is_integral_type (TYPE_TARGET_TYPE (type2))
  7740.           && TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
  7741.                < TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
  7742.         {
  7743.           /* Allow implicit promotion of the array elements to
  7744.              a wider type.  */
  7745.           return ada_promote_array_of_integrals (type, val);
  7746.         }

  7747.       if (TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
  7748.           != TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
  7749.         error (_("Incompatible types in assignment"));
  7750.       deprecated_set_value_type (val, type);
  7751.     }
  7752.   return val;
  7753. }

  7754. static struct value *
  7755. ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
  7756. {
  7757.   struct value *val;
  7758.   struct type *type1, *type2;
  7759.   LONGEST v, v1, v2;

  7760.   arg1 = coerce_ref (arg1);
  7761.   arg2 = coerce_ref (arg2);
  7762.   type1 = get_base_type (ada_check_typedef (value_type (arg1)));
  7763.   type2 = get_base_type (ada_check_typedef (value_type (arg2)));

  7764.   if (TYPE_CODE (type1) != TYPE_CODE_INT
  7765.       || TYPE_CODE (type2) != TYPE_CODE_INT)
  7766.     return value_binop (arg1, arg2, op);

  7767.   switch (op)
  7768.     {
  7769.     case BINOP_MOD:
  7770.     case BINOP_DIV:
  7771.     case BINOP_REM:
  7772.       break;
  7773.     default:
  7774.       return value_binop (arg1, arg2, op);
  7775.     }

  7776.   v2 = value_as_long (arg2);
  7777.   if (v2 == 0)
  7778.     error (_("second operand of %s must not be zero."), op_string (op));

  7779.   if (TYPE_UNSIGNED (type1) || op == BINOP_MOD)
  7780.     return value_binop (arg1, arg2, op);

  7781.   v1 = value_as_long (arg1);
  7782.   switch (op)
  7783.     {
  7784.     case BINOP_DIV:
  7785.       v = v1 / v2;
  7786.       if (!TRUNCATION_TOWARDS_ZERO && v1 * (v1 % v2) < 0)
  7787.         v += v > 0 ? -1 : 1;
  7788.       break;
  7789.     case BINOP_REM:
  7790.       v = v1 % v2;
  7791.       if (v * v1 < 0)
  7792.         v -= v2;
  7793.       break;
  7794.     default:
  7795.       /* Should not reach this point.  */
  7796.       v = 0;
  7797.     }

  7798.   val = allocate_value (type1);
  7799.   store_unsigned_integer (value_contents_raw (val),
  7800.                           TYPE_LENGTH (value_type (val)),
  7801.                           gdbarch_byte_order (get_type_arch (type1)), v);
  7802.   return val;
  7803. }

  7804. static int
  7805. ada_value_equal (struct value *arg1, struct value *arg2)
  7806. {
  7807.   if (ada_is_direct_array_type (value_type (arg1))
  7808.       || ada_is_direct_array_type (value_type (arg2)))
  7809.     {
  7810.       /* Automatically dereference any array reference before
  7811.          we attempt to perform the comparison.  */
  7812.       arg1 = ada_coerce_ref (arg1);
  7813.       arg2 = ada_coerce_ref (arg2);

  7814.       arg1 = ada_coerce_to_simple_array (arg1);
  7815.       arg2 = ada_coerce_to_simple_array (arg2);
  7816.       if (TYPE_CODE (value_type (arg1)) != TYPE_CODE_ARRAY
  7817.           || TYPE_CODE (value_type (arg2)) != TYPE_CODE_ARRAY)
  7818.         error (_("Attempt to compare array with non-array"));
  7819.       /* FIXME: The following works only for types whose
  7820.          representations use all bits (no padding or undefined bits)
  7821.          and do not have user-defined equality.  */
  7822.       return
  7823.         TYPE_LENGTH (value_type (arg1)) == TYPE_LENGTH (value_type (arg2))
  7824.         && memcmp (value_contents (arg1), value_contents (arg2),
  7825.                    TYPE_LENGTH (value_type (arg1))) == 0;
  7826.     }
  7827.   return value_equal (arg1, arg2);
  7828. }

  7829. /* Total number of component associations in the aggregate starting at
  7830.    index PC in EXP.  Assumes that index PC is the start of an
  7831.    OP_AGGREGATE.  */

  7832. static int
  7833. num_component_specs (struct expression *exp, int pc)
  7834. {
  7835.   int n, m, i;

  7836.   m = exp->elts[pc + 1].longconst;
  7837.   pc += 3;
  7838.   n = 0;
  7839.   for (i = 0; i < m; i += 1)
  7840.     {
  7841.       switch (exp->elts[pc].opcode)
  7842.         {
  7843.         default:
  7844.           n += 1;
  7845.           break;
  7846.         case OP_CHOICES:
  7847.           n += exp->elts[pc + 1].longconst;
  7848.           break;
  7849.         }
  7850.       ada_evaluate_subexp (NULL, exp, &pc, EVAL_SKIP);
  7851.     }
  7852.   return n;
  7853. }

  7854. /* Assign the result of evaluating EXP starting at *POS to the INDEXth
  7855.    component of LHS (a simple array or a record), updating *POS past
  7856.    the expression, assuming that LHS is contained in CONTAINER.  Does
  7857.    not modify the inferior's memory, nor does it modify LHS (unless
  7858.    LHS == CONTAINER).  */

  7859. static void
  7860. assign_component (struct value *container, struct value *lhs, LONGEST index,
  7861.                   struct expression *exp, int *pos)
  7862. {
  7863.   struct value *mark = value_mark ();
  7864.   struct value *elt;

  7865.   if (TYPE_CODE (value_type (lhs)) == TYPE_CODE_ARRAY)
  7866.     {
  7867.       struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
  7868.       struct value *index_val = value_from_longest (index_type, index);

  7869.       elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
  7870.     }
  7871.   else
  7872.     {
  7873.       elt = ada_index_struct_field (index, lhs, 0, value_type (lhs));
  7874.       elt = ada_to_fixed_value (elt);
  7875.     }

  7876.   if (exp->elts[*pos].opcode == OP_AGGREGATE)
  7877.     assign_aggregate (container, elt, exp, pos, EVAL_NORMAL);
  7878.   else
  7879.     value_assign_to_component (container, elt,
  7880.                                ada_evaluate_subexp (NULL, exp, pos,
  7881.                                                     EVAL_NORMAL));

  7882.   value_free_to_mark (mark);
  7883. }

  7884. /* Assuming that LHS represents an lvalue having a record or array
  7885.    type, and EXP->ELTS[*POS] is an OP_AGGREGATE, evaluate an assignment
  7886.    of that aggregate's value to LHS, advancing *POS past the
  7887.    aggregate.  NOSIDE is as for evaluate_subexp.  CONTAINER is an
  7888.    lvalue containing LHS (possibly LHS itself).  Does not modify
  7889.    the inferior's memory, nor does it modify the contents of
  7890.    LHS (unless == CONTAINER).  Returns the modified CONTAINER.  */

  7891. static struct value *
  7892. assign_aggregate (struct value *container,
  7893.                   struct value *lhs, struct expression *exp,
  7894.                   int *pos, enum noside noside)
  7895. {
  7896.   struct type *lhs_type;
  7897.   int n = exp->elts[*pos+1].longconst;
  7898.   LONGEST low_index, high_index;
  7899.   int num_specs;
  7900.   LONGEST *indices;
  7901.   int max_indices, num_indices;
  7902.   int i;

  7903.   *pos += 3;
  7904.   if (noside != EVAL_NORMAL)
  7905.     {
  7906.       for (i = 0; i < n; i += 1)
  7907.         ada_evaluate_subexp (NULL, exp, pos, noside);
  7908.       return container;
  7909.     }

  7910.   container = ada_coerce_ref (container);
  7911.   if (ada_is_direct_array_type (value_type (container)))
  7912.     container = ada_coerce_to_simple_array (container);
  7913.   lhs = ada_coerce_ref (lhs);
  7914.   if (!deprecated_value_modifiable (lhs))
  7915.     error (_("Left operand of assignment is not a modifiable lvalue."));

  7916.   lhs_type = value_type (lhs);
  7917.   if (ada_is_direct_array_type (lhs_type))
  7918.     {
  7919.       lhs = ada_coerce_to_simple_array (lhs);
  7920.       lhs_type = value_type (lhs);
  7921.       low_index = TYPE_ARRAY_LOWER_BOUND_VALUE (lhs_type);
  7922.       high_index = TYPE_ARRAY_UPPER_BOUND_VALUE (lhs_type);
  7923.     }
  7924.   else if (TYPE_CODE (lhs_type) == TYPE_CODE_STRUCT)
  7925.     {
  7926.       low_index = 0;
  7927.       high_index = num_visible_fields (lhs_type) - 1;
  7928.     }
  7929.   else
  7930.     error (_("Left-hand side must be array or record."));

  7931.   num_specs = num_component_specs (exp, *pos - 3);
  7932.   max_indices = 4 * num_specs + 4;
  7933.   indices = alloca (max_indices * sizeof (indices[0]));
  7934.   indices[0] = indices[1] = low_index - 1;
  7935.   indices[2] = indices[3] = high_index + 1;
  7936.   num_indices = 4;

  7937.   for (i = 0; i < n; i += 1)
  7938.     {
  7939.       switch (exp->elts[*pos].opcode)
  7940.         {
  7941.           case OP_CHOICES:
  7942.             aggregate_assign_from_choices (container, lhs, exp, pos, indices,
  7943.                                            &num_indices, max_indices,
  7944.                                            low_index, high_index);
  7945.             break;
  7946.           case OP_POSITIONAL:
  7947.             aggregate_assign_positional (container, lhs, exp, pos, indices,
  7948.                                          &num_indices, max_indices,
  7949.                                          low_index, high_index);
  7950.             break;
  7951.           case OP_OTHERS:
  7952.             if (i != n-1)
  7953.               error (_("Misplaced 'others' clause"));
  7954.             aggregate_assign_others (container, lhs, exp, pos, indices,
  7955.                                      num_indices, low_index, high_index);
  7956.             break;
  7957.           default:
  7958.             error (_("Internal error: bad aggregate clause"));
  7959.         }
  7960.     }

  7961.   return container;
  7962. }

  7963. /* Assign into the component of LHS indexed by the OP_POSITIONAL
  7964.    construct at *POS, updating *POS past the construct, given that
  7965.    the positions are relative to lower bound LOW, where HIGH is the
  7966.    upper bound.  Record the position in INDICES[0 .. MAX_INDICES-1]
  7967.    updating *NUM_INDICES as needed.  CONTAINER is as for
  7968.    assign_aggregate.  */
  7969. static void
  7970. aggregate_assign_positional (struct value *container,
  7971.                              struct value *lhs, struct expression *exp,
  7972.                              int *pos, LONGEST *indices, int *num_indices,
  7973.                              int max_indices, LONGEST low, LONGEST high)
  7974. {
  7975.   LONGEST ind = longest_to_int (exp->elts[*pos + 1].longconst) + low;

  7976.   if (ind - 1 == high)
  7977.     warning (_("Extra components in aggregate ignored."));
  7978.   if (ind <= high)
  7979.     {
  7980.       add_component_interval (ind, ind, indices, num_indices, max_indices);
  7981.       *pos += 3;
  7982.       assign_component (container, lhs, ind, exp, pos);
  7983.     }
  7984.   else
  7985.     ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
  7986. }

  7987. /* Assign into the components of LHS indexed by the OP_CHOICES
  7988.    construct at *POS, updating *POS past the construct, given that
  7989.    the allowable indices are LOW..HIGH.  Record the indices assigned
  7990.    to in INDICES[0 .. MAX_INDICES-1], updating *NUM_INDICES as
  7991.    needed.  CONTAINER is as for assign_aggregate.  */
  7992. static void
  7993. aggregate_assign_from_choices (struct value *container,
  7994.                                struct value *lhs, struct expression *exp,
  7995.                                int *pos, LONGEST *indices, int *num_indices,
  7996.                                int max_indices, LONGEST low, LONGEST high)
  7997. {
  7998.   int j;
  7999.   int n_choices = longest_to_int (exp->elts[*pos+1].longconst);
  8000.   int choice_pos, expr_pc;
  8001.   int is_array = ada_is_direct_array_type (value_type (lhs));

  8002.   choice_pos = *pos += 3;

  8003.   for (j = 0; j < n_choices; j += 1)
  8004.     ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
  8005.   expr_pc = *pos;
  8006.   ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);

  8007.   for (j = 0; j < n_choices; j += 1)
  8008.     {
  8009.       LONGEST lower, upper;
  8010.       enum exp_opcode op = exp->elts[choice_pos].opcode;

  8011.       if (op == OP_DISCRETE_RANGE)
  8012.         {
  8013.           choice_pos += 1;
  8014.           lower = value_as_long (ada_evaluate_subexp (NULL, exp, pos,
  8015.                                                       EVAL_NORMAL));
  8016.           upper = value_as_long (ada_evaluate_subexp (NULL, exp, pos,
  8017.                                                       EVAL_NORMAL));
  8018.         }
  8019.       else if (is_array)
  8020.         {
  8021.           lower = value_as_long (ada_evaluate_subexp (NULL, exp, &choice_pos,
  8022.                                                       EVAL_NORMAL));
  8023.           upper = lower;
  8024.         }
  8025.       else
  8026.         {
  8027.           int ind;
  8028.           const char *name;

  8029.           switch (op)
  8030.             {
  8031.             case OP_NAME:
  8032.               name = &exp->elts[choice_pos + 2].string;
  8033.               break;
  8034.             case OP_VAR_VALUE:
  8035.               name = SYMBOL_NATURAL_NAME (exp->elts[choice_pos + 2].symbol);
  8036.               break;
  8037.             default:
  8038.               error (_("Invalid record component association."));
  8039.             }
  8040.           ada_evaluate_subexp (NULL, exp, &choice_pos, EVAL_SKIP);
  8041.           ind = 0;
  8042.           if (! find_struct_field (name, value_type (lhs), 0,
  8043.                                    NULL, NULL, NULL, NULL, &ind))
  8044.             error (_("Unknown component name: %s."), name);
  8045.           lower = upper = ind;
  8046.         }

  8047.       if (lower <= upper && (lower < low || upper > high))
  8048.         error (_("Index in component association out of bounds."));

  8049.       add_component_interval (lower, upper, indices, num_indices,
  8050.                               max_indices);
  8051.       while (lower <= upper)
  8052.         {
  8053.           int pos1;

  8054.           pos1 = expr_pc;
  8055.           assign_component (container, lhs, lower, exp, &pos1);
  8056.           lower += 1;
  8057.         }
  8058.     }
  8059. }

  8060. /* Assign the value of the expression in the OP_OTHERS construct in
  8061.    EXP at *POS into the components of LHS indexed from LOW .. HIGH that
  8062.    have not been previously assigned.  The index intervals already assigned
  8063.    are in INDICES[0 .. NUM_INDICES-1].  Updates *POS to after the
  8064.    OP_OTHERS clause.  CONTAINER is as for assign_aggregate.  */
  8065. static void
  8066. aggregate_assign_others (struct value *container,
  8067.                          struct value *lhs, struct expression *exp,
  8068.                          int *pos, LONGEST *indices, int num_indices,
  8069.                          LONGEST low, LONGEST high)
  8070. {
  8071.   int i;
  8072.   int expr_pc = *pos + 1;

  8073.   for (i = 0; i < num_indices - 2; i += 2)
  8074.     {
  8075.       LONGEST ind;

  8076.       for (ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
  8077.         {
  8078.           int localpos;

  8079.           localpos = expr_pc;
  8080.           assign_component (container, lhs, ind, exp, &localpos);
  8081.         }
  8082.     }
  8083.   ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
  8084. }

  8085. /* Add the interval [LOW .. HIGH] to the sorted set of intervals
  8086.    [ INDICES[0] .. INDICES[1] ],..., [ INDICES[*SIZE-2] .. INDICES[*SIZE-1] ],
  8087.    modifying *SIZE as needed.  It is an error if *SIZE exceeds
  8088.    MAX_SIZE.  The resulting intervals do not overlap.  */
  8089. static void
  8090. add_component_interval (LONGEST low, LONGEST high,
  8091.                         LONGEST* indices, int *size, int max_size)
  8092. {
  8093.   int i, j;

  8094.   for (i = 0; i < *size; i += 2) {
  8095.     if (high >= indices[i] && low <= indices[i + 1])
  8096.       {
  8097.         int kh;

  8098.         for (kh = i + 2; kh < *size; kh += 2)
  8099.           if (high < indices[kh])
  8100.             break;
  8101.         if (low < indices[i])
  8102.           indices[i] = low;
  8103.         indices[i + 1] = indices[kh - 1];
  8104.         if (high > indices[i + 1])
  8105.           indices[i + 1] = high;
  8106.         memcpy (indices + i + 2, indices + kh, *size - kh);
  8107.         *size -= kh - i - 2;
  8108.         return;
  8109.       }
  8110.     else if (high < indices[i])
  8111.       break;
  8112.   }

  8113.   if (*size == max_size)
  8114.     error (_("Internal error: miscounted aggregate components."));
  8115.   *size += 2;
  8116.   for (j = *size-1; j >= i+2; j -= 1)
  8117.     indices[j] = indices[j - 2];
  8118.   indices[i] = low;
  8119.   indices[i + 1] = high;
  8120. }

  8121. /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
  8122.    is different.  */

  8123. static struct value *
  8124. ada_value_cast (struct type *type, struct value *arg2, enum noside noside)
  8125. {
  8126.   if (type == ada_check_typedef (value_type (arg2)))
  8127.     return arg2;

  8128.   if (ada_is_fixed_point_type (type))
  8129.     return (cast_to_fixed (type, arg2));

  8130.   if (ada_is_fixed_point_type (value_type (arg2)))
  8131.     return cast_from_fixed (type, arg2);

  8132.   return value_cast (type, arg2);
  8133. }

  8134. /*  Evaluating Ada expressions, and printing their result.
  8135.     ------------------------------------------------------

  8136.     1. Introduction:
  8137.     ----------------

  8138.     We usually evaluate an Ada expression in order to print its value.
  8139.     We also evaluate an expression in order to print its type, which
  8140.     happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
  8141.     but we'll focus mostly on the EVAL_NORMAL phase.  In practice, the
  8142.     EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
  8143.     the evaluation compared to the EVAL_NORMAL, but is otherwise very
  8144.     similar.

  8145.     Evaluating expressions is a little more complicated for Ada entities
  8146.     than it is for entities in languages such as C.  The main reason for
  8147.     this is that Ada provides types whose definition might be dynamic.
  8148.     One example of such types is variant records.  Or another example
  8149.     would be an array whose bounds can only be known at run time.

  8150.     The following description is a general guide as to what should be
  8151.     done (and what should NOT be done) in order to evaluate an expression
  8152.     involving such types, and when.  This does not cover how the semantic
  8153.     information is encoded by GNAT as this is covered separatly.  For the
  8154.     document used as the reference for the GNAT encoding, see exp_dbug.ads
  8155.     in the GNAT sources.

  8156.     Ideally, we should embed each part of this description next to its
  8157.     associated code.  Unfortunately, the amount of code is so vast right
  8158.     now that it's hard to see whether the code handling a particular
  8159.     situation might be duplicated or not.  One day, when the code is
  8160.     cleaned up, this guide might become redundant with the comments
  8161.     inserted in the code, and we might want to remove it.

  8162.     2. ``Fixing'' an Entity, the Simple Case:
  8163.     -----------------------------------------

  8164.     When evaluating Ada expressions, the tricky issue is that they may
  8165.     reference entities whose type contents and size are not statically
  8166.     known.  Consider for instance a variant record:

  8167.        type Rec (Empty : Boolean := True) is record
  8168.           case Empty is
  8169.              when True => null;
  8170.              when False => Value : Integer;
  8171.           end case;
  8172.        end record;
  8173.        Yes : Rec := (Empty => False, Value => 1);
  8174.        No  : Rec := (empty => True);

  8175.     The size and contents of that record depends on the value of the
  8176.     descriminant (Rec.Empty).  At this point, neither the debugging
  8177.     information nor the associated type structure in GDB are able to
  8178.     express such dynamic types.  So what the debugger does is to create
  8179.     "fixed" versions of the type that applies to the specific object.
  8180.     We also informally refer to this opperation as "fixing" an object,
  8181.     which means creating its associated fixed type.

  8182.     Example: when printing the value of variable "Yes" above, its fixed
  8183.     type would look like this:

  8184.        type Rec is record
  8185.           Empty : Boolean;
  8186.           Value : Integer;
  8187.        end record;

  8188.     On the other hand, if we printed the value of "No", its fixed type
  8189.     would become:

  8190.        type Rec is record
  8191.           Empty : Boolean;
  8192.        end record;

  8193.     Things become a little more complicated when trying to fix an entity
  8194.     with a dynamic type that directly contains another dynamic type,
  8195.     such as an array of variant records, for instance.  There are
  8196.     two possible cases: Arrays, and records.

  8197.     3. ``Fixing'' Arrays:
  8198.     ---------------------

  8199.     The type structure in GDB describes an array in terms of its bounds,
  8200.     and the type of its elements.  By design, all elements in the array
  8201.     have the same type and we cannot represent an array of variant elements
  8202.     using the current type structure in GDB.  When fixing an array,
  8203.     we cannot fix the array element, as we would potentially need one
  8204.     fixed type per element of the array.  As a result, the best we can do
  8205.     when fixing an array is to produce an array whose bounds and size
  8206.     are correct (allowing us to read it from memory), but without having
  8207.     touched its element type.  Fixing each element will be done later,
  8208.     when (if) necessary.

  8209.     Arrays are a little simpler to handle than records, because the same
  8210.     amount of memory is allocated for each element of the array, even if
  8211.     the amount of space actually used by each element differs from element
  8212.     to element.  Consider for instance the following array of type Rec:

  8213.        type Rec_Array is array (1 .. 2) of Rec;

  8214.     The actual amount of memory occupied by each element might be different
  8215.     from element to element, depending on the value of their discriminant.
  8216.     But the amount of space reserved for each element in the array remains
  8217.     fixed regardless.  So we simply need to compute that size using
  8218.     the debugging information available, from which we can then determine
  8219.     the array size (we multiply the number of elements of the array by
  8220.     the size of each element).

  8221.     The simplest case is when we have an array of a constrained element
  8222.     type. For instance, consider the following type declarations:

  8223.         type Bounded_String (Max_Size : Integer) is
  8224.            Length : Integer;
  8225.            Buffer : String (1 .. Max_Size);
  8226.         end record;
  8227.         type Bounded_String_Array is array (1 ..2) of Bounded_String (80);

  8228.     In this case, the compiler describes the array as an array of
  8229.     variable-size elements (identified by its XVS suffix) for which
  8230.     the size can be read in the parallel XVZ variable.

  8231.     In the case of an array of an unconstrained element type, the compiler
  8232.     wraps the array element inside a private PAD type.  This type should not
  8233.     be shown to the user, and must be "unwrap"'ed before printing.  Note
  8234.     that we also use the adjective "aligner" in our code to designate
  8235.     these wrapper types.

  8236.     In some cases, the size allocated for each element is statically
  8237.     known.  In that case, the PAD type already has the correct size,
  8238.     and the array element should remain unfixed.

  8239.     But there are cases when this size is not statically known.
  8240.     For instance, assuming that "Five" is an integer variable:

  8241.         type Dynamic is array (1 .. Five) of Integer;
  8242.         type Wrapper (Has_Length : Boolean := False) is record
  8243.            Data : Dynamic;
  8244.            case Has_Length is
  8245.               when True => Length : Integer;
  8246.               when False => null;
  8247.            end case;
  8248.         end record;
  8249.         type Wrapper_Array is array (1 .. 2) of Wrapper;

  8250.         Hello : Wrapper_Array := (others => (Has_Length => True,
  8251.                                              Data => (others => 17),
  8252.                                              Length => 1));


  8253.     The debugging info would describe variable Hello as being an
  8254.     array of a PAD type.  The size of that PAD type is not statically
  8255.     known, but can be determined using a parallel XVZ variable.
  8256.     In that case, a copy of the PAD type with the correct size should
  8257.     be used for the fixed array.

  8258.     3. ``Fixing'' record type objects:
  8259.     ----------------------------------

  8260.     Things are slightly different from arrays in the case of dynamic
  8261.     record types.  In this case, in order to compute the associated
  8262.     fixed type, we need to determine the size and offset of each of
  8263.     its components.  This, in turn, requires us to compute the fixed
  8264.     type of each of these components.

  8265.     Consider for instance the example:

  8266.         type Bounded_String (Max_Size : Natural) is record
  8267.            Str : String (1 .. Max_Size);
  8268.            Length : Natural;
  8269.         end record;
  8270.         My_String : Bounded_String (Max_Size => 10);

  8271.     In that case, the position of field "Length" depends on the size
  8272.     of field Str, which itself depends on the value of the Max_Size
  8273.     discriminant.  In order to fix the type of variable My_String,
  8274.     we need to fix the type of field Str.  Therefore, fixing a variant
  8275.     record requires us to fix each of its components.

  8276.     However, if a component does not have a dynamic size, the component
  8277.     should not be fixed.  In particular, fields that use a PAD type
  8278.     should not fixed.  Here is an example where this might happen
  8279.     (assuming type Rec above):

  8280.        type Container (Big : Boolean) is record
  8281.           First : Rec;
  8282.           After : Integer;
  8283.           case Big is
  8284.              when True => Another : Integer;
  8285.              when False => null;
  8286.           end case;
  8287.        end record;
  8288.        My_Container : Container := (Big => False,
  8289.                                     First => (Empty => True),
  8290.                                     After => 42);

  8291.     In that example, the compiler creates a PAD type for component First,
  8292.     whose size is constant, and then positions the component After just
  8293.     right after it.  The offset of component After is therefore constant
  8294.     in this case.

  8295.     The debugger computes the position of each field based on an algorithm
  8296.     that uses, among other things, the actual position and size of the field
  8297.     preceding it.  Let's now imagine that the user is trying to print
  8298.     the value of My_Container.  If the type fixing was recursive, we would
  8299.     end up computing the offset of field After based on the size of the
  8300.     fixed version of field First.  And since in our example First has
  8301.     only one actual field, the size of the fixed type is actually smaller
  8302.     than the amount of space allocated to that field, and thus we would
  8303.     compute the wrong offset of field After.

  8304.     To make things more complicated, we need to watch out for dynamic
  8305.     components of variant records (identified by the ___XVL suffix in
  8306.     the component name).  Even if the target type is a PAD type, the size
  8307.     of that type might not be statically known.  So the PAD type needs
  8308.     to be unwrapped and the resulting type needs to be fixed.  Otherwise,
  8309.     we might end up with the wrong size for our component.  This can be
  8310.     observed with the following type declarations:

  8311.         type Octal is new Integer range 0 .. 7;
  8312.         type Octal_Array is array (Positive range <>) of Octal;
  8313.         pragma Pack (Octal_Array);

  8314.         type Octal_Buffer (Size : Positive) is record
  8315.            Buffer : Octal_Array (1 .. Size);
  8316.            Length : Integer;
  8317.         end record;

  8318.     In that case, Buffer is a PAD type whose size is unset and needs
  8319.     to be computed by fixing the unwrapped type.

  8320.     4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
  8321.     ----------------------------------------------------------

  8322.     Lastly, when should the sub-elements of an entity that remained unfixed
  8323.     thus far, be actually fixed?

  8324.     The answer is: Only when referencing that element.  For instance
  8325.     when selecting one component of a record, this specific component
  8326.     should be fixed at that point in time.  Or when printing the value
  8327.     of a record, each component should be fixed before its value gets
  8328.     printed.  Similarly for arrays, the element of the array should be
  8329.     fixed when printing each element of the array, or when extracting
  8330.     one element out of that array.  On the other hand, fixing should
  8331.     not be performed on the elements when taking a slice of an array!

  8332.     Note that one of the side-effects of miscomputing the offset and
  8333.     size of each field is that we end up also miscomputing the size
  8334.     of the containing type.  This can have adverse results when computing
  8335.     the value of an entity.  GDB fetches the value of an entity based
  8336.     on the size of its type, and thus a wrong size causes GDB to fetch
  8337.     the wrong amount of memory.  In the case where the computed size is
  8338.     too small, GDB fetches too little data to print the value of our
  8339.     entiry.  Results in this case as unpredicatble, as we usually read
  8340.     past the buffer containing the data =:-o.  */

  8341. /* Implement the evaluate_exp routine in the exp_descriptor structure
  8342.    for the Ada language.  */

  8343. static struct value *
  8344. ada_evaluate_subexp (struct type *expect_type, struct expression *exp,
  8345.                      int *pos, enum noside noside)
  8346. {
  8347.   enum exp_opcode op;
  8348.   int tem;
  8349.   int pc;
  8350.   int preeval_pos;
  8351.   struct value *arg1 = NULL, *arg2 = NULL, *arg3;
  8352.   struct type *type;
  8353.   int nargs, oplen;
  8354.   struct value **argvec;

  8355.   pc = *pos;
  8356.   *pos += 1;
  8357.   op = exp->elts[pc].opcode;

  8358.   switch (op)
  8359.     {
  8360.     default:
  8361.       *pos -= 1;
  8362.       arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);

  8363.       if (noside == EVAL_NORMAL)
  8364.         arg1 = unwrap_value (arg1);

  8365.       /* If evaluating an OP_DOUBLE and an EXPECT_TYPE was provided,
  8366.          then we need to perform the conversion manually, because
  8367.          evaluate_subexp_standard doesn't do it.  This conversion is
  8368.          necessary in Ada because the different kinds of float/fixed
  8369.          types in Ada have different representations.

  8370.          Similarly, we need to perform the conversion from OP_LONG
  8371.          ourselves.  */
  8372.       if ((op == OP_DOUBLE || op == OP_LONG) && expect_type != NULL)
  8373.         arg1 = ada_value_cast (expect_type, arg1, noside);

  8374.       return arg1;

  8375.     case OP_STRING:
  8376.       {
  8377.         struct value *result;

  8378.         *pos -= 1;
  8379.         result = evaluate_subexp_standard (expect_type, exp, pos, noside);
  8380.         /* The result type will have code OP_STRING, bashed there from
  8381.            OP_ARRAY.  Bash it back.  */
  8382.         if (TYPE_CODE (value_type (result)) == TYPE_CODE_STRING)
  8383.           TYPE_CODE (value_type (result)) = TYPE_CODE_ARRAY;
  8384.         return result;
  8385.       }

  8386.     case UNOP_CAST:
  8387.       (*pos) += 2;
  8388.       type = exp->elts[pc + 1].type;
  8389.       arg1 = evaluate_subexp (type, exp, pos, noside);
  8390.       if (noside == EVAL_SKIP)
  8391.         goto nosideret;
  8392.       arg1 = ada_value_cast (type, arg1, noside);
  8393.       return arg1;

  8394.     case UNOP_QUAL:
  8395.       (*pos) += 2;
  8396.       type = exp->elts[pc + 1].type;
  8397.       return ada_evaluate_subexp (type, exp, pos, noside);

  8398.     case BINOP_ASSIGN:
  8399.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  8400.       if (exp->elts[*pos].opcode == OP_AGGREGATE)
  8401.         {
  8402.           arg1 = assign_aggregate (arg1, arg1, exp, pos, noside);
  8403.           if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
  8404.             return arg1;
  8405.           return ada_value_assign (arg1, arg1);
  8406.         }
  8407.       /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
  8408.          except if the lhs of our assignment is a convenience variable.
  8409.          In the case of assigning to a convenience variable, the lhs
  8410.          should be exactly the result of the evaluation of the rhs.  */
  8411.       type = value_type (arg1);
  8412.       if (VALUE_LVAL (arg1) == lval_internalvar)
  8413.          type = NULL;
  8414.       arg2 = evaluate_subexp (type, exp, pos, noside);
  8415.       if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
  8416.         return arg1;
  8417.       if (ada_is_fixed_point_type (value_type (arg1)))
  8418.         arg2 = cast_to_fixed (value_type (arg1), arg2);
  8419.       else if (ada_is_fixed_point_type (value_type (arg2)))
  8420.         error
  8421.           (_("Fixed-point values must be assigned to fixed-point variables"));
  8422.       else
  8423.         arg2 = coerce_for_assign (value_type (arg1), arg2);
  8424.       return ada_value_assign (arg1, arg2);

  8425.     case BINOP_ADD:
  8426.       arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
  8427.       arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
  8428.       if (noside == EVAL_SKIP)
  8429.         goto nosideret;
  8430.       if (TYPE_CODE (value_type (arg1)) == TYPE_CODE_PTR)
  8431.         return (value_from_longest
  8432.                  (value_type (arg1),
  8433.                   value_as_long (arg1) + value_as_long (arg2)));
  8434.       if (TYPE_CODE (value_type (arg2)) == TYPE_CODE_PTR)
  8435.         return (value_from_longest
  8436.                  (value_type (arg2),
  8437.                   value_as_long (arg1) + value_as_long (arg2)));
  8438.       if ((ada_is_fixed_point_type (value_type (arg1))
  8439.            || ada_is_fixed_point_type (value_type (arg2)))
  8440.           && value_type (arg1) != value_type (arg2))
  8441.         error (_("Operands of fixed-point addition must have the same type"));
  8442.       /* Do the addition, and cast the result to the type of the first
  8443.          argument.  We cannot cast the result to a reference type, so if
  8444.          ARG1 is a reference type, find its underlying type.  */
  8445.       type = value_type (arg1);
  8446.       while (TYPE_CODE (type) == TYPE_CODE_REF)
  8447.         type = TYPE_TARGET_TYPE (type);
  8448.       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
  8449.       return value_cast (type, value_binop (arg1, arg2, BINOP_ADD));

  8450.     case BINOP_SUB:
  8451.       arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
  8452.       arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
  8453.       if (noside == EVAL_SKIP)
  8454.         goto nosideret;
  8455.       if (TYPE_CODE (value_type (arg1)) == TYPE_CODE_PTR)
  8456.         return (value_from_longest
  8457.                  (value_type (arg1),
  8458.                   value_as_long (arg1) - value_as_long (arg2)));
  8459.       if (TYPE_CODE (value_type (arg2)) == TYPE_CODE_PTR)
  8460.         return (value_from_longest
  8461.                  (value_type (arg2),
  8462.                   value_as_long (arg1) - value_as_long (arg2)));
  8463.       if ((ada_is_fixed_point_type (value_type (arg1))
  8464.            || ada_is_fixed_point_type (value_type (arg2)))
  8465.           && value_type (arg1) != value_type (arg2))
  8466.         error (_("Operands of fixed-point subtraction "
  8467.                  "must have the same type"));
  8468.       /* Do the substraction, and cast the result to the type of the first
  8469.          argument.  We cannot cast the result to a reference type, so if
  8470.          ARG1 is a reference type, find its underlying type.  */
  8471.       type = value_type (arg1);
  8472.       while (TYPE_CODE (type) == TYPE_CODE_REF)
  8473.         type = TYPE_TARGET_TYPE (type);
  8474.       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
  8475.       return value_cast (type, value_binop (arg1, arg2, BINOP_SUB));

  8476.     case BINOP_MUL:
  8477.     case BINOP_DIV:
  8478.     case BINOP_REM:
  8479.     case BINOP_MOD:
  8480.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  8481.       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  8482.       if (noside == EVAL_SKIP)
  8483.         goto nosideret;
  8484.       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
  8485.         {
  8486.           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
  8487.           return value_zero (value_type (arg1), not_lval);
  8488.         }
  8489.       else
  8490.         {
  8491.           type = builtin_type (exp->gdbarch)->builtin_double;
  8492.           if (ada_is_fixed_point_type (value_type (arg1)))
  8493.             arg1 = cast_from_fixed (type, arg1);
  8494.           if (ada_is_fixed_point_type (value_type (arg2)))
  8495.             arg2 = cast_from_fixed (type, arg2);
  8496.           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
  8497.           return ada_value_binop (arg1, arg2, op);
  8498.         }

  8499.     case BINOP_EQUAL:
  8500.     case BINOP_NOTEQUAL:
  8501.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  8502.       arg2 = evaluate_subexp (value_type (arg1), exp, pos, noside);
  8503.       if (noside == EVAL_SKIP)
  8504.         goto nosideret;
  8505.       if (noside == EVAL_AVOID_SIDE_EFFECTS)
  8506.         tem = 0;
  8507.       else
  8508.         {
  8509.           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
  8510.           tem = ada_value_equal (arg1, arg2);
  8511.         }
  8512.       if (op == BINOP_NOTEQUAL)
  8513.         tem = !tem;
  8514.       type = language_bool_type (exp->language_defn, exp->gdbarch);
  8515.       return value_from_longest (type, (LONGEST) tem);

  8516.     case UNOP_NEG:
  8517.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  8518.       if (noside == EVAL_SKIP)
  8519.         goto nosideret;
  8520.       else if (ada_is_fixed_point_type (value_type (arg1)))
  8521.         return value_cast (value_type (arg1), value_neg (arg1));
  8522.       else
  8523.         {
  8524.           unop_promote (exp->language_defn, exp->gdbarch, &arg1);
  8525.           return value_neg (arg1);
  8526.         }

  8527.     case BINOP_LOGICAL_AND:
  8528.     case BINOP_LOGICAL_OR:
  8529.     case UNOP_LOGICAL_NOT:
  8530.       {
  8531.         struct value *val;

  8532.         *pos -= 1;
  8533.         val = evaluate_subexp_standard (expect_type, exp, pos, noside);
  8534.         type = language_bool_type (exp->language_defn, exp->gdbarch);
  8535.         return value_cast (type, val);
  8536.       }

  8537.     case BINOP_BITWISE_AND:
  8538.     case BINOP_BITWISE_IOR:
  8539.     case BINOP_BITWISE_XOR:
  8540.       {
  8541.         struct value *val;

  8542.         arg1 = evaluate_subexp (NULL_TYPE, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
  8543.         *pos = pc;
  8544.         val = evaluate_subexp_standard (expect_type, exp, pos, noside);

  8545.         return value_cast (value_type (arg1), val);
  8546.       }

  8547.     case OP_VAR_VALUE:
  8548.       *pos -= 1;

  8549.       if (noside == EVAL_SKIP)
  8550.         {
  8551.           *pos += 4;
  8552.           goto nosideret;
  8553.         }

  8554.       if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
  8555.         /* Only encountered when an unresolved symbol occurs in a
  8556.            context other than a function call, in which case, it is
  8557.            invalid.  */
  8558.         error (_("Unexpected unresolved symbol, %s, during evaluation"),
  8559.                SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));

  8560.       if (noside == EVAL_AVOID_SIDE_EFFECTS)
  8561.         {
  8562.           type = static_unwrap_type (SYMBOL_TYPE (exp->elts[pc + 2].symbol));
  8563.           /* Check to see if this is a tagged type.  We also need to handle
  8564.              the case where the type is a reference to a tagged type, but
  8565.              we have to be careful to exclude pointers to tagged types.
  8566.              The latter should be shown as usual (as a pointer), whereas
  8567.              a reference should mostly be transparent to the user.  */
  8568.           if (ada_is_tagged_type (type, 0)
  8569.               || (TYPE_CODE (type) == TYPE_CODE_REF
  8570.                   && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0)))
  8571.             {
  8572.               /* Tagged types are a little special in the fact that the real
  8573.                  type is dynamic and can only be determined by inspecting the
  8574.                  object's tag.  This means that we need to get the object's
  8575.                  value first (EVAL_NORMAL) and then extract the actual object
  8576.                  type from its tag.

  8577.                  Note that we cannot skip the final step where we extract
  8578.                  the object type from its tag, because the EVAL_NORMAL phase
  8579.                  results in dynamic components being resolved into fixed ones.
  8580.                  This can cause problems when trying to print the type
  8581.                  description of tagged types whose parent has a dynamic size:
  8582.                  We use the type name of the "_parent" component in order
  8583.                  to print the name of the ancestor type in the type description.
  8584.                  If that component had a dynamic size, the resolution into
  8585.                  a fixed type would result in the loss of that type name,
  8586.                  thus preventing us from printing the name of the ancestor
  8587.                  type in the type description.  */
  8588.               arg1 = evaluate_subexp (NULL_TYPE, exp, pos, EVAL_NORMAL);

  8589.               if (TYPE_CODE (type) != TYPE_CODE_REF)
  8590.                 {
  8591.                   struct type *actual_type;

  8592.                   actual_type = type_from_tag (ada_value_tag (arg1));
  8593.                   if (actual_type == NULL)
  8594.                     /* If, for some reason, we were unable to determine
  8595.                        the actual type from the tag, then use the static
  8596.                        approximation that we just computed as a fallback.
  8597.                        This can happen if the debugging information is
  8598.                        incomplete, for instance.  */
  8599.                     actual_type = type;
  8600.                   return value_zero (actual_type, not_lval);
  8601.                 }
  8602.               else
  8603.                 {
  8604.                   /* In the case of a ref, ada_coerce_ref takes care
  8605.                      of determining the actual type.  But the evaluation
  8606.                      should return a ref as it should be valid to ask
  8607.                      for its address; so rebuild a ref after coerce.  */
  8608.                   arg1 = ada_coerce_ref (arg1);
  8609.                   return value_ref (arg1);
  8610.                 }
  8611.             }

  8612.           /* Records and unions for which GNAT encodings have been
  8613.              generated need to be statically fixed as well.
  8614.              Otherwise, non-static fixing produces a type where
  8615.              all dynamic properties are removed, which prevents "ptype"
  8616.              from being able to completely describe the type.
  8617.              For instance, a case statement in a variant record would be
  8618.              replaced by the relevant components based on the actual
  8619.              value of the discriminants.  */
  8620.           if ((TYPE_CODE (type) == TYPE_CODE_STRUCT
  8621.                && dynamic_template_type (type) != NULL)
  8622.               || (TYPE_CODE (type) == TYPE_CODE_UNION
  8623.                   && ada_find_parallel_type (type, "___XVU") != NULL))
  8624.             {
  8625.               *pos += 4;
  8626.               return value_zero (to_static_fixed_type (type), not_lval);
  8627.             }
  8628.         }

  8629.       arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
  8630.       return ada_to_fixed_value (arg1);

  8631.     case OP_FUNCALL:
  8632.       (*pos) += 2;

  8633.       /* Allocate arg vector, including space for the function to be
  8634.          called in argvec[0] and a terminating NULL.  */
  8635.       nargs = longest_to_int (exp->elts[pc + 1].longconst);
  8636.       argvec =
  8637.         (struct value **) alloca (sizeof (struct value *) * (nargs + 2));

  8638.       if (exp->elts[*pos].opcode == OP_VAR_VALUE
  8639.           && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
  8640.         error (_("Unexpected unresolved symbol, %s, during evaluation"),
  8641.                SYMBOL_PRINT_NAME (exp->elts[pc + 5].symbol));
  8642.       else
  8643.         {
  8644.           for (tem = 0; tem <= nargs; tem += 1)
  8645.             argvec[tem] = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  8646.           argvec[tem] = 0;

  8647.           if (noside == EVAL_SKIP)
  8648.             goto nosideret;
  8649.         }

  8650.       if (ada_is_constrained_packed_array_type
  8651.           (desc_base_type (value_type (argvec[0]))))
  8652.         argvec[0] = ada_coerce_to_simple_array (argvec[0]);
  8653.       else if (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_ARRAY
  8654.                && TYPE_FIELD_BITSIZE (value_type (argvec[0]), 0) != 0)
  8655.         /* This is a packed array that has already been fixed, and
  8656.            therefore already coerced to a simple array.  Nothing further
  8657.            to do.  */
  8658.         ;
  8659.       else if (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_REF
  8660.                || (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_ARRAY
  8661.                    && VALUE_LVAL (argvec[0]) == lval_memory))
  8662.         argvec[0] = value_addr (argvec[0]);

  8663.       type = ada_check_typedef (value_type (argvec[0]));

  8664.       /* Ada allows us to implicitly dereference arrays when subscripting
  8665.          them.  So, if this is an array typedef (encoding use for array
  8666.          access types encoded as fat pointers), strip it now.  */
  8667.       if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
  8668.         type = ada_typedef_target_type (type);

  8669.       if (TYPE_CODE (type) == TYPE_CODE_PTR)
  8670.         {
  8671.           switch (TYPE_CODE (ada_check_typedef (TYPE_TARGET_TYPE (type))))
  8672.             {
  8673.             case TYPE_CODE_FUNC:
  8674.               type = ada_check_typedef (TYPE_TARGET_TYPE (type));
  8675.               break;
  8676.             case TYPE_CODE_ARRAY:
  8677.               break;
  8678.             case TYPE_CODE_STRUCT:
  8679.               if (noside != EVAL_AVOID_SIDE_EFFECTS)
  8680.                 argvec[0] = ada_value_ind (argvec[0]);
  8681.               type = ada_check_typedef (TYPE_TARGET_TYPE (type));
  8682.               break;
  8683.             default:
  8684.               error (_("cannot subscript or call something of type `%s'"),
  8685.                      ada_type_name (value_type (argvec[0])));
  8686.               break;
  8687.             }
  8688.         }

  8689.       switch (TYPE_CODE (type))
  8690.         {
  8691.         case TYPE_CODE_FUNC:
  8692.           if (noside == EVAL_AVOID_SIDE_EFFECTS)
  8693.             {
  8694.               struct type *rtype = TYPE_TARGET_TYPE (type);

  8695.               if (TYPE_GNU_IFUNC (type))
  8696.                 return allocate_value (TYPE_TARGET_TYPE (rtype));
  8697.               return allocate_value (rtype);
  8698.             }
  8699.           return call_function_by_hand (argvec[0], nargs, argvec + 1);
  8700.         case TYPE_CODE_INTERNAL_FUNCTION:
  8701.           if (noside == EVAL_AVOID_SIDE_EFFECTS)
  8702.             /* We don't know anything about what the internal
  8703.                function might return, but we have to return
  8704.                something.  */
  8705.             return value_zero (builtin_type (exp->gdbarch)->builtin_int,
  8706.                                not_lval);
  8707.           else
  8708.             return call_internal_function (exp->gdbarch, exp->language_defn,
  8709.                                            argvec[0], nargs, argvec + 1);

  8710.         case TYPE_CODE_STRUCT:
  8711.           {
  8712.             int arity;

  8713.             arity = ada_array_arity (type);
  8714.             type = ada_array_element_type (type, nargs);
  8715.             if (type == NULL)
  8716.               error (_("cannot subscript or call a record"));
  8717.             if (arity != nargs)
  8718.               error (_("wrong number of subscripts; expecting %d"), arity);
  8719.             if (noside == EVAL_AVOID_SIDE_EFFECTS)
  8720.               return value_zero (ada_aligned_type (type), lval_memory);
  8721.             return
  8722.               unwrap_value (ada_value_subscript
  8723.                             (argvec[0], nargs, argvec + 1));
  8724.           }
  8725.         case TYPE_CODE_ARRAY:
  8726.           if (noside == EVAL_AVOID_SIDE_EFFECTS)
  8727.             {
  8728.               type = ada_array_element_type (type, nargs);
  8729.               if (type == NULL)
  8730.                 error (_("element type of array unknown"));
  8731.               else
  8732.                 return value_zero (ada_aligned_type (type), lval_memory);
  8733.             }
  8734.           return
  8735.             unwrap_value (ada_value_subscript
  8736.                           (ada_coerce_to_simple_array (argvec[0]),
  8737.                            nargs, argvec + 1));
  8738.         case TYPE_CODE_PTR:     /* Pointer to array */
  8739.           if (noside == EVAL_AVOID_SIDE_EFFECTS)
  8740.             {
  8741.               type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
  8742.               type = ada_array_element_type (type, nargs);
  8743.               if (type == NULL)
  8744.                 error (_("element type of array unknown"));
  8745.               else
  8746.                 return value_zero (ada_aligned_type (type), lval_memory);
  8747.             }
  8748.           return
  8749.             unwrap_value (ada_value_ptr_subscript (argvec[0],
  8750.                                                    nargs, argvec + 1));

  8751.         default:
  8752.           error (_("Attempt to index or call something other than an "
  8753.                    "array or function"));
  8754.         }

  8755.     case TERNOP_SLICE:
  8756.       {
  8757.         struct value *array = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  8758.         struct value *low_bound_val =
  8759.           evaluate_subexp (NULL_TYPE, exp, pos, noside);
  8760.         struct value *high_bound_val =
  8761.           evaluate_subexp (NULL_TYPE, exp, pos, noside);
  8762.         LONGEST low_bound;
  8763.         LONGEST high_bound;

  8764.         low_bound_val = coerce_ref (low_bound_val);
  8765.         high_bound_val = coerce_ref (high_bound_val);
  8766.         low_bound = pos_atr (low_bound_val);
  8767.         high_bound = pos_atr (high_bound_val);

  8768.         if (noside == EVAL_SKIP)
  8769.           goto nosideret;

  8770.         /* If this is a reference to an aligner type, then remove all
  8771.            the aligners.  */
  8772.         if (TYPE_CODE (value_type (array)) == TYPE_CODE_REF
  8773.             && ada_is_aligner_type (TYPE_TARGET_TYPE (value_type (array))))
  8774.           TYPE_TARGET_TYPE (value_type (array)) =
  8775.             ada_aligned_type (TYPE_TARGET_TYPE (value_type (array)));

  8776.         if (ada_is_constrained_packed_array_type (value_type (array)))
  8777.           error (_("cannot slice a packed array"));

  8778.         /* If this is a reference to an array or an array lvalue,
  8779.            convert to a pointer.  */
  8780.         if (TYPE_CODE (value_type (array)) == TYPE_CODE_REF
  8781.             || (TYPE_CODE (value_type (array)) == TYPE_CODE_ARRAY
  8782.                 && VALUE_LVAL (array) == lval_memory))
  8783.           array = value_addr (array);

  8784.         if (noside == EVAL_AVOID_SIDE_EFFECTS
  8785.             && ada_is_array_descriptor_type (ada_check_typedef
  8786.                                              (value_type (array))))
  8787.           return empty_array (ada_type_of_array (array, 0), low_bound);

  8788.         array = ada_coerce_to_simple_array_ptr (array);

  8789.         /* If we have more than one level of pointer indirection,
  8790.            dereference the value until we get only one level.  */
  8791.         while (TYPE_CODE (value_type (array)) == TYPE_CODE_PTR
  8792.                && (TYPE_CODE (TYPE_TARGET_TYPE (value_type (array)))
  8793.                      == TYPE_CODE_PTR))
  8794.           array = value_ind (array);

  8795.         /* Make sure we really do have an array type before going further,
  8796.            to avoid a SEGV when trying to get the index type or the target
  8797.            type later down the road if the debug info generated by
  8798.            the compiler is incorrect or incomplete.  */
  8799.         if (!ada_is_simple_array_type (value_type (array)))
  8800.           error (_("cannot take slice of non-array"));

  8801.         if (TYPE_CODE (ada_check_typedef (value_type (array)))
  8802.             == TYPE_CODE_PTR)
  8803.           {
  8804.             struct type *type0 = ada_check_typedef (value_type (array));

  8805.             if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
  8806.               return empty_array (TYPE_TARGET_TYPE (type0), low_bound);
  8807.             else
  8808.               {
  8809.                 struct type *arr_type0 =
  8810.                   to_fixed_array_type (TYPE_TARGET_TYPE (type0), NULL, 1);

  8811.                 return ada_value_slice_from_ptr (array, arr_type0,
  8812.                                                  longest_to_int (low_bound),
  8813.                                                  longest_to_int (high_bound));
  8814.               }
  8815.           }
  8816.         else if (noside == EVAL_AVOID_SIDE_EFFECTS)
  8817.           return array;
  8818.         else if (high_bound < low_bound)
  8819.           return empty_array (value_type (array), low_bound);
  8820.         else
  8821.           return ada_value_slice (array, longest_to_int (low_bound),
  8822.                                   longest_to_int (high_bound));
  8823.       }

  8824.     case UNOP_IN_RANGE:
  8825.       (*pos) += 2;
  8826.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  8827.       type = check_typedef (exp->elts[pc + 1].type);

  8828.       if (noside == EVAL_SKIP)
  8829.         goto nosideret;

  8830.       switch (TYPE_CODE (type))
  8831.         {
  8832.         default:
  8833.           lim_warning (_("Membership test incompletely implemented; "
  8834.                          "always returns true"));
  8835.           type = language_bool_type (exp->language_defn, exp->gdbarch);
  8836.           return value_from_longest (type, (LONGEST) 1);

  8837.         case TYPE_CODE_RANGE:
  8838.           arg2 = value_from_longest (type, TYPE_LOW_BOUND (type));
  8839.           arg3 = value_from_longest (type, TYPE_HIGH_BOUND (type));
  8840.           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
  8841.           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
  8842.           type = language_bool_type (exp->language_defn, exp->gdbarch);
  8843.           return
  8844.             value_from_longest (type,
  8845.                                 (value_less (arg1, arg3)
  8846.                                  || value_equal (arg1, arg3))
  8847.                                 && (value_less (arg2, arg1)
  8848.                                     || value_equal (arg2, arg1)));
  8849.         }

  8850.     case BINOP_IN_BOUNDS:
  8851.       (*pos) += 2;
  8852.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  8853.       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);

  8854.       if (noside == EVAL_SKIP)
  8855.         goto nosideret;

  8856.       if (noside == EVAL_AVOID_SIDE_EFFECTS)
  8857.         {
  8858.           type = language_bool_type (exp->language_defn, exp->gdbarch);
  8859.           return value_zero (type, not_lval);
  8860.         }

  8861.       tem = longest_to_int (exp->elts[pc + 1].longconst);

  8862.       type = ada_index_type (value_type (arg2), tem, "range");
  8863.       if (!type)
  8864.         type = value_type (arg1);

  8865.       arg3 = value_from_longest (type, ada_array_bound (arg2, tem, 1));
  8866.       arg2 = value_from_longest (type, ada_array_bound (arg2, tem, 0));

  8867.       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
  8868.       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
  8869.       type = language_bool_type (exp->language_defn, exp->gdbarch);
  8870.       return
  8871.         value_from_longest (type,
  8872.                             (value_less (arg1, arg3)
  8873.                              || value_equal (arg1, arg3))
  8874.                             && (value_less (arg2, arg1)
  8875.                                 || value_equal (arg2, arg1)));

  8876.     case TERNOP_IN_RANGE:
  8877.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  8878.       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  8879.       arg3 = evaluate_subexp (NULL_TYPE, exp, pos, noside);

  8880.       if (noside == EVAL_SKIP)
  8881.         goto nosideret;

  8882.       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
  8883.       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
  8884.       type = language_bool_type (exp->language_defn, exp->gdbarch);
  8885.       return
  8886.         value_from_longest (type,
  8887.                             (value_less (arg1, arg3)
  8888.                              || value_equal (arg1, arg3))
  8889.                             && (value_less (arg2, arg1)
  8890.                                 || value_equal (arg2, arg1)));

  8891.     case OP_ATR_FIRST:
  8892.     case OP_ATR_LAST:
  8893.     case OP_ATR_LENGTH:
  8894.       {
  8895.         struct type *type_arg;

  8896.         if (exp->elts[*pos].opcode == OP_TYPE)
  8897.           {
  8898.             evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
  8899.             arg1 = NULL;
  8900.             type_arg = check_typedef (exp->elts[pc + 2].type);
  8901.           }
  8902.         else
  8903.           {
  8904.             arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  8905.             type_arg = NULL;
  8906.           }

  8907.         if (exp->elts[*pos].opcode != OP_LONG)
  8908.           error (_("Invalid operand to '%s"), ada_attribute_name (op));
  8909.         tem = longest_to_int (exp->elts[*pos + 2].longconst);
  8910.         *pos += 4;

  8911.         if (noside == EVAL_SKIP)
  8912.           goto nosideret;

  8913.         if (type_arg == NULL)
  8914.           {
  8915.             arg1 = ada_coerce_ref (arg1);

  8916.             if (ada_is_constrained_packed_array_type (value_type (arg1)))
  8917.               arg1 = ada_coerce_to_simple_array (arg1);

  8918.             if (op == OP_ATR_LENGTH)
  8919.               type = builtin_type (exp->gdbarch)->builtin_int;
  8920.             else
  8921.               {
  8922.                 type = ada_index_type (value_type (arg1), tem,
  8923.                                        ada_attribute_name (op));
  8924.                 if (type == NULL)
  8925.                   type = builtin_type (exp->gdbarch)->builtin_int;
  8926.               }

  8927.             if (noside == EVAL_AVOID_SIDE_EFFECTS)
  8928.               return allocate_value (type);

  8929.             switch (op)
  8930.               {
  8931.               default:          /* Should never happen.  */
  8932.                 error (_("unexpected attribute encountered"));
  8933.               case OP_ATR_FIRST:
  8934.                 return value_from_longest
  8935.                         (type, ada_array_bound (arg1, tem, 0));
  8936.               case OP_ATR_LAST:
  8937.                 return value_from_longest
  8938.                         (type, ada_array_bound (arg1, tem, 1));
  8939.               case OP_ATR_LENGTH:
  8940.                 return value_from_longest
  8941.                         (type, ada_array_length (arg1, tem));
  8942.               }
  8943.           }
  8944.         else if (discrete_type_p (type_arg))
  8945.           {
  8946.             struct type *range_type;
  8947.             const char *name = ada_type_name (type_arg);

  8948.             range_type = NULL;
  8949.             if (name != NULL && TYPE_CODE (type_arg) != TYPE_CODE_ENUM)
  8950.               range_type = to_fixed_range_type (type_arg, NULL);
  8951.             if (range_type == NULL)
  8952.               range_type = type_arg;
  8953.             switch (op)
  8954.               {
  8955.               default:
  8956.                 error (_("unexpected attribute encountered"));
  8957.               case OP_ATR_FIRST:
  8958.                 return value_from_longest
  8959.                   (range_type, ada_discrete_type_low_bound (range_type));
  8960.               case OP_ATR_LAST:
  8961.                 return value_from_longest
  8962.                   (range_type, ada_discrete_type_high_bound (range_type));
  8963.               case OP_ATR_LENGTH:
  8964.                 error (_("the 'length attribute applies only to array types"));
  8965.               }
  8966.           }
  8967.         else if (TYPE_CODE (type_arg) == TYPE_CODE_FLT)
  8968.           error (_("unimplemented type attribute"));
  8969.         else
  8970.           {
  8971.             LONGEST low, high;

  8972.             if (ada_is_constrained_packed_array_type (type_arg))
  8973.               type_arg = decode_constrained_packed_array_type (type_arg);

  8974.             if (op == OP_ATR_LENGTH)
  8975.               type = builtin_type (exp->gdbarch)->builtin_int;
  8976.             else
  8977.               {
  8978.                 type = ada_index_type (type_arg, tem, ada_attribute_name (op));
  8979.                 if (type == NULL)
  8980.                   type = builtin_type (exp->gdbarch)->builtin_int;
  8981.               }

  8982.             if (noside == EVAL_AVOID_SIDE_EFFECTS)
  8983.               return allocate_value (type);

  8984.             switch (op)
  8985.               {
  8986.               default:
  8987.                 error (_("unexpected attribute encountered"));
  8988.               case OP_ATR_FIRST:
  8989.                 low = ada_array_bound_from_type (type_arg, tem, 0);
  8990.                 return value_from_longest (type, low);
  8991.               case OP_ATR_LAST:
  8992.                 high = ada_array_bound_from_type (type_arg, tem, 1);
  8993.                 return value_from_longest (type, high);
  8994.               case OP_ATR_LENGTH:
  8995.                 low = ada_array_bound_from_type (type_arg, tem, 0);
  8996.                 high = ada_array_bound_from_type (type_arg, tem, 1);
  8997.                 return value_from_longest (type, high - low + 1);
  8998.               }
  8999.           }
  9000.       }

  9001.     case OP_ATR_TAG:
  9002.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  9003.       if (noside == EVAL_SKIP)
  9004.         goto nosideret;

  9005.       if (noside == EVAL_AVOID_SIDE_EFFECTS)
  9006.         return value_zero (ada_tag_type (arg1), not_lval);

  9007.       return ada_value_tag (arg1);

  9008.     case OP_ATR_MIN:
  9009.     case OP_ATR_MAX:
  9010.       evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
  9011.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  9012.       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  9013.       if (noside == EVAL_SKIP)
  9014.         goto nosideret;
  9015.       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
  9016.         return value_zero (value_type (arg1), not_lval);
  9017.       else
  9018.         {
  9019.           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
  9020.           return value_binop (arg1, arg2,
  9021.                               op == OP_ATR_MIN ? BINOP_MIN : BINOP_MAX);
  9022.         }

  9023.     case OP_ATR_MODULUS:
  9024.       {
  9025.         struct type *type_arg = check_typedef (exp->elts[pc + 2].type);

  9026.         evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
  9027.         if (noside == EVAL_SKIP)
  9028.           goto nosideret;

  9029.         if (!ada_is_modular_type (type_arg))
  9030.           error (_("'modulus must be applied to modular type"));

  9031.         return value_from_longest (TYPE_TARGET_TYPE (type_arg),
  9032.                                    ada_modulus (type_arg));
  9033.       }


  9034.     case OP_ATR_POS:
  9035.       evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
  9036.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  9037.       if (noside == EVAL_SKIP)
  9038.         goto nosideret;
  9039.       type = builtin_type (exp->gdbarch)->builtin_int;
  9040.       if (noside == EVAL_AVOID_SIDE_EFFECTS)
  9041.         return value_zero (type, not_lval);
  9042.       else
  9043.         return value_pos_atr (type, arg1);

  9044.     case OP_ATR_SIZE:
  9045.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  9046.       type = value_type (arg1);

  9047.       /* If the argument is a reference, then dereference its type, since
  9048.          the user is really asking for the size of the actual object,
  9049.          not the size of the pointer.  */
  9050.       if (TYPE_CODE (type) == TYPE_CODE_REF)
  9051.         type = TYPE_TARGET_TYPE (type);

  9052.       if (noside == EVAL_SKIP)
  9053.         goto nosideret;
  9054.       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
  9055.         return value_zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
  9056.       else
  9057.         return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
  9058.                                    TARGET_CHAR_BIT * TYPE_LENGTH (type));

  9059.     case OP_ATR_VAL:
  9060.       evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
  9061.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  9062.       type = exp->elts[pc + 2].type;
  9063.       if (noside == EVAL_SKIP)
  9064.         goto nosideret;
  9065.       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
  9066.         return value_zero (type, not_lval);
  9067.       else
  9068.         return value_val_atr (type, arg1);

  9069.     case BINOP_EXP:
  9070.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  9071.       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  9072.       if (noside == EVAL_SKIP)
  9073.         goto nosideret;
  9074.       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
  9075.         return value_zero (value_type (arg1), not_lval);
  9076.       else
  9077.         {
  9078.           /* For integer exponentiation operations,
  9079.              only promote the first argument.  */
  9080.           if (is_integral_type (value_type (arg2)))
  9081.             unop_promote (exp->language_defn, exp->gdbarch, &arg1);
  9082.           else
  9083.             binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);

  9084.           return value_binop (arg1, arg2, op);
  9085.         }

  9086.     case UNOP_PLUS:
  9087.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  9088.       if (noside == EVAL_SKIP)
  9089.         goto nosideret;
  9090.       else
  9091.         return arg1;

  9092.     case UNOP_ABS:
  9093.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  9094.       if (noside == EVAL_SKIP)
  9095.         goto nosideret;
  9096.       unop_promote (exp->language_defn, exp->gdbarch, &arg1);
  9097.       if (value_less (arg1, value_zero (value_type (arg1), not_lval)))
  9098.         return value_neg (arg1);
  9099.       else
  9100.         return arg1;

  9101.     case UNOP_IND:
  9102.       preeval_pos = *pos;
  9103.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  9104.       if (noside == EVAL_SKIP)
  9105.         goto nosideret;
  9106.       type = ada_check_typedef (value_type (arg1));
  9107.       if (noside == EVAL_AVOID_SIDE_EFFECTS)
  9108.         {
  9109.           if (ada_is_array_descriptor_type (type))
  9110.             /* GDB allows dereferencing GNAT array descriptors.  */
  9111.             {
  9112.               struct type *arrType = ada_type_of_array (arg1, 0);

  9113.               if (arrType == NULL)
  9114.                 error (_("Attempt to dereference null array pointer."));
  9115.               return value_at_lazy (arrType, 0);
  9116.             }
  9117.           else if (TYPE_CODE (type) == TYPE_CODE_PTR
  9118.                    || TYPE_CODE (type) == TYPE_CODE_REF
  9119.                    /* In C you can dereference an array to get the 1st elt.  */
  9120.                    || TYPE_CODE (type) == TYPE_CODE_ARRAY)
  9121.             {
  9122.             /* As mentioned in the OP_VAR_VALUE case, tagged types can
  9123.                only be determined by inspecting the object's tag.
  9124.                This means that we need to evaluate completely the
  9125.                expression in order to get its type.  */

  9126.               if ((TYPE_CODE (type) == TYPE_CODE_REF
  9127.                    || TYPE_CODE (type) == TYPE_CODE_PTR)
  9128.                   && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0))
  9129.                 {
  9130.                   arg1 = evaluate_subexp (NULL_TYPE, exp, &preeval_pos,
  9131.                                           EVAL_NORMAL);
  9132.                   type = value_type (ada_value_ind (arg1));
  9133.                 }
  9134.               else
  9135.                 {
  9136.                   type = to_static_fixed_type
  9137.                     (ada_aligned_type
  9138.                      (ada_check_typedef (TYPE_TARGET_TYPE (type))));
  9139.                 }
  9140.               ada_ensure_varsize_limit (type);
  9141.               return value_zero (type, lval_memory);
  9142.             }
  9143.           else if (TYPE_CODE (type) == TYPE_CODE_INT)
  9144.             {
  9145.               /* GDB allows dereferencing an int.  */
  9146.               if (expect_type == NULL)
  9147.                 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
  9148.                                    lval_memory);
  9149.               else
  9150.                 {
  9151.                   expect_type =
  9152.                     to_static_fixed_type (ada_aligned_type (expect_type));
  9153.                   return value_zero (expect_type, lval_memory);
  9154.                 }
  9155.             }
  9156.           else
  9157.             error (_("Attempt to take contents of a non-pointer value."));
  9158.         }
  9159.       arg1 = ada_coerce_ref (arg1);     /* FIXME: What is this for??  */
  9160.       type = ada_check_typedef (value_type (arg1));

  9161.       if (TYPE_CODE (type) == TYPE_CODE_INT)
  9162.           /* GDB allows dereferencing an int.  If we were given
  9163.              the expect_type, then use that as the target type.
  9164.              Otherwise, assume that the target type is an int.  */
  9165.         {
  9166.           if (expect_type != NULL)
  9167.             return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
  9168.                                               arg1));
  9169.           else
  9170.             return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
  9171.                                   (CORE_ADDR) value_as_address (arg1));
  9172.         }

  9173.       if (ada_is_array_descriptor_type (type))
  9174.         /* GDB allows dereferencing GNAT array descriptors.  */
  9175.         return ada_coerce_to_simple_array (arg1);
  9176.       else
  9177.         return ada_value_ind (arg1);

  9178.     case STRUCTOP_STRUCT:
  9179.       tem = longest_to_int (exp->elts[pc + 1].longconst);
  9180.       (*pos) += 3 + BYTES_TO_EXP_ELEM (tem + 1);
  9181.       preeval_pos = *pos;
  9182.       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
  9183.       if (noside == EVAL_SKIP)
  9184.         goto nosideret;
  9185.       if (noside == EVAL_AVOID_SIDE_EFFECTS)
  9186.         {
  9187.           struct type *type1 = value_type (arg1);

  9188.           if (ada_is_tagged_type (type1, 1))
  9189.             {
  9190.               type = ada_lookup_struct_elt_type (type1,
  9191.                                                  &exp->elts[pc + 2].string,
  9192.                                                  1, 1, NULL);

  9193.               /* If the field is not found, check if it exists in the
  9194.                  extension of this object's type. This means that we
  9195.                  need to evaluate completely the expression.  */

  9196.               if (type == NULL)
  9197.                 {
  9198.                   arg1 = evaluate_subexp (NULL_TYPE, exp, &preeval_pos,
  9199.                                           EVAL_NORMAL);
  9200.                   arg1 = ada_value_struct_elt (arg1,
  9201.                                                &exp->elts[pc + 2].string,
  9202.                                                0);
  9203.                   arg1 = unwrap_value (arg1);
  9204.                   type = value_type (ada_to_fixed_value (arg1));
  9205.                 }
  9206.             }
  9207.           else
  9208.             type =
  9209.               ada_lookup_struct_elt_type (type1, &exp->elts[pc + 2].string, 1,
  9210.                                           0, NULL);

  9211.           return value_zero (ada_aligned_type (type), lval_memory);
  9212.         }
  9213.       else
  9214.         arg1 = ada_value_struct_elt (arg1, &exp->elts[pc + 2].string, 0);
  9215.         arg1 = unwrap_value (arg1);
  9216.         return ada_to_fixed_value (arg1);

  9217.     case OP_TYPE:
  9218.       /* The value is not supposed to be used.  This is here to make it
  9219.          easier to accommodate expressions that contain types.  */
  9220.       (*pos) += 2;
  9221.       if (noside == EVAL_SKIP)
  9222.         goto nosideret;
  9223.       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
  9224.         return allocate_value (exp->elts[pc + 1].type);
  9225.       else
  9226.         error (_("Attempt to use a type name as an expression"));

  9227.     case OP_AGGREGATE:
  9228.     case OP_CHOICES:
  9229.     case OP_OTHERS:
  9230.     case OP_DISCRETE_RANGE:
  9231.     case OP_POSITIONAL:
  9232.     case OP_NAME:
  9233.       if (noside == EVAL_NORMAL)
  9234.         switch (op)
  9235.           {
  9236.           case OP_NAME:
  9237.             error (_("Undefined name, ambiguous name, or renaming used in "
  9238.                      "component association: %s."), &exp->elts[pc+2].string);
  9239.           case OP_AGGREGATE:
  9240.             error (_("Aggregates only allowed on the right of an assignment"));
  9241.           default:
  9242.             internal_error (__FILE__, __LINE__,
  9243.                             _("aggregate apparently mangled"));
  9244.           }

  9245.       ada_forward_operator_length (exp, pc, &oplen, &nargs);
  9246.       *pos += oplen - 1;
  9247.       for (tem = 0; tem < nargs; tem += 1)
  9248.         ada_evaluate_subexp (NULL, exp, pos, noside);
  9249.       goto nosideret;
  9250.     }

  9251. nosideret:
  9252.   return value_from_longest (builtin_type (exp->gdbarch)->builtin_int, 1);
  9253. }


  9254.                                 /* Fixed point */

  9255. /* If TYPE encodes an Ada fixed-point type, return the suffix of the
  9256.    type name that encodes the 'small and 'delta information.
  9257.    Otherwise, return NULL.  */

  9258. static const char *
  9259. fixed_type_info (struct type *type)
  9260. {
  9261.   const char *name = ada_type_name (type);
  9262.   enum type_code code = (type == NULL) ? TYPE_CODE_UNDEF : TYPE_CODE (type);

  9263.   if ((code == TYPE_CODE_INT || code == TYPE_CODE_RANGE) && name != NULL)
  9264.     {
  9265.       const char *tail = strstr (name, "___XF_");

  9266.       if (tail == NULL)
  9267.         return NULL;
  9268.       else
  9269.         return tail + 5;
  9270.     }
  9271.   else if (code == TYPE_CODE_RANGE && TYPE_TARGET_TYPE (type) != type)
  9272.     return fixed_type_info (TYPE_TARGET_TYPE (type));
  9273.   else
  9274.     return NULL;
  9275. }

  9276. /* Returns non-zero iff TYPE represents an Ada fixed-point type.  */

  9277. int
  9278. ada_is_fixed_point_type (struct type *type)
  9279. {
  9280.   return fixed_type_info (type) != NULL;
  9281. }

  9282. /* Return non-zero iff TYPE represents a System.Address type.  */

  9283. int
  9284. ada_is_system_address_type (struct type *type)
  9285. {
  9286.   return (TYPE_NAME (type)
  9287.           && strcmp (TYPE_NAME (type), "system__address") == 0);
  9288. }

  9289. /* Assuming that TYPE is the representation of an Ada fixed-point
  9290.    type, return its delta, or -1 if the type is malformed and the
  9291.    delta cannot be determined.  */

  9292. DOUBLEST
  9293. ada_delta (struct type *type)
  9294. {
  9295.   const char *encoding = fixed_type_info (type);
  9296.   DOUBLEST num, den;

  9297.   /* Strictly speaking, num and den are encoded as integer.  However,
  9298.      they may not fit into a long, and they will have to be converted
  9299.      to DOUBLEST anyway.  So scan them as DOUBLEST.  */
  9300.   if (sscanf (encoding, "_%" DOUBLEST_SCAN_FORMAT "_%" DOUBLEST_SCAN_FORMAT,
  9301.               &num, &den) < 2)
  9302.     return -1.0;
  9303.   else
  9304.     return num / den;
  9305. }

  9306. /* Assuming that ada_is_fixed_point_type (TYPE), return the scaling
  9307.    factor ('SMALL value) associated with the type.  */

  9308. static DOUBLEST
  9309. scaling_factor (struct type *type)
  9310. {
  9311.   const char *encoding = fixed_type_info (type);
  9312.   DOUBLEST num0, den0, num1, den1;
  9313.   int n;

  9314.   /* Strictly speaking, num's and den's are encoded as integer.  However,
  9315.      they may not fit into a long, and they will have to be converted
  9316.      to DOUBLEST anyway.  So scan them as DOUBLEST.  */
  9317.   n = sscanf (encoding,
  9318.               "_%" DOUBLEST_SCAN_FORMAT "_%" DOUBLEST_SCAN_FORMAT
  9319.               "_%" DOUBLEST_SCAN_FORMAT "_%" DOUBLEST_SCAN_FORMAT,
  9320.               &num0, &den0, &num1, &den1);

  9321.   if (n < 2)
  9322.     return 1.0;
  9323.   else if (n == 4)
  9324.     return num1 / den1;
  9325.   else
  9326.     return num0 / den0;
  9327. }


  9328. /* Assuming that X is the representation of a value of fixed-point
  9329.    type TYPE, return its floating-point equivalent.  */

  9330. DOUBLEST
  9331. ada_fixed_to_float (struct type *type, LONGEST x)
  9332. {
  9333.   return (DOUBLEST) x *scaling_factor (type);
  9334. }

  9335. /* The representation of a fixed-point value of type TYPE
  9336.    corresponding to the value X.  */

  9337. LONGEST
  9338. ada_float_to_fixed (struct type *type, DOUBLEST x)
  9339. {
  9340.   return (LONGEST) (x / scaling_factor (type) + 0.5);
  9341. }



  9342.                                 /* Range types */

  9343. /* Scan STR beginning at position K for a discriminant name, and
  9344.    return the value of that discriminant field of DVAL in *PX.  If
  9345.    PNEW_K is not null, put the position of the character beyond the
  9346.    name scanned in *PNEW_K.  Return 1 if successful; return 0 and do
  9347.    not alter *PX and *PNEW_K if unsuccessful.  */

  9348. static int
  9349. scan_discrim_bound (char *str, int k, struct value *dval, LONGEST * px,
  9350.                     int *pnew_k)
  9351. {
  9352.   static char *bound_buffer = NULL;
  9353.   static size_t bound_buffer_len = 0;
  9354.   char *bound;
  9355.   char *pend;
  9356.   struct value *bound_val;

  9357.   if (dval == NULL || str == NULL || str[k] == '\0')
  9358.     return 0;

  9359.   pend = strstr (str + k, "__");
  9360.   if (pend == NULL)
  9361.     {
  9362.       bound = str + k;
  9363.       k += strlen (bound);
  9364.     }
  9365.   else
  9366.     {
  9367.       GROW_VECT (bound_buffer, bound_buffer_len, pend - (str + k) + 1);
  9368.       bound = bound_buffer;
  9369.       strncpy (bound_buffer, str + k, pend - (str + k));
  9370.       bound[pend - (str + k)] = '\0';
  9371.       k = pend - str;
  9372.     }

  9373.   bound_val = ada_search_struct_field (bound, dval, 0, value_type (dval));
  9374.   if (bound_val == NULL)
  9375.     return 0;

  9376.   *px = value_as_long (bound_val);
  9377.   if (pnew_k != NULL)
  9378.     *pnew_k = k;
  9379.   return 1;
  9380. }

  9381. /* Value of variable named NAME in the current environment.  If
  9382.    no such variable found, then if ERR_MSG is null, returns 0, and
  9383.    otherwise causes an error with message ERR_MSG.  */

  9384. static struct value *
  9385. get_var_value (char *name, char *err_msg)
  9386. {
  9387.   struct ada_symbol_info *syms;
  9388.   int nsyms;

  9389.   nsyms = ada_lookup_symbol_list (name, get_selected_block (0), VAR_DOMAIN,
  9390.                                   &syms);

  9391.   if (nsyms != 1)
  9392.     {
  9393.       if (err_msg == NULL)
  9394.         return 0;
  9395.       else
  9396.         error (("%s"), err_msg);
  9397.     }

  9398.   return value_of_variable (syms[0].sym, syms[0].block);
  9399. }

  9400. /* Value of integer variable named NAME in the current environment.  If
  9401.    no such variable found, returns 0, and sets *FLAG to 0.  If
  9402.    successful, sets *FLAG to 1.  */

  9403. LONGEST
  9404. get_int_var_value (char *name, int *flag)
  9405. {
  9406.   struct value *var_val = get_var_value (name, 0);

  9407.   if (var_val == 0)
  9408.     {
  9409.       if (flag != NULL)
  9410.         *flag = 0;
  9411.       return 0;
  9412.     }
  9413.   else
  9414.     {
  9415.       if (flag != NULL)
  9416.         *flag = 1;
  9417.       return value_as_long (var_val);
  9418.     }
  9419. }


  9420. /* Return a range type whose base type is that of the range type named
  9421.    NAME in the current environment, and whose bounds are calculated
  9422.    from NAME according to the GNAT range encoding conventions.
  9423.    Extract discriminant values, if needed, from DVAL.  ORIG_TYPE is the
  9424.    corresponding range type from debug information; fall back to using it
  9425.    if symbol lookup fails.  If a new type must be created, allocate it
  9426.    like ORIG_TYPE was.  The bounds information, in general, is encoded
  9427.    in NAME, the base type given in the named range type.  */

  9428. static struct type *
  9429. to_fixed_range_type (struct type *raw_type, struct value *dval)
  9430. {
  9431.   const char *name;
  9432.   struct type *base_type;
  9433.   char *subtype_info;

  9434.   gdb_assert (raw_type != NULL);
  9435.   gdb_assert (TYPE_NAME (raw_type) != NULL);

  9436.   if (TYPE_CODE (raw_type) == TYPE_CODE_RANGE)
  9437.     base_type = TYPE_TARGET_TYPE (raw_type);
  9438.   else
  9439.     base_type = raw_type;

  9440.   name = TYPE_NAME (raw_type);
  9441.   subtype_info = strstr (name, "___XD");
  9442.   if (subtype_info == NULL)
  9443.     {
  9444.       LONGEST L = ada_discrete_type_low_bound (raw_type);
  9445.       LONGEST U = ada_discrete_type_high_bound (raw_type);

  9446.       if (L < INT_MIN || U > INT_MAX)
  9447.         return raw_type;
  9448.       else
  9449.         return create_static_range_type (alloc_type_copy (raw_type), raw_type,
  9450.                                          L, U);
  9451.     }
  9452.   else
  9453.     {
  9454.       static char *name_buf = NULL;
  9455.       static size_t name_len = 0;
  9456.       int prefix_len = subtype_info - name;
  9457.       LONGEST L, U;
  9458.       struct type *type;
  9459.       char *bounds_str;
  9460.       int n;

  9461.       GROW_VECT (name_buf, name_len, prefix_len + 5);
  9462.       strncpy (name_buf, name, prefix_len);
  9463.       name_buf[prefix_len] = '\0';

  9464.       subtype_info += 5;
  9465.       bounds_str = strchr (subtype_info, '_');
  9466.       n = 1;

  9467.       if (*subtype_info == 'L')
  9468.         {
  9469.           if (!ada_scan_number (bounds_str, n, &L, &n)
  9470.               && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
  9471.             return raw_type;
  9472.           if (bounds_str[n] == '_')
  9473.             n += 2;
  9474.           else if (bounds_str[n] == '.')     /* FIXME? SGI Workshop kludge.  */
  9475.             n += 1;
  9476.           subtype_info += 1;
  9477.         }
  9478.       else
  9479.         {
  9480.           int ok;

  9481.           strcpy (name_buf + prefix_len, "___L");
  9482.           L = get_int_var_value (name_buf, &ok);
  9483.           if (!ok)
  9484.             {
  9485.               lim_warning (_("Unknown lower bound, using 1."));
  9486.               L = 1;
  9487.             }
  9488.         }

  9489.       if (*subtype_info == 'U')
  9490.         {
  9491.           if (!ada_scan_number (bounds_str, n, &U, &n)
  9492.               && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
  9493.             return raw_type;
  9494.         }
  9495.       else
  9496.         {
  9497.           int ok;

  9498.           strcpy (name_buf + prefix_len, "___U");
  9499.           U = get_int_var_value (name_buf, &ok);
  9500.           if (!ok)
  9501.             {
  9502.               lim_warning (_("Unknown upper bound, using %ld."), (long) L);
  9503.               U = L;
  9504.             }
  9505.         }

  9506.       type = create_static_range_type (alloc_type_copy (raw_type),
  9507.                                        base_type, L, U);
  9508.       TYPE_NAME (type) = name;
  9509.       return type;
  9510.     }
  9511. }

  9512. /* True iff NAME is the name of a range type.  */

  9513. int
  9514. ada_is_range_type_name (const char *name)
  9515. {
  9516.   return (name != NULL && strstr (name, "___XD"));
  9517. }


  9518.                                 /* Modular types */

  9519. /* True iff TYPE is an Ada modular type.  */

  9520. int
  9521. ada_is_modular_type (struct type *type)
  9522. {
  9523.   struct type *subranged_type = get_base_type (type);

  9524.   return (subranged_type != NULL && TYPE_CODE (type) == TYPE_CODE_RANGE
  9525.           && TYPE_CODE (subranged_type) == TYPE_CODE_INT
  9526.           && TYPE_UNSIGNED (subranged_type));
  9527. }

  9528. /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE.  */

  9529. ULONGEST
  9530. ada_modulus (struct type *type)
  9531. {
  9532.   return (ULONGEST) TYPE_HIGH_BOUND (type) + 1;
  9533. }


  9534. /* Ada exception catchpoint support:
  9535.    ---------------------------------

  9536.    We support 3 kinds of exception catchpoints:
  9537.      . catchpoints on Ada exceptions
  9538.      . catchpoints on unhandled Ada exceptions
  9539.      . catchpoints on failed assertions

  9540.    Exceptions raised during failed assertions, or unhandled exceptions
  9541.    could perfectly be caught with the general catchpoint on Ada exceptions.
  9542.    However, we can easily differentiate these two special cases, and having
  9543.    the option to distinguish these two cases from the rest can be useful
  9544.    to zero-in on certain situations.

  9545.    Exception catchpoints are a specialized form of breakpoint,
  9546.    since they rely on inserting breakpoints inside known routines
  9547.    of the GNAT runtime.  The implementation therefore uses a standard
  9548.    breakpoint structure of the BP_BREAKPOINT type, but with its own set
  9549.    of breakpoint_ops.

  9550.    Support in the runtime for exception catchpoints have been changed
  9551.    a few times already, and these changes affect the implementation
  9552.    of these catchpoints.  In order to be able to support several
  9553.    variants of the runtime, we use a sniffer that will determine
  9554.    the runtime variant used by the program being debugged.  */

  9555. /* Ada's standard exceptions.

  9556.    The Ada 83 standard also defined Numeric_Error.  But there so many
  9557.    situations where it was unclear from the Ada 83 Reference Manual
  9558.    (RM) whether Constraint_Error or Numeric_Error should be raised,
  9559.    that the ARG (Ada Rapporteur Group) eventually issued a Binding
  9560.    Interpretation saying that anytime the RM says that Numeric_Error
  9561.    should be raised, the implementation may raise Constraint_Error.
  9562.    Ada 95 went one step further and pretty much removed Numeric_Error
  9563.    from the list of standard exceptions (it made it a renaming of
  9564.    Constraint_Error, to help preserve compatibility when compiling
  9565.    an Ada83 compiler). As such, we do not include Numeric_Error from
  9566.    this list of standard exceptions.  */

  9567. static char *standard_exc[] = {
  9568.   "constraint_error",
  9569.   "program_error",
  9570.   "storage_error",
  9571.   "tasking_error"
  9572. };

  9573. typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);

  9574. /* A structure that describes how to support exception catchpoints
  9575.    for a given executable.  */

  9576. struct exception_support_info
  9577. {
  9578.    /* The name of the symbol to break on in order to insert
  9579.       a catchpoint on exceptions.  */
  9580.    const char *catch_exception_sym;

  9581.    /* The name of the symbol to break on in order to insert
  9582.       a catchpoint on unhandled exceptions.  */
  9583.    const char *catch_exception_unhandled_sym;

  9584.    /* The name of the symbol to break on in order to insert
  9585.       a catchpoint on failed assertions.  */
  9586.    const char *catch_assert_sym;

  9587.    /* Assuming that the inferior just triggered an unhandled exception
  9588.       catchpoint, this function is responsible for returning the address
  9589.       in inferior memory where the name of that exception is stored.
  9590.       Return zero if the address could not be computed.  */
  9591.    ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
  9592. };

  9593. static CORE_ADDR ada_unhandled_exception_name_addr (void);
  9594. static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);

  9595. /* The following exception support info structure describes how to
  9596.    implement exception catchpoints with the latest version of the
  9597.    Ada runtime (as of 2007-03-06).  */

  9598. static const struct exception_support_info default_exception_support_info =
  9599. {
  9600.   "__gnat_debug_raise_exception", /* catch_exception_sym */
  9601.   "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
  9602.   "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
  9603.   ada_unhandled_exception_name_addr
  9604. };

  9605. /* The following exception support info structure describes how to
  9606.    implement exception catchpoints with a slightly older version
  9607.    of the Ada runtime.  */

  9608. static const struct exception_support_info exception_support_info_fallback =
  9609. {
  9610.   "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
  9611.   "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
  9612.   "system__assertions__raise_assert_failure"/* catch_assert_sym */
  9613.   ada_unhandled_exception_name_addr_from_raise
  9614. };

  9615. /* Return nonzero if we can detect the exception support routines
  9616.    described in EINFO.

  9617.    This function errors out if an abnormal situation is detected
  9618.    (for instance, if we find the exception support routines, but
  9619.    that support is found to be incomplete).  */

  9620. static int
  9621. ada_has_this_exception_support (const struct exception_support_info *einfo)
  9622. {
  9623.   struct symbol *sym;

  9624.   /* The symbol we're looking up is provided by a unit in the GNAT runtime
  9625.      that should be compiled with debugging information.  As a result, we
  9626.      expect to find that symbol in the symtabs.  */

  9627.   sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
  9628.   if (sym == NULL)
  9629.     {
  9630.       /* Perhaps we did not find our symbol because the Ada runtime was
  9631.          compiled without debugging info, or simply stripped of it.
  9632.          It happens on some GNU/Linux distributions for instance, where
  9633.          users have to install a separate debug package in order to get
  9634.          the runtime's debugging info.  In that situation, let the user
  9635.          know why we cannot insert an Ada exception catchpoint.

  9636.          Note: Just for the purpose of inserting our Ada exception
  9637.          catchpoint, we could rely purely on the associated minimal symbol.
  9638.          But we would be operating in degraded mode anyway, since we are
  9639.          still lacking the debugging info needed later on to extract
  9640.          the name of the exception being raised (this name is printed in
  9641.          the catchpoint message, and is also used when trying to catch
  9642.          a specific exception).  We do not handle this case for now.  */
  9643.       struct bound_minimal_symbol msym
  9644.         = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);

  9645.       if (msym.minsym && MSYMBOL_TYPE (msym.minsym) != mst_solib_trampoline)
  9646.         error (_("Your Ada runtime appears to be missing some debugging "
  9647.                  "information.\nCannot insert Ada exception catchpoint "
  9648.                  "in this configuration."));

  9649.       return 0;
  9650.     }

  9651.   /* Make sure that the symbol we found corresponds to a function.  */

  9652.   if (SYMBOL_CLASS (sym) != LOC_BLOCK)
  9653.     error (_("Symbol \"%s\" is not a function (class = %d)"),
  9654.            SYMBOL_LINKAGE_NAME (sym), SYMBOL_CLASS (sym));

  9655.   return 1;
  9656. }

  9657. /* Inspect the Ada runtime and determine which exception info structure
  9658.    should be used to provide support for exception catchpoints.

  9659.    This function will always set the per-inferior exception_info,
  9660.    or raise an error.  */

  9661. static void
  9662. ada_exception_support_info_sniffer (void)
  9663. {
  9664.   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());

  9665.   /* If the exception info is already known, then no need to recompute it.  */
  9666.   if (data->exception_info != NULL)
  9667.     return;

  9668.   /* Check the latest (default) exception support info.  */
  9669.   if (ada_has_this_exception_support (&default_exception_support_info))
  9670.     {
  9671.       data->exception_info = &default_exception_support_info;
  9672.       return;
  9673.     }

  9674.   /* Try our fallback exception suport info.  */
  9675.   if (ada_has_this_exception_support (&exception_support_info_fallback))
  9676.     {
  9677.       data->exception_info = &exception_support_info_fallback;
  9678.       return;
  9679.     }

  9680.   /* Sometimes, it is normal for us to not be able to find the routine
  9681.      we are looking for.  This happens when the program is linked with
  9682.      the shared version of the GNAT runtime, and the program has not been
  9683.      started yet.  Inform the user of these two possible causes if
  9684.      applicable.  */

  9685.   if (ada_update_initial_language (language_unknown) != language_ada)
  9686.     error (_("Unable to insert catchpoint.  Is this an Ada main program?"));

  9687.   /* If the symbol does not exist, then check that the program is
  9688.      already started, to make sure that shared libraries have been
  9689.      loaded.  If it is not started, this may mean that the symbol is
  9690.      in a shared library.  */

  9691.   if (ptid_get_pid (inferior_ptid) == 0)
  9692.     error (_("Unable to insert catchpoint. Try to start the program first."));

  9693.   /* At this point, we know that we are debugging an Ada program and
  9694.      that the inferior has been started, but we still are not able to
  9695.      find the run-time symbols.  That can mean that we are in
  9696.      configurable run time mode, or that a-except as been optimized
  9697.      out by the linker...  In any case, at this point it is not worth
  9698.      supporting this feature.  */

  9699.   error (_("Cannot insert Ada exception catchpoints in this configuration."));
  9700. }

  9701. /* True iff FRAME is very likely to be that of a function that is
  9702.    part of the runtime system.  This is all very heuristic, but is
  9703.    intended to be used as advice as to what frames are uninteresting
  9704.    to most users.  */

  9705. static int
  9706. is_known_support_routine (struct frame_info *frame)
  9707. {
  9708.   struct symtab_and_line sal;
  9709.   char *func_name;
  9710.   enum language func_lang;
  9711.   int i;
  9712.   const char *fullname;

  9713.   /* If this code does not have any debugging information (no symtab),
  9714.      This cannot be any user code.  */

  9715.   find_frame_sal (frame, &sal);
  9716.   if (sal.symtab == NULL)
  9717.     return 1;

  9718.   /* If there is a symtab, but the associated source file cannot be
  9719.      located, then assume this is not user code:  Selecting a frame
  9720.      for which we cannot display the code would not be very helpful
  9721.      for the user.  This should also take care of case such as VxWorks
  9722.      where the kernel has some debugging info provided for a few units.  */

  9723.   fullname = symtab_to_fullname (sal.symtab);
  9724.   if (access (fullname, R_OK) != 0)
  9725.     return 1;

  9726.   /* Check the unit filename againt the Ada runtime file naming.
  9727.      We also check the name of the objfile against the name of some
  9728.      known system libraries that sometimes come with debugging info
  9729.      too.  */

  9730.   for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
  9731.     {
  9732.       re_comp (known_runtime_file_name_patterns[i]);
  9733.       if (re_exec (lbasename (sal.symtab->filename)))
  9734.         return 1;
  9735.       if (SYMTAB_OBJFILE (sal.symtab) != NULL
  9736.           && re_exec (objfile_name (SYMTAB_OBJFILE (sal.symtab))))
  9737.         return 1;
  9738.     }

  9739.   /* Check whether the function is a GNAT-generated entity.  */

  9740.   find_frame_funname (frame, &func_name, &func_lang, NULL);
  9741.   if (func_name == NULL)
  9742.     return 1;

  9743.   for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
  9744.     {
  9745.       re_comp (known_auxiliary_function_name_patterns[i]);
  9746.       if (re_exec (func_name))
  9747.         {
  9748.           xfree (func_name);
  9749.           return 1;
  9750.         }
  9751.     }

  9752.   xfree (func_name);
  9753.   return 0;
  9754. }

  9755. /* Find the first frame that contains debugging information and that is not
  9756.    part of the Ada run-time, starting from FI and moving upward.  */

  9757. void
  9758. ada_find_printable_frame (struct frame_info *fi)
  9759. {
  9760.   for (; fi != NULL; fi = get_prev_frame (fi))
  9761.     {
  9762.       if (!is_known_support_routine (fi))
  9763.         {
  9764.           select_frame (fi);
  9765.           break;
  9766.         }
  9767.     }

  9768. }

  9769. /* Assuming that the inferior just triggered an unhandled exception
  9770.    catchpoint, return the address in inferior memory where the name
  9771.    of the exception is stored.

  9772.    Return zero if the address could not be computed.  */

  9773. static CORE_ADDR
  9774. ada_unhandled_exception_name_addr (void)
  9775. {
  9776.   return parse_and_eval_address ("e.full_name");
  9777. }

  9778. /* Same as ada_unhandled_exception_name_addr, except that this function
  9779.    should be used when the inferior uses an older version of the runtime,
  9780.    where the exception name needs to be extracted from a specific frame
  9781.    several frames up in the callstack.  */

  9782. static CORE_ADDR
  9783. ada_unhandled_exception_name_addr_from_raise (void)
  9784. {
  9785.   int frame_level;
  9786.   struct frame_info *fi;
  9787.   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
  9788.   struct cleanup *old_chain;

  9789.   /* To determine the name of this exception, we need to select
  9790.      the frame corresponding to RAISE_SYM_NAME.  This frame is
  9791.      at least 3 levels up, so we simply skip the first 3 frames
  9792.      without checking the name of their associated function.  */
  9793.   fi = get_current_frame ();
  9794.   for (frame_level = 0; frame_level < 3; frame_level += 1)
  9795.     if (fi != NULL)
  9796.       fi = get_prev_frame (fi);

  9797.   old_chain = make_cleanup (null_cleanup, NULL);
  9798.   while (fi != NULL)
  9799.     {
  9800.       char *func_name;
  9801.       enum language func_lang;

  9802.       find_frame_funname (fi, &func_name, &func_lang, NULL);
  9803.       if (func_name != NULL)
  9804.         {
  9805.           make_cleanup (xfree, func_name);

  9806.           if (strcmp (func_name,
  9807.                       data->exception_info->catch_exception_sym) == 0)
  9808.             break; /* We found the frame we were looking for...  */
  9809.           fi = get_prev_frame (fi);
  9810.         }
  9811.     }
  9812.   do_cleanups (old_chain);

  9813.   if (fi == NULL)
  9814.     return 0;

  9815.   select_frame (fi);
  9816.   return parse_and_eval_address ("id.full_name");
  9817. }

  9818. /* Assuming the inferior just triggered an Ada exception catchpoint
  9819.    (of any type), return the address in inferior memory where the name
  9820.    of the exception is stored, if applicable.

  9821.    Return zero if the address could not be computed, or if not relevant.  */

  9822. static CORE_ADDR
  9823. ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex,
  9824.                            struct breakpoint *b)
  9825. {
  9826.   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());

  9827.   switch (ex)
  9828.     {
  9829.       case ada_catch_exception:
  9830.         return (parse_and_eval_address ("e.full_name"));
  9831.         break;

  9832.       case ada_catch_exception_unhandled:
  9833.         return data->exception_info->unhandled_exception_name_addr ();
  9834.         break;

  9835.       case ada_catch_assert:
  9836.         return 0/* Exception name is not relevant in this case.  */
  9837.         break;

  9838.       default:
  9839.         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
  9840.         break;
  9841.     }

  9842.   return 0; /* Should never be reached.  */
  9843. }

  9844. /* Same as ada_exception_name_addr_1, except that it intercepts and contains
  9845.    any error that ada_exception_name_addr_1 might cause to be thrown.
  9846.    When an error is intercepted, a warning with the error message is printed,
  9847.    and zero is returned.  */

  9848. static CORE_ADDR
  9849. ada_exception_name_addr (enum ada_exception_catchpoint_kind ex,
  9850.                          struct breakpoint *b)
  9851. {
  9852.   volatile struct gdb_exception e;
  9853.   CORE_ADDR result = 0;

  9854.   TRY_CATCH (e, RETURN_MASK_ERROR)
  9855.     {
  9856.       result = ada_exception_name_addr_1 (ex, b);
  9857.     }

  9858.   if (e.reason < 0)
  9859.     {
  9860.       warning (_("failed to get exception name: %s"), e.message);
  9861.       return 0;
  9862.     }

  9863.   return result;
  9864. }

  9865. static char *ada_exception_catchpoint_cond_string (const char *excep_string);

  9866. /* Ada catchpoints.

  9867.    In the case of catchpoints on Ada exceptions, the catchpoint will
  9868.    stop the target on every exception the program throws.  When a user
  9869.    specifies the name of a specific exception, we translate this
  9870.    request into a condition expression (in text form), and then parse
  9871.    it into an expression stored in each of the catchpoint's locations.
  9872.    We then use this condition to check whether the exception that was
  9873.    raised is the one the user is interested in.  If not, then the
  9874.    target is resumed again.  We store the name of the requested
  9875.    exception, in order to be able to re-set the condition expression
  9876.    when symbols change.  */

  9877. /* An instance of this type is used to represent an Ada catchpoint
  9878.    breakpoint location.  It includes a "struct bp_location" as a kind
  9879.    of base class; users downcast to "struct bp_location *" when
  9880.    needed.  */

  9881. struct ada_catchpoint_location
  9882. {
  9883.   /* The base class.  */
  9884.   struct bp_location base;

  9885.   /* The condition that checks whether the exception that was raised
  9886.      is the specific exception the user specified on catchpoint
  9887.      creation.  */
  9888.   struct expression *excep_cond_expr;
  9889. };

  9890. /* Implement the DTOR method in the bp_location_ops structure for all
  9891.    Ada exception catchpoint kinds.  */

  9892. static void
  9893. ada_catchpoint_location_dtor (struct bp_location *bl)
  9894. {
  9895.   struct ada_catchpoint_location *al = (struct ada_catchpoint_location *) bl;

  9896.   xfree (al->excep_cond_expr);
  9897. }

  9898. /* The vtable to be used in Ada catchpoint locations.  */

  9899. static const struct bp_location_ops ada_catchpoint_location_ops =
  9900. {
  9901.   ada_catchpoint_location_dtor
  9902. };

  9903. /* An instance of this type is used to represent an Ada catchpoint.
  9904.    It includes a "struct breakpoint" as a kind of base class; users
  9905.    downcast to "struct breakpoint *" when needed.  */

  9906. struct ada_catchpoint
  9907. {
  9908.   /* The base class.  */
  9909.   struct breakpoint base;

  9910.   /* The name of the specific exception the user specified.  */
  9911.   char *excep_string;
  9912. };

  9913. /* Parse the exception condition string in the context of each of the
  9914.    catchpoint's locations, and store them for later evaluation.  */

  9915. static void
  9916. create_excep_cond_exprs (struct ada_catchpoint *c)
  9917. {
  9918.   struct cleanup *old_chain;
  9919.   struct bp_location *bl;
  9920.   char *cond_string;

  9921.   /* Nothing to do if there's no specific exception to catch.  */
  9922.   if (c->excep_string == NULL)
  9923.     return;

  9924.   /* Same if there are no locations... */
  9925.   if (c->base.loc == NULL)
  9926.     return;

  9927.   /* Compute the condition expression in text form, from the specific
  9928.      expection we want to catch.  */
  9929.   cond_string = ada_exception_catchpoint_cond_string (c->excep_string);
  9930.   old_chain = make_cleanup (xfree, cond_string);

  9931.   /* Iterate over all the catchpoint's locations, and parse an
  9932.      expression for each.  */
  9933.   for (bl = c->base.loc; bl != NULL; bl = bl->next)
  9934.     {
  9935.       struct ada_catchpoint_location *ada_loc
  9936.         = (struct ada_catchpoint_location *) bl;
  9937.       struct expression *exp = NULL;

  9938.       if (!bl->shlib_disabled)
  9939.         {
  9940.           volatile struct gdb_exception e;
  9941.           const char *s;

  9942.           s = cond_string;
  9943.           TRY_CATCH (e, RETURN_MASK_ERROR)
  9944.             {
  9945.               exp = parse_exp_1 (&s, bl->address,
  9946.                                  block_for_pc (bl->address), 0);
  9947.             }
  9948.           if (e.reason < 0)
  9949.             {
  9950.               warning (_("failed to reevaluate internal exception condition "
  9951.                          "for catchpoint %d: %s"),
  9952.                        c->base.number, e.message);
  9953.               /* There is a bug in GCC on sparc-solaris when building with
  9954.                  optimization which causes EXP to change unexpectedly
  9955.                  (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=56982).
  9956.                  The problem should be fixed starting with GCC 4.9.
  9957.                  In the meantime, work around it by forcing EXP back
  9958.                  to NULL.  */
  9959.               exp = NULL;
  9960.             }
  9961.         }

  9962.       ada_loc->excep_cond_expr = exp;
  9963.     }

  9964.   do_cleanups (old_chain);
  9965. }

  9966. /* Implement the DTOR method in the breakpoint_ops structure for all
  9967.    exception catchpoint kinds.  */

  9968. static void
  9969. dtor_exception (enum ada_exception_catchpoint_kind ex, struct breakpoint *b)
  9970. {
  9971.   struct ada_catchpoint *c = (struct ada_catchpoint *) b;

  9972.   xfree (c->excep_string);

  9973.   bkpt_breakpoint_ops.dtor (b);
  9974. }

  9975. /* Implement the ALLOCATE_LOCATION method in the breakpoint_ops
  9976.    structure for all exception catchpoint kinds.  */

  9977. static struct bp_location *
  9978. allocate_location_exception (enum ada_exception_catchpoint_kind ex,
  9979.                              struct breakpoint *self)
  9980. {
  9981.   struct ada_catchpoint_location *loc;

  9982.   loc = XNEW (struct ada_catchpoint_location);
  9983.   init_bp_location (&loc->base, &ada_catchpoint_location_ops, self);
  9984.   loc->excep_cond_expr = NULL;
  9985.   return &loc->base;
  9986. }

  9987. /* Implement the RE_SET method in the breakpoint_ops structure for all
  9988.    exception catchpoint kinds.  */

  9989. static void
  9990. re_set_exception (enum ada_exception_catchpoint_kind ex, struct breakpoint *b)
  9991. {
  9992.   struct ada_catchpoint *c = (struct ada_catchpoint *) b;

  9993.   /* Call the base class's method.  This updates the catchpoint's
  9994.      locations.  */
  9995.   bkpt_breakpoint_ops.re_set (b);

  9996.   /* Reparse the exception conditional expressions.  One for each
  9997.      location.  */
  9998.   create_excep_cond_exprs (c);
  9999. }

  10000. /* Returns true if we should stop for this breakpoint hit.  If the
  10001.    user specified a specific exception, we only want to cause a stop
  10002.    if the program thrown that exception.  */

  10003. static int
  10004. should_stop_exception (const struct bp_location *bl)
  10005. {
  10006.   struct ada_catchpoint *c = (struct ada_catchpoint *) bl->owner;
  10007.   const struct ada_catchpoint_location *ada_loc
  10008.     = (const struct ada_catchpoint_location *) bl;
  10009.   volatile struct gdb_exception ex;
  10010.   int stop;

  10011.   /* With no specific exception, should always stop.  */
  10012.   if (c->excep_string == NULL)
  10013.     return 1;

  10014.   if (ada_loc->excep_cond_expr == NULL)
  10015.     {
  10016.       /* We will have a NULL expression if back when we were creating
  10017.          the expressions, this location's had failed to parse.  */
  10018.       return 1;
  10019.     }

  10020.   stop = 1;
  10021.   TRY_CATCH (ex, RETURN_MASK_ALL)
  10022.     {
  10023.       struct value *mark;

  10024.       mark = value_mark ();
  10025.       stop = value_true (evaluate_expression (ada_loc->excep_cond_expr));
  10026.       value_free_to_mark (mark);
  10027.     }
  10028.   if (ex.reason < 0)
  10029.     exception_fprintf (gdb_stderr, ex,
  10030.                        _("Error in testing exception condition:\n"));
  10031.   return stop;
  10032. }

  10033. /* Implement the CHECK_STATUS method in the breakpoint_ops structure
  10034.    for all exception catchpoint kinds.  */

  10035. static void
  10036. check_status_exception (enum ada_exception_catchpoint_kind ex, bpstat bs)
  10037. {
  10038.   bs->stop = should_stop_exception (bs->bp_location_at);
  10039. }

  10040. /* Implement the PRINT_IT method in the breakpoint_ops structure
  10041.    for all exception catchpoint kinds.  */

  10042. static enum print_stop_action
  10043. print_it_exception (enum ada_exception_catchpoint_kind ex, bpstat bs)
  10044. {
  10045.   struct ui_out *uiout = current_uiout;
  10046.   struct breakpoint *b = bs->breakpoint_at;

  10047.   annotate_catchpoint (b->number);

  10048.   if (ui_out_is_mi_like_p (uiout))
  10049.     {
  10050.       ui_out_field_string (uiout, "reason",
  10051.                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
  10052.       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
  10053.     }

  10054.   ui_out_text (uiout,
  10055.                b->disposition == disp_del ? "\nTemporary catchpoint "
  10056.                                           : "\nCatchpoint ");
  10057.   ui_out_field_int (uiout, "bkptno", b->number);
  10058.   ui_out_text (uiout, ", ");

  10059.   switch (ex)
  10060.     {
  10061.       case ada_catch_exception:
  10062.       case ada_catch_exception_unhandled:
  10063.         {
  10064.           const CORE_ADDR addr = ada_exception_name_addr (ex, b);
  10065.           char exception_name[256];

  10066.           if (addr != 0)
  10067.             {
  10068.               read_memory (addr, (gdb_byte *) exception_name,
  10069.                            sizeof (exception_name) - 1);
  10070.               exception_name [sizeof (exception_name) - 1] = '\0';
  10071.             }
  10072.           else
  10073.             {
  10074.               /* For some reason, we were unable to read the exception
  10075.                  name.  This could happen if the Runtime was compiled
  10076.                  without debugging info, for instance.  In that case,
  10077.                  just replace the exception name by the generic string
  10078.                  "exception" - it will read as "an exception" in the
  10079.                  notification we are about to print.  */
  10080.               memcpy (exception_name, "exception", sizeof ("exception"));
  10081.             }
  10082.           /* In the case of unhandled exception breakpoints, we print
  10083.              the exception name as "unhandled EXCEPTION_NAME", to make
  10084.              it clearer to the user which kind of catchpoint just got
  10085.              hit.  We used ui_out_text to make sure that this extra
  10086.              info does not pollute the exception name in the MI case.  */
  10087.           if (ex == ada_catch_exception_unhandled)
  10088.             ui_out_text (uiout, "unhandled ");
  10089.           ui_out_field_string (uiout, "exception-name", exception_name);
  10090.         }
  10091.         break;
  10092.       case ada_catch_assert:
  10093.         /* In this case, the name of the exception is not really
  10094.            important.  Just print "failed assertion" to make it clearer
  10095.            that his program just hit an assertion-failure catchpoint.
  10096.            We used ui_out_text because this info does not belong in
  10097.            the MI output.  */
  10098.         ui_out_text (uiout, "failed assertion");
  10099.         break;
  10100.     }
  10101.   ui_out_text (uiout, " at ");
  10102.   ada_find_printable_frame (get_current_frame ());

  10103.   return PRINT_SRC_AND_LOC;
  10104. }

  10105. /* Implement the PRINT_ONE method in the breakpoint_ops structure
  10106.    for all exception catchpoint kinds.  */

  10107. static void
  10108. print_one_exception (enum ada_exception_catchpoint_kind ex,
  10109.                      struct breakpoint *b, struct bp_location **last_loc)
  10110. {
  10111.   struct ui_out *uiout = current_uiout;
  10112.   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
  10113.   struct value_print_options opts;

  10114.   get_user_print_options (&opts);
  10115.   if (opts.addressprint)
  10116.     {
  10117.       annotate_field (4);
  10118.       ui_out_field_core_addr (uiout, "addr", b->loc->gdbarch, b->loc->address);
  10119.     }

  10120.   annotate_field (5);
  10121.   *last_loc = b->loc;
  10122.   switch (ex)
  10123.     {
  10124.       case ada_catch_exception:
  10125.         if (c->excep_string != NULL)
  10126.           {
  10127.             char *msg = xstrprintf (_("`%s' Ada exception"), c->excep_string);

  10128.             ui_out_field_string (uiout, "what", msg);
  10129.             xfree (msg);
  10130.           }
  10131.         else
  10132.           ui_out_field_string (uiout, "what", "all Ada exceptions");

  10133.         break;

  10134.       case ada_catch_exception_unhandled:
  10135.         ui_out_field_string (uiout, "what", "unhandled Ada exceptions");
  10136.         break;

  10137.       case ada_catch_assert:
  10138.         ui_out_field_string (uiout, "what", "failed Ada assertions");
  10139.         break;

  10140.       default:
  10141.         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
  10142.         break;
  10143.     }
  10144. }

  10145. /* Implement the PRINT_MENTION method in the breakpoint_ops structure
  10146.    for all exception catchpoint kinds.  */

  10147. static void
  10148. print_mention_exception (enum ada_exception_catchpoint_kind ex,
  10149.                          struct breakpoint *b)
  10150. {
  10151.   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
  10152.   struct ui_out *uiout = current_uiout;

  10153.   ui_out_text (uiout, b->disposition == disp_del ? _("Temporary catchpoint ")
  10154.                                                  : _("Catchpoint "));
  10155.   ui_out_field_int (uiout, "bkptno", b->number);
  10156.   ui_out_text (uiout, ": ");

  10157.   switch (ex)
  10158.     {
  10159.       case ada_catch_exception:
  10160.         if (c->excep_string != NULL)
  10161.           {
  10162.             char *info = xstrprintf (_("`%s' Ada exception"), c->excep_string);
  10163.             struct cleanup *old_chain = make_cleanup (xfree, info);

  10164.             ui_out_text (uiout, info);
  10165.             do_cleanups (old_chain);
  10166.           }
  10167.         else
  10168.           ui_out_text (uiout, _("all Ada exceptions"));
  10169.         break;

  10170.       case ada_catch_exception_unhandled:
  10171.         ui_out_text (uiout, _("unhandled Ada exceptions"));
  10172.         break;

  10173.       case ada_catch_assert:
  10174.         ui_out_text (uiout, _("failed Ada assertions"));
  10175.         break;

  10176.       default:
  10177.         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
  10178.         break;
  10179.     }
  10180. }

  10181. /* Implement the PRINT_RECREATE method in the breakpoint_ops structure
  10182.    for all exception catchpoint kinds.  */

  10183. static void
  10184. print_recreate_exception (enum ada_exception_catchpoint_kind ex,
  10185.                           struct breakpoint *b, struct ui_file *fp)
  10186. {
  10187.   struct ada_catchpoint *c = (struct ada_catchpoint *) b;

  10188.   switch (ex)
  10189.     {
  10190.       case ada_catch_exception:
  10191.         fprintf_filtered (fp, "catch exception");
  10192.         if (c->excep_string != NULL)
  10193.           fprintf_filtered (fp, " %s", c->excep_string);
  10194.         break;

  10195.       case ada_catch_exception_unhandled:
  10196.         fprintf_filtered (fp, "catch exception unhandled");
  10197.         break;

  10198.       case ada_catch_assert:
  10199.         fprintf_filtered (fp, "catch assert");
  10200.         break;

  10201.       default:
  10202.         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
  10203.     }
  10204.   print_recreate_thread (b, fp);
  10205. }

  10206. /* Virtual table for "catch exception" breakpoints.  */

  10207. static void
  10208. dtor_catch_exception (struct breakpoint *b)
  10209. {
  10210.   dtor_exception (ada_catch_exception, b);
  10211. }

  10212. static struct bp_location *
  10213. allocate_location_catch_exception (struct breakpoint *self)
  10214. {
  10215.   return allocate_location_exception (ada_catch_exception, self);
  10216. }

  10217. static void
  10218. re_set_catch_exception (struct breakpoint *b)
  10219. {
  10220.   re_set_exception (ada_catch_exception, b);
  10221. }

  10222. static void
  10223. check_status_catch_exception (bpstat bs)
  10224. {
  10225.   check_status_exception (ada_catch_exception, bs);
  10226. }

  10227. static enum print_stop_action
  10228. print_it_catch_exception (bpstat bs)
  10229. {
  10230.   return print_it_exception (ada_catch_exception, bs);
  10231. }

  10232. static void
  10233. print_one_catch_exception (struct breakpoint *b, struct bp_location **last_loc)
  10234. {
  10235.   print_one_exception (ada_catch_exception, b, last_loc);
  10236. }

  10237. static void
  10238. print_mention_catch_exception (struct breakpoint *b)
  10239. {
  10240.   print_mention_exception (ada_catch_exception, b);
  10241. }

  10242. static void
  10243. print_recreate_catch_exception (struct breakpoint *b, struct ui_file *fp)
  10244. {
  10245.   print_recreate_exception (ada_catch_exception, b, fp);
  10246. }

  10247. static struct breakpoint_ops catch_exception_breakpoint_ops;

  10248. /* Virtual table for "catch exception unhandled" breakpoints.  */

  10249. static void
  10250. dtor_catch_exception_unhandled (struct breakpoint *b)
  10251. {
  10252.   dtor_exception (ada_catch_exception_unhandled, b);
  10253. }

  10254. static struct bp_location *
  10255. allocate_location_catch_exception_unhandled (struct breakpoint *self)
  10256. {
  10257.   return allocate_location_exception (ada_catch_exception_unhandled, self);
  10258. }

  10259. static void
  10260. re_set_catch_exception_unhandled (struct breakpoint *b)
  10261. {
  10262.   re_set_exception (ada_catch_exception_unhandled, b);
  10263. }

  10264. static void
  10265. check_status_catch_exception_unhandled (bpstat bs)
  10266. {
  10267.   check_status_exception (ada_catch_exception_unhandled, bs);
  10268. }

  10269. static enum print_stop_action
  10270. print_it_catch_exception_unhandled (bpstat bs)
  10271. {
  10272.   return print_it_exception (ada_catch_exception_unhandled, bs);
  10273. }

  10274. static void
  10275. print_one_catch_exception_unhandled (struct breakpoint *b,
  10276.                                      struct bp_location **last_loc)
  10277. {
  10278.   print_one_exception (ada_catch_exception_unhandled, b, last_loc);
  10279. }

  10280. static void
  10281. print_mention_catch_exception_unhandled (struct breakpoint *b)
  10282. {
  10283.   print_mention_exception (ada_catch_exception_unhandled, b);
  10284. }

  10285. static void
  10286. print_recreate_catch_exception_unhandled (struct breakpoint *b,
  10287.                                           struct ui_file *fp)
  10288. {
  10289.   print_recreate_exception (ada_catch_exception_unhandled, b, fp);
  10290. }

  10291. static struct breakpoint_ops catch_exception_unhandled_breakpoint_ops;

  10292. /* Virtual table for "catch assert" breakpoints.  */

  10293. static void
  10294. dtor_catch_assert (struct breakpoint *b)
  10295. {
  10296.   dtor_exception (ada_catch_assert, b);
  10297. }

  10298. static struct bp_location *
  10299. allocate_location_catch_assert (struct breakpoint *self)
  10300. {
  10301.   return allocate_location_exception (ada_catch_assert, self);
  10302. }

  10303. static void
  10304. re_set_catch_assert (struct breakpoint *b)
  10305. {
  10306.   re_set_exception (ada_catch_assert, b);
  10307. }

  10308. static void
  10309. check_status_catch_assert (bpstat bs)
  10310. {
  10311.   check_status_exception (ada_catch_assert, bs);
  10312. }

  10313. static enum print_stop_action
  10314. print_it_catch_assert (bpstat bs)
  10315. {
  10316.   return print_it_exception (ada_catch_assert, bs);
  10317. }

  10318. static void
  10319. print_one_catch_assert (struct breakpoint *b, struct bp_location **last_loc)
  10320. {
  10321.   print_one_exception (ada_catch_assert, b, last_loc);
  10322. }

  10323. static void
  10324. print_mention_catch_assert (struct breakpoint *b)
  10325. {
  10326.   print_mention_exception (ada_catch_assert, b);
  10327. }

  10328. static void
  10329. print_recreate_catch_assert (struct breakpoint *b, struct ui_file *fp)
  10330. {
  10331.   print_recreate_exception (ada_catch_assert, b, fp);
  10332. }

  10333. static struct breakpoint_ops catch_assert_breakpoint_ops;

  10334. /* Return a newly allocated copy of the first space-separated token
  10335.    in ARGSP, and then adjust ARGSP to point immediately after that
  10336.    token.

  10337.    Return NULL if ARGPS does not contain any more tokens.  */

  10338. static char *
  10339. ada_get_next_arg (char **argsp)
  10340. {
  10341.   char *args = *argsp;
  10342.   char *end;
  10343.   char *result;

  10344.   args = skip_spaces (args);
  10345.   if (args[0] == '\0')
  10346.     return NULL; /* No more arguments.  */

  10347.   /* Find the end of the current argument.  */

  10348.   end = skip_to_space (args);

  10349.   /* Adjust ARGSP to point to the start of the next argument.  */

  10350.   *argsp = end;

  10351.   /* Make a copy of the current argument and return it.  */

  10352.   result = xmalloc (end - args + 1);
  10353.   strncpy (result, args, end - args);
  10354.   result[end - args] = '\0';

  10355.   return result;
  10356. }

  10357. /* Split the arguments specified in a "catch exception" command.
  10358.    Set EX to the appropriate catchpoint type.
  10359.    Set EXCEP_STRING to the name of the specific exception if
  10360.    specified by the user.
  10361.    If a condition is found at the end of the arguments, the condition
  10362.    expression is stored in COND_STRING (memory must be deallocated
  10363.    after use).  Otherwise COND_STRING is set to NULL.  */

  10364. static void
  10365. catch_ada_exception_command_split (char *args,
  10366.                                    enum ada_exception_catchpoint_kind *ex,
  10367.                                    char **excep_string,
  10368.                                    char **cond_string)
  10369. {
  10370.   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
  10371.   char *exception_name;
  10372.   char *cond = NULL;

  10373.   exception_name = ada_get_next_arg (&args);
  10374.   if (exception_name != NULL && strcmp (exception_name, "if") == 0)
  10375.     {
  10376.       /* This is not an exception name; this is the start of a condition
  10377.          expression for a catchpoint on all exceptions.  So, "un-get"
  10378.          this token, and set exception_name to NULL.  */
  10379.       xfree (exception_name);
  10380.       exception_name = NULL;
  10381.       args -= 2;
  10382.     }
  10383.   make_cleanup (xfree, exception_name);

  10384.   /* Check to see if we have a condition.  */

  10385.   args = skip_spaces (args);
  10386.   if (strncmp (args, "if", 2) == 0
  10387.       && (isspace (args[2]) || args[2] == '\0'))
  10388.     {
  10389.       args += 2;
  10390.       args = skip_spaces (args);

  10391.       if (args[0] == '\0')
  10392.         error (_("Condition missing after `if' keyword"));
  10393.       cond = xstrdup (args);
  10394.       make_cleanup (xfree, cond);

  10395.       args += strlen (args);
  10396.     }

  10397.   /* Check that we do not have any more arguments.  Anything else
  10398.      is unexpected.  */

  10399.   if (args[0] != '\0')
  10400.     error (_("Junk at end of expression"));

  10401.   discard_cleanups (old_chain);

  10402.   if (exception_name == NULL)
  10403.     {
  10404.       /* Catch all exceptions.  */
  10405.       *ex = ada_catch_exception;
  10406.       *excep_string = NULL;
  10407.     }
  10408.   else if (strcmp (exception_name, "unhandled") == 0)
  10409.     {
  10410.       /* Catch unhandled exceptions.  */
  10411.       *ex = ada_catch_exception_unhandled;
  10412.       *excep_string = NULL;
  10413.     }
  10414.   else
  10415.     {
  10416.       /* Catch a specific exception.  */
  10417.       *ex = ada_catch_exception;
  10418.       *excep_string = exception_name;
  10419.     }
  10420.   *cond_string = cond;
  10421. }

  10422. /* Return the name of the symbol on which we should break in order to
  10423.    implement a catchpoint of the EX kind.  */

  10424. static const char *
  10425. ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
  10426. {
  10427.   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());

  10428.   gdb_assert (data->exception_info != NULL);

  10429.   switch (ex)
  10430.     {
  10431.       case ada_catch_exception:
  10432.         return (data->exception_info->catch_exception_sym);
  10433.         break;
  10434.       case ada_catch_exception_unhandled:
  10435.         return (data->exception_info->catch_exception_unhandled_sym);
  10436.         break;
  10437.       case ada_catch_assert:
  10438.         return (data->exception_info->catch_assert_sym);
  10439.         break;
  10440.       default:
  10441.         internal_error (__FILE__, __LINE__,
  10442.                         _("unexpected catchpoint kind (%d)"), ex);
  10443.     }
  10444. }

  10445. /* Return the breakpoint ops "virtual table" used for catchpoints
  10446.    of the EX kind.  */

  10447. static const struct breakpoint_ops *
  10448. ada_exception_breakpoint_ops (enum ada_exception_catchpoint_kind ex)
  10449. {
  10450.   switch (ex)
  10451.     {
  10452.       case ada_catch_exception:
  10453.         return (&catch_exception_breakpoint_ops);
  10454.         break;
  10455.       case ada_catch_exception_unhandled:
  10456.         return (&catch_exception_unhandled_breakpoint_ops);
  10457.         break;
  10458.       case ada_catch_assert:
  10459.         return (&catch_assert_breakpoint_ops);
  10460.         break;
  10461.       default:
  10462.         internal_error (__FILE__, __LINE__,
  10463.                         _("unexpected catchpoint kind (%d)"), ex);
  10464.     }
  10465. }

  10466. /* Return the condition that will be used to match the current exception
  10467.    being raised with the exception that the user wants to catch.  This
  10468.    assumes that this condition is used when the inferior just triggered
  10469.    an exception catchpoint.

  10470.    The string returned is a newly allocated string that needs to be
  10471.    deallocated later.  */

  10472. static char *
  10473. ada_exception_catchpoint_cond_string (const char *excep_string)
  10474. {
  10475.   int i;

  10476.   /* The standard exceptions are a special case.  They are defined in
  10477.      runtime units that have been compiled without debugging info; if
  10478.      EXCEP_STRING is the not-fully-qualified name of a standard
  10479.      exception (e.g. "constraint_error") then, during the evaluation
  10480.      of the condition expression, the symbol lookup on this name would
  10481.      *not* return this standard exception.  The catchpoint condition
  10482.      may then be set only on user-defined exceptions which have the
  10483.      same not-fully-qualified name (e.g. my_package.constraint_error).

  10484.      To avoid this unexcepted behavior, these standard exceptions are
  10485.      systematically prefixed by "standard".  This means that "catch
  10486.      exception constraint_error" is rewritten into "catch exception
  10487.      standard.constraint_error".

  10488.      If an exception named contraint_error is defined in another package of
  10489.      the inferior program, then the only way to specify this exception as a
  10490.      breakpoint condition is to use its fully-qualified named:
  10491.      e.g. my_package.constraint_error.  */

  10492.   for (i = 0; i < sizeof (standard_exc) / sizeof (char *); i++)
  10493.     {
  10494.       if (strcmp (standard_exc [i], excep_string) == 0)
  10495.         {
  10496.           return xstrprintf ("long_integer (e) = long_integer (&standard.%s)",
  10497.                              excep_string);
  10498.         }
  10499.     }
  10500.   return xstrprintf ("long_integer (e) = long_integer (&%s)", excep_string);
  10501. }

  10502. /* Return the symtab_and_line that should be used to insert an exception
  10503.    catchpoint of the TYPE kind.

  10504.    EXCEP_STRING should contain the name of a specific exception that
  10505.    the catchpoint should catch, or NULL otherwise.

  10506.    ADDR_STRING returns the name of the function where the real
  10507.    breakpoint that implements the catchpoints is set, depending on the
  10508.    type of catchpoint we need to create.  */

  10509. static struct symtab_and_line
  10510. ada_exception_sal (enum ada_exception_catchpoint_kind ex, char *excep_string,
  10511.                    char **addr_string, const struct breakpoint_ops **ops)
  10512. {
  10513.   const char *sym_name;
  10514.   struct symbol *sym;

  10515.   /* First, find out which exception support info to use.  */
  10516.   ada_exception_support_info_sniffer ();

  10517.   /* Then lookup the function on which we will break in order to catch
  10518.      the Ada exceptions requested by the user.  */
  10519.   sym_name = ada_exception_sym_name (ex);
  10520.   sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);

  10521.   /* We can assume that SYM is not NULL at this stage.  If the symbol
  10522.      did not exist, ada_exception_support_info_sniffer would have
  10523.      raised an exception.

  10524.      Also, ada_exception_support_info_sniffer should have already
  10525.      verified that SYM is a function symbol.  */
  10526.   gdb_assert (sym != NULL);
  10527.   gdb_assert (SYMBOL_CLASS (sym) == LOC_BLOCK);

  10528.   /* Set ADDR_STRING.  */
  10529.   *addr_string = xstrdup (sym_name);

  10530.   /* Set OPS.  */
  10531.   *ops = ada_exception_breakpoint_ops (ex);

  10532.   return find_function_start_sal (sym, 1);
  10533. }

  10534. /* Create an Ada exception catchpoint.

  10535.    EX_KIND is the kind of exception catchpoint to be created.

  10536.    If EXCEPT_STRING is NULL, this catchpoint is expected to trigger
  10537.    for all exceptions.  Otherwise, EXCEPT_STRING indicates the name
  10538.    of the exception to which this catchpoint applies.  When not NULL,
  10539.    the string must be allocated on the heap, and its deallocation
  10540.    is no longer the responsibility of the caller.

  10541.    COND_STRING, if not NULL, is the catchpoint condition.  This string
  10542.    must be allocated on the heap, and its deallocation is no longer
  10543.    the responsibility of the caller.

  10544.    TEMPFLAG, if nonzero, means that the underlying breakpoint
  10545.    should be temporary.

  10546.    FROM_TTY is the usual argument passed to all commands implementations.  */

  10547. void
  10548. create_ada_exception_catchpoint (struct gdbarch *gdbarch,
  10549.                                  enum ada_exception_catchpoint_kind ex_kind,
  10550.                                  char *excep_string,
  10551.                                  char *cond_string,
  10552.                                  int tempflag,
  10553.                                  int disabled,
  10554.                                  int from_tty)
  10555. {
  10556.   struct ada_catchpoint *c;
  10557.   char *addr_string = NULL;
  10558.   const struct breakpoint_ops *ops = NULL;
  10559.   struct symtab_and_line sal
  10560.     = ada_exception_sal (ex_kind, excep_string, &addr_string, &ops);

  10561.   c = XNEW (struct ada_catchpoint);
  10562.   init_ada_exception_breakpoint (&c->base, gdbarch, sal, addr_string,
  10563.                                  ops, tempflag, disabled, from_tty);
  10564.   c->excep_string = excep_string;
  10565.   create_excep_cond_exprs (c);
  10566.   if (cond_string != NULL)
  10567.     set_breakpoint_condition (&c->base, cond_string, from_tty);
  10568.   install_breakpoint (0, &c->base, 1);
  10569. }

  10570. /* Implement the "catch exception" command.  */

  10571. static void
  10572. catch_ada_exception_command (char *arg, int from_tty,
  10573.                              struct cmd_list_element *command)
  10574. {
  10575.   struct gdbarch *gdbarch = get_current_arch ();
  10576.   int tempflag;
  10577.   enum ada_exception_catchpoint_kind ex_kind;
  10578.   char *excep_string = NULL;
  10579.   char *cond_string = NULL;

  10580.   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;

  10581.   if (!arg)
  10582.     arg = "";
  10583.   catch_ada_exception_command_split (arg, &ex_kind, &excep_string,
  10584.                                      &cond_string);
  10585.   create_ada_exception_catchpoint (gdbarch, ex_kind,
  10586.                                    excep_string, cond_string,
  10587.                                    tempflag, 1 /* enabled */,
  10588.                                    from_tty);
  10589. }

  10590. /* Split the arguments specified in a "catch assert" command.

  10591.    ARGS contains the command's arguments (or the empty string if
  10592.    no arguments were passed).

  10593.    If ARGS contains a condition, set COND_STRING to that condition
  10594.    (the memory needs to be deallocated after use).  */

  10595. static void
  10596. catch_ada_assert_command_split (char *args, char **cond_string)
  10597. {
  10598.   args = skip_spaces (args);

  10599.   /* Check whether a condition was provided.  */
  10600.   if (strncmp (args, "if", 2) == 0
  10601.       && (isspace (args[2]) || args[2] == '\0'))
  10602.     {
  10603.       args += 2;
  10604.       args = skip_spaces (args);
  10605.       if (args[0] == '\0')
  10606.         error (_("condition missing after `if' keyword"));
  10607.       *cond_string = xstrdup (args);
  10608.     }

  10609.   /* Otherwise, there should be no other argument at the end of
  10610.      the command.  */
  10611.   else if (args[0] != '\0')
  10612.     error (_("Junk at end of arguments."));
  10613. }

  10614. /* Implement the "catch assert" command.  */

  10615. static void
  10616. catch_assert_command (char *arg, int from_tty,
  10617.                       struct cmd_list_element *command)
  10618. {
  10619.   struct gdbarch *gdbarch = get_current_arch ();
  10620.   int tempflag;
  10621.   char *cond_string = NULL;

  10622.   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;

  10623.   if (!arg)
  10624.     arg = "";
  10625.   catch_ada_assert_command_split (arg, &cond_string);
  10626.   create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
  10627.                                    NULL, cond_string,
  10628.                                    tempflag, 1 /* enabled */,
  10629.                                    from_tty);
  10630. }

  10631. /* Return non-zero if the symbol SYM is an Ada exception object.  */

  10632. static int
  10633. ada_is_exception_sym (struct symbol *sym)
  10634. {
  10635.   const char *type_name = type_name_no_tag (SYMBOL_TYPE (sym));

  10636.   return (SYMBOL_CLASS (sym) != LOC_TYPEDEF
  10637.           && SYMBOL_CLASS (sym) != LOC_BLOCK
  10638.           && SYMBOL_CLASS (sym) != LOC_CONST
  10639.           && SYMBOL_CLASS (sym) != LOC_UNRESOLVED
  10640.           && type_name != NULL && strcmp (type_name, "exception") == 0);
  10641. }

  10642. /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
  10643.    Ada exception object.  This matches all exceptions except the ones
  10644.    defined by the Ada language.  */

  10645. static int
  10646. ada_is_non_standard_exception_sym (struct symbol *sym)
  10647. {
  10648.   int i;

  10649.   if (!ada_is_exception_sym (sym))
  10650.     return 0;

  10651.   for (i = 0; i < ARRAY_SIZE (standard_exc); i++)
  10652.     if (strcmp (SYMBOL_LINKAGE_NAME (sym), standard_exc[i]) == 0)
  10653.       return 0/* A standard exception.  */

  10654.   /* Numeric_Error is also a standard exception, so exclude it.
  10655.      See the STANDARD_EXC description for more details as to why
  10656.      this exception is not listed in that array.  */
  10657.   if (strcmp (SYMBOL_LINKAGE_NAME (sym), "numeric_error") == 0)
  10658.     return 0;

  10659.   return 1;
  10660. }

  10661. /* A helper function for qsort, comparing two struct ada_exc_info
  10662.    objects.

  10663.    The comparison is determined first by exception name, and then
  10664.    by exception address.  */

  10665. static int
  10666. compare_ada_exception_info (const void *a, const void *b)
  10667. {
  10668.   const struct ada_exc_info *exc_a = (struct ada_exc_info *) a;
  10669.   const struct ada_exc_info *exc_b = (struct ada_exc_info *) b;
  10670.   int result;

  10671.   result = strcmp (exc_a->name, exc_b->name);
  10672.   if (result != 0)
  10673.     return result;

  10674.   if (exc_a->addr < exc_b->addr)
  10675.     return -1;
  10676.   if (exc_a->addr > exc_b->addr)
  10677.     return 1;

  10678.   return 0;
  10679. }

  10680. /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
  10681.    routine, but keeping the first SKIP elements untouched.

  10682.    All duplicates are also removed.  */

  10683. static void
  10684. sort_remove_dups_ada_exceptions_list (VEC(ada_exc_info) **exceptions,
  10685.                                       int skip)
  10686. {
  10687.   struct ada_exc_info *to_sort
  10688.     = VEC_address (ada_exc_info, *exceptions) + skip;
  10689.   int to_sort_len
  10690.     = VEC_length (ada_exc_info, *exceptions) - skip;
  10691.   int i, j;

  10692.   qsort (to_sort, to_sort_len, sizeof (struct ada_exc_info),
  10693.          compare_ada_exception_info);

  10694.   for (i = 1, j = 1; i < to_sort_len; i++)
  10695.     if (compare_ada_exception_info (&to_sort[i], &to_sort[j - 1]) != 0)
  10696.       to_sort[j++] = to_sort[i];
  10697.   to_sort_len = j;
  10698.   VEC_truncate(ada_exc_info, *exceptions, skip + to_sort_len);
  10699. }

  10700. /* A function intended as the "name_matcher" callback in the struct
  10701.    quick_symbol_functions' expand_symtabs_matching method.

  10702.    SEARCH_NAME is the symbol's search name.

  10703.    If USER_DATA is not NULL, it is a pointer to a regext_t object
  10704.    used to match the symbol (by natural name).  Otherwise, when USER_DATA
  10705.    is null, no filtering is performed, and all symbols are a positive
  10706.    match.  */

  10707. static int
  10708. ada_exc_search_name_matches (const char *search_name, void *user_data)
  10709. {
  10710.   regex_t *preg = user_data;

  10711.   if (preg == NULL)
  10712.     return 1;

  10713.   /* In Ada, the symbol "search name" is a linkage name, whereas
  10714.      the regular expression used to do the matching refers to
  10715.      the natural name.  So match against the decoded name.  */
  10716.   return (regexec (preg, ada_decode (search_name), 0, NULL, 0) == 0);
  10717. }

  10718. /* Add all exceptions defined by the Ada standard whose name match
  10719.    a regular expression.

  10720.    If PREG is not NULL, then this regexp_t object is used to
  10721.    perform the symbol name matching.  Otherwise, no name-based
  10722.    filtering is performed.

  10723.    EXCEPTIONS is a vector of exceptions to which matching exceptions
  10724.    gets pushed.  */

  10725. static void
  10726. ada_add_standard_exceptions (regex_t *preg, VEC(ada_exc_info) **exceptions)
  10727. {
  10728.   int i;

  10729.   for (i = 0; i < ARRAY_SIZE (standard_exc); i++)
  10730.     {
  10731.       if (preg == NULL
  10732.           || regexec (preg, standard_exc[i], 0, NULL, 0) == 0)
  10733.         {
  10734.           struct bound_minimal_symbol msymbol
  10735.             = ada_lookup_simple_minsym (standard_exc[i]);

  10736.           if (msymbol.minsym != NULL)
  10737.             {
  10738.               struct ada_exc_info info
  10739.                 = {standard_exc[i], BMSYMBOL_VALUE_ADDRESS (msymbol)};

  10740.               VEC_safe_push (ada_exc_info, *exceptions, &info);
  10741.             }
  10742.         }
  10743.     }
  10744. }

  10745. /* Add all Ada exceptions defined locally and accessible from the given
  10746.    FRAME.

  10747.    If PREG is not NULL, then this regexp_t object is used to
  10748.    perform the symbol name matching.  Otherwise, no name-based
  10749.    filtering is performed.

  10750.    EXCEPTIONS is a vector of exceptions to which matching exceptions
  10751.    gets pushed.  */

  10752. static void
  10753. ada_add_exceptions_from_frame (regex_t *preg, struct frame_info *frame,
  10754.                                VEC(ada_exc_info) **exceptions)
  10755. {
  10756.   const struct block *block = get_frame_block (frame, 0);

  10757.   while (block != 0)
  10758.     {
  10759.       struct block_iterator iter;
  10760.       struct symbol *sym;

  10761.       ALL_BLOCK_SYMBOLS (block, iter, sym)
  10762.         {
  10763.           switch (SYMBOL_CLASS (sym))
  10764.             {
  10765.             case LOC_TYPEDEF:
  10766.             case LOC_BLOCK:
  10767.             case LOC_CONST:
  10768.               break;
  10769.             default:
  10770.               if (ada_is_exception_sym (sym))
  10771.                 {
  10772.                   struct ada_exc_info info = {SYMBOL_PRINT_NAME (sym),
  10773.                                               SYMBOL_VALUE_ADDRESS (sym)};

  10774.                   VEC_safe_push (ada_exc_info, *exceptions, &info);
  10775.                 }
  10776.             }
  10777.         }
  10778.       if (BLOCK_FUNCTION (block) != NULL)
  10779.         break;
  10780.       block = BLOCK_SUPERBLOCK (block);
  10781.     }
  10782. }

  10783. /* Add all exceptions defined globally whose name name match
  10784.    a regular expression, excluding standard exceptions.

  10785.    The reason we exclude standard exceptions is that they need
  10786.    to be handled separately: Standard exceptions are defined inside
  10787.    a runtime unit which is normally not compiled with debugging info,
  10788.    and thus usually do not show up in our symbol search.  However,
  10789.    if the unit was in fact built with debugging info, we need to
  10790.    exclude them because they would duplicate the entry we found
  10791.    during the special loop that specifically searches for those
  10792.    standard exceptions.

  10793.    If PREG is not NULL, then this regexp_t object is used to
  10794.    perform the symbol name matching.  Otherwise, no name-based
  10795.    filtering is performed.

  10796.    EXCEPTIONS is a vector of exceptions to which matching exceptions
  10797.    gets pushed.  */

  10798. static void
  10799. ada_add_global_exceptions (regex_t *preg, VEC(ada_exc_info) **exceptions)
  10800. {
  10801.   struct objfile *objfile;
  10802.   struct compunit_symtab *s;

  10803.   expand_symtabs_matching (NULL, ada_exc_search_name_matches,
  10804.                            VARIABLES_DOMAIN, preg);

  10805.   ALL_COMPUNITS (objfile, s)
  10806.     {
  10807.       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (s);
  10808.       int i;

  10809.       for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
  10810.         {
  10811.           struct block *b = BLOCKVECTOR_BLOCK (bv, i);
  10812.           struct block_iterator iter;
  10813.           struct symbol *sym;

  10814.           ALL_BLOCK_SYMBOLS (b, iter, sym)
  10815.             if (ada_is_non_standard_exception_sym (sym)
  10816.                 && (preg == NULL
  10817.                     || regexec (preg, SYMBOL_NATURAL_NAME (sym),
  10818.                                 0, NULL, 0) == 0))
  10819.               {
  10820.                 struct ada_exc_info info
  10821.                   = {SYMBOL_PRINT_NAME (sym), SYMBOL_VALUE_ADDRESS (sym)};

  10822.                 VEC_safe_push (ada_exc_info, *exceptions, &info);
  10823.               }
  10824.         }
  10825.     }
  10826. }

  10827. /* Implements ada_exceptions_list with the regular expression passed
  10828.    as a regex_t, rather than a string.

  10829.    If not NULL, PREG is used to filter out exceptions whose names
  10830.    do not match.  Otherwise, all exceptions are listed.  */

  10831. static VEC(ada_exc_info) *
  10832. ada_exceptions_list_1 (regex_t *preg)
  10833. {
  10834.   VEC(ada_exc_info) *result = NULL;
  10835.   struct cleanup *old_chain
  10836.     = make_cleanup (VEC_cleanup (ada_exc_info), &result);
  10837.   int prev_len;

  10838.   /* First, list the known standard exceptions.  These exceptions
  10839.      need to be handled separately, as they are usually defined in
  10840.      runtime units that have been compiled without debugging info.  */

  10841.   ada_add_standard_exceptions (preg, &result);

  10842.   /* Next, find all exceptions whose scope is local and accessible
  10843.      from the currently selected frame.  */

  10844.   if (has_stack_frames ())
  10845.     {
  10846.       prev_len = VEC_length (ada_exc_info, result);
  10847.       ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
  10848.                                      &result);
  10849.       if (VEC_length (ada_exc_info, result) > prev_len)
  10850.         sort_remove_dups_ada_exceptions_list (&result, prev_len);
  10851.     }

  10852.   /* Add all exceptions whose scope is global.  */

  10853.   prev_len = VEC_length (ada_exc_info, result);
  10854.   ada_add_global_exceptions (preg, &result);
  10855.   if (VEC_length (ada_exc_info, result) > prev_len)
  10856.     sort_remove_dups_ada_exceptions_list (&result, prev_len);

  10857.   discard_cleanups (old_chain);
  10858.   return result;
  10859. }

  10860. /* Return a vector of ada_exc_info.

  10861.    If REGEXP is NULL, all exceptions are included in the result.
  10862.    Otherwise, it should contain a valid regular expression,
  10863.    and only the exceptions whose names match that regular expression
  10864.    are included in the result.

  10865.    The exceptions are sorted in the following order:
  10866.      - Standard exceptions (defined by the Ada language), in
  10867.        alphabetical order;
  10868.      - Exceptions only visible from the current frame, in
  10869.        alphabetical order;
  10870.      - Exceptions whose scope is global, in alphabetical order.  */

  10871. VEC(ada_exc_info) *
  10872. ada_exceptions_list (const char *regexp)
  10873. {
  10874.   VEC(ada_exc_info) *result = NULL;
  10875.   struct cleanup *old_chain = NULL;
  10876.   regex_t reg;

  10877.   if (regexp != NULL)
  10878.     old_chain = compile_rx_or_error (&reg, regexp,
  10879.                                      _("invalid regular expression"));

  10880.   result = ada_exceptions_list_1 (regexp != NULL ? &reg : NULL);

  10881.   if (old_chain != NULL)
  10882.     do_cleanups (old_chain);
  10883.   return result;
  10884. }

  10885. /* Implement the "info exceptions" command.  */

  10886. static void
  10887. info_exceptions_command (char *regexp, int from_tty)
  10888. {
  10889.   VEC(ada_exc_info) *exceptions;
  10890.   struct cleanup *cleanup;
  10891.   struct gdbarch *gdbarch = get_current_arch ();
  10892.   int ix;
  10893.   struct ada_exc_info *info;

  10894.   exceptions = ada_exceptions_list (regexp);
  10895.   cleanup = make_cleanup (VEC_cleanup (ada_exc_info), &exceptions);

  10896.   if (regexp != NULL)
  10897.     printf_filtered
  10898.       (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
  10899.   else
  10900.     printf_filtered (_("All defined Ada exceptions:\n"));

  10901.   for (ix = 0; VEC_iterate(ada_exc_info, exceptions, ix, info); ix++)
  10902.     printf_filtered ("%s: %s\n", info->name, paddress (gdbarch, info->addr));

  10903.   do_cleanups (cleanup);
  10904. }

  10905.                                 /* Operators */
  10906. /* Information about operators given special treatment in functions
  10907.    below.  */
  10908. /* Format: OP_DEFN (<operator>, <operator length>, <# args>, <binop>).  */

  10909. #define ADA_OPERATORS \
  10910.     OP_DEFN (OP_VAR_VALUE, 4, 0, 0) \
  10911.     OP_DEFN (BINOP_IN_BOUNDS, 3, 2, 0) \
  10912.     OP_DEFN (TERNOP_IN_RANGE, 1, 3, 0) \
  10913.     OP_DEFN (OP_ATR_FIRST, 1, 2, 0) \
  10914.     OP_DEFN (OP_ATR_LAST, 1, 2, 0) \
  10915.     OP_DEFN (OP_ATR_LENGTH, 1, 2, 0) \
  10916.     OP_DEFN (OP_ATR_IMAGE, 1, 2, 0) \
  10917.     OP_DEFN (OP_ATR_MAX, 1, 3, 0) \
  10918.     OP_DEFN (OP_ATR_MIN, 1, 3, 0) \
  10919.     OP_DEFN (OP_ATR_MODULUS, 1, 1, 0) \
  10920.     OP_DEFN (OP_ATR_POS, 1, 2, 0) \
  10921.     OP_DEFN (OP_ATR_SIZE, 1, 1, 0) \
  10922.     OP_DEFN (OP_ATR_TAG, 1, 1, 0) \
  10923.     OP_DEFN (OP_ATR_VAL, 1, 2, 0) \
  10924.     OP_DEFN (UNOP_QUAL, 3, 1, 0) \
  10925.     OP_DEFN (UNOP_IN_RANGE, 3, 1, 0) \
  10926.     OP_DEFN (OP_OTHERS, 1, 1, 0) \
  10927.     OP_DEFN (OP_POSITIONAL, 3, 1, 0) \
  10928.     OP_DEFN (OP_DISCRETE_RANGE, 1, 2, 0)

  10929. static void
  10930. ada_operator_length (const struct expression *exp, int pc, int *oplenp,
  10931.                      int *argsp)
  10932. {
  10933.   switch (exp->elts[pc - 1].opcode)
  10934.     {
  10935.     default:
  10936.       operator_length_standard (exp, pc, oplenp, argsp);
  10937.       break;

  10938. #define OP_DEFN(op, len, args, binop) \
  10939.     case op: *oplenp = len; *argsp = args; break;
  10940.       ADA_OPERATORS;
  10941. #undef OP_DEFN

  10942.     case OP_AGGREGATE:
  10943.       *oplenp = 3;
  10944.       *argsp = longest_to_int (exp->elts[pc - 2].longconst);
  10945.       break;

  10946.     case OP_CHOICES:
  10947.       *oplenp = 3;
  10948.       *argsp = longest_to_int (exp->elts[pc - 2].longconst) + 1;
  10949.       break;
  10950.     }
  10951. }

  10952. /* Implementation of the exp_descriptor method operator_check.  */

  10953. static int
  10954. ada_operator_check (struct expression *exp, int pos,
  10955.                     int (*objfile_func) (struct objfile *objfile, void *data),
  10956.                     void *data)
  10957. {
  10958.   const union exp_element *const elts = exp->elts;
  10959.   struct type *type = NULL;

  10960.   switch (elts[pos].opcode)
  10961.     {
  10962.       case UNOP_IN_RANGE:
  10963.       case UNOP_QUAL:
  10964.         type = elts[pos + 1].type;
  10965.         break;

  10966.       default:
  10967.         return operator_check_standard (exp, pos, objfile_func, data);
  10968.     }

  10969.   /* Invoke callbacks for TYPE and OBJFILE if they were set as non-NULL.  */

  10970.   if (type && TYPE_OBJFILE (type)
  10971.       && (*objfile_func) (TYPE_OBJFILE (type), data))
  10972.     return 1;

  10973.   return 0;
  10974. }

  10975. static char *
  10976. ada_op_name (enum exp_opcode opcode)
  10977. {
  10978.   switch (opcode)
  10979.     {
  10980.     default:
  10981.       return op_name_standard (opcode);

  10982. #define OP_DEFN(op, len, args, binop) case op: return #op;
  10983.       ADA_OPERATORS;
  10984. #undef OP_DEFN

  10985.     case OP_AGGREGATE:
  10986.       return "OP_AGGREGATE";
  10987.     case OP_CHOICES:
  10988.       return "OP_CHOICES";
  10989.     case OP_NAME:
  10990.       return "OP_NAME";
  10991.     }
  10992. }

  10993. /* As for operator_length, but assumes PC is pointing at the first
  10994.    element of the operator, and gives meaningful results only for the
  10995.    Ada-specific operators, returning 0 for *OPLENP and *ARGSP otherwise.  */

  10996. static void
  10997. ada_forward_operator_length (struct expression *exp, int pc,
  10998.                              int *oplenp, int *argsp)
  10999. {
  11000.   switch (exp->elts[pc].opcode)
  11001.     {
  11002.     default:
  11003.       *oplenp = *argsp = 0;
  11004.       break;

  11005. #define OP_DEFN(op, len, args, binop) \
  11006.     case op: *oplenp = len; *argsp = args; break;
  11007.       ADA_OPERATORS;
  11008. #undef OP_DEFN

  11009.     case OP_AGGREGATE:
  11010.       *oplenp = 3;
  11011.       *argsp = longest_to_int (exp->elts[pc + 1].longconst);
  11012.       break;

  11013.     case OP_CHOICES:
  11014.       *oplenp = 3;
  11015.       *argsp = longest_to_int (exp->elts[pc + 1].longconst) + 1;
  11016.       break;

  11017.     case OP_STRING:
  11018.     case OP_NAME:
  11019.       {
  11020.         int len = longest_to_int (exp->elts[pc + 1].longconst);

  11021.         *oplenp = 4 + BYTES_TO_EXP_ELEM (len + 1);
  11022.         *argsp = 0;
  11023.         break;
  11024.       }
  11025.     }
  11026. }

  11027. static int
  11028. ada_dump_subexp_body (struct expression *exp, struct ui_file *stream, int elt)
  11029. {
  11030.   enum exp_opcode op = exp->elts[elt].opcode;
  11031.   int oplen, nargs;
  11032.   int pc = elt;
  11033.   int i;

  11034.   ada_forward_operator_length (exp, elt, &oplen, &nargs);

  11035.   switch (op)
  11036.     {
  11037.       /* Ada attributes ('Foo).  */
  11038.     case OP_ATR_FIRST:
  11039.     case OP_ATR_LAST:
  11040.     case OP_ATR_LENGTH:
  11041.     case OP_ATR_IMAGE:
  11042.     case OP_ATR_MAX:
  11043.     case OP_ATR_MIN:
  11044.     case OP_ATR_MODULUS:
  11045.     case OP_ATR_POS:
  11046.     case OP_ATR_SIZE:
  11047.     case OP_ATR_TAG:
  11048.     case OP_ATR_VAL:
  11049.       break;

  11050.     case UNOP_IN_RANGE:
  11051.     case UNOP_QUAL:
  11052.       /* XXX: gdb_sprint_host_address, type_sprint */
  11053.       fprintf_filtered (stream, _("Type @"));
  11054.       gdb_print_host_address (exp->elts[pc + 1].type, stream);
  11055.       fprintf_filtered (stream, " (");
  11056.       type_print (exp->elts[pc + 1].type, NULL, stream, 0);
  11057.       fprintf_filtered (stream, ")");
  11058.       break;
  11059.     case BINOP_IN_BOUNDS:
  11060.       fprintf_filtered (stream, " (%d)",
  11061.                         longest_to_int (exp->elts[pc + 2].longconst));
  11062.       break;
  11063.     case TERNOP_IN_RANGE:
  11064.       break;

  11065.     case OP_AGGREGATE:
  11066.     case OP_OTHERS:
  11067.     case OP_DISCRETE_RANGE:
  11068.     case OP_POSITIONAL:
  11069.     case OP_CHOICES:
  11070.       break;

  11071.     case OP_NAME:
  11072.     case OP_STRING:
  11073.       {
  11074.         char *name = &exp->elts[elt + 2].string;
  11075.         int len = longest_to_int (exp->elts[elt + 1].longconst);

  11076.         fprintf_filtered (stream, "Text: `%.*s'", len, name);
  11077.         break;
  11078.       }

  11079.     default:
  11080.       return dump_subexp_body_standard (exp, stream, elt);
  11081.     }

  11082.   elt += oplen;
  11083.   for (i = 0; i < nargs; i += 1)
  11084.     elt = dump_subexp (exp, stream, elt);

  11085.   return elt;
  11086. }

  11087. /* The Ada extension of print_subexp (q.v.).  */

  11088. static void
  11089. ada_print_subexp (struct expression *exp, int *pos,
  11090.                   struct ui_file *stream, enum precedence prec)
  11091. {
  11092.   int oplen, nargs, i;
  11093.   int pc = *pos;
  11094.   enum exp_opcode op = exp->elts[pc].opcode;

  11095.   ada_forward_operator_length (exp, pc, &oplen, &nargs);

  11096.   *pos += oplen;
  11097.   switch (op)
  11098.     {
  11099.     default:
  11100.       *pos -= oplen;
  11101.       print_subexp_standard (exp, pos, stream, prec);
  11102.       return;

  11103.     case OP_VAR_VALUE:
  11104.       fputs_filtered (SYMBOL_NATURAL_NAME (exp->elts[pc + 2].symbol), stream);
  11105.       return;

  11106.     case BINOP_IN_BOUNDS:
  11107.       /* XXX: sprint_subexp */
  11108.       print_subexp (exp, pos, stream, PREC_SUFFIX);
  11109.       fputs_filtered (" in ", stream);
  11110.       print_subexp (exp, pos, stream, PREC_SUFFIX);
  11111.       fputs_filtered ("'range", stream);
  11112.       if (exp->elts[pc + 1].longconst > 1)
  11113.         fprintf_filtered (stream, "(%ld)",
  11114.                           (long) exp->elts[pc + 1].longconst);
  11115.       return;

  11116.     case TERNOP_IN_RANGE:
  11117.       if (prec >= PREC_EQUAL)
  11118.         fputs_filtered ("(", stream);
  11119.       /* XXX: sprint_subexp */
  11120.       print_subexp (exp, pos, stream, PREC_SUFFIX);
  11121.       fputs_filtered (" in ", stream);
  11122.       print_subexp (exp, pos, stream, PREC_EQUAL);
  11123.       fputs_filtered (" .. ", stream);
  11124.       print_subexp (exp, pos, stream, PREC_EQUAL);
  11125.       if (prec >= PREC_EQUAL)
  11126.         fputs_filtered (")", stream);
  11127.       return;

  11128.     case OP_ATR_FIRST:
  11129.     case OP_ATR_LAST:
  11130.     case OP_ATR_LENGTH:
  11131.     case OP_ATR_IMAGE:
  11132.     case OP_ATR_MAX:
  11133.     case OP_ATR_MIN:
  11134.     case OP_ATR_MODULUS:
  11135.     case OP_ATR_POS:
  11136.     case OP_ATR_SIZE:
  11137.     case OP_ATR_TAG:
  11138.     case OP_ATR_VAL:
  11139.       if (exp->elts[*pos].opcode == OP_TYPE)
  11140.         {
  11141.           if (TYPE_CODE (exp->elts[*pos + 1].type) != TYPE_CODE_VOID)
  11142.             LA_PRINT_TYPE (exp->elts[*pos + 1].type, "", stream, 0, 0,
  11143.                            &type_print_raw_options);
  11144.           *pos += 3;
  11145.         }
  11146.       else
  11147.         print_subexp (exp, pos, stream, PREC_SUFFIX);
  11148.       fprintf_filtered (stream, "'%s", ada_attribute_name (op));
  11149.       if (nargs > 1)
  11150.         {
  11151.           int tem;

  11152.           for (tem = 1; tem < nargs; tem += 1)
  11153.             {
  11154.               fputs_filtered ((tem == 1) ? " (" : ", ", stream);
  11155.               print_subexp (exp, pos, stream, PREC_ABOVE_COMMA);
  11156.             }
  11157.           fputs_filtered (")", stream);
  11158.         }
  11159.       return;

  11160.     case UNOP_QUAL:
  11161.       type_print (exp->elts[pc + 1].type, "", stream, 0);
  11162.       fputs_filtered ("'(", stream);
  11163.       print_subexp (exp, pos, stream, PREC_PREFIX);
  11164.       fputs_filtered (")", stream);
  11165.       return;

  11166.     case UNOP_IN_RANGE:
  11167.       /* XXX: sprint_subexp */
  11168.       print_subexp (exp, pos, stream, PREC_SUFFIX);
  11169.       fputs_filtered (" in ", stream);
  11170.       LA_PRINT_TYPE (exp->elts[pc + 1].type, "", stream, 1, 0,
  11171.                      &type_print_raw_options);
  11172.       return;

  11173.     case OP_DISCRETE_RANGE:
  11174.       print_subexp (exp, pos, stream, PREC_SUFFIX);
  11175.       fputs_filtered ("..", stream);
  11176.       print_subexp (exp, pos, stream, PREC_SUFFIX);
  11177.       return;

  11178.     case OP_OTHERS:
  11179.       fputs_filtered ("others => ", stream);
  11180.       print_subexp (exp, pos, stream, PREC_SUFFIX);
  11181.       return;

  11182.     case OP_CHOICES:
  11183.       for (i = 0; i < nargs-1; i += 1)
  11184.         {
  11185.           if (i > 0)
  11186.             fputs_filtered ("|", stream);
  11187.           print_subexp (exp, pos, stream, PREC_SUFFIX);
  11188.         }
  11189.       fputs_filtered (" => ", stream);
  11190.       print_subexp (exp, pos, stream, PREC_SUFFIX);
  11191.       return;

  11192.     case OP_POSITIONAL:
  11193.       print_subexp (exp, pos, stream, PREC_SUFFIX);
  11194.       return;

  11195.     case OP_AGGREGATE:
  11196.       fputs_filtered ("(", stream);
  11197.       for (i = 0; i < nargs; i += 1)
  11198.         {
  11199.           if (i > 0)
  11200.             fputs_filtered (", ", stream);
  11201.           print_subexp (exp, pos, stream, PREC_SUFFIX);
  11202.         }
  11203.       fputs_filtered (")", stream);
  11204.       return;
  11205.     }
  11206. }

  11207. /* Table mapping opcodes into strings for printing operators
  11208.    and precedences of the operators.  */

  11209. static const struct op_print ada_op_print_tab[] = {
  11210.   {":=", BINOP_ASSIGN, PREC_ASSIGN, 1},
  11211.   {"or else", BINOP_LOGICAL_OR, PREC_LOGICAL_OR, 0},
  11212.   {"and then", BINOP_LOGICAL_AND, PREC_LOGICAL_AND, 0},
  11213.   {"or", BINOP_BITWISE_IOR, PREC_BITWISE_IOR, 0},
  11214.   {"xor", BINOP_BITWISE_XOR, PREC_BITWISE_XOR, 0},
  11215.   {"and", BINOP_BITWISE_AND, PREC_BITWISE_AND, 0},
  11216.   {"=", BINOP_EQUAL, PREC_EQUAL, 0},
  11217.   {"/=", BINOP_NOTEQUAL, PREC_EQUAL, 0},
  11218.   {"<=", BINOP_LEQ, PREC_ORDER, 0},
  11219.   {">=", BINOP_GEQ, PREC_ORDER, 0},
  11220.   {">", BINOP_GTR, PREC_ORDER, 0},
  11221.   {"<", BINOP_LESS, PREC_ORDER, 0},
  11222.   {">>", BINOP_RSH, PREC_SHIFT, 0},
  11223.   {"<<", BINOP_LSH, PREC_SHIFT, 0},
  11224.   {"+", BINOP_ADD, PREC_ADD, 0},
  11225.   {"-", BINOP_SUB, PREC_ADD, 0},
  11226.   {"&", BINOP_CONCAT, PREC_ADD, 0},
  11227.   {"*", BINOP_MUL, PREC_MUL, 0},
  11228.   {"/", BINOP_DIV, PREC_MUL, 0},
  11229.   {"rem", BINOP_REM, PREC_MUL, 0},
  11230.   {"mod", BINOP_MOD, PREC_MUL, 0},
  11231.   {"**", BINOP_EXP, PREC_REPEAT, 0},
  11232.   {"@", BINOP_REPEAT, PREC_REPEAT, 0},
  11233.   {"-", UNOP_NEG, PREC_PREFIX, 0},
  11234.   {"+", UNOP_PLUS, PREC_PREFIX, 0},
  11235.   {"not ", UNOP_LOGICAL_NOT, PREC_PREFIX, 0},
  11236.   {"not ", UNOP_COMPLEMENT, PREC_PREFIX, 0},
  11237.   {"abs ", UNOP_ABS, PREC_PREFIX, 0},
  11238.   {".all", UNOP_IND, PREC_SUFFIX, 1},
  11239.   {"'access", UNOP_ADDR, PREC_SUFFIX, 1},
  11240.   {"'size", OP_ATR_SIZE, PREC_SUFFIX, 1},
  11241.   {NULL, 0, 0, 0}
  11242. };

  11243. enum ada_primitive_types {
  11244.   ada_primitive_type_int,
  11245.   ada_primitive_type_long,
  11246.   ada_primitive_type_short,
  11247.   ada_primitive_type_char,
  11248.   ada_primitive_type_float,
  11249.   ada_primitive_type_double,
  11250.   ada_primitive_type_void,
  11251.   ada_primitive_type_long_long,
  11252.   ada_primitive_type_long_double,
  11253.   ada_primitive_type_natural,
  11254.   ada_primitive_type_positive,
  11255.   ada_primitive_type_system_address,
  11256.   nr_ada_primitive_types
  11257. };

  11258. static void
  11259. ada_language_arch_info (struct gdbarch *gdbarch,
  11260.                         struct language_arch_info *lai)
  11261. {
  11262.   const struct builtin_type *builtin = builtin_type (gdbarch);

  11263.   lai->primitive_type_vector
  11264.     = GDBARCH_OBSTACK_CALLOC (gdbarch, nr_ada_primitive_types + 1,
  11265.                               struct type *);

  11266.   lai->primitive_type_vector [ada_primitive_type_int]
  11267.     = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
  11268.                          0, "integer");
  11269.   lai->primitive_type_vector [ada_primitive_type_long]
  11270.     = arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
  11271.                          0, "long_integer");
  11272.   lai->primitive_type_vector [ada_primitive_type_short]
  11273.     = arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
  11274.                          0, "short_integer");
  11275.   lai->string_char_type
  11276.     = lai->primitive_type_vector [ada_primitive_type_char]
  11277.     = arch_integer_type (gdbarch, TARGET_CHAR_BIT, 0, "character");
  11278.   lai->primitive_type_vector [ada_primitive_type_float]
  11279.     = arch_float_type (gdbarch, gdbarch_float_bit (gdbarch),
  11280.                        "float", NULL);
  11281.   lai->primitive_type_vector [ada_primitive_type_double]
  11282.     = arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
  11283.                        "long_float", NULL);
  11284.   lai->primitive_type_vector [ada_primitive_type_long_long]
  11285.     = arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
  11286.                          0, "long_long_integer");
  11287.   lai->primitive_type_vector [ada_primitive_type_long_double]
  11288.     = arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
  11289.                        "long_long_float", NULL);
  11290.   lai->primitive_type_vector [ada_primitive_type_natural]
  11291.     = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
  11292.                          0, "natural");
  11293.   lai->primitive_type_vector [ada_primitive_type_positive]
  11294.     = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
  11295.                          0, "positive");
  11296.   lai->primitive_type_vector [ada_primitive_type_void]
  11297.     = builtin->builtin_void;

  11298.   lai->primitive_type_vector [ada_primitive_type_system_address]
  11299.     = lookup_pointer_type (arch_type (gdbarch, TYPE_CODE_VOID, 1, "void"));
  11300.   TYPE_NAME (lai->primitive_type_vector [ada_primitive_type_system_address])
  11301.     = "system__address";

  11302.   lai->bool_type_symbol = NULL;
  11303.   lai->bool_type_default = builtin->builtin_bool;
  11304. }

  11305.                                 /* Language vector */

  11306. /* Not really used, but needed in the ada_language_defn.  */

  11307. static void
  11308. emit_char (int c, struct type *type, struct ui_file *stream, int quoter)
  11309. {
  11310.   ada_emit_char (c, type, stream, quoter, 1);
  11311. }

  11312. static int
  11313. parse (struct parser_state *ps)
  11314. {
  11315.   warnings_issued = 0;
  11316.   return ada_parse (ps);
  11317. }

  11318. static const struct exp_descriptor ada_exp_descriptor = {
  11319.   ada_print_subexp,
  11320.   ada_operator_length,
  11321.   ada_operator_check,
  11322.   ada_op_name,
  11323.   ada_dump_subexp_body,
  11324.   ada_evaluate_subexp
  11325. };

  11326. /* Implement the "la_get_symbol_name_cmp" language_defn method
  11327.    for Ada.  */

  11328. static symbol_name_cmp_ftype
  11329. ada_get_symbol_name_cmp (const char *lookup_name)
  11330. {
  11331.   if (should_use_wild_match (lookup_name))
  11332.     return wild_match;
  11333.   else
  11334.     return compare_names;
  11335. }

  11336. /* Implement the "la_read_var_value" language_defn method for Ada.  */

  11337. static struct value *
  11338. ada_read_var_value (struct symbol *var, struct frame_info *frame)
  11339. {
  11340.   const struct block *frame_block = NULL;
  11341.   struct symbol *renaming_sym = NULL;

  11342.   /* The only case where default_read_var_value is not sufficient
  11343.      is when VAR is a renaming...  */
  11344.   if (frame)
  11345.     frame_block = get_frame_block (frame, NULL);
  11346.   if (frame_block)
  11347.     renaming_sym = ada_find_renaming_symbol (var, frame_block);
  11348.   if (renaming_sym != NULL)
  11349.     return ada_read_renaming_var_value (renaming_sym, frame_block);

  11350.   /* This is a typical case where we expect the default_read_var_value
  11351.      function to work.  */
  11352.   return default_read_var_value (var, frame);
  11353. }

  11354. const struct language_defn ada_language_defn = {
  11355.   "ada",                        /* Language name */
  11356.   "Ada",
  11357.   language_ada,
  11358.   range_check_off,
  11359.   case_sensitive_on,            /* Yes, Ada is case-insensitive, but
  11360.                                    that's not quite what this means.  */
  11361.   array_row_major,
  11362.   macro_expansion_no,
  11363.   &ada_exp_descriptor,
  11364.   parse,
  11365.   ada_error,
  11366.   resolve,
  11367.   ada_printchar,                /* Print a character constant */
  11368.   ada_printstr,                 /* Function to print string constant */
  11369.   emit_char,                    /* Function to print single char (not used) */
  11370.   ada_print_type,               /* Print a type using appropriate syntax */
  11371.   ada_print_typedef,            /* Print a typedef using appropriate syntax */
  11372.   ada_val_print,                /* Print a value using appropriate syntax */
  11373.   ada_value_print,              /* Print a top-level value */
  11374.   ada_read_var_value,                /* la_read_var_value */
  11375.   NULL,                         /* Language specific skip_trampoline */
  11376.   NULL,                         /* name_of_this */
  11377.   ada_lookup_symbol_nonlocal,   /* Looking up non-local symbols.  */
  11378.   basic_lookup_transparent_type,        /* lookup_transparent_type */
  11379.   ada_la_decode,                /* Language specific symbol demangler */
  11380.   NULL,                         /* Language specific
  11381.                                    class_name_from_physname */
  11382.   ada_op_print_tab,             /* expression operators for printing */
  11383.   0,                            /* c-style arrays */
  11384.   1,                            /* String lower bound */
  11385.   ada_get_gdb_completer_word_break_characters,
  11386.   ada_make_symbol_completion_list,
  11387.   ada_language_arch_info,
  11388.   ada_print_array_index,
  11389.   default_pass_by_reference,
  11390.   c_get_string,
  11391.   ada_get_symbol_name_cmp,        /* la_get_symbol_name_cmp */
  11392.   ada_iterate_over_symbols,
  11393.   &ada_varobj_ops,
  11394.   NULL,
  11395.   NULL,
  11396.   LANG_MAGIC
  11397. };

  11398. /* Provide a prototype to silence -Wmissing-prototypes.  */
  11399. extern initialize_file_ftype _initialize_ada_language;

  11400. /* Command-list for the "set/show ada" prefix command.  */
  11401. static struct cmd_list_element *set_ada_list;
  11402. static struct cmd_list_element *show_ada_list;

  11403. /* Implement the "set ada" prefix command.  */

  11404. static void
  11405. set_ada_command (char *arg, int from_tty)
  11406. {
  11407.   printf_unfiltered (_(\
  11408. "\"set ada\" must be followed by the name of a setting.\n"));
  11409.   help_list (set_ada_list, "set ada ", all_commands, gdb_stdout);
  11410. }

  11411. /* Implement the "show ada" prefix command.  */

  11412. static void
  11413. show_ada_command (char *args, int from_tty)
  11414. {
  11415.   cmd_show_list (show_ada_list, from_tty, "");
  11416. }

  11417. static void
  11418. initialize_ada_catchpoint_ops (void)
  11419. {
  11420.   struct breakpoint_ops *ops;

  11421.   initialize_breakpoint_ops ();

  11422.   ops = &catch_exception_breakpoint_ops;
  11423.   *ops = bkpt_breakpoint_ops;
  11424.   ops->dtor = dtor_catch_exception;
  11425.   ops->allocate_location = allocate_location_catch_exception;
  11426.   ops->re_set = re_set_catch_exception;
  11427.   ops->check_status = check_status_catch_exception;
  11428.   ops->print_it = print_it_catch_exception;
  11429.   ops->print_one = print_one_catch_exception;
  11430.   ops->print_mention = print_mention_catch_exception;
  11431.   ops->print_recreate = print_recreate_catch_exception;

  11432.   ops = &catch_exception_unhandled_breakpoint_ops;
  11433.   *ops = bkpt_breakpoint_ops;
  11434.   ops->dtor = dtor_catch_exception_unhandled;
  11435.   ops->allocate_location = allocate_location_catch_exception_unhandled;
  11436.   ops->re_set = re_set_catch_exception_unhandled;
  11437.   ops->check_status = check_status_catch_exception_unhandled;
  11438.   ops->print_it = print_it_catch_exception_unhandled;
  11439.   ops->print_one = print_one_catch_exception_unhandled;
  11440.   ops->print_mention = print_mention_catch_exception_unhandled;
  11441.   ops->print_recreate = print_recreate_catch_exception_unhandled;

  11442.   ops = &catch_assert_breakpoint_ops;
  11443.   *ops = bkpt_breakpoint_ops;
  11444.   ops->dtor = dtor_catch_assert;
  11445.   ops->allocate_location = allocate_location_catch_assert;
  11446.   ops->re_set = re_set_catch_assert;
  11447.   ops->check_status = check_status_catch_assert;
  11448.   ops->print_it = print_it_catch_assert;
  11449.   ops->print_one = print_one_catch_assert;
  11450.   ops->print_mention = print_mention_catch_assert;
  11451.   ops->print_recreate = print_recreate_catch_assert;
  11452. }

  11453. /* This module's 'new_objfile' observer.  */

  11454. static void
  11455. ada_new_objfile_observer (struct objfile *objfile)
  11456. {
  11457.   ada_clear_symbol_cache ();
  11458. }

  11459. /* This module's 'free_objfile' observer.  */

  11460. static void
  11461. ada_free_objfile_observer (struct objfile *objfile)
  11462. {
  11463.   ada_clear_symbol_cache ();
  11464. }

  11465. void
  11466. _initialize_ada_language (void)
  11467. {
  11468.   add_language (&ada_language_defn);

  11469.   initialize_ada_catchpoint_ops ();

  11470.   add_prefix_cmd ("ada", no_class, set_ada_command,
  11471.                   _("Prefix command for changing Ada-specfic settings"),
  11472.                   &set_ada_list, "set ada ", 0, &setlist);

  11473.   add_prefix_cmd ("ada", no_class, show_ada_command,
  11474.                   _("Generic command for showing Ada-specific settings."),
  11475.                   &show_ada_list, "show ada ", 0, &showlist);

  11476.   add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
  11477.                            &trust_pad_over_xvs, _("\
  11478. Enable or disable an optimization trusting PAD types over XVS types"), _("\
  11479. Show whether an optimization trusting PAD types over XVS types is activated"),
  11480.                            _("\
  11481. This is related to the encoding used by the GNAT compiler.  The debugger\n\
  11482. should normally trust the contents of PAD types, but certain older versions\n\
  11483. of GNAT have a bug that sometimes causes the information in the PAD type\n\
  11484. to be incorrect.  Turning this setting \"off\" allows the debugger to\n\
  11485. work around this bug.  It is always safe to turn this option \"off\", but\n\
  11486. this incurs a slight performance penalty, so it is recommended to NOT change\n\
  11487. this option to \"off\" unless necessary."),
  11488.                             NULL, NULL, &set_ada_list, &show_ada_list);

  11489.   add_catch_command ("exception", _("\
  11490. Catch Ada exceptions, when raised.\n\
  11491. With an argument, catch only exceptions with the given name."),
  11492.                      catch_ada_exception_command,
  11493.                      NULL,
  11494.                      CATCH_PERMANENT,
  11495.                      CATCH_TEMPORARY);
  11496.   add_catch_command ("assert", _("\
  11497. Catch failed Ada assertions, when raised.\n\
  11498. With an argument, catch only exceptions with the given name."),
  11499.                      catch_assert_command,
  11500.                      NULL,
  11501.                      CATCH_PERMANENT,
  11502.                      CATCH_TEMPORARY);

  11503.   varsize_limit = 65536;

  11504.   add_info ("exceptions", info_exceptions_command,
  11505.             _("\
  11506. List all Ada exception names.\n\
  11507. If a regular expression is passed as an argument, only those matching\n\
  11508. the regular expression are listed."));

  11509.   add_prefix_cmd ("ada", class_maintenance, maint_set_ada_cmd,
  11510.                   _("Set Ada maintenance-related variables."),
  11511.                   &maint_set_ada_cmdlist, "maintenance set ada ",
  11512.                   0/*allow-unknown*/, &maintenance_set_cmdlist);

  11513.   add_prefix_cmd ("ada", class_maintenance, maint_show_ada_cmd,
  11514.                   _("Show Ada maintenance-related variables"),
  11515.                   &maint_show_ada_cmdlist, "maintenance show ada ",
  11516.                   0/*allow-unknown*/, &maintenance_show_cmdlist);

  11517.   add_setshow_boolean_cmd
  11518.     ("ignore-descriptive-types", class_maintenance,
  11519.      &ada_ignore_descriptive_types_p,
  11520.      _("Set whether descriptive types generated by GNAT should be ignored."),
  11521.      _("Show whether descriptive types generated by GNAT should be ignored."),
  11522.      _("\
  11523. When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
  11524. DWARF attribute."),
  11525.      NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);

  11526.   obstack_init (&symbol_list_obstack);

  11527.   decoded_names_store = htab_create_alloc
  11528.     (256, htab_hash_string, (int (*)(const void *, const void *)) streq,
  11529.      NULL, xcalloc, xfree);

  11530.   /* The ada-lang observers.  */
  11531.   observer_attach_new_objfile (ada_new_objfile_observer);
  11532.   observer_attach_free_objfile (ada_free_objfile_observer);
  11533.   observer_attach_inferior_exit (ada_inferior_exit);

  11534.   /* Setup various context-specific data.  */
  11535.   ada_inferior_data
  11536.     = register_inferior_data_with_cleanup (NULL, ada_inferior_data_cleanup);
  11537.   ada_pspace_data_handle
  11538.     = register_program_space_data_with_cleanup (NULL, ada_pspace_data_cleanup);
  11539. }