1 /* DWARF 2 debugging format support for GDB.
2 
3    Copyright (C) 1994-2021 Free Software Foundation, Inc.
4 
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11 
12    This file is part of GDB.
13 
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18 
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23 
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26 
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30 
31 #include "defs.h"
32 #include "dwarf2/read.h"
33 #include "dwarf2/abbrev.h"
34 #include "dwarf2/attribute.h"
35 #include "dwarf2/comp-unit-head.h"
36 #include "dwarf2/cu.h"
37 #include "dwarf2/index-cache.h"
38 #include "dwarf2/index-common.h"
39 #include "dwarf2/leb.h"
40 #include "dwarf2/line-header.h"
41 #include "dwarf2/dwz.h"
42 #include "dwarf2/macro.h"
43 #include "dwarf2/die.h"
44 #include "dwarf2/sect-names.h"
45 #include "dwarf2/stringify.h"
46 #include "dwarf2/public.h"
47 #include "bfd.h"
48 #include "elf-bfd.h"
49 #include "symtab.h"
50 #include "gdbtypes.h"
51 #include "objfiles.h"
52 #include "dwarf2.h"
53 #include "demangle.h"
54 #include "gdb-demangle.h"
55 #include "filenames.h"	/* for DOSish file names */
56 #include "language.h"
57 #include "complaints.h"
58 #include "dwarf2/expr.h"
59 #include "dwarf2/loc.h"
60 #include "cp-support.h"
61 #include "hashtab.h"
62 #include "command.h"
63 #include "gdbcmd.h"
64 #include "block.h"
65 #include "addrmap.h"
66 #include "typeprint.h"
67 #include "psympriv.h"
68 #include "c-lang.h"
69 #include "go-lang.h"
70 #include "valprint.h"
71 #include "gdbcore.h" /* for gnutarget */
72 #include "gdb/gdb-index.h"
73 #include "gdb_bfd.h"
74 #include "f-lang.h"
75 #include "source.h"
76 #include "build-id.h"
77 #include "namespace.h"
78 #include "gdbsupport/function-view.h"
79 #include "gdbsupport/gdb_optional.h"
80 #include "gdbsupport/underlying.h"
81 #include "gdbsupport/hash_enum.h"
82 #include "filename-seen-cache.h"
83 #include "producer.h"
84 #include <fcntl.h>
85 #include <algorithm>
86 #include <unordered_map>
87 #include "gdbsupport/selftest.h"
88 #include "rust-lang.h"
89 #include "gdbsupport/pathstuff.h"
90 #include "count-one-bits.h"
91 #include <unordered_set>
92 
93 /* When == 1, print basic high level tracing messages.
94    When > 1, be more verbose.
95    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
96 static unsigned int dwarf_read_debug = 0;
97 
98 /* Print a "dwarf-read" debug statement if dwarf_read_debug is >= 1.  */
99 
100 #define dwarf_read_debug_printf(fmt, ...) \
101   debug_prefixed_printf_cond (dwarf_read_debug >= 1, "dwarf-read", fmt, \
102 			      ##__VA_ARGS__)
103 
104 /* Print a "dwarf-read" debug statement if dwarf_read_debug is >= 2.  */
105 
106 #define dwarf_read_debug_printf_v(fmt, ...) \
107   debug_prefixed_printf_cond (dwarf_read_debug >= 2, "dwarf-read", fmt, \
108 			      ##__VA_ARGS__)
109 
110 /* When non-zero, dump DIEs after they are read in.  */
111 static unsigned int dwarf_die_debug = 0;
112 
113 /* When non-zero, dump line number entries as they are read in.  */
114 unsigned int dwarf_line_debug = 0;
115 
116 /* When true, cross-check physname against demangler.  */
117 static bool check_physname = false;
118 
119 /* When true, do not reject deprecated .gdb_index sections.  */
120 static bool use_deprecated_index_sections = false;
121 
122 /* This is used to store the data that is always per objfile.  */
123 static const objfile_key<dwarf2_per_objfile> dwarf2_objfile_data_key;
124 
125 /* These are used to store the dwarf2_per_bfd objects.
126 
127    objfiles having the same BFD, which doesn't require relocations, are going to
128    share a dwarf2_per_bfd object, which is held in the _bfd_data_key version.
129 
130    Other objfiles are not going to share a dwarf2_per_bfd with any other
131    objfiles, so they'll have their own version kept in the _objfile_data_key
132    version.  */
133 static const struct bfd_key<dwarf2_per_bfd> dwarf2_per_bfd_bfd_data_key;
134 static const struct objfile_key<dwarf2_per_bfd> dwarf2_per_bfd_objfile_data_key;
135 
136 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
137 
138 static int dwarf2_locexpr_index;
139 static int dwarf2_loclist_index;
140 static int dwarf2_locexpr_block_index;
141 static int dwarf2_loclist_block_index;
142 
143 /* Size of .debug_loclists section header for 32-bit DWARF format.  */
144 #define LOCLIST_HEADER_SIZE32 12
145 
146 /* Size of .debug_loclists section header for 64-bit DWARF format.  */
147 #define LOCLIST_HEADER_SIZE64 20
148 
149 /* Size of .debug_rnglists section header for 32-bit DWARF format.  */
150 #define RNGLIST_HEADER_SIZE32 12
151 
152 /* Size of .debug_rnglists section header for 64-bit DWARF format.  */
153 #define RNGLIST_HEADER_SIZE64 20
154 
155 /* An index into a (C++) symbol name component in a symbol name as
156    recorded in the mapped_index's symbol table.  For each C++ symbol
157    in the symbol table, we record one entry for the start of each
158    component in the symbol in a table of name components, and then
159    sort the table, in order to be able to binary search symbol names,
160    ignoring leading namespaces, both completion and regular look up.
161    For example, for symbol "A::B::C", we'll have an entry that points
162    to "A::B::C", another that points to "B::C", and another for "C".
163    Note that function symbols in GDB index have no parameter
164    information, just the function/method names.  You can convert a
165    name_component to a "const char *" using the
166    'mapped_index::symbol_name_at(offset_type)' method.  */
167 
168 struct name_component
169 {
170   /* Offset in the symbol name where the component starts.  Stored as
171      a (32-bit) offset instead of a pointer to save memory and improve
172      locality on 64-bit architectures.  */
173   offset_type name_offset;
174 
175   /* The symbol's index in the symbol and constant pool tables of a
176      mapped_index.  */
177   offset_type idx;
178 };
179 
180 /* Base class containing bits shared by both .gdb_index and
181    .debug_name indexes.  */
182 
183 struct mapped_index_base
184 {
185   mapped_index_base () = default;
186   DISABLE_COPY_AND_ASSIGN (mapped_index_base);
187 
188   /* The name_component table (a sorted vector).  See name_component's
189      description above.  */
190   std::vector<name_component> name_components;
191 
192   /* How NAME_COMPONENTS is sorted.  */
193   enum case_sensitivity name_components_casing;
194 
195   /* Return the number of names in the symbol table.  */
196   virtual size_t symbol_name_count () const = 0;
197 
198   /* Get the name of the symbol at IDX in the symbol table.  */
199   virtual const char *symbol_name_at
200     (offset_type idx, dwarf2_per_objfile *per_objfile) const = 0;
201 
202   /* Return whether the name at IDX in the symbol table should be
203      ignored.  */
204   virtual bool symbol_name_slot_invalid (offset_type idx) const
205   {
206     return false;
207   }
208 
209   /* Build the symbol name component sorted vector, if we haven't
210      yet.  */
211   void build_name_components (dwarf2_per_objfile *per_objfile);
212 
213   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
214      possible matches for LN_NO_PARAMS in the name component
215      vector.  */
216   std::pair<std::vector<name_component>::const_iterator,
217 	    std::vector<name_component>::const_iterator>
218     find_name_components_bounds (const lookup_name_info &ln_no_params,
219 				 enum language lang,
220 				 dwarf2_per_objfile *per_objfile) const;
221 
222   /* Prevent deleting/destroying via a base class pointer.  */
223 protected:
224   ~mapped_index_base() = default;
225 };
226 
227 /* This is a view into the index that converts from bytes to an
228    offset_type, and allows indexing.  Unaligned bytes are specifically
229    allowed here, and handled via unpacking.  */
230 
231 class offset_view
232 {
233 public:
234   offset_view () = default;
235 
236   explicit offset_view (gdb::array_view<const gdb_byte> bytes)
237     : m_bytes (bytes)
238   {
239   }
240 
241   /* Extract the INDEXth offset_type from the array.  */
242   offset_type operator[] (size_t index) const
243   {
244     const gdb_byte *bytes = &m_bytes[index * sizeof (offset_type)];
245     return (offset_type) extract_unsigned_integer (bytes,
246 						   sizeof (offset_type),
247 						   BFD_ENDIAN_LITTLE);
248   }
249 
250   /* Return the number of offset_types in this array.  */
251   size_t size () const
252   {
253     return m_bytes.size () / sizeof (offset_type);
254   }
255 
256   /* Return true if this view is empty.  */
257   bool empty () const
258   {
259     return m_bytes.empty ();
260   }
261 
262 private:
263   /* The underlying bytes.  */
264   gdb::array_view<const gdb_byte> m_bytes;
265 };
266 
267 /* A description of the mapped index.  The file format is described in
268    a comment by the code that writes the index.  */
269 struct mapped_index final : public mapped_index_base
270 {
271   /* Index data format version.  */
272   int version = 0;
273 
274   /* The address table data.  */
275   gdb::array_view<const gdb_byte> address_table;
276 
277   /* The symbol table, implemented as a hash table.  */
278   offset_view symbol_table;
279 
280   /* A pointer to the constant pool.  */
281   gdb::array_view<const gdb_byte> constant_pool;
282 
283   /* Return the index into the constant pool of the name of the IDXth
284      symbol in the symbol table.  */
285   offset_type symbol_name_index (offset_type idx) const
286   {
287     return symbol_table[2 * idx];
288   }
289 
290   /* Return the index into the constant pool of the CU vector of the
291      IDXth symbol in the symbol table.  */
292   offset_type symbol_vec_index (offset_type idx) const
293   {
294     return symbol_table[2 * idx + 1];
295   }
296 
297   bool symbol_name_slot_invalid (offset_type idx) const override
298   {
299     return (symbol_name_index (idx) == 0
300 	    && symbol_vec_index (idx) == 0);
301   }
302 
303   /* Convenience method to get at the name of the symbol at IDX in the
304      symbol table.  */
305   const char *symbol_name_at
306     (offset_type idx, dwarf2_per_objfile *per_objfile) const override
307   {
308     return (const char *) (this->constant_pool.data ()
309 			   + symbol_name_index (idx));
310   }
311 
312   size_t symbol_name_count () const override
313   { return this->symbol_table.size () / 2; }
314 };
315 
316 /* A description of the mapped .debug_names.
317    Uninitialized map has CU_COUNT 0.  */
318 struct mapped_debug_names final : public mapped_index_base
319 {
320   bfd_endian dwarf5_byte_order;
321   bool dwarf5_is_dwarf64;
322   bool augmentation_is_gdb;
323   uint8_t offset_size;
324   uint32_t cu_count = 0;
325   uint32_t tu_count, bucket_count, name_count;
326   const gdb_byte *cu_table_reordered, *tu_table_reordered;
327   const uint32_t *bucket_table_reordered, *hash_table_reordered;
328   const gdb_byte *name_table_string_offs_reordered;
329   const gdb_byte *name_table_entry_offs_reordered;
330   const gdb_byte *entry_pool;
331 
332   struct index_val
333   {
334     ULONGEST dwarf_tag;
335     struct attr
336     {
337       /* Attribute name DW_IDX_*.  */
338       ULONGEST dw_idx;
339 
340       /* Attribute form DW_FORM_*.  */
341       ULONGEST form;
342 
343       /* Value if FORM is DW_FORM_implicit_const.  */
344       LONGEST implicit_const;
345     };
346     std::vector<attr> attr_vec;
347   };
348 
349   std::unordered_map<ULONGEST, index_val> abbrev_map;
350 
351   const char *namei_to_name
352     (uint32_t namei, dwarf2_per_objfile *per_objfile) const;
353 
354   /* Implementation of the mapped_index_base virtual interface, for
355      the name_components cache.  */
356 
357   const char *symbol_name_at
358     (offset_type idx, dwarf2_per_objfile *per_objfile) const override
359   { return namei_to_name (idx, per_objfile); }
360 
361   size_t symbol_name_count () const override
362   { return this->name_count; }
363 };
364 
365 /* See dwarf2read.h.  */
366 
367 dwarf2_per_objfile *
368 get_dwarf2_per_objfile (struct objfile *objfile)
369 {
370   return dwarf2_objfile_data_key.get (objfile);
371 }
372 
373 /* Default names of the debugging sections.  */
374 
375 /* Note that if the debugging section has been compressed, it might
376    have a name like .zdebug_info.  */
377 
378 const struct dwarf2_debug_sections dwarf2_elf_names =
379 {
380   { ".debug_info", ".zdebug_info" },
381   { ".debug_abbrev", ".zdebug_abbrev" },
382   { ".debug_line", ".zdebug_line" },
383   { ".debug_loc", ".zdebug_loc" },
384   { ".debug_loclists", ".zdebug_loclists" },
385   { ".debug_macinfo", ".zdebug_macinfo" },
386   { ".debug_macro", ".zdebug_macro" },
387   { ".debug_str", ".zdebug_str" },
388   { ".debug_str_offsets", ".zdebug_str_offsets" },
389   { ".debug_line_str", ".zdebug_line_str" },
390   { ".debug_ranges", ".zdebug_ranges" },
391   { ".debug_rnglists", ".zdebug_rnglists" },
392   { ".debug_types", ".zdebug_types" },
393   { ".debug_addr", ".zdebug_addr" },
394   { ".debug_frame", ".zdebug_frame" },
395   { ".eh_frame", NULL },
396   { ".gdb_index", ".zgdb_index" },
397   { ".debug_names", ".zdebug_names" },
398   { ".debug_aranges", ".zdebug_aranges" },
399   23
400 };
401 
402 /* List of DWO/DWP sections.  */
403 
404 static const struct dwop_section_names
405 {
406   struct dwarf2_section_names abbrev_dwo;
407   struct dwarf2_section_names info_dwo;
408   struct dwarf2_section_names line_dwo;
409   struct dwarf2_section_names loc_dwo;
410   struct dwarf2_section_names loclists_dwo;
411   struct dwarf2_section_names macinfo_dwo;
412   struct dwarf2_section_names macro_dwo;
413   struct dwarf2_section_names rnglists_dwo;
414   struct dwarf2_section_names str_dwo;
415   struct dwarf2_section_names str_offsets_dwo;
416   struct dwarf2_section_names types_dwo;
417   struct dwarf2_section_names cu_index;
418   struct dwarf2_section_names tu_index;
419 }
420 dwop_section_names =
421 {
422   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
423   { ".debug_info.dwo", ".zdebug_info.dwo" },
424   { ".debug_line.dwo", ".zdebug_line.dwo" },
425   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
426   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
427   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
428   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
429   { ".debug_rnglists.dwo", ".zdebug_rnglists.dwo" },
430   { ".debug_str.dwo", ".zdebug_str.dwo" },
431   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
432   { ".debug_types.dwo", ".zdebug_types.dwo" },
433   { ".debug_cu_index", ".zdebug_cu_index" },
434   { ".debug_tu_index", ".zdebug_tu_index" },
435 };
436 
437 /* local data types */
438 
439 /* The location list and range list sections (.debug_loclists & .debug_rnglists)
440    begin with a header,  which contains the following information.  */
441 struct loclists_rnglists_header
442 {
443   /* A 4-byte or 12-byte length containing the length of the
444      set of entries for this compilation unit, not including the
445      length field itself.  */
446   unsigned int length;
447 
448   /* A 2-byte version identifier.  */
449   short version;
450 
451   /* A 1-byte unsigned integer containing the size in bytes of an address on
452      the target system.  */
453   unsigned char addr_size;
454 
455   /* A 1-byte unsigned integer containing the size in bytes of a segment selector
456      on the target system.  */
457   unsigned char segment_collector_size;
458 
459   /* A 4-byte count of the number of offsets that follow the header.  */
460   unsigned int offset_entry_count;
461 };
462 
463 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
464    This includes type_unit_group and quick_file_names.  */
465 
466 struct stmt_list_hash
467 {
468   /* The DWO unit this table is from or NULL if there is none.  */
469   struct dwo_unit *dwo_unit;
470 
471   /* Offset in .debug_line or .debug_line.dwo.  */
472   sect_offset line_sect_off;
473 };
474 
475 /* Each element of dwarf2_per_bfd->type_unit_groups is a pointer to
476    an object of this type.  This contains elements of type unit groups
477    that can be shared across objfiles.  The non-shareable parts are in
478    type_unit_group_unshareable.  */
479 
480 struct type_unit_group : public dwarf2_per_cu_data
481 {
482   /* The TUs that share this DW_AT_stmt_list entry.
483      This is added to while parsing type units to build partial symtabs,
484      and is deleted afterwards and not used again.  */
485   std::vector<signatured_type *> *tus = nullptr;
486 
487   /* The data used to construct the hash key.  */
488   struct stmt_list_hash hash {};
489 };
490 
491 /* These sections are what may appear in a (real or virtual) DWO file.  */
492 
493 struct dwo_sections
494 {
495   struct dwarf2_section_info abbrev;
496   struct dwarf2_section_info line;
497   struct dwarf2_section_info loc;
498   struct dwarf2_section_info loclists;
499   struct dwarf2_section_info macinfo;
500   struct dwarf2_section_info macro;
501   struct dwarf2_section_info rnglists;
502   struct dwarf2_section_info str;
503   struct dwarf2_section_info str_offsets;
504   /* In the case of a virtual DWO file, these two are unused.  */
505   struct dwarf2_section_info info;
506   std::vector<dwarf2_section_info> types;
507 };
508 
509 /* CUs/TUs in DWP/DWO files.  */
510 
511 struct dwo_unit
512 {
513   /* Backlink to the containing struct dwo_file.  */
514   struct dwo_file *dwo_file;
515 
516   /* The "id" that distinguishes this CU/TU.
517      .debug_info calls this "dwo_id", .debug_types calls this "signature".
518      Since signatures came first, we stick with it for consistency.  */
519   ULONGEST signature;
520 
521   /* The section this CU/TU lives in, in the DWO file.  */
522   struct dwarf2_section_info *section;
523 
524   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
525   sect_offset sect_off;
526   unsigned int length;
527 
528   /* For types, offset in the type's DIE of the type defined by this TU.  */
529   cu_offset type_offset_in_tu;
530 };
531 
532 /* include/dwarf2.h defines the DWP section codes.
533    It defines a max value but it doesn't define a min value, which we
534    use for error checking, so provide one.  */
535 
536 enum dwp_v2_section_ids
537 {
538   DW_SECT_MIN = 1
539 };
540 
541 /* Data for one DWO file.
542 
543    This includes virtual DWO files (a virtual DWO file is a DWO file as it
544    appears in a DWP file).  DWP files don't really have DWO files per se -
545    comdat folding of types "loses" the DWO file they came from, and from
546    a high level view DWP files appear to contain a mass of random types.
547    However, to maintain consistency with the non-DWP case we pretend DWP
548    files contain virtual DWO files, and we assign each TU with one virtual
549    DWO file (generally based on the line and abbrev section offsets -
550    a heuristic that seems to work in practice).  */
551 
552 struct dwo_file
553 {
554   dwo_file () = default;
555   DISABLE_COPY_AND_ASSIGN (dwo_file);
556 
557   /* The DW_AT_GNU_dwo_name or DW_AT_dwo_name attribute.
558      For virtual DWO files the name is constructed from the section offsets
559      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
560      from related CU+TUs.  */
561   const char *dwo_name = nullptr;
562 
563   /* The DW_AT_comp_dir attribute.  */
564   const char *comp_dir = nullptr;
565 
566   /* The bfd, when the file is open.  Otherwise this is NULL.
567      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
568   gdb_bfd_ref_ptr dbfd;
569 
570   /* The sections that make up this DWO file.
571      Remember that for virtual DWO files in DWP V2 or DWP V5, these are virtual
572      sections (for lack of a better name).  */
573   struct dwo_sections sections {};
574 
575   /* The CUs in the file.
576      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
577      an extension to handle LLVM's Link Time Optimization output (where
578      multiple source files may be compiled into a single object/dwo pair). */
579   htab_up cus;
580 
581   /* Table of TUs in the file.
582      Each element is a struct dwo_unit.  */
583   htab_up tus;
584 };
585 
586 /* These sections are what may appear in a DWP file.  */
587 
588 struct dwp_sections
589 {
590   /* These are used by all DWP versions (1, 2 and 5).  */
591   struct dwarf2_section_info str;
592   struct dwarf2_section_info cu_index;
593   struct dwarf2_section_info tu_index;
594 
595   /* These are only used by DWP version 2 and version 5 files.
596      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
597      sections are referenced by section number, and are not recorded here.
598      In DWP version 2 or 5 there is at most one copy of all these sections,
599      each section being (effectively) comprised of the concatenation of all of
600      the individual sections that exist in the version 1 format.
601      To keep the code simple we treat each of these concatenated pieces as a
602      section itself (a virtual section?).  */
603   struct dwarf2_section_info abbrev;
604   struct dwarf2_section_info info;
605   struct dwarf2_section_info line;
606   struct dwarf2_section_info loc;
607   struct dwarf2_section_info loclists;
608   struct dwarf2_section_info macinfo;
609   struct dwarf2_section_info macro;
610   struct dwarf2_section_info rnglists;
611   struct dwarf2_section_info str_offsets;
612   struct dwarf2_section_info types;
613 };
614 
615 /* These sections are what may appear in a virtual DWO file in DWP version 1.
616    A virtual DWO file is a DWO file as it appears in a DWP file.  */
617 
618 struct virtual_v1_dwo_sections
619 {
620   struct dwarf2_section_info abbrev;
621   struct dwarf2_section_info line;
622   struct dwarf2_section_info loc;
623   struct dwarf2_section_info macinfo;
624   struct dwarf2_section_info macro;
625   struct dwarf2_section_info str_offsets;
626   /* Each DWP hash table entry records one CU or one TU.
627      That is recorded here, and copied to dwo_unit.section.  */
628   struct dwarf2_section_info info_or_types;
629 };
630 
631 /* Similar to virtual_v1_dwo_sections, but for DWP version 2 or 5.
632    In version 2, the sections of the DWO files are concatenated together
633    and stored in one section of that name.  Thus each ELF section contains
634    several "virtual" sections.  */
635 
636 struct virtual_v2_or_v5_dwo_sections
637 {
638   bfd_size_type abbrev_offset;
639   bfd_size_type abbrev_size;
640 
641   bfd_size_type line_offset;
642   bfd_size_type line_size;
643 
644   bfd_size_type loc_offset;
645   bfd_size_type loc_size;
646 
647   bfd_size_type loclists_offset;
648   bfd_size_type loclists_size;
649 
650   bfd_size_type macinfo_offset;
651   bfd_size_type macinfo_size;
652 
653   bfd_size_type macro_offset;
654   bfd_size_type macro_size;
655 
656   bfd_size_type rnglists_offset;
657   bfd_size_type rnglists_size;
658 
659   bfd_size_type str_offsets_offset;
660   bfd_size_type str_offsets_size;
661 
662   /* Each DWP hash table entry records one CU or one TU.
663      That is recorded here, and copied to dwo_unit.section.  */
664   bfd_size_type info_or_types_offset;
665   bfd_size_type info_or_types_size;
666 };
667 
668 /* Contents of DWP hash tables.  */
669 
670 struct dwp_hash_table
671 {
672   uint32_t version, nr_columns;
673   uint32_t nr_units, nr_slots;
674   const gdb_byte *hash_table, *unit_table;
675   union
676   {
677     struct
678     {
679       const gdb_byte *indices;
680     } v1;
681     struct
682     {
683       /* This is indexed by column number and gives the id of the section
684 	 in that column.  */
685 #define MAX_NR_V2_DWO_SECTIONS \
686   (1 /* .debug_info or .debug_types */ \
687    + 1 /* .debug_abbrev */ \
688    + 1 /* .debug_line */ \
689    + 1 /* .debug_loc */ \
690    + 1 /* .debug_str_offsets */ \
691    + 1 /* .debug_macro or .debug_macinfo */)
692       int section_ids[MAX_NR_V2_DWO_SECTIONS];
693       const gdb_byte *offsets;
694       const gdb_byte *sizes;
695     } v2;
696     struct
697     {
698       /* This is indexed by column number and gives the id of the section
699 	 in that column.  */
700 #define MAX_NR_V5_DWO_SECTIONS \
701   (1 /* .debug_info */ \
702    + 1 /* .debug_abbrev */ \
703    + 1 /* .debug_line */ \
704    + 1 /* .debug_loclists */ \
705    + 1 /* .debug_str_offsets */ \
706    + 1 /* .debug_macro */ \
707    + 1 /* .debug_rnglists */)
708       int section_ids[MAX_NR_V5_DWO_SECTIONS];
709       const gdb_byte *offsets;
710       const gdb_byte *sizes;
711     } v5;
712   } section_pool;
713 };
714 
715 /* Data for one DWP file.  */
716 
717 struct dwp_file
718 {
719   dwp_file (const char *name_, gdb_bfd_ref_ptr &&abfd)
720     : name (name_),
721       dbfd (std::move (abfd))
722   {
723   }
724 
725   /* Name of the file.  */
726   const char *name;
727 
728   /* File format version.  */
729   int version = 0;
730 
731   /* The bfd.  */
732   gdb_bfd_ref_ptr dbfd;
733 
734   /* Section info for this file.  */
735   struct dwp_sections sections {};
736 
737   /* Table of CUs in the file.  */
738   const struct dwp_hash_table *cus = nullptr;
739 
740   /* Table of TUs in the file.  */
741   const struct dwp_hash_table *tus = nullptr;
742 
743   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
744   htab_up loaded_cus;
745   htab_up loaded_tus;
746 
747   /* Table to map ELF section numbers to their sections.
748      This is only needed for the DWP V1 file format.  */
749   unsigned int num_sections = 0;
750   asection **elf_sections = nullptr;
751 };
752 
753 /* Struct used to pass misc. parameters to read_die_and_children, et
754    al.  which are used for both .debug_info and .debug_types dies.
755    All parameters here are unchanging for the life of the call.  This
756    struct exists to abstract away the constant parameters of die reading.  */
757 
758 struct die_reader_specs
759 {
760   /* The bfd of die_section.  */
761   bfd *abfd;
762 
763   /* The CU of the DIE we are parsing.  */
764   struct dwarf2_cu *cu;
765 
766   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
767   struct dwo_file *dwo_file;
768 
769   /* The section the die comes from.
770      This is either .debug_info or .debug_types, or the .dwo variants.  */
771   struct dwarf2_section_info *die_section;
772 
773   /* die_section->buffer.  */
774   const gdb_byte *buffer;
775 
776   /* The end of the buffer.  */
777   const gdb_byte *buffer_end;
778 
779   /* The abbreviation table to use when reading the DIEs.  */
780   struct abbrev_table *abbrev_table;
781 };
782 
783 /* A subclass of die_reader_specs that holds storage and has complex
784    constructor and destructor behavior.  */
785 
786 class cutu_reader : public die_reader_specs
787 {
788 public:
789 
790   cutu_reader (dwarf2_per_cu_data *this_cu,
791 	       dwarf2_per_objfile *per_objfile,
792 	       struct abbrev_table *abbrev_table,
793 	       dwarf2_cu *existing_cu,
794 	       bool skip_partial);
795 
796   explicit cutu_reader (struct dwarf2_per_cu_data *this_cu,
797 			dwarf2_per_objfile *per_objfile,
798 			struct dwarf2_cu *parent_cu = nullptr,
799 			struct dwo_file *dwo_file = nullptr);
800 
801   DISABLE_COPY_AND_ASSIGN (cutu_reader);
802 
803   const gdb_byte *info_ptr = nullptr;
804   struct die_info *comp_unit_die = nullptr;
805   bool dummy_p = false;
806 
807   /* Release the new CU, putting it on the chain.  This cannot be done
808      for dummy CUs.  */
809   void keep ();
810 
811 private:
812   void init_tu_and_read_dwo_dies (dwarf2_per_cu_data *this_cu,
813 				  dwarf2_per_objfile *per_objfile,
814 				  dwarf2_cu *existing_cu);
815 
816   struct dwarf2_per_cu_data *m_this_cu;
817   std::unique_ptr<dwarf2_cu> m_new_cu;
818 
819   /* The ordinary abbreviation table.  */
820   abbrev_table_up m_abbrev_table_holder;
821 
822   /* The DWO abbreviation table.  */
823   abbrev_table_up m_dwo_abbrev_table;
824 };
825 
826 /* When we construct a partial symbol table entry we only
827    need this much information.  */
828 struct partial_die_info : public allocate_on_obstack
829   {
830     partial_die_info (sect_offset sect_off, const struct abbrev_info *abbrev);
831 
832     /* Disable assign but still keep copy ctor, which is needed
833        load_partial_dies.   */
834     partial_die_info& operator=(const partial_die_info& rhs) = delete;
835     partial_die_info (const partial_die_info &) = default;
836 
837     /* Adjust the partial die before generating a symbol for it.  This
838        function may set the is_external flag or change the DIE's
839        name.  */
840     void fixup (struct dwarf2_cu *cu);
841 
842     /* Read a minimal amount of information into the minimal die
843        structure.  */
844     const gdb_byte *read (const struct die_reader_specs *reader,
845 			  const struct abbrev_info &abbrev,
846 			  const gdb_byte *info_ptr);
847 
848     /* Compute the name of this partial DIE.  This memoizes the
849        result, so it is safe to call multiple times.  */
850     const char *name (dwarf2_cu *cu);
851 
852     /* Offset of this DIE.  */
853     const sect_offset sect_off;
854 
855     /* DWARF-2 tag for this DIE.  */
856     const ENUM_BITFIELD(dwarf_tag) tag : 16;
857 
858     /* Assorted flags describing the data found in this DIE.  */
859     const unsigned int has_children : 1;
860 
861     unsigned int is_external : 1;
862     unsigned int is_declaration : 1;
863     unsigned int has_type : 1;
864     unsigned int has_specification : 1;
865     unsigned int has_pc_info : 1;
866     unsigned int may_be_inlined : 1;
867 
868     /* This DIE has been marked DW_AT_main_subprogram.  */
869     unsigned int main_subprogram : 1;
870 
871     /* Flag set if the SCOPE field of this structure has been
872        computed.  */
873     unsigned int scope_set : 1;
874 
875     /* Flag set if the DIE has a byte_size attribute.  */
876     unsigned int has_byte_size : 1;
877 
878     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
879     unsigned int has_const_value : 1;
880 
881     /* Flag set if any of the DIE's children are template arguments.  */
882     unsigned int has_template_arguments : 1;
883 
884     /* Flag set if fixup has been called on this die.  */
885     unsigned int fixup_called : 1;
886 
887     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
888     unsigned int is_dwz : 1;
889 
890     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
891     unsigned int spec_is_dwz : 1;
892 
893     unsigned int canonical_name : 1;
894 
895     /* The name of this DIE.  Normally the value of DW_AT_name, but
896        sometimes a default name for unnamed DIEs.  */
897     const char *raw_name = nullptr;
898 
899     /* The linkage name, if present.  */
900     const char *linkage_name = nullptr;
901 
902     /* The scope to prepend to our children.  This is generally
903        allocated on the comp_unit_obstack, so will disappear
904        when this compilation unit leaves the cache.  */
905     const char *scope = nullptr;
906 
907     /* Some data associated with the partial DIE.  The tag determines
908        which field is live.  */
909     union
910     {
911       /* The location description associated with this DIE, if any.  */
912       struct dwarf_block *locdesc;
913       /* The offset of an import, for DW_TAG_imported_unit.  */
914       sect_offset sect_off;
915     } d {};
916 
917     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
918     CORE_ADDR lowpc = 0;
919     CORE_ADDR highpc = 0;
920 
921     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
922        DW_AT_sibling, if any.  */
923     /* NOTE: This member isn't strictly necessary, partial_die_info::read
924        could return DW_AT_sibling values to its caller load_partial_dies.  */
925     const gdb_byte *sibling = nullptr;
926 
927     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
928        DW_AT_specification (or DW_AT_abstract_origin or
929        DW_AT_extension).  */
930     sect_offset spec_offset {};
931 
932     /* Pointers to this DIE's parent, first child, and next sibling,
933        if any.  */
934     struct partial_die_info *die_parent = nullptr;
935     struct partial_die_info *die_child = nullptr;
936     struct partial_die_info *die_sibling = nullptr;
937 
938     friend struct partial_die_info *
939     dwarf2_cu::find_partial_die (sect_offset sect_off);
940 
941   private:
942     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
943     partial_die_info (sect_offset sect_off)
944       : partial_die_info (sect_off, DW_TAG_padding, 0)
945     {
946     }
947 
948     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
949 		      int has_children_)
950       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
951     {
952       is_external = 0;
953       is_declaration = 0;
954       has_type = 0;
955       has_specification = 0;
956       has_pc_info = 0;
957       may_be_inlined = 0;
958       main_subprogram = 0;
959       scope_set = 0;
960       has_byte_size = 0;
961       has_const_value = 0;
962       has_template_arguments = 0;
963       fixup_called = 0;
964       is_dwz = 0;
965       spec_is_dwz = 0;
966       canonical_name = 0;
967     }
968   };
969 
970 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
971    but this would require a corresponding change in unpack_field_as_long
972    and friends.  */
973 static int bits_per_byte = 8;
974 
975 struct variant_part_builder;
976 
977 /* When reading a variant, we track a bit more information about the
978    field, and store it in an object of this type.  */
979 
980 struct variant_field
981 {
982   int first_field = -1;
983   int last_field = -1;
984 
985   /* A variant can contain other variant parts.  */
986   std::vector<variant_part_builder> variant_parts;
987 
988   /* If we see a DW_TAG_variant, then this will be set if this is the
989      default branch.  */
990   bool default_branch = false;
991   /* If we see a DW_AT_discr_value, then this will be the discriminant
992      value.  */
993   ULONGEST discriminant_value = 0;
994   /* If we see a DW_AT_discr_list, then this is a pointer to the list
995      data.  */
996   struct dwarf_block *discr_list_data = nullptr;
997 };
998 
999 /* This represents a DW_TAG_variant_part.  */
1000 
1001 struct variant_part_builder
1002 {
1003   /* The offset of the discriminant field.  */
1004   sect_offset discriminant_offset {};
1005 
1006   /* Variants that are direct children of this variant part.  */
1007   std::vector<variant_field> variants;
1008 
1009   /* True if we're currently reading a variant.  */
1010   bool processing_variant = false;
1011 };
1012 
1013 struct nextfield
1014 {
1015   int accessibility = 0;
1016   int virtuality = 0;
1017   /* Variant parts need to find the discriminant, which is a DIE
1018      reference.  We track the section offset of each field to make
1019      this link.  */
1020   sect_offset offset;
1021   struct field field {};
1022 };
1023 
1024 struct fnfieldlist
1025 {
1026   const char *name = nullptr;
1027   std::vector<struct fn_field> fnfields;
1028 };
1029 
1030 /* The routines that read and process dies for a C struct or C++ class
1031    pass lists of data member fields and lists of member function fields
1032    in an instance of a field_info structure, as defined below.  */
1033 struct field_info
1034 {
1035   /* List of data member and baseclasses fields.  */
1036   std::vector<struct nextfield> fields;
1037   std::vector<struct nextfield> baseclasses;
1038 
1039   /* Set if the accessibility of one of the fields is not public.  */
1040   bool non_public_fields = false;
1041 
1042   /* Member function fieldlist array, contains name of possibly overloaded
1043      member function, number of overloaded member functions and a pointer
1044      to the head of the member function field chain.  */
1045   std::vector<struct fnfieldlist> fnfieldlists;
1046 
1047   /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1048      a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1049   std::vector<struct decl_field> typedef_field_list;
1050 
1051   /* Nested types defined by this class and the number of elements in this
1052      list.  */
1053   std::vector<struct decl_field> nested_types_list;
1054 
1055   /* If non-null, this is the variant part we are currently
1056      reading.  */
1057   variant_part_builder *current_variant_part = nullptr;
1058   /* This holds all the top-level variant parts attached to the type
1059      we're reading.  */
1060   std::vector<variant_part_builder> variant_parts;
1061 
1062   /* Return the total number of fields (including baseclasses).  */
1063   int nfields () const
1064   {
1065     return fields.size () + baseclasses.size ();
1066   }
1067 };
1068 
1069 /* Loaded secondary compilation units are kept in memory until they
1070    have not been referenced for the processing of this many
1071    compilation units.  Set this to zero to disable caching.  Cache
1072    sizes of up to at least twenty will improve startup time for
1073    typical inter-CU-reference binaries, at an obvious memory cost.  */
1074 static int dwarf_max_cache_age = 5;
1075 static void
1076 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1077 			  struct cmd_list_element *c, const char *value)
1078 {
1079   fprintf_filtered (file, _("The upper bound on the age of cached "
1080 			    "DWARF compilation units is %s.\n"),
1081 		    value);
1082 }
1083 
1084 /* local function prototypes */
1085 
1086 static void dwarf2_find_base_address (struct die_info *die,
1087 				      struct dwarf2_cu *cu);
1088 
1089 static dwarf2_psymtab *create_partial_symtab
1090   (dwarf2_per_cu_data *per_cu, dwarf2_per_objfile *per_objfile,
1091    const char *name);
1092 
1093 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1094 					const gdb_byte *info_ptr,
1095 					struct die_info *type_unit_die);
1096 
1097 static void dwarf2_build_psymtabs_hard (dwarf2_per_objfile *per_objfile);
1098 
1099 static void scan_partial_symbols (struct partial_die_info *,
1100 				  CORE_ADDR *, CORE_ADDR *,
1101 				  int, struct dwarf2_cu *);
1102 
1103 static void add_partial_symbol (struct partial_die_info *,
1104 				struct dwarf2_cu *);
1105 
1106 static void add_partial_namespace (struct partial_die_info *pdi,
1107 				   CORE_ADDR *lowpc, CORE_ADDR *highpc,
1108 				   int set_addrmap, struct dwarf2_cu *cu);
1109 
1110 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1111 				CORE_ADDR *highpc, int set_addrmap,
1112 				struct dwarf2_cu *cu);
1113 
1114 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1115 				     struct dwarf2_cu *cu);
1116 
1117 static void add_partial_subprogram (struct partial_die_info *pdi,
1118 				    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1119 				    int need_pc, struct dwarf2_cu *cu);
1120 
1121 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1122 
1123 static struct partial_die_info *load_partial_dies
1124   (const struct die_reader_specs *, const gdb_byte *, int);
1125 
1126 /* A pair of partial_die_info and compilation unit.  */
1127 struct cu_partial_die_info
1128 {
1129   /* The compilation unit of the partial_die_info.  */
1130   struct dwarf2_cu *cu;
1131   /* A partial_die_info.  */
1132   struct partial_die_info *pdi;
1133 
1134   cu_partial_die_info (struct dwarf2_cu *cu, struct partial_die_info *pdi)
1135     : cu (cu),
1136       pdi (pdi)
1137   { /* Nothing.  */ }
1138 
1139 private:
1140   cu_partial_die_info () = delete;
1141 };
1142 
1143 static const struct cu_partial_die_info find_partial_die (sect_offset, int,
1144 							  struct dwarf2_cu *);
1145 
1146 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1147 				       struct attribute *,
1148 				       const struct attr_abbrev *,
1149 				       const gdb_byte *);
1150 
1151 static void read_attribute_reprocess (const struct die_reader_specs *reader,
1152 				      struct attribute *attr, dwarf_tag tag);
1153 
1154 static CORE_ADDR read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index);
1155 
1156 static sect_offset read_abbrev_offset (dwarf2_per_objfile *per_objfile,
1157 				       dwarf2_section_info *, sect_offset);
1158 
1159 static const char *read_indirect_string
1160   (dwarf2_per_objfile *per_objfile, bfd *, const gdb_byte *,
1161    const struct comp_unit_head *, unsigned int *);
1162 
1163 static const char *read_indirect_string_at_offset
1164   (dwarf2_per_objfile *per_objfile, LONGEST str_offset);
1165 
1166 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1167 					      const gdb_byte *,
1168 					      unsigned int *);
1169 
1170 static const char *read_dwo_str_index (const struct die_reader_specs *reader,
1171 				       ULONGEST str_index);
1172 
1173 static const char *read_stub_str_index (struct dwarf2_cu *cu,
1174 					ULONGEST str_index);
1175 
1176 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1177 				      struct dwarf2_cu *);
1178 
1179 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1180 				       struct dwarf2_cu *cu);
1181 
1182 static const char *dwarf2_dwo_name (struct die_info *die, struct dwarf2_cu *cu);
1183 
1184 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1185 			       struct dwarf2_cu *cu);
1186 
1187 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1188 
1189 static struct die_info *die_specification (struct die_info *die,
1190 					   struct dwarf2_cu **);
1191 
1192 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1193 						struct dwarf2_cu *cu);
1194 
1195 static void dwarf_decode_lines (struct line_header *, const char *,
1196 				struct dwarf2_cu *, dwarf2_psymtab *,
1197 				CORE_ADDR, int decode_mapping);
1198 
1199 static void dwarf2_start_subfile (struct dwarf2_cu *, const char *,
1200 				  const char *);
1201 
1202 static struct symbol *new_symbol (struct die_info *, struct type *,
1203 				  struct dwarf2_cu *, struct symbol * = NULL);
1204 
1205 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1206 				struct dwarf2_cu *);
1207 
1208 static void dwarf2_const_value_attr (const struct attribute *attr,
1209 				     struct type *type,
1210 				     const char *name,
1211 				     struct obstack *obstack,
1212 				     struct dwarf2_cu *cu, LONGEST *value,
1213 				     const gdb_byte **bytes,
1214 				     struct dwarf2_locexpr_baton **baton);
1215 
1216 static struct type *read_subrange_index_type (struct die_info *die,
1217 					      struct dwarf2_cu *cu);
1218 
1219 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1220 
1221 static int need_gnat_info (struct dwarf2_cu *);
1222 
1223 static struct type *die_descriptive_type (struct die_info *,
1224 					  struct dwarf2_cu *);
1225 
1226 static void set_descriptive_type (struct type *, struct die_info *,
1227 				  struct dwarf2_cu *);
1228 
1229 static struct type *die_containing_type (struct die_info *,
1230 					 struct dwarf2_cu *);
1231 
1232 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1233 				     struct dwarf2_cu *);
1234 
1235 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1236 
1237 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1238 
1239 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1240 
1241 static char *typename_concat (struct obstack *obs, const char *prefix,
1242 			      const char *suffix, int physname,
1243 			      struct dwarf2_cu *cu);
1244 
1245 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1246 
1247 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1248 
1249 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1250 
1251 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1252 
1253 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1254 
1255 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1256 
1257 /* Return the .debug_loclists section to use for cu.  */
1258 static struct dwarf2_section_info *cu_debug_loc_section (struct dwarf2_cu *cu);
1259 
1260 /* Return the .debug_rnglists section to use for cu.  */
1261 static struct dwarf2_section_info *cu_debug_rnglists_section
1262   (struct dwarf2_cu *cu, dwarf_tag tag);
1263 
1264 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1265    values.  Keep the items ordered with increasing constraints compliance.  */
1266 enum pc_bounds_kind
1267 {
1268   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1269   PC_BOUNDS_NOT_PRESENT,
1270 
1271   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1272      were present but they do not form a valid range of PC addresses.  */
1273   PC_BOUNDS_INVALID,
1274 
1275   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1276   PC_BOUNDS_RANGES,
1277 
1278   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1279   PC_BOUNDS_HIGH_LOW,
1280 };
1281 
1282 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1283 						 CORE_ADDR *, CORE_ADDR *,
1284 						 struct dwarf2_cu *,
1285 						 dwarf2_psymtab *);
1286 
1287 static void get_scope_pc_bounds (struct die_info *,
1288 				 CORE_ADDR *, CORE_ADDR *,
1289 				 struct dwarf2_cu *);
1290 
1291 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1292 					CORE_ADDR, struct dwarf2_cu *);
1293 
1294 static void dwarf2_add_field (struct field_info *, struct die_info *,
1295 			      struct dwarf2_cu *);
1296 
1297 static void dwarf2_attach_fields_to_type (struct field_info *,
1298 					  struct type *, struct dwarf2_cu *);
1299 
1300 static void dwarf2_add_member_fn (struct field_info *,
1301 				  struct die_info *, struct type *,
1302 				  struct dwarf2_cu *);
1303 
1304 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1305 					     struct type *,
1306 					     struct dwarf2_cu *);
1307 
1308 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1309 
1310 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1311 
1312 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1313 
1314 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1315 
1316 static struct using_direct **using_directives (struct dwarf2_cu *cu);
1317 
1318 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1319 
1320 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1321 
1322 static struct type *read_module_type (struct die_info *die,
1323 				      struct dwarf2_cu *cu);
1324 
1325 static const char *namespace_name (struct die_info *die,
1326 				   int *is_anonymous, struct dwarf2_cu *);
1327 
1328 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1329 
1330 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *,
1331 				 bool * = nullptr);
1332 
1333 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1334 						       struct dwarf2_cu *);
1335 
1336 static struct die_info *read_die_and_siblings_1
1337   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1338    struct die_info *);
1339 
1340 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1341 					       const gdb_byte *info_ptr,
1342 					       const gdb_byte **new_info_ptr,
1343 					       struct die_info *parent);
1344 
1345 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1346 					struct die_info **, const gdb_byte *,
1347 					int);
1348 
1349 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1350 				      struct die_info **, const gdb_byte *);
1351 
1352 static void process_die (struct die_info *, struct dwarf2_cu *);
1353 
1354 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1355 					     struct objfile *);
1356 
1357 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1358 
1359 static const char *dwarf2_full_name (const char *name,
1360 				     struct die_info *die,
1361 				     struct dwarf2_cu *cu);
1362 
1363 static const char *dwarf2_physname (const char *name, struct die_info *die,
1364 				    struct dwarf2_cu *cu);
1365 
1366 static struct die_info *dwarf2_extension (struct die_info *die,
1367 					  struct dwarf2_cu **);
1368 
1369 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1370 
1371 static void dump_die_for_error (struct die_info *);
1372 
1373 static void dump_die_1 (struct ui_file *, int level, int max_level,
1374 			struct die_info *);
1375 
1376 /*static*/ void dump_die (struct die_info *, int max_level);
1377 
1378 static void store_in_ref_table (struct die_info *,
1379 				struct dwarf2_cu *);
1380 
1381 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1382 					       const struct attribute *,
1383 					       struct dwarf2_cu **);
1384 
1385 static struct die_info *follow_die_ref (struct die_info *,
1386 					const struct attribute *,
1387 					struct dwarf2_cu **);
1388 
1389 static struct die_info *follow_die_sig (struct die_info *,
1390 					const struct attribute *,
1391 					struct dwarf2_cu **);
1392 
1393 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1394 					 struct dwarf2_cu *);
1395 
1396 static struct type *get_DW_AT_signature_type (struct die_info *,
1397 					      const struct attribute *,
1398 					      struct dwarf2_cu *);
1399 
1400 static void load_full_type_unit (dwarf2_per_cu_data *per_cu,
1401 				 dwarf2_per_objfile *per_objfile);
1402 
1403 static void read_signatured_type (signatured_type *sig_type,
1404 				  dwarf2_per_objfile *per_objfile);
1405 
1406 static int attr_to_dynamic_prop (const struct attribute *attr,
1407 				 struct die_info *die, struct dwarf2_cu *cu,
1408 				 struct dynamic_prop *prop, struct type *type);
1409 
1410 /* memory allocation interface */
1411 
1412 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1413 
1414 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1415 
1416 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1417 
1418 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1419 				   struct dwarf2_loclist_baton *baton,
1420 				   const struct attribute *attr);
1421 
1422 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1423 					 struct symbol *sym,
1424 					 struct dwarf2_cu *cu,
1425 					 int is_block);
1426 
1427 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1428 				     const gdb_byte *info_ptr,
1429 				     const struct abbrev_info *abbrev);
1430 
1431 static hashval_t partial_die_hash (const void *item);
1432 
1433 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1434 
1435 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1436   (sect_offset sect_off, unsigned int offset_in_dwz,
1437    dwarf2_per_objfile *per_objfile);
1438 
1439 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1440 				   struct die_info *comp_unit_die,
1441 				   enum language pretend_language);
1442 
1443 static struct type *set_die_type (struct die_info *, struct type *,
1444 				  struct dwarf2_cu *, bool = false);
1445 
1446 static void create_all_comp_units (dwarf2_per_objfile *per_objfile);
1447 
1448 static void load_full_comp_unit (dwarf2_per_cu_data *per_cu,
1449 				 dwarf2_per_objfile *per_objfile,
1450 				 dwarf2_cu *existing_cu,
1451 				 bool skip_partial,
1452 				 enum language pretend_language);
1453 
1454 static void process_full_comp_unit (dwarf2_cu *cu,
1455 				    enum language pretend_language);
1456 
1457 static void process_full_type_unit (dwarf2_cu *cu,
1458 				    enum language pretend_language);
1459 
1460 static struct type *get_die_type_at_offset (sect_offset,
1461 					    dwarf2_per_cu_data *per_cu,
1462 					    dwarf2_per_objfile *per_objfile);
1463 
1464 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1465 
1466 static void queue_comp_unit (dwarf2_per_cu_data *per_cu,
1467 			     dwarf2_per_objfile *per_objfile,
1468 			     enum language pretend_language);
1469 
1470 static void process_queue (dwarf2_per_objfile *per_objfile);
1471 
1472 /* Class, the destructor of which frees all allocated queue entries.  This
1473    will only have work to do if an error was thrown while processing the
1474    dwarf.  If no error was thrown then the queue entries should have all
1475    been processed, and freed, as we went along.  */
1476 
1477 class dwarf2_queue_guard
1478 {
1479 public:
1480   explicit dwarf2_queue_guard (dwarf2_per_objfile *per_objfile)
1481     : m_per_objfile (per_objfile)
1482   {
1483     gdb_assert (!m_per_objfile->per_bfd->queue.has_value ());
1484 
1485     m_per_objfile->per_bfd->queue.emplace ();
1486   }
1487 
1488   /* Free any entries remaining on the queue.  There should only be
1489      entries left if we hit an error while processing the dwarf.  */
1490   ~dwarf2_queue_guard ()
1491   {
1492     gdb_assert (m_per_objfile->per_bfd->queue.has_value ());
1493 
1494     m_per_objfile->per_bfd->queue.reset ();
1495   }
1496 
1497   DISABLE_COPY_AND_ASSIGN (dwarf2_queue_guard);
1498 
1499 private:
1500   dwarf2_per_objfile *m_per_objfile;
1501 };
1502 
1503 dwarf2_queue_item::~dwarf2_queue_item ()
1504 {
1505   /* Anything still marked queued is likely to be in an
1506      inconsistent state, so discard it.  */
1507   if (per_cu->queued)
1508     {
1509       per_objfile->remove_cu (per_cu);
1510       per_cu->queued = 0;
1511     }
1512 }
1513 
1514 /* See dwarf2/read.h.  */
1515 
1516 void
1517 dwarf2_per_cu_data_deleter::operator() (dwarf2_per_cu_data *data)
1518 {
1519   if (data->is_debug_types)
1520     delete static_cast<signatured_type *> (data);
1521   else
1522     delete data;
1523 }
1524 
1525 /* The return type of find_file_and_directory.  Note, the enclosed
1526    string pointers are only valid while this object is valid.  */
1527 
1528 struct file_and_directory
1529 {
1530   /* The filename.  This is never NULL.  */
1531   const char *name;
1532 
1533   /* The compilation directory.  NULL if not known.  If we needed to
1534      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1535      points directly to the DW_AT_comp_dir string attribute owned by
1536      the obstack that owns the DIE.  */
1537   const char *comp_dir;
1538 
1539   /* If we needed to build a new string for comp_dir, this is what
1540      owns the storage.  */
1541   std::string comp_dir_storage;
1542 };
1543 
1544 static file_and_directory find_file_and_directory (struct die_info *die,
1545 						   struct dwarf2_cu *cu);
1546 
1547 static htab_up allocate_signatured_type_table ();
1548 
1549 static htab_up allocate_dwo_unit_table ();
1550 
1551 static struct dwo_unit *lookup_dwo_unit_in_dwp
1552   (dwarf2_per_objfile *per_objfile, struct dwp_file *dwp_file,
1553    const char *comp_dir, ULONGEST signature, int is_debug_types);
1554 
1555 static struct dwp_file *get_dwp_file (dwarf2_per_objfile *per_objfile);
1556 
1557 static struct dwo_unit *lookup_dwo_comp_unit
1558   (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir,
1559    ULONGEST signature);
1560 
1561 static struct dwo_unit *lookup_dwo_type_unit
1562   (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir);
1563 
1564 static void queue_and_load_all_dwo_tus (dwarf2_cu *cu);
1565 
1566 /* A unique pointer to a dwo_file.  */
1567 
1568 typedef std::unique_ptr<struct dwo_file> dwo_file_up;
1569 
1570 static void process_cu_includes (dwarf2_per_objfile *per_objfile);
1571 
1572 static void check_producer (struct dwarf2_cu *cu);
1573 
1574 /* Various complaints about symbol reading that don't abort the process.  */
1575 
1576 static void
1577 dwarf2_debug_line_missing_file_complaint (void)
1578 {
1579   complaint (_(".debug_line section has line data without a file"));
1580 }
1581 
1582 static void
1583 dwarf2_debug_line_missing_end_sequence_complaint (void)
1584 {
1585   complaint (_(".debug_line section has line "
1586 	       "program sequence without an end"));
1587 }
1588 
1589 static void
1590 dwarf2_complex_location_expr_complaint (void)
1591 {
1592   complaint (_("location expression too complex"));
1593 }
1594 
1595 static void
1596 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1597 					      int arg3)
1598 {
1599   complaint (_("const value length mismatch for '%s', got %d, expected %d"),
1600 	     arg1, arg2, arg3);
1601 }
1602 
1603 static void
1604 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1605 {
1606   complaint (_("invalid attribute class or form for '%s' in '%s'"),
1607 	     arg1, arg2);
1608 }
1609 
1610 /* Hash function for line_header_hash.  */
1611 
1612 static hashval_t
1613 line_header_hash (const struct line_header *ofs)
1614 {
1615   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
1616 }
1617 
1618 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
1619 
1620 static hashval_t
1621 line_header_hash_voidp (const void *item)
1622 {
1623   const struct line_header *ofs = (const struct line_header *) item;
1624 
1625   return line_header_hash (ofs);
1626 }
1627 
1628 /* Equality function for line_header_hash.  */
1629 
1630 static int
1631 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
1632 {
1633   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
1634   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
1635 
1636   return (ofs_lhs->sect_off == ofs_rhs->sect_off
1637 	  && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
1638 }
1639 
1640 
1641 
1642 /* An iterator for all_comp_units that is based on index.  This
1643    approach makes it possible to iterate over all_comp_units safely,
1644    when some caller in the loop may add new units.  */
1645 
1646 class all_comp_units_iterator
1647 {
1648 public:
1649 
1650   all_comp_units_iterator (dwarf2_per_bfd *per_bfd, bool start)
1651     : m_per_bfd (per_bfd),
1652       m_index (start ? 0 : per_bfd->all_comp_units.size ())
1653   {
1654   }
1655 
1656   all_comp_units_iterator &operator++ ()
1657   {
1658     ++m_index;
1659     return *this;
1660   }
1661 
1662   dwarf2_per_cu_data *operator* () const
1663   {
1664     return m_per_bfd->get_cu (m_index);
1665   }
1666 
1667   bool operator== (const all_comp_units_iterator &other) const
1668   {
1669     return m_index == other.m_index;
1670   }
1671 
1672 
1673   bool operator!= (const all_comp_units_iterator &other) const
1674   {
1675     return m_index != other.m_index;
1676   }
1677 
1678 private:
1679 
1680   dwarf2_per_bfd *m_per_bfd;
1681   size_t m_index;
1682 };
1683 
1684 /* A range adapter for the all_comp_units_iterator.  */
1685 class all_comp_units_range
1686 {
1687 public:
1688 
1689   all_comp_units_range (dwarf2_per_bfd *per_bfd)
1690     : m_per_bfd (per_bfd)
1691   {
1692   }
1693 
1694   all_comp_units_iterator begin ()
1695   {
1696     return all_comp_units_iterator (m_per_bfd, true);
1697   }
1698 
1699   all_comp_units_iterator end ()
1700   {
1701     return all_comp_units_iterator (m_per_bfd, false);
1702   }
1703 
1704 private:
1705 
1706   dwarf2_per_bfd *m_per_bfd;
1707 };
1708 
1709 /* See declaration.  */
1710 
1711 dwarf2_per_bfd::dwarf2_per_bfd (bfd *obfd, const dwarf2_debug_sections *names,
1712 				bool can_copy_)
1713   : obfd (obfd),
1714     can_copy (can_copy_)
1715 {
1716   if (names == NULL)
1717     names = &dwarf2_elf_names;
1718 
1719   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
1720     locate_sections (obfd, sec, *names);
1721 }
1722 
1723 dwarf2_per_bfd::~dwarf2_per_bfd ()
1724 {
1725   for (auto &per_cu : all_comp_units)
1726     per_cu->imported_symtabs_free ();
1727 
1728   /* Everything else should be on this->obstack.  */
1729 }
1730 
1731 /* See read.h.  */
1732 
1733 void
1734 dwarf2_per_objfile::remove_all_cus ()
1735 {
1736   gdb_assert (!this->per_bfd->queue.has_value ());
1737 
1738   for (auto pair : m_dwarf2_cus)
1739     delete pair.second;
1740 
1741   m_dwarf2_cus.clear ();
1742 }
1743 
1744 /* A helper class that calls free_cached_comp_units on
1745    destruction.  */
1746 
1747 class free_cached_comp_units
1748 {
1749 public:
1750 
1751   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
1752     : m_per_objfile (per_objfile)
1753   {
1754   }
1755 
1756   ~free_cached_comp_units ()
1757   {
1758     m_per_objfile->remove_all_cus ();
1759   }
1760 
1761   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
1762 
1763 private:
1764 
1765   dwarf2_per_objfile *m_per_objfile;
1766 };
1767 
1768 /* See read.h.  */
1769 
1770 bool
1771 dwarf2_per_objfile::symtab_set_p (const dwarf2_per_cu_data *per_cu) const
1772 {
1773   if (per_cu->index < this->m_symtabs.size ())
1774     return this->m_symtabs[per_cu->index] != nullptr;
1775   return false;
1776 }
1777 
1778 /* See read.h.  */
1779 
1780 compunit_symtab *
1781 dwarf2_per_objfile::get_symtab (const dwarf2_per_cu_data *per_cu) const
1782 {
1783   if (per_cu->index < this->m_symtabs.size ())
1784     return this->m_symtabs[per_cu->index];
1785   return nullptr;
1786 }
1787 
1788 /* See read.h.  */
1789 
1790 void
1791 dwarf2_per_objfile::set_symtab (const dwarf2_per_cu_data *per_cu,
1792 				compunit_symtab *symtab)
1793 {
1794   if (per_cu->index >= this->m_symtabs.size ())
1795     this->m_symtabs.resize (per_cu->index + 1);
1796   gdb_assert (this->m_symtabs[per_cu->index] == nullptr);
1797   this->m_symtabs[per_cu->index] = symtab;
1798 }
1799 
1800 /* Try to locate the sections we need for DWARF 2 debugging
1801    information and return true if we have enough to do something.
1802    NAMES points to the dwarf2 section names, or is NULL if the standard
1803    ELF names are used.  CAN_COPY is true for formats where symbol
1804    interposition is possible and so symbol values must follow copy
1805    relocation rules.  */
1806 
1807 int
1808 dwarf2_has_info (struct objfile *objfile,
1809 		 const struct dwarf2_debug_sections *names,
1810 		 bool can_copy)
1811 {
1812   if (objfile->flags & OBJF_READNEVER)
1813     return 0;
1814 
1815   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
1816 
1817   if (per_objfile == NULL)
1818     {
1819       dwarf2_per_bfd *per_bfd;
1820 
1821       /* We can share a "dwarf2_per_bfd" with other objfiles if the
1822 	 BFD doesn't require relocations.
1823 
1824 	 We don't share with objfiles for which -readnow was requested,
1825 	 because it would complicate things when loading the same BFD with
1826 	 -readnow and then without -readnow.  */
1827       if (!gdb_bfd_requires_relocations (objfile->obfd)
1828 	  && (objfile->flags & OBJF_READNOW) == 0)
1829 	{
1830 	  /* See if one has been created for this BFD yet.  */
1831 	  per_bfd = dwarf2_per_bfd_bfd_data_key.get (objfile->obfd);
1832 
1833 	  if (per_bfd == nullptr)
1834 	    {
1835 	      /* No, create it now.  */
1836 	      per_bfd = new dwarf2_per_bfd (objfile->obfd, names, can_copy);
1837 	      dwarf2_per_bfd_bfd_data_key.set (objfile->obfd, per_bfd);
1838 	    }
1839 	}
1840       else
1841 	{
1842 	  /* No sharing possible, create one specifically for this objfile.  */
1843 	  per_bfd = new dwarf2_per_bfd (objfile->obfd, names, can_copy);
1844 	  dwarf2_per_bfd_objfile_data_key.set (objfile, per_bfd);
1845 	}
1846 
1847       per_objfile = dwarf2_objfile_data_key.emplace (objfile, objfile, per_bfd);
1848     }
1849 
1850   return (!per_objfile->per_bfd->info.is_virtual
1851 	  && per_objfile->per_bfd->info.s.section != NULL
1852 	  && !per_objfile->per_bfd->abbrev.is_virtual
1853 	  && per_objfile->per_bfd->abbrev.s.section != NULL);
1854 }
1855 
1856 /* See declaration.  */
1857 
1858 void
1859 dwarf2_per_bfd::locate_sections (bfd *abfd, asection *sectp,
1860 				 const dwarf2_debug_sections &names)
1861 {
1862   flagword aflag = bfd_section_flags (sectp);
1863 
1864   if ((aflag & SEC_HAS_CONTENTS) == 0)
1865     {
1866     }
1867   else if (elf_section_data (sectp)->this_hdr.sh_size
1868 	   > bfd_get_file_size (abfd))
1869     {
1870       bfd_size_type size = elf_section_data (sectp)->this_hdr.sh_size;
1871       warning (_("Discarding section %s which has a section size (%s"
1872 		 ") larger than the file size [in module %s]"),
1873 	       bfd_section_name (sectp), phex_nz (size, sizeof (size)),
1874 	       bfd_get_filename (abfd));
1875     }
1876   else if (names.info.matches (sectp->name))
1877     {
1878       this->info.s.section = sectp;
1879       this->info.size = bfd_section_size (sectp);
1880     }
1881   else if (names.abbrev.matches (sectp->name))
1882     {
1883       this->abbrev.s.section = sectp;
1884       this->abbrev.size = bfd_section_size (sectp);
1885     }
1886   else if (names.line.matches (sectp->name))
1887     {
1888       this->line.s.section = sectp;
1889       this->line.size = bfd_section_size (sectp);
1890     }
1891   else if (names.loc.matches (sectp->name))
1892     {
1893       this->loc.s.section = sectp;
1894       this->loc.size = bfd_section_size (sectp);
1895     }
1896   else if (names.loclists.matches (sectp->name))
1897     {
1898       this->loclists.s.section = sectp;
1899       this->loclists.size = bfd_section_size (sectp);
1900     }
1901   else if (names.macinfo.matches (sectp->name))
1902     {
1903       this->macinfo.s.section = sectp;
1904       this->macinfo.size = bfd_section_size (sectp);
1905     }
1906   else if (names.macro.matches (sectp->name))
1907     {
1908       this->macro.s.section = sectp;
1909       this->macro.size = bfd_section_size (sectp);
1910     }
1911   else if (names.str.matches (sectp->name))
1912     {
1913       this->str.s.section = sectp;
1914       this->str.size = bfd_section_size (sectp);
1915     }
1916   else if (names.str_offsets.matches (sectp->name))
1917     {
1918       this->str_offsets.s.section = sectp;
1919       this->str_offsets.size = bfd_section_size (sectp);
1920     }
1921   else if (names.line_str.matches (sectp->name))
1922     {
1923       this->line_str.s.section = sectp;
1924       this->line_str.size = bfd_section_size (sectp);
1925     }
1926   else if (names.addr.matches (sectp->name))
1927     {
1928       this->addr.s.section = sectp;
1929       this->addr.size = bfd_section_size (sectp);
1930     }
1931   else if (names.frame.matches (sectp->name))
1932     {
1933       this->frame.s.section = sectp;
1934       this->frame.size = bfd_section_size (sectp);
1935     }
1936   else if (names.eh_frame.matches (sectp->name))
1937     {
1938       this->eh_frame.s.section = sectp;
1939       this->eh_frame.size = bfd_section_size (sectp);
1940     }
1941   else if (names.ranges.matches (sectp->name))
1942     {
1943       this->ranges.s.section = sectp;
1944       this->ranges.size = bfd_section_size (sectp);
1945     }
1946   else if (names.rnglists.matches (sectp->name))
1947     {
1948       this->rnglists.s.section = sectp;
1949       this->rnglists.size = bfd_section_size (sectp);
1950     }
1951   else if (names.types.matches (sectp->name))
1952     {
1953       struct dwarf2_section_info type_section;
1954 
1955       memset (&type_section, 0, sizeof (type_section));
1956       type_section.s.section = sectp;
1957       type_section.size = bfd_section_size (sectp);
1958 
1959       this->types.push_back (type_section);
1960     }
1961   else if (names.gdb_index.matches (sectp->name))
1962     {
1963       this->gdb_index.s.section = sectp;
1964       this->gdb_index.size = bfd_section_size (sectp);
1965     }
1966   else if (names.debug_names.matches (sectp->name))
1967     {
1968       this->debug_names.s.section = sectp;
1969       this->debug_names.size = bfd_section_size (sectp);
1970     }
1971   else if (names.debug_aranges.matches (sectp->name))
1972     {
1973       this->debug_aranges.s.section = sectp;
1974       this->debug_aranges.size = bfd_section_size (sectp);
1975     }
1976 
1977   if ((bfd_section_flags (sectp) & (SEC_LOAD | SEC_ALLOC))
1978       && bfd_section_vma (sectp) == 0)
1979     this->has_section_at_zero = true;
1980 }
1981 
1982 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
1983    SECTION_NAME.  */
1984 
1985 void
1986 dwarf2_get_section_info (struct objfile *objfile,
1987 			 enum dwarf2_section_enum sect,
1988 			 asection **sectp, const gdb_byte **bufp,
1989 			 bfd_size_type *sizep)
1990 {
1991   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
1992   struct dwarf2_section_info *info;
1993 
1994   /* We may see an objfile without any DWARF, in which case we just
1995      return nothing.  */
1996   if (per_objfile == NULL)
1997     {
1998       *sectp = NULL;
1999       *bufp = NULL;
2000       *sizep = 0;
2001       return;
2002     }
2003   switch (sect)
2004     {
2005     case DWARF2_DEBUG_FRAME:
2006       info = &per_objfile->per_bfd->frame;
2007       break;
2008     case DWARF2_EH_FRAME:
2009       info = &per_objfile->per_bfd->eh_frame;
2010       break;
2011     default:
2012       gdb_assert_not_reached ("unexpected section");
2013     }
2014 
2015   info->read (objfile);
2016 
2017   *sectp = info->get_bfd_section ();
2018   *bufp = info->buffer;
2019   *sizep = info->size;
2020 }
2021 
2022 
2023 /* DWARF quick_symbol_functions support.  */
2024 
2025 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2026    unique line tables, so we maintain a separate table of all .debug_line
2027    derived entries to support the sharing.
2028    All the quick functions need is the list of file names.  We discard the
2029    line_header when we're done and don't need to record it here.  */
2030 struct quick_file_names
2031 {
2032   /* The data used to construct the hash key.  */
2033   struct stmt_list_hash hash;
2034 
2035   /* The number of entries in file_names, real_names.  */
2036   unsigned int num_file_names;
2037 
2038   /* The file names from the line table, after being run through
2039      file_full_name.  */
2040   const char **file_names;
2041 
2042   /* The file names from the line table after being run through
2043      gdb_realpath.  These are computed lazily.  */
2044   const char **real_names;
2045 };
2046 
2047 /* When using the index (and thus not using psymtabs), each CU has an
2048    object of this type.  This is used to hold information needed by
2049    the various "quick" methods.  */
2050 struct dwarf2_per_cu_quick_data
2051 {
2052   /* The file table.  This can be NULL if there was no file table
2053      or it's currently not read in.
2054      NOTE: This points into dwarf2_per_objfile->per_bfd->quick_file_names_table.  */
2055   struct quick_file_names *file_names;
2056 
2057   /* A temporary mark bit used when iterating over all CUs in
2058      expand_symtabs_matching.  */
2059   unsigned int mark : 1;
2060 
2061   /* True if we've tried to read the file table and found there isn't one.
2062      There will be no point in trying to read it again next time.  */
2063   unsigned int no_file_data : 1;
2064 };
2065 
2066 /* A subclass of psymbol_functions that arranges to read the DWARF
2067    partial symbols when needed.  */
2068 struct lazy_dwarf_reader : public psymbol_functions
2069 {
2070   using psymbol_functions::psymbol_functions;
2071 
2072   bool can_lazily_read_symbols () override
2073   {
2074     return true;
2075   }
2076 
2077   void read_partial_symbols (struct objfile *objfile) override
2078   {
2079     if (dwarf2_has_info (objfile, nullptr))
2080       dwarf2_build_psymtabs (objfile, this);
2081   }
2082 };
2083 
2084 static quick_symbol_functions_up
2085 make_lazy_dwarf_reader ()
2086 {
2087   return quick_symbol_functions_up (new lazy_dwarf_reader);
2088 }
2089 
2090 struct dwarf2_base_index_functions : public quick_symbol_functions
2091 {
2092   bool has_symbols (struct objfile *objfile) override;
2093 
2094   bool has_unexpanded_symtabs (struct objfile *objfile) override;
2095 
2096   struct symtab *find_last_source_symtab (struct objfile *objfile) override;
2097 
2098   void forget_cached_source_info (struct objfile *objfile) override;
2099 
2100   enum language lookup_global_symbol_language (struct objfile *objfile,
2101 					       const char *name,
2102 					       domain_enum domain,
2103 					       bool *symbol_found_p) override
2104   {
2105     *symbol_found_p = false;
2106     return language_unknown;
2107   }
2108 
2109   void print_stats (struct objfile *objfile, bool print_bcache) override;
2110 
2111   void expand_all_symtabs (struct objfile *objfile) override;
2112 
2113   struct compunit_symtab *find_pc_sect_compunit_symtab
2114     (struct objfile *objfile, struct bound_minimal_symbol msymbol,
2115      CORE_ADDR pc, struct obj_section *section, int warn_if_readin) override;
2116 
2117   struct compunit_symtab *find_compunit_symtab_by_address
2118     (struct objfile *objfile, CORE_ADDR address) override
2119   {
2120     return nullptr;
2121   }
2122 
2123   void map_symbol_filenames (struct objfile *objfile,
2124 			     gdb::function_view<symbol_filename_ftype> fun,
2125 			     bool need_fullname) override;
2126 };
2127 
2128 struct dwarf2_gdb_index : public dwarf2_base_index_functions
2129 {
2130   void dump (struct objfile *objfile) override;
2131 
2132   void expand_matching_symbols
2133     (struct objfile *,
2134      const lookup_name_info &lookup_name,
2135      domain_enum domain,
2136      int global,
2137      symbol_compare_ftype *ordered_compare) override;
2138 
2139   bool expand_symtabs_matching
2140     (struct objfile *objfile,
2141      gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
2142      const lookup_name_info *lookup_name,
2143      gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
2144      gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
2145      block_search_flags search_flags,
2146      domain_enum domain,
2147      enum search_domain kind) override;
2148 };
2149 
2150 struct dwarf2_debug_names_index : public dwarf2_base_index_functions
2151 {
2152   void dump (struct objfile *objfile) override;
2153 
2154   void expand_matching_symbols
2155     (struct objfile *,
2156      const lookup_name_info &lookup_name,
2157      domain_enum domain,
2158      int global,
2159      symbol_compare_ftype *ordered_compare) override;
2160 
2161   bool expand_symtabs_matching
2162     (struct objfile *objfile,
2163      gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
2164      const lookup_name_info *lookup_name,
2165      gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
2166      gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
2167      block_search_flags search_flags,
2168      domain_enum domain,
2169      enum search_domain kind) override;
2170 };
2171 
2172 static quick_symbol_functions_up
2173 make_dwarf_gdb_index ()
2174 {
2175   return quick_symbol_functions_up (new dwarf2_gdb_index);
2176 }
2177 
2178 static quick_symbol_functions_up
2179 make_dwarf_debug_names ()
2180 {
2181   return quick_symbol_functions_up (new dwarf2_debug_names_index);
2182 }
2183 
2184 /* Utility hash function for a stmt_list_hash.  */
2185 
2186 static hashval_t
2187 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2188 {
2189   hashval_t v = 0;
2190 
2191   if (stmt_list_hash->dwo_unit != NULL)
2192     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2193   v += to_underlying (stmt_list_hash->line_sect_off);
2194   return v;
2195 }
2196 
2197 /* Utility equality function for a stmt_list_hash.  */
2198 
2199 static int
2200 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2201 		    const struct stmt_list_hash *rhs)
2202 {
2203   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2204     return 0;
2205   if (lhs->dwo_unit != NULL
2206       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2207     return 0;
2208 
2209   return lhs->line_sect_off == rhs->line_sect_off;
2210 }
2211 
2212 /* Hash function for a quick_file_names.  */
2213 
2214 static hashval_t
2215 hash_file_name_entry (const void *e)
2216 {
2217   const struct quick_file_names *file_data
2218     = (const struct quick_file_names *) e;
2219 
2220   return hash_stmt_list_entry (&file_data->hash);
2221 }
2222 
2223 /* Equality function for a quick_file_names.  */
2224 
2225 static int
2226 eq_file_name_entry (const void *a, const void *b)
2227 {
2228   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2229   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2230 
2231   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2232 }
2233 
2234 /* Delete function for a quick_file_names.  */
2235 
2236 static void
2237 delete_file_name_entry (void *e)
2238 {
2239   struct quick_file_names *file_data = (struct quick_file_names *) e;
2240   int i;
2241 
2242   for (i = 0; i < file_data->num_file_names; ++i)
2243     {
2244       xfree ((void*) file_data->file_names[i]);
2245       if (file_data->real_names)
2246 	xfree ((void*) file_data->real_names[i]);
2247     }
2248 
2249   /* The space for the struct itself lives on the obstack, so we don't
2250      free it here.  */
2251 }
2252 
2253 /* Create a quick_file_names hash table.  */
2254 
2255 static htab_up
2256 create_quick_file_names_table (unsigned int nr_initial_entries)
2257 {
2258   return htab_up (htab_create_alloc (nr_initial_entries,
2259 				     hash_file_name_entry, eq_file_name_entry,
2260 				     delete_file_name_entry, xcalloc, xfree));
2261 }
2262 
2263 /* Read in CU (dwarf2_cu object) for PER_CU in the context of PER_OBJFILE.  This
2264    function is unrelated to symtabs, symtab would have to be created afterwards.
2265    You should call age_cached_comp_units after processing the CU.  */
2266 
2267 static dwarf2_cu *
2268 load_cu (dwarf2_per_cu_data *per_cu, dwarf2_per_objfile *per_objfile,
2269 	 bool skip_partial)
2270 {
2271   if (per_cu->is_debug_types)
2272     load_full_type_unit (per_cu, per_objfile);
2273   else
2274     load_full_comp_unit (per_cu, per_objfile, per_objfile->get_cu (per_cu),
2275 			 skip_partial, language_minimal);
2276 
2277   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
2278   if (cu == nullptr)
2279     return nullptr;  /* Dummy CU.  */
2280 
2281   dwarf2_find_base_address (cu->dies, cu);
2282 
2283   return cu;
2284 }
2285 
2286 /* Read in the symbols for PER_CU in the context of PER_OBJFILE.  */
2287 
2288 static void
2289 dw2_do_instantiate_symtab (dwarf2_per_cu_data *per_cu,
2290 			   dwarf2_per_objfile *per_objfile, bool skip_partial)
2291 {
2292   /* Skip type_unit_groups, reading the type units they contain
2293      is handled elsewhere.  */
2294   if (per_cu->type_unit_group_p ())
2295     return;
2296 
2297   {
2298     /* The destructor of dwarf2_queue_guard frees any entries left on
2299        the queue.  After this point we're guaranteed to leave this function
2300        with the dwarf queue empty.  */
2301     dwarf2_queue_guard q_guard (per_objfile);
2302 
2303     if (!per_objfile->symtab_set_p (per_cu))
2304       {
2305 	queue_comp_unit (per_cu, per_objfile, language_minimal);
2306 	dwarf2_cu *cu = load_cu (per_cu, per_objfile, skip_partial);
2307 
2308 	/* If we just loaded a CU from a DWO, and we're working with an index
2309 	   that may badly handle TUs, load all the TUs in that DWO as well.
2310 	   http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2311 	if (!per_cu->is_debug_types
2312 	    && cu != NULL
2313 	    && cu->dwo_unit != NULL
2314 	    && per_objfile->per_bfd->index_table != NULL
2315 	    && per_objfile->per_bfd->index_table->version <= 7
2316 	    /* DWP files aren't supported yet.  */
2317 	    && get_dwp_file (per_objfile) == NULL)
2318 	  queue_and_load_all_dwo_tus (cu);
2319       }
2320 
2321     process_queue (per_objfile);
2322   }
2323 
2324   /* Age the cache, releasing compilation units that have not
2325      been used recently.  */
2326   per_objfile->age_comp_units ();
2327 }
2328 
2329 /* Ensure that the symbols for PER_CU have been read in.  DWARF2_PER_OBJFILE is
2330    the per-objfile for which this symtab is instantiated.
2331 
2332    Returns the resulting symbol table.  */
2333 
2334 static struct compunit_symtab *
2335 dw2_instantiate_symtab (dwarf2_per_cu_data *per_cu,
2336 			dwarf2_per_objfile *per_objfile,
2337 			bool skip_partial)
2338 {
2339   gdb_assert (per_objfile->per_bfd->using_index);
2340 
2341   if (!per_objfile->symtab_set_p (per_cu))
2342     {
2343       free_cached_comp_units freer (per_objfile);
2344       scoped_restore decrementer = increment_reading_symtab ();
2345       dw2_do_instantiate_symtab (per_cu, per_objfile, skip_partial);
2346       process_cu_includes (per_objfile);
2347     }
2348 
2349   return per_objfile->get_symtab (per_cu);
2350 }
2351 
2352 /* See read.h.  */
2353 
2354 dwarf2_per_cu_data_up
2355 dwarf2_per_bfd::allocate_per_cu ()
2356 {
2357   dwarf2_per_cu_data_up result (new dwarf2_per_cu_data);
2358   result->per_bfd = this;
2359   result->index = all_comp_units.size ();
2360   return result;
2361 }
2362 
2363 /* See read.h.  */
2364 
2365 signatured_type_up
2366 dwarf2_per_bfd::allocate_signatured_type (ULONGEST signature)
2367 {
2368   signatured_type_up result (new signatured_type (signature));
2369   result->per_bfd = this;
2370   result->index = all_comp_units.size ();
2371   result->is_debug_types = true;
2372   tu_stats.nr_tus++;
2373   return result;
2374 }
2375 
2376 /* Return a new dwarf2_per_cu_data allocated on the per-bfd
2377    obstack, and constructed with the specified field values.  */
2378 
2379 static dwarf2_per_cu_data_up
2380 create_cu_from_index_list (dwarf2_per_bfd *per_bfd,
2381 			   struct dwarf2_section_info *section,
2382 			   int is_dwz,
2383 			   sect_offset sect_off, ULONGEST length)
2384 {
2385   dwarf2_per_cu_data_up the_cu = per_bfd->allocate_per_cu ();
2386   the_cu->sect_off = sect_off;
2387   the_cu->length = length;
2388   the_cu->section = section;
2389   the_cu->v.quick = OBSTACK_ZALLOC (&per_bfd->obstack,
2390 				    struct dwarf2_per_cu_quick_data);
2391   the_cu->is_dwz = is_dwz;
2392   return the_cu;
2393 }
2394 
2395 /* A helper for create_cus_from_index that handles a given list of
2396    CUs.  */
2397 
2398 static void
2399 create_cus_from_index_list (dwarf2_per_bfd *per_bfd,
2400 			    const gdb_byte *cu_list, offset_type n_elements,
2401 			    struct dwarf2_section_info *section,
2402 			    int is_dwz)
2403 {
2404   for (offset_type i = 0; i < n_elements; i += 2)
2405     {
2406       gdb_static_assert (sizeof (ULONGEST) >= 8);
2407 
2408       sect_offset sect_off
2409 	= (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2410       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2411       cu_list += 2 * 8;
2412 
2413       dwarf2_per_cu_data_up per_cu
2414 	= create_cu_from_index_list (per_bfd, section, is_dwz, sect_off,
2415 				     length);
2416       per_bfd->all_comp_units.push_back (std::move (per_cu));
2417     }
2418 }
2419 
2420 /* Read the CU list from the mapped index, and use it to create all
2421    the CU objects for PER_BFD.  */
2422 
2423 static void
2424 create_cus_from_index (dwarf2_per_bfd *per_bfd,
2425 		       const gdb_byte *cu_list, offset_type cu_list_elements,
2426 		       const gdb_byte *dwz_list, offset_type dwz_elements)
2427 {
2428   gdb_assert (per_bfd->all_comp_units.empty ());
2429   per_bfd->all_comp_units.reserve ((cu_list_elements + dwz_elements) / 2);
2430 
2431   create_cus_from_index_list (per_bfd, cu_list, cu_list_elements,
2432 			      &per_bfd->info, 0);
2433 
2434   if (dwz_elements == 0)
2435     return;
2436 
2437   dwz_file *dwz = dwarf2_get_dwz_file (per_bfd);
2438   create_cus_from_index_list (per_bfd, dwz_list, dwz_elements,
2439 			      &dwz->info, 1);
2440 }
2441 
2442 /* Create the signatured type hash table from the index.  */
2443 
2444 static void
2445 create_signatured_type_table_from_index
2446   (dwarf2_per_bfd *per_bfd, struct dwarf2_section_info *section,
2447    const gdb_byte *bytes, offset_type elements)
2448 {
2449   htab_up sig_types_hash = allocate_signatured_type_table ();
2450 
2451   for (offset_type i = 0; i < elements; i += 3)
2452     {
2453       signatured_type_up sig_type;
2454       ULONGEST signature;
2455       void **slot;
2456       cu_offset type_offset_in_tu;
2457 
2458       gdb_static_assert (sizeof (ULONGEST) >= 8);
2459       sect_offset sect_off
2460 	= (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2461       type_offset_in_tu
2462 	= (cu_offset) extract_unsigned_integer (bytes + 8, 8,
2463 						BFD_ENDIAN_LITTLE);
2464       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2465       bytes += 3 * 8;
2466 
2467       sig_type = per_bfd->allocate_signatured_type (signature);
2468       sig_type->type_offset_in_tu = type_offset_in_tu;
2469       sig_type->section = section;
2470       sig_type->sect_off = sect_off;
2471       sig_type->v.quick
2472 	= OBSTACK_ZALLOC (&per_bfd->obstack,
2473 			  struct dwarf2_per_cu_quick_data);
2474 
2475       slot = htab_find_slot (sig_types_hash.get (), sig_type.get (), INSERT);
2476       *slot = sig_type.get ();
2477 
2478       per_bfd->all_comp_units.emplace_back (sig_type.release ());
2479     }
2480 
2481   per_bfd->signatured_types = std::move (sig_types_hash);
2482 }
2483 
2484 /* Create the signatured type hash table from .debug_names.  */
2485 
2486 static void
2487 create_signatured_type_table_from_debug_names
2488   (dwarf2_per_objfile *per_objfile,
2489    const mapped_debug_names &map,
2490    struct dwarf2_section_info *section,
2491    struct dwarf2_section_info *abbrev_section)
2492 {
2493   struct objfile *objfile = per_objfile->objfile;
2494 
2495   section->read (objfile);
2496   abbrev_section->read (objfile);
2497 
2498   htab_up sig_types_hash = allocate_signatured_type_table ();
2499 
2500   for (uint32_t i = 0; i < map.tu_count; ++i)
2501     {
2502       signatured_type_up sig_type;
2503       void **slot;
2504 
2505       sect_offset sect_off
2506 	= (sect_offset) (extract_unsigned_integer
2507 			 (map.tu_table_reordered + i * map.offset_size,
2508 			  map.offset_size,
2509 			  map.dwarf5_byte_order));
2510 
2511       comp_unit_head cu_header;
2512       read_and_check_comp_unit_head (per_objfile, &cu_header, section,
2513 				     abbrev_section,
2514 				     section->buffer + to_underlying (sect_off),
2515 				     rcuh_kind::TYPE);
2516 
2517       sig_type = per_objfile->per_bfd->allocate_signatured_type
2518 	(cu_header.signature);
2519       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
2520       sig_type->section = section;
2521       sig_type->sect_off = sect_off;
2522       sig_type->v.quick
2523 	= OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack,
2524 			  struct dwarf2_per_cu_quick_data);
2525 
2526       slot = htab_find_slot (sig_types_hash.get (), sig_type.get (), INSERT);
2527       *slot = sig_type.get ();
2528 
2529       per_objfile->per_bfd->all_comp_units.emplace_back (sig_type.release ());
2530     }
2531 
2532   per_objfile->per_bfd->signatured_types = std::move (sig_types_hash);
2533 }
2534 
2535 /* Read the address map data from the mapped index, and use it to
2536    populate the psymtabs_addrmap.  */
2537 
2538 static void
2539 create_addrmap_from_index (dwarf2_per_objfile *per_objfile,
2540 			   struct mapped_index *index)
2541 {
2542   struct objfile *objfile = per_objfile->objfile;
2543   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
2544   struct gdbarch *gdbarch = objfile->arch ();
2545   const gdb_byte *iter, *end;
2546   struct addrmap *mutable_map;
2547   CORE_ADDR baseaddr;
2548 
2549   auto_obstack temp_obstack;
2550 
2551   mutable_map = addrmap_create_mutable (&temp_obstack);
2552 
2553   iter = index->address_table.data ();
2554   end = iter + index->address_table.size ();
2555 
2556   baseaddr = objfile->text_section_offset ();
2557 
2558   while (iter < end)
2559     {
2560       ULONGEST hi, lo, cu_index;
2561       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2562       iter += 8;
2563       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2564       iter += 8;
2565       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2566       iter += 4;
2567 
2568       if (lo > hi)
2569 	{
2570 	  complaint (_(".gdb_index address table has invalid range (%s - %s)"),
2571 		     hex_string (lo), hex_string (hi));
2572 	  continue;
2573 	}
2574 
2575       if (cu_index >= per_bfd->all_comp_units.size ())
2576 	{
2577 	  complaint (_(".gdb_index address table has invalid CU number %u"),
2578 		     (unsigned) cu_index);
2579 	  continue;
2580 	}
2581 
2582       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr) - baseaddr;
2583       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr) - baseaddr;
2584       addrmap_set_empty (mutable_map, lo, hi - 1,
2585 			 per_bfd->get_cu (cu_index));
2586     }
2587 
2588   per_bfd->index_addrmap = addrmap_create_fixed (mutable_map,
2589 						 &per_bfd->obstack);
2590 }
2591 
2592 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
2593    populate the psymtabs_addrmap.  */
2594 
2595 static void
2596 create_addrmap_from_aranges (dwarf2_per_objfile *per_objfile,
2597 			     struct dwarf2_section_info *section)
2598 {
2599   struct objfile *objfile = per_objfile->objfile;
2600   bfd *abfd = objfile->obfd;
2601   struct gdbarch *gdbarch = objfile->arch ();
2602   const CORE_ADDR baseaddr = objfile->text_section_offset ();
2603   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
2604 
2605   auto_obstack temp_obstack;
2606   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
2607 
2608   std::unordered_map<sect_offset,
2609 		     dwarf2_per_cu_data *,
2610 		     gdb::hash_enum<sect_offset>>
2611     debug_info_offset_to_per_cu;
2612   for (const auto &per_cu : per_bfd->all_comp_units)
2613     {
2614       const auto insertpair
2615 	= debug_info_offset_to_per_cu.emplace (per_cu->sect_off,
2616 					       per_cu.get ());
2617       if (!insertpair.second)
2618 	{
2619 	  warning (_("Section .debug_aranges in %s has duplicate "
2620 		     "debug_info_offset %s, ignoring .debug_aranges."),
2621 		   objfile_name (objfile), sect_offset_str (per_cu->sect_off));
2622 	  return;
2623 	}
2624     }
2625 
2626   section->read (objfile);
2627 
2628   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
2629 
2630   const gdb_byte *addr = section->buffer;
2631 
2632   while (addr < section->buffer + section->size)
2633     {
2634       const gdb_byte *const entry_addr = addr;
2635       unsigned int bytes_read;
2636 
2637       const LONGEST entry_length = read_initial_length (abfd, addr,
2638 							&bytes_read);
2639       addr += bytes_read;
2640 
2641       const gdb_byte *const entry_end = addr + entry_length;
2642       const bool dwarf5_is_dwarf64 = bytes_read != 4;
2643       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
2644       if (addr + entry_length > section->buffer + section->size)
2645 	{
2646 	  warning (_("Section .debug_aranges in %s entry at offset %s "
2647 		     "length %s exceeds section length %s, "
2648 		     "ignoring .debug_aranges."),
2649 		   objfile_name (objfile),
2650 		   plongest (entry_addr - section->buffer),
2651 		   plongest (bytes_read + entry_length),
2652 		   pulongest (section->size));
2653 	  return;
2654 	}
2655 
2656       /* The version number.  */
2657       const uint16_t version = read_2_bytes (abfd, addr);
2658       addr += 2;
2659       if (version != 2)
2660 	{
2661 	  warning (_("Section .debug_aranges in %s entry at offset %s "
2662 		     "has unsupported version %d, ignoring .debug_aranges."),
2663 		   objfile_name (objfile),
2664 		   plongest (entry_addr - section->buffer), version);
2665 	  return;
2666 	}
2667 
2668       const uint64_t debug_info_offset
2669 	= extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
2670       addr += offset_size;
2671       const auto per_cu_it
2672 	= debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
2673       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
2674 	{
2675 	  warning (_("Section .debug_aranges in %s entry at offset %s "
2676 		     "debug_info_offset %s does not exists, "
2677 		     "ignoring .debug_aranges."),
2678 		   objfile_name (objfile),
2679 		   plongest (entry_addr - section->buffer),
2680 		   pulongest (debug_info_offset));
2681 	  return;
2682 	}
2683       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
2684 
2685       const uint8_t address_size = *addr++;
2686       if (address_size < 1 || address_size > 8)
2687 	{
2688 	  warning (_("Section .debug_aranges in %s entry at offset %s "
2689 		     "address_size %u is invalid, ignoring .debug_aranges."),
2690 		   objfile_name (objfile),
2691 		   plongest (entry_addr - section->buffer), address_size);
2692 	  return;
2693 	}
2694 
2695       const uint8_t segment_selector_size = *addr++;
2696       if (segment_selector_size != 0)
2697 	{
2698 	  warning (_("Section .debug_aranges in %s entry at offset %s "
2699 		     "segment_selector_size %u is not supported, "
2700 		     "ignoring .debug_aranges."),
2701 		   objfile_name (objfile),
2702 		   plongest (entry_addr - section->buffer),
2703 		   segment_selector_size);
2704 	  return;
2705 	}
2706 
2707       /* Must pad to an alignment boundary that is twice the address
2708 	 size.  It is undocumented by the DWARF standard but GCC does
2709 	 use it.  However, not every compiler does this.  We can see
2710 	 whether it has happened by looking at the total length of the
2711 	 contents of the aranges for this CU -- it if isn't a multiple
2712 	 of twice the address size, then we skip any leftover
2713 	 bytes.  */
2714       addr += (entry_end - addr) % (2 * address_size);
2715 
2716       for (;;)
2717 	{
2718 	  if (addr + 2 * address_size > entry_end)
2719 	    {
2720 	      warning (_("Section .debug_aranges in %s entry at offset %s "
2721 			 "address list is not properly terminated, "
2722 			 "ignoring .debug_aranges."),
2723 		       objfile_name (objfile),
2724 		       plongest (entry_addr - section->buffer));
2725 	      return;
2726 	    }
2727 	  ULONGEST start = extract_unsigned_integer (addr, address_size,
2728 						     dwarf5_byte_order);
2729 	  addr += address_size;
2730 	  ULONGEST length = extract_unsigned_integer (addr, address_size,
2731 						      dwarf5_byte_order);
2732 	  addr += address_size;
2733 	  if (start == 0 && length == 0)
2734 	    break;
2735 	  if (start == 0 && !per_bfd->has_section_at_zero)
2736 	    {
2737 	      /* Symbol was eliminated due to a COMDAT group.  */
2738 	      continue;
2739 	    }
2740 	  ULONGEST end = start + length;
2741 	  start = (gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr)
2742 		   - baseaddr);
2743 	  end = (gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr)
2744 		 - baseaddr);
2745 	  addrmap_set_empty (mutable_map, start, end - 1, per_cu);
2746 	}
2747     }
2748 
2749   per_bfd->index_addrmap = addrmap_create_fixed (mutable_map,
2750 						 &per_bfd->obstack);
2751 }
2752 
2753 /* A helper function that reads the .gdb_index from BUFFER and fills
2754    in MAP.  FILENAME is the name of the file containing the data;
2755    it is used for error reporting.  DEPRECATED_OK is true if it is
2756    ok to use deprecated sections.
2757 
2758    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2759    out parameters that are filled in with information about the CU and
2760    TU lists in the section.
2761 
2762    Returns true if all went well, false otherwise.  */
2763 
2764 static bool
2765 read_gdb_index_from_buffer (const char *filename,
2766 			    bool deprecated_ok,
2767 			    gdb::array_view<const gdb_byte> buffer,
2768 			    struct mapped_index *map,
2769 			    const gdb_byte **cu_list,
2770 			    offset_type *cu_list_elements,
2771 			    const gdb_byte **types_list,
2772 			    offset_type *types_list_elements)
2773 {
2774   const gdb_byte *addr = &buffer[0];
2775   offset_view metadata (buffer);
2776 
2777   /* Version check.  */
2778   offset_type version = metadata[0];
2779   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2780      causes the index to behave very poorly for certain requests.  Version 3
2781      contained incomplete addrmap.  So, it seems better to just ignore such
2782      indices.  */
2783   if (version < 4)
2784     {
2785       static int warning_printed = 0;
2786       if (!warning_printed)
2787 	{
2788 	  warning (_("Skipping obsolete .gdb_index section in %s."),
2789 		   filename);
2790 	  warning_printed = 1;
2791 	}
2792       return 0;
2793     }
2794   /* Index version 4 uses a different hash function than index version
2795      5 and later.
2796 
2797      Versions earlier than 6 did not emit psymbols for inlined
2798      functions.  Using these files will cause GDB not to be able to
2799      set breakpoints on inlined functions by name, so we ignore these
2800      indices unless the user has done
2801      "set use-deprecated-index-sections on".  */
2802   if (version < 6 && !deprecated_ok)
2803     {
2804       static int warning_printed = 0;
2805       if (!warning_printed)
2806 	{
2807 	  warning (_("\
2808 Skipping deprecated .gdb_index section in %s.\n\
2809 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2810 to use the section anyway."),
2811 		   filename);
2812 	  warning_printed = 1;
2813 	}
2814       return 0;
2815     }
2816   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2817      of the TU (for symbols coming from TUs),
2818      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
2819      Plus gold-generated indices can have duplicate entries for global symbols,
2820      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
2821      These are just performance bugs, and we can't distinguish gdb-generated
2822      indices from gold-generated ones, so issue no warning here.  */
2823 
2824   /* Indexes with higher version than the one supported by GDB may be no
2825      longer backward compatible.  */
2826   if (version > 8)
2827     return 0;
2828 
2829   map->version = version;
2830 
2831   int i = 1;
2832   *cu_list = addr + metadata[i];
2833   *cu_list_elements = (metadata[i + 1] - metadata[i]) / 8;
2834   ++i;
2835 
2836   *types_list = addr + metadata[i];
2837   *types_list_elements = (metadata[i + 1] - metadata[i]) / 8;
2838   ++i;
2839 
2840   const gdb_byte *address_table = addr + metadata[i];
2841   const gdb_byte *address_table_end = addr + metadata[i + 1];
2842   map->address_table
2843     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
2844   ++i;
2845 
2846   const gdb_byte *symbol_table = addr + metadata[i];
2847   const gdb_byte *symbol_table_end = addr + metadata[i + 1];
2848   map->symbol_table
2849     = offset_view (gdb::array_view<const gdb_byte> (symbol_table,
2850 						    symbol_table_end));
2851 
2852   ++i;
2853   map->constant_pool = buffer.slice (metadata[i]);
2854 
2855   return 1;
2856 }
2857 
2858 /* Callback types for dwarf2_read_gdb_index.  */
2859 
2860 typedef gdb::function_view
2861     <gdb::array_view<const gdb_byte>(objfile *, dwarf2_per_bfd *)>
2862     get_gdb_index_contents_ftype;
2863 typedef gdb::function_view
2864     <gdb::array_view<const gdb_byte>(objfile *, dwz_file *)>
2865     get_gdb_index_contents_dwz_ftype;
2866 
2867 /* Read .gdb_index.  If everything went ok, initialize the "quick"
2868    elements of all the CUs and return 1.  Otherwise, return 0.  */
2869 
2870 static int
2871 dwarf2_read_gdb_index
2872   (dwarf2_per_objfile *per_objfile,
2873    get_gdb_index_contents_ftype get_gdb_index_contents,
2874    get_gdb_index_contents_dwz_ftype get_gdb_index_contents_dwz)
2875 {
2876   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2877   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2878   struct dwz_file *dwz;
2879   struct objfile *objfile = per_objfile->objfile;
2880   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
2881 
2882   gdb::array_view<const gdb_byte> main_index_contents
2883     = get_gdb_index_contents (objfile, per_bfd);
2884 
2885   if (main_index_contents.empty ())
2886     return 0;
2887 
2888   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
2889   if (!read_gdb_index_from_buffer (objfile_name (objfile),
2890 				   use_deprecated_index_sections,
2891 				   main_index_contents, map.get (), &cu_list,
2892 				   &cu_list_elements, &types_list,
2893 				   &types_list_elements))
2894     return 0;
2895 
2896   /* Don't use the index if it's empty.  */
2897   if (map->symbol_table.empty ())
2898     return 0;
2899 
2900   /* If there is a .dwz file, read it so we can get its CU list as
2901      well.  */
2902   dwz = dwarf2_get_dwz_file (per_bfd);
2903   if (dwz != NULL)
2904     {
2905       struct mapped_index dwz_map;
2906       const gdb_byte *dwz_types_ignore;
2907       offset_type dwz_types_elements_ignore;
2908 
2909       gdb::array_view<const gdb_byte> dwz_index_content
2910 	= get_gdb_index_contents_dwz (objfile, dwz);
2911 
2912       if (dwz_index_content.empty ())
2913 	return 0;
2914 
2915       if (!read_gdb_index_from_buffer (bfd_get_filename (dwz->dwz_bfd.get ()),
2916 				       1, dwz_index_content, &dwz_map,
2917 				       &dwz_list, &dwz_list_elements,
2918 				       &dwz_types_ignore,
2919 				       &dwz_types_elements_ignore))
2920 	{
2921 	  warning (_("could not read '.gdb_index' section from %s; skipping"),
2922 		   bfd_get_filename (dwz->dwz_bfd.get ()));
2923 	  return 0;
2924 	}
2925     }
2926 
2927   create_cus_from_index (per_bfd, cu_list, cu_list_elements, dwz_list,
2928 			 dwz_list_elements);
2929 
2930   if (types_list_elements)
2931     {
2932       /* We can only handle a single .debug_types when we have an
2933 	 index.  */
2934       if (per_bfd->types.size () != 1)
2935 	return 0;
2936 
2937       dwarf2_section_info *section = &per_bfd->types[0];
2938 
2939       create_signatured_type_table_from_index (per_bfd, section, types_list,
2940 					       types_list_elements);
2941     }
2942 
2943   create_addrmap_from_index (per_objfile, map.get ());
2944 
2945   per_bfd->index_table = std::move (map);
2946   per_bfd->using_index = 1;
2947   per_bfd->quick_file_names_table =
2948     create_quick_file_names_table (per_bfd->all_comp_units.size ());
2949 
2950   return 1;
2951 }
2952 
2953 /* die_reader_func for dw2_get_file_names.  */
2954 
2955 static void
2956 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2957 			   struct die_info *comp_unit_die)
2958 {
2959   struct dwarf2_cu *cu = reader->cu;
2960   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
2961   dwarf2_per_objfile *per_objfile = cu->per_objfile;
2962   struct dwarf2_per_cu_data *lh_cu;
2963   struct attribute *attr;
2964   void **slot;
2965   struct quick_file_names *qfn;
2966 
2967   gdb_assert (! this_cu->is_debug_types);
2968 
2969   /* Our callers never want to match partial units -- instead they
2970      will match the enclosing full CU.  */
2971   if (comp_unit_die->tag == DW_TAG_partial_unit)
2972     {
2973       this_cu->v.quick->no_file_data = 1;
2974       return;
2975     }
2976 
2977   lh_cu = this_cu;
2978   slot = NULL;
2979 
2980   line_header_up lh;
2981   sect_offset line_offset {};
2982 
2983   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2984   if (attr != nullptr && attr->form_is_unsigned ())
2985     {
2986       struct quick_file_names find_entry;
2987 
2988       line_offset = (sect_offset) attr->as_unsigned ();
2989 
2990       /* We may have already read in this line header (TU line header sharing).
2991 	 If we have we're done.  */
2992       find_entry.hash.dwo_unit = cu->dwo_unit;
2993       find_entry.hash.line_sect_off = line_offset;
2994       slot = htab_find_slot (per_objfile->per_bfd->quick_file_names_table.get (),
2995 			     &find_entry, INSERT);
2996       if (*slot != NULL)
2997 	{
2998 	  lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
2999 	  return;
3000 	}
3001 
3002       lh = dwarf_decode_line_header (line_offset, cu);
3003     }
3004   if (lh == NULL)
3005     {
3006       lh_cu->v.quick->no_file_data = 1;
3007       return;
3008     }
3009 
3010   qfn = XOBNEW (&per_objfile->per_bfd->obstack, struct quick_file_names);
3011   qfn->hash.dwo_unit = cu->dwo_unit;
3012   qfn->hash.line_sect_off = line_offset;
3013   gdb_assert (slot != NULL);
3014   *slot = qfn;
3015 
3016   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3017 
3018   int offset = 0;
3019   if (strcmp (fnd.name, "<unknown>") != 0)
3020     ++offset;
3021 
3022   qfn->num_file_names = offset + lh->file_names_size ();
3023   qfn->file_names =
3024     XOBNEWVEC (&per_objfile->per_bfd->obstack, const char *,
3025 	       qfn->num_file_names);
3026   if (offset != 0)
3027     qfn->file_names[0] = xstrdup (fnd.name);
3028   for (int i = 0; i < lh->file_names_size (); ++i)
3029     qfn->file_names[i + offset] = lh->file_full_name (i + 1,
3030 						      fnd.comp_dir).release ();
3031   qfn->real_names = NULL;
3032 
3033   lh_cu->v.quick->file_names = qfn;
3034 }
3035 
3036 /* A helper for the "quick" functions which attempts to read the line
3037    table for THIS_CU.  */
3038 
3039 static struct quick_file_names *
3040 dw2_get_file_names (dwarf2_per_cu_data *this_cu,
3041 		    dwarf2_per_objfile *per_objfile)
3042 {
3043   /* This should never be called for TUs.  */
3044   gdb_assert (! this_cu->is_debug_types);
3045   /* Nor type unit groups.  */
3046   gdb_assert (! this_cu->type_unit_group_p ());
3047 
3048   if (this_cu->v.quick->file_names != NULL)
3049     return this_cu->v.quick->file_names;
3050   /* If we know there is no line data, no point in looking again.  */
3051   if (this_cu->v.quick->no_file_data)
3052     return NULL;
3053 
3054   cutu_reader reader (this_cu, per_objfile);
3055   if (!reader.dummy_p)
3056     dw2_get_file_names_reader (&reader, reader.comp_unit_die);
3057 
3058   if (this_cu->v.quick->no_file_data)
3059     return NULL;
3060   return this_cu->v.quick->file_names;
3061 }
3062 
3063 /* A helper for the "quick" functions which computes and caches the
3064    real path for a given file name from the line table.  */
3065 
3066 static const char *
3067 dw2_get_real_path (dwarf2_per_objfile *per_objfile,
3068 		   struct quick_file_names *qfn, int index)
3069 {
3070   if (qfn->real_names == NULL)
3071     qfn->real_names = OBSTACK_CALLOC (&per_objfile->per_bfd->obstack,
3072 				      qfn->num_file_names, const char *);
3073 
3074   if (qfn->real_names[index] == NULL)
3075     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3076 
3077   return qfn->real_names[index];
3078 }
3079 
3080 struct symtab *
3081 dwarf2_base_index_functions::find_last_source_symtab (struct objfile *objfile)
3082 {
3083   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3084   dwarf2_per_cu_data *dwarf_cu
3085     = per_objfile->per_bfd->all_comp_units.back ().get ();
3086   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, per_objfile, false);
3087 
3088   if (cust == NULL)
3089     return NULL;
3090 
3091   return compunit_primary_filetab (cust);
3092 }
3093 
3094 /* Traversal function for dw2_forget_cached_source_info.  */
3095 
3096 static int
3097 dw2_free_cached_file_names (void **slot, void *info)
3098 {
3099   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3100 
3101   if (file_data->real_names)
3102     {
3103       int i;
3104 
3105       for (i = 0; i < file_data->num_file_names; ++i)
3106 	{
3107 	  xfree ((void*) file_data->real_names[i]);
3108 	  file_data->real_names[i] = NULL;
3109 	}
3110     }
3111 
3112   return 1;
3113 }
3114 
3115 void
3116 dwarf2_base_index_functions::forget_cached_source_info
3117      (struct objfile *objfile)
3118 {
3119   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3120 
3121   htab_traverse_noresize (per_objfile->per_bfd->quick_file_names_table.get (),
3122 			  dw2_free_cached_file_names, NULL);
3123 }
3124 
3125 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3126 
3127 struct dw2_symtab_iterator
3128 {
3129   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3130   dwarf2_per_objfile *per_objfile;
3131   /* If set, only look for symbols that match that block.  Valid values are
3132      GLOBAL_BLOCK and STATIC_BLOCK.  */
3133   gdb::optional<block_enum> block_index;
3134   /* The kind of symbol we're looking for.  */
3135   domain_enum domain;
3136   /* The list of CUs from the index entry of the symbol,
3137      or NULL if not found.  */
3138   offset_view vec;
3139   /* The next element in VEC to look at.  */
3140   int next;
3141   /* The number of elements in VEC, or zero if there is no match.  */
3142   int length;
3143   /* Have we seen a global version of the symbol?
3144      If so we can ignore all further global instances.
3145      This is to work around gold/15646, inefficient gold-generated
3146      indices.  */
3147   int global_seen;
3148 };
3149 
3150 /* Initialize the index symtab iterator ITER, offset_type NAMEI variant.  */
3151 
3152 static void
3153 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3154 		      dwarf2_per_objfile *per_objfile,
3155 		      gdb::optional<block_enum> block_index,
3156 		      domain_enum domain, offset_type namei)
3157 {
3158   iter->per_objfile = per_objfile;
3159   iter->block_index = block_index;
3160   iter->domain = domain;
3161   iter->next = 0;
3162   iter->global_seen = 0;
3163   iter->vec = {};
3164   iter->length = 0;
3165 
3166   mapped_index *index = per_objfile->per_bfd->index_table.get ();
3167   /* index is NULL if OBJF_READNOW.  */
3168   if (index == NULL)
3169     return;
3170 
3171   gdb_assert (!index->symbol_name_slot_invalid (namei));
3172   offset_type vec_idx = index->symbol_vec_index (namei);
3173 
3174   iter->vec = offset_view (index->constant_pool.slice (vec_idx));
3175   iter->length = iter->vec[0];
3176 }
3177 
3178 /* Return the next matching CU or NULL if there are no more.  */
3179 
3180 static struct dwarf2_per_cu_data *
3181 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3182 {
3183   dwarf2_per_objfile *per_objfile = iter->per_objfile;
3184 
3185   for ( ; iter->next < iter->length; ++iter->next)
3186     {
3187       offset_type cu_index_and_attrs = iter->vec[iter->next + 1];
3188       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3189       gdb_index_symbol_kind symbol_kind =
3190 	GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3191       /* Only check the symbol attributes if they're present.
3192 	 Indices prior to version 7 don't record them,
3193 	 and indices >= 7 may elide them for certain symbols
3194 	 (gold does this).  */
3195       int attrs_valid =
3196 	(per_objfile->per_bfd->index_table->version >= 7
3197 	 && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3198 
3199       /* Don't crash on bad data.  */
3200       if (cu_index >= per_objfile->per_bfd->all_comp_units.size ())
3201 	{
3202 	  complaint (_(".gdb_index entry has bad CU index"
3203 		       " [in module %s]"), objfile_name (per_objfile->objfile));
3204 	  continue;
3205 	}
3206 
3207       dwarf2_per_cu_data *per_cu = per_objfile->per_bfd->get_cu (cu_index);
3208 
3209       /* Skip if already read in.  */
3210       if (per_objfile->symtab_set_p (per_cu))
3211 	continue;
3212 
3213       /* Check static vs global.  */
3214       if (attrs_valid)
3215 	{
3216 	  bool is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3217 
3218 	  if (iter->block_index.has_value ())
3219 	    {
3220 	      bool want_static = *iter->block_index == STATIC_BLOCK;
3221 
3222 	      if (is_static != want_static)
3223 		continue;
3224 	    }
3225 
3226 	  /* Work around gold/15646.  */
3227 	  if (!is_static
3228 	      && symbol_kind == GDB_INDEX_SYMBOL_KIND_TYPE)
3229 	    {
3230 	      if (iter->global_seen)
3231 		continue;
3232 
3233 	      iter->global_seen = 1;
3234 	    }
3235 	}
3236 
3237       /* Only check the symbol's kind if it has one.  */
3238       if (attrs_valid)
3239 	{
3240 	  switch (iter->domain)
3241 	    {
3242 	    case VAR_DOMAIN:
3243 	      if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3244 		  && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3245 		  /* Some types are also in VAR_DOMAIN.  */
3246 		  && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3247 		continue;
3248 	      break;
3249 	    case STRUCT_DOMAIN:
3250 	      if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3251 		continue;
3252 	      break;
3253 	    case LABEL_DOMAIN:
3254 	      if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3255 		continue;
3256 	      break;
3257 	    case MODULE_DOMAIN:
3258 	      if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3259 		continue;
3260 	      break;
3261 	    default:
3262 	      break;
3263 	    }
3264 	}
3265 
3266       ++iter->next;
3267       return per_cu;
3268     }
3269 
3270   return NULL;
3271 }
3272 
3273 void
3274 dwarf2_base_index_functions::print_stats (struct objfile *objfile,
3275 					  bool print_bcache)
3276 {
3277   if (print_bcache)
3278     return;
3279 
3280   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3281   int total = per_objfile->per_bfd->all_comp_units.size ();
3282   int count = 0;
3283 
3284   for (int i = 0; i < total; ++i)
3285     {
3286       dwarf2_per_cu_data *per_cu = per_objfile->per_bfd->get_cu (i);
3287 
3288       if (!per_objfile->symtab_set_p (per_cu))
3289 	++count;
3290     }
3291   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3292   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3293 }
3294 
3295 /* This dumps minimal information about the index.
3296    It is called via "mt print objfiles".
3297    One use is to verify .gdb_index has been loaded by the
3298    gdb.dwarf2/gdb-index.exp testcase.  */
3299 
3300 void
3301 dwarf2_gdb_index::dump (struct objfile *objfile)
3302 {
3303   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3304 
3305   gdb_assert (per_objfile->per_bfd->using_index);
3306   printf_filtered (".gdb_index:");
3307   if (per_objfile->per_bfd->index_table != NULL)
3308     {
3309       printf_filtered (" version %d\n",
3310 		       per_objfile->per_bfd->index_table->version);
3311     }
3312   else
3313     printf_filtered (" faked for \"readnow\"\n");
3314   printf_filtered ("\n");
3315 }
3316 
3317 void
3318 dwarf2_base_index_functions::expand_all_symtabs (struct objfile *objfile)
3319 {
3320   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3321   int total_units = per_objfile->per_bfd->all_comp_units.size ();
3322 
3323   for (int i = 0; i < total_units; ++i)
3324     {
3325       dwarf2_per_cu_data *per_cu = per_objfile->per_bfd->get_cu (i);
3326 
3327       /* We don't want to directly expand a partial CU, because if we
3328 	 read it with the wrong language, then assertion failures can
3329 	 be triggered later on.  See PR symtab/23010.  So, tell
3330 	 dw2_instantiate_symtab to skip partial CUs -- any important
3331 	 partial CU will be read via DW_TAG_imported_unit anyway.  */
3332       dw2_instantiate_symtab (per_cu, per_objfile, true);
3333     }
3334 }
3335 
3336 static bool
3337 dw2_expand_symtabs_matching_symbol
3338   (mapped_index_base &index,
3339    const lookup_name_info &lookup_name_in,
3340    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
3341    gdb::function_view<bool (offset_type)> match_callback,
3342    dwarf2_per_objfile *per_objfile);
3343 
3344 static bool
3345 dw2_expand_symtabs_matching_one
3346   (dwarf2_per_cu_data *per_cu,
3347    dwarf2_per_objfile *per_objfile,
3348    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
3349    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify);
3350 
3351 void
3352 dwarf2_gdb_index::expand_matching_symbols
3353   (struct objfile *objfile,
3354    const lookup_name_info &name, domain_enum domain,
3355    int global,
3356    symbol_compare_ftype *ordered_compare)
3357 {
3358   /* Used for Ada.  */
3359   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3360 
3361   const block_enum block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
3362 
3363   if (per_objfile->per_bfd->index_table != nullptr)
3364     {
3365       mapped_index &index = *per_objfile->per_bfd->index_table;
3366 
3367       const char *match_name = name.ada ().lookup_name ().c_str ();
3368       auto matcher = [&] (const char *symname)
3369 	{
3370 	  if (ordered_compare == nullptr)
3371 	    return true;
3372 	  return ordered_compare (symname, match_name) == 0;
3373 	};
3374 
3375       dw2_expand_symtabs_matching_symbol (index, name, matcher,
3376 					  [&] (offset_type namei)
3377       {
3378 	struct dw2_symtab_iterator iter;
3379 	struct dwarf2_per_cu_data *per_cu;
3380 
3381 	dw2_symtab_iter_init (&iter, per_objfile, block_kind, domain,
3382 			      namei);
3383 	while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3384 	  dw2_expand_symtabs_matching_one (per_cu, per_objfile, nullptr,
3385 					   nullptr);
3386 	return true;
3387       }, per_objfile);
3388     }
3389   else
3390     {
3391       /* We have -readnow: no .gdb_index, but no partial symtabs either.  So,
3392 	 proceed assuming all symtabs have been read in.  */
3393     }
3394 }
3395 
3396 /* Starting from a search name, return the string that finds the upper
3397    bound of all strings that start with SEARCH_NAME in a sorted name
3398    list.  Returns the empty string to indicate that the upper bound is
3399    the end of the list.  */
3400 
3401 static std::string
3402 make_sort_after_prefix_name (const char *search_name)
3403 {
3404   /* When looking to complete "func", we find the upper bound of all
3405      symbols that start with "func" by looking for where we'd insert
3406      the closest string that would follow "func" in lexicographical
3407      order.  Usually, that's "func"-with-last-character-incremented,
3408      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
3409      will be UTF-8 multi-byte sequences, but we can't be certain.
3410      Especially mind the 0xff character, which is a valid character in
3411      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
3412      rule out compilers allowing it in identifiers.  Note that
3413      conveniently, strcmp/strcasecmp are specified to compare
3414      characters interpreted as unsigned char.  So what we do is treat
3415      the whole string as a base 256 number composed of a sequence of
3416      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
3417      to 0, and carries 1 to the following more-significant position.
3418      If the very first character in SEARCH_NAME ends up incremented
3419      and carries/overflows, then the upper bound is the end of the
3420      list.  The string after the empty string is also the empty
3421      string.
3422 
3423      Some examples of this operation:
3424 
3425        SEARCH_NAME  => "+1" RESULT
3426 
3427        "abc"              => "abd"
3428        "ab\xff"           => "ac"
3429        "\xff" "a" "\xff"  => "\xff" "b"
3430        "\xff"             => ""
3431        "\xff\xff"         => ""
3432        ""                 => ""
3433 
3434      Then, with these symbols for example:
3435 
3436       func
3437       func1
3438       fund
3439 
3440      completing "func" looks for symbols between "func" and
3441      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
3442      which finds "func" and "func1", but not "fund".
3443 
3444      And with:
3445 
3446       funcÿ     (Latin1 'ÿ' [0xff])
3447       funcÿ1
3448       fund
3449 
3450      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
3451      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
3452 
3453      And with:
3454 
3455       ÿÿ        (Latin1 'ÿ' [0xff])
3456       ÿÿ1
3457 
3458      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
3459      the end of the list.
3460   */
3461   std::string after = search_name;
3462   while (!after.empty () && (unsigned char) after.back () == 0xff)
3463     after.pop_back ();
3464   if (!after.empty ())
3465     after.back () = (unsigned char) after.back () + 1;
3466   return after;
3467 }
3468 
3469 /* See declaration.  */
3470 
3471 std::pair<std::vector<name_component>::const_iterator,
3472 	  std::vector<name_component>::const_iterator>
3473 mapped_index_base::find_name_components_bounds
3474   (const lookup_name_info &lookup_name_without_params, language lang,
3475    dwarf2_per_objfile *per_objfile) const
3476 {
3477   auto *name_cmp
3478     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
3479 
3480   const char *lang_name
3481     = lookup_name_without_params.language_lookup_name (lang);
3482 
3483   /* Comparison function object for lower_bound that matches against a
3484      given symbol name.  */
3485   auto lookup_compare_lower = [&] (const name_component &elem,
3486 				   const char *name)
3487     {
3488       const char *elem_qualified = this->symbol_name_at (elem.idx, per_objfile);
3489       const char *elem_name = elem_qualified + elem.name_offset;
3490       return name_cmp (elem_name, name) < 0;
3491     };
3492 
3493   /* Comparison function object for upper_bound that matches against a
3494      given symbol name.  */
3495   auto lookup_compare_upper = [&] (const char *name,
3496 				   const name_component &elem)
3497     {
3498       const char *elem_qualified = this->symbol_name_at (elem.idx, per_objfile);
3499       const char *elem_name = elem_qualified + elem.name_offset;
3500       return name_cmp (name, elem_name) < 0;
3501     };
3502 
3503   auto begin = this->name_components.begin ();
3504   auto end = this->name_components.end ();
3505 
3506   /* Find the lower bound.  */
3507   auto lower = [&] ()
3508     {
3509       if (lookup_name_without_params.completion_mode () && lang_name[0] == '\0')
3510 	return begin;
3511       else
3512 	return std::lower_bound (begin, end, lang_name, lookup_compare_lower);
3513     } ();
3514 
3515   /* Find the upper bound.  */
3516   auto upper = [&] ()
3517     {
3518       if (lookup_name_without_params.completion_mode ())
3519 	{
3520 	  /* In completion mode, we want UPPER to point past all
3521 	     symbols names that have the same prefix.  I.e., with
3522 	     these symbols, and completing "func":
3523 
3524 	      function        << lower bound
3525 	      function1
3526 	      other_function  << upper bound
3527 
3528 	     We find the upper bound by looking for the insertion
3529 	     point of "func"-with-last-character-incremented,
3530 	     i.e. "fund".  */
3531 	  std::string after = make_sort_after_prefix_name (lang_name);
3532 	  if (after.empty ())
3533 	    return end;
3534 	  return std::lower_bound (lower, end, after.c_str (),
3535 				   lookup_compare_lower);
3536 	}
3537       else
3538 	return std::upper_bound (lower, end, lang_name, lookup_compare_upper);
3539     } ();
3540 
3541   return {lower, upper};
3542 }
3543 
3544 /* See declaration.  */
3545 
3546 void
3547 mapped_index_base::build_name_components (dwarf2_per_objfile *per_objfile)
3548 {
3549   if (!this->name_components.empty ())
3550     return;
3551 
3552   this->name_components_casing = case_sensitivity;
3553   auto *name_cmp
3554     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
3555 
3556   /* The code below only knows how to break apart components of C++
3557      symbol names (and other languages that use '::' as
3558      namespace/module separator) and Ada symbol names.  */
3559   auto count = this->symbol_name_count ();
3560   for (offset_type idx = 0; idx < count; idx++)
3561     {
3562       if (this->symbol_name_slot_invalid (idx))
3563 	continue;
3564 
3565       const char *name = this->symbol_name_at (idx, per_objfile);
3566 
3567       /* Add each name component to the name component table.  */
3568       unsigned int previous_len = 0;
3569 
3570       if (strstr (name, "::") != nullptr)
3571 	{
3572 	  for (unsigned int current_len = cp_find_first_component (name);
3573 	       name[current_len] != '\0';
3574 	       current_len += cp_find_first_component (name + current_len))
3575 	    {
3576 	      gdb_assert (name[current_len] == ':');
3577 	      this->name_components.push_back ({previous_len, idx});
3578 	      /* Skip the '::'.  */
3579 	      current_len += 2;
3580 	      previous_len = current_len;
3581 	    }
3582 	}
3583       else
3584 	{
3585 	  /* Handle the Ada encoded (aka mangled) form here.  */
3586 	  for (const char *iter = strstr (name, "__");
3587 	       iter != nullptr;
3588 	       iter = strstr (iter, "__"))
3589 	    {
3590 	      this->name_components.push_back ({previous_len, idx});
3591 	      iter += 2;
3592 	      previous_len = iter - name;
3593 	    }
3594 	}
3595 
3596       this->name_components.push_back ({previous_len, idx});
3597     }
3598 
3599   /* Sort name_components elements by name.  */
3600   auto name_comp_compare = [&] (const name_component &left,
3601 				const name_component &right)
3602     {
3603       const char *left_qualified
3604 	= this->symbol_name_at (left.idx, per_objfile);
3605       const char *right_qualified
3606 	= this->symbol_name_at (right.idx, per_objfile);
3607 
3608       const char *left_name = left_qualified + left.name_offset;
3609       const char *right_name = right_qualified + right.name_offset;
3610 
3611       return name_cmp (left_name, right_name) < 0;
3612     };
3613 
3614   std::sort (this->name_components.begin (),
3615 	     this->name_components.end (),
3616 	     name_comp_compare);
3617 }
3618 
3619 /* Helper for dw2_expand_symtabs_matching that works with a
3620    mapped_index_base instead of the containing objfile.  This is split
3621    to a separate function in order to be able to unit test the
3622    name_components matching using a mock mapped_index_base.  For each
3623    symbol name that matches, calls MATCH_CALLBACK, passing it the
3624    symbol's index in the mapped_index_base symbol table.  */
3625 
3626 static bool
3627 dw2_expand_symtabs_matching_symbol
3628   (mapped_index_base &index,
3629    const lookup_name_info &lookup_name_in,
3630    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
3631    gdb::function_view<bool (offset_type)> match_callback,
3632    dwarf2_per_objfile *per_objfile)
3633 {
3634   lookup_name_info lookup_name_without_params
3635     = lookup_name_in.make_ignore_params ();
3636 
3637   /* Build the symbol name component sorted vector, if we haven't
3638      yet.  */
3639   index.build_name_components (per_objfile);
3640 
3641   /* The same symbol may appear more than once in the range though.
3642      E.g., if we're looking for symbols that complete "w", and we have
3643      a symbol named "w1::w2", we'll find the two name components for
3644      that same symbol in the range.  To be sure we only call the
3645      callback once per symbol, we first collect the symbol name
3646      indexes that matched in a temporary vector and ignore
3647      duplicates.  */
3648   std::vector<offset_type> matches;
3649 
3650   struct name_and_matcher
3651   {
3652     symbol_name_matcher_ftype *matcher;
3653     const char *name;
3654 
3655     bool operator== (const name_and_matcher &other) const
3656     {
3657       return matcher == other.matcher && strcmp (name, other.name) == 0;
3658     }
3659   };
3660 
3661   /* A vector holding all the different symbol name matchers, for all
3662      languages.  */
3663   std::vector<name_and_matcher> matchers;
3664 
3665   for (int i = 0; i < nr_languages; i++)
3666     {
3667       enum language lang_e = (enum language) i;
3668 
3669       const language_defn *lang = language_def (lang_e);
3670       symbol_name_matcher_ftype *name_matcher
3671 	= lang->get_symbol_name_matcher (lookup_name_without_params);
3672 
3673       name_and_matcher key {
3674 	 name_matcher,
3675 	 lookup_name_without_params.language_lookup_name (lang_e)
3676       };
3677 
3678       /* Don't insert the same comparison routine more than once.
3679 	 Note that we do this linear walk.  This is not a problem in
3680 	 practice because the number of supported languages is
3681 	 low.  */
3682       if (std::find (matchers.begin (), matchers.end (), key)
3683 	  != matchers.end ())
3684 	continue;
3685       matchers.push_back (std::move (key));
3686 
3687       auto bounds
3688 	= index.find_name_components_bounds (lookup_name_without_params,
3689 					     lang_e, per_objfile);
3690 
3691       /* Now for each symbol name in range, check to see if we have a name
3692 	 match, and if so, call the MATCH_CALLBACK callback.  */
3693 
3694       for (; bounds.first != bounds.second; ++bounds.first)
3695 	{
3696 	  const char *qualified
3697 	    = index.symbol_name_at (bounds.first->idx, per_objfile);
3698 
3699 	  if (!name_matcher (qualified, lookup_name_without_params, NULL)
3700 	      || (symbol_matcher != NULL && !symbol_matcher (qualified)))
3701 	    continue;
3702 
3703 	  matches.push_back (bounds.first->idx);
3704 	}
3705     }
3706 
3707   std::sort (matches.begin (), matches.end ());
3708 
3709   /* Finally call the callback, once per match.  */
3710   ULONGEST prev = -1;
3711   bool result = true;
3712   for (offset_type idx : matches)
3713     {
3714       if (prev != idx)
3715 	{
3716 	  if (!match_callback (idx))
3717 	    {
3718 	      result = false;
3719 	      break;
3720 	    }
3721 	  prev = idx;
3722 	}
3723     }
3724 
3725   /* Above we use a type wider than idx's for 'prev', since 0 and
3726      (offset_type)-1 are both possible values.  */
3727   static_assert (sizeof (prev) > sizeof (offset_type), "");
3728 
3729   return result;
3730 }
3731 
3732 #if GDB_SELF_TEST
3733 
3734 namespace selftests { namespace dw2_expand_symtabs_matching {
3735 
3736 /* A mock .gdb_index/.debug_names-like name index table, enough to
3737    exercise dw2_expand_symtabs_matching_symbol, which works with the
3738    mapped_index_base interface.  Builds an index from the symbol list
3739    passed as parameter to the constructor.  */
3740 class mock_mapped_index : public mapped_index_base
3741 {
3742 public:
3743   mock_mapped_index (gdb::array_view<const char *> symbols)
3744     : m_symbol_table (symbols)
3745   {}
3746 
3747   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
3748 
3749   /* Return the number of names in the symbol table.  */
3750   size_t symbol_name_count () const override
3751   {
3752     return m_symbol_table.size ();
3753   }
3754 
3755   /* Get the name of the symbol at IDX in the symbol table.  */
3756   const char *symbol_name_at
3757     (offset_type idx, dwarf2_per_objfile *per_objfile) const override
3758   {
3759     return m_symbol_table[idx];
3760   }
3761 
3762 private:
3763   gdb::array_view<const char *> m_symbol_table;
3764 };
3765 
3766 /* Convenience function that converts a NULL pointer to a "<null>"
3767    string, to pass to print routines.  */
3768 
3769 static const char *
3770 string_or_null (const char *str)
3771 {
3772   return str != NULL ? str : "<null>";
3773 }
3774 
3775 /* Check if a lookup_name_info built from
3776    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
3777    index.  EXPECTED_LIST is the list of expected matches, in expected
3778    matching order.  If no match expected, then an empty list is
3779    specified.  Returns true on success.  On failure prints a warning
3780    indicating the file:line that failed, and returns false.  */
3781 
3782 static bool
3783 check_match (const char *file, int line,
3784 	     mock_mapped_index &mock_index,
3785 	     const char *name, symbol_name_match_type match_type,
3786 	     bool completion_mode,
3787 	     std::initializer_list<const char *> expected_list,
3788 	     dwarf2_per_objfile *per_objfile)
3789 {
3790   lookup_name_info lookup_name (name, match_type, completion_mode);
3791 
3792   bool matched = true;
3793 
3794   auto mismatch = [&] (const char *expected_str,
3795 		       const char *got)
3796   {
3797     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
3798 	       "expected=\"%s\", got=\"%s\"\n"),
3799 	     file, line,
3800 	     (match_type == symbol_name_match_type::FULL
3801 	      ? "FULL" : "WILD"),
3802 	     name, string_or_null (expected_str), string_or_null (got));
3803     matched = false;
3804   };
3805 
3806   auto expected_it = expected_list.begin ();
3807   auto expected_end = expected_list.end ();
3808 
3809   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
3810 				      nullptr,
3811 				      [&] (offset_type idx)
3812   {
3813     const char *matched_name = mock_index.symbol_name_at (idx, per_objfile);
3814     const char *expected_str
3815       = expected_it == expected_end ? NULL : *expected_it++;
3816 
3817     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
3818       mismatch (expected_str, matched_name);
3819     return true;
3820   }, per_objfile);
3821 
3822   const char *expected_str
3823   = expected_it == expected_end ? NULL : *expected_it++;
3824   if (expected_str != NULL)
3825     mismatch (expected_str, NULL);
3826 
3827   return matched;
3828 }
3829 
3830 /* The symbols added to the mock mapped_index for testing (in
3831    canonical form).  */
3832 static const char *test_symbols[] = {
3833   "function",
3834   "std::bar",
3835   "std::zfunction",
3836   "std::zfunction2",
3837   "w1::w2",
3838   "ns::foo<char*>",
3839   "ns::foo<int>",
3840   "ns::foo<long>",
3841   "ns2::tmpl<int>::foo2",
3842   "(anonymous namespace)::A::B::C",
3843 
3844   /* These are used to check that the increment-last-char in the
3845      matching algorithm for completion doesn't match "t1_fund" when
3846      completing "t1_func".  */
3847   "t1_func",
3848   "t1_func1",
3849   "t1_fund",
3850   "t1_fund1",
3851 
3852   /* A UTF-8 name with multi-byte sequences to make sure that
3853      cp-name-parser understands this as a single identifier ("função"
3854      is "function" in PT).  */
3855   u8"u8função",
3856 
3857   /* \377 (0xff) is Latin1 'ÿ'.  */
3858   "yfunc\377",
3859 
3860   /* \377 (0xff) is Latin1 'ÿ'.  */
3861   "\377",
3862   "\377\377123",
3863 
3864   /* A name with all sorts of complications.  Starts with "z" to make
3865      it easier for the completion tests below.  */
3866 #define Z_SYM_NAME \
3867   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
3868     "::tuple<(anonymous namespace)::ui*, " \
3869     "std::default_delete<(anonymous namespace)::ui>, void>"
3870 
3871   Z_SYM_NAME
3872 };
3873 
3874 /* Returns true if the mapped_index_base::find_name_component_bounds
3875    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
3876    in completion mode.  */
3877 
3878 static bool
3879 check_find_bounds_finds (mapped_index_base &index,
3880 			 const char *search_name,
3881 			 gdb::array_view<const char *> expected_syms,
3882 			 dwarf2_per_objfile *per_objfile)
3883 {
3884   lookup_name_info lookup_name (search_name,
3885 				symbol_name_match_type::FULL, true);
3886 
3887   auto bounds = index.find_name_components_bounds (lookup_name,
3888 						   language_cplus,
3889 						   per_objfile);
3890 
3891   size_t distance = std::distance (bounds.first, bounds.second);
3892   if (distance != expected_syms.size ())
3893     return false;
3894 
3895   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
3896     {
3897       auto nc_elem = bounds.first + exp_elem;
3898       const char *qualified = index.symbol_name_at (nc_elem->idx, per_objfile);
3899       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
3900 	return false;
3901     }
3902 
3903   return true;
3904 }
3905 
3906 /* Test the lower-level mapped_index::find_name_component_bounds
3907    method.  */
3908 
3909 static void
3910 test_mapped_index_find_name_component_bounds ()
3911 {
3912   mock_mapped_index mock_index (test_symbols);
3913 
3914   mock_index.build_name_components (NULL /* per_objfile */);
3915 
3916   /* Test the lower-level mapped_index::find_name_component_bounds
3917      method in completion mode.  */
3918   {
3919     static const char *expected_syms[] = {
3920       "t1_func",
3921       "t1_func1",
3922     };
3923 
3924     SELF_CHECK (check_find_bounds_finds
3925 		  (mock_index, "t1_func", expected_syms,
3926 		   NULL /* per_objfile */));
3927   }
3928 
3929   /* Check that the increment-last-char in the name matching algorithm
3930      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
3931   {
3932     static const char *expected_syms1[] = {
3933       "\377",
3934       "\377\377123",
3935     };
3936     SELF_CHECK (check_find_bounds_finds
3937 		  (mock_index, "\377", expected_syms1, NULL /* per_objfile */));
3938 
3939     static const char *expected_syms2[] = {
3940       "\377\377123",
3941     };
3942     SELF_CHECK (check_find_bounds_finds
3943 		  (mock_index, "\377\377", expected_syms2,
3944 		   NULL /* per_objfile */));
3945   }
3946 }
3947 
3948 /* Test dw2_expand_symtabs_matching_symbol.  */
3949 
3950 static void
3951 test_dw2_expand_symtabs_matching_symbol ()
3952 {
3953   mock_mapped_index mock_index (test_symbols);
3954 
3955   /* We let all tests run until the end even if some fails, for debug
3956      convenience.  */
3957   bool any_mismatch = false;
3958 
3959   /* Create the expected symbols list (an initializer_list).  Needed
3960      because lists have commas, and we need to pass them to CHECK,
3961      which is a macro.  */
3962 #define EXPECT(...) { __VA_ARGS__ }
3963 
3964   /* Wrapper for check_match that passes down the current
3965      __FILE__/__LINE__.  */
3966 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)	\
3967   any_mismatch |= !check_match (__FILE__, __LINE__,			\
3968 				mock_index,				\
3969 				NAME, MATCH_TYPE, COMPLETION_MODE,	\
3970 				EXPECTED_LIST, NULL)
3971 
3972   /* Identity checks.  */
3973   for (const char *sym : test_symbols)
3974     {
3975       /* Should be able to match all existing symbols.  */
3976       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
3977 		   EXPECT (sym));
3978 
3979       /* Should be able to match all existing symbols with
3980 	 parameters.  */
3981       std::string with_params = std::string (sym) + "(int)";
3982       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
3983 		   EXPECT (sym));
3984 
3985       /* Should be able to match all existing symbols with
3986 	 parameters and qualifiers.  */
3987       with_params = std::string (sym) + " ( int ) const";
3988       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
3989 		   EXPECT (sym));
3990 
3991       /* This should really find sym, but cp-name-parser.y doesn't
3992 	 know about lvalue/rvalue qualifiers yet.  */
3993       with_params = std::string (sym) + " ( int ) &&";
3994       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
3995 		   {});
3996     }
3997 
3998   /* Check that the name matching algorithm for completion doesn't get
3999      confused with Latin1 'ÿ' / 0xff.  */
4000   {
4001     static const char str[] = "\377";
4002     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4003 		 EXPECT ("\377", "\377\377123"));
4004   }
4005 
4006   /* Check that the increment-last-char in the matching algorithm for
4007      completion doesn't match "t1_fund" when completing "t1_func".  */
4008   {
4009     static const char str[] = "t1_func";
4010     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4011 		 EXPECT ("t1_func", "t1_func1"));
4012   }
4013 
4014   /* Check that completion mode works at each prefix of the expected
4015      symbol name.  */
4016   {
4017     static const char str[] = "function(int)";
4018     size_t len = strlen (str);
4019     std::string lookup;
4020 
4021     for (size_t i = 1; i < len; i++)
4022       {
4023 	lookup.assign (str, i);
4024 	CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4025 		     EXPECT ("function"));
4026       }
4027   }
4028 
4029   /* While "w" is a prefix of both components, the match function
4030      should still only be called once.  */
4031   {
4032     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4033 		 EXPECT ("w1::w2"));
4034     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4035 		 EXPECT ("w1::w2"));
4036   }
4037 
4038   /* Same, with a "complicated" symbol.  */
4039   {
4040     static const char str[] = Z_SYM_NAME;
4041     size_t len = strlen (str);
4042     std::string lookup;
4043 
4044     for (size_t i = 1; i < len; i++)
4045       {
4046 	lookup.assign (str, i);
4047 	CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4048 		     EXPECT (Z_SYM_NAME));
4049       }
4050   }
4051 
4052   /* In FULL mode, an incomplete symbol doesn't match.  */
4053   {
4054     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4055 		 {});
4056   }
4057 
4058   /* A complete symbol with parameters matches any overload, since the
4059      index has no overload info.  */
4060   {
4061     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4062 		 EXPECT ("std::zfunction", "std::zfunction2"));
4063     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4064 		 EXPECT ("std::zfunction", "std::zfunction2"));
4065     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4066 		 EXPECT ("std::zfunction", "std::zfunction2"));
4067   }
4068 
4069   /* Check that whitespace is ignored appropriately.  A symbol with a
4070      template argument list. */
4071   {
4072     static const char expected[] = "ns::foo<int>";
4073     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4074 		 EXPECT (expected));
4075     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4076 		 EXPECT (expected));
4077   }
4078 
4079   /* Check that whitespace is ignored appropriately.  A symbol with a
4080      template argument list that includes a pointer.  */
4081   {
4082     static const char expected[] = "ns::foo<char*>";
4083     /* Try both completion and non-completion modes.  */
4084     static const bool completion_mode[2] = {false, true};
4085     for (size_t i = 0; i < 2; i++)
4086       {
4087 	CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4088 		     completion_mode[i], EXPECT (expected));
4089 	CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4090 		     completion_mode[i], EXPECT (expected));
4091 
4092 	CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4093 		     completion_mode[i], EXPECT (expected));
4094 	CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4095 		     completion_mode[i], EXPECT (expected));
4096       }
4097   }
4098 
4099   {
4100     /* Check method qualifiers are ignored.  */
4101     static const char expected[] = "ns::foo<char*>";
4102     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4103 		 symbol_name_match_type::FULL, true, EXPECT (expected));
4104     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4105 		 symbol_name_match_type::FULL, true, EXPECT (expected));
4106     CHECK_MATCH ("foo < char * >  ( int ) const",
4107 		 symbol_name_match_type::WILD, true, EXPECT (expected));
4108     CHECK_MATCH ("foo < char * >  ( int ) &&",
4109 		 symbol_name_match_type::WILD, true, EXPECT (expected));
4110   }
4111 
4112   /* Test lookup names that don't match anything.  */
4113   {
4114     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4115 		 {});
4116 
4117     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4118 		 {});
4119   }
4120 
4121   /* Some wild matching tests, exercising "(anonymous namespace)",
4122      which should not be confused with a parameter list.  */
4123   {
4124     static const char *syms[] = {
4125       "A::B::C",
4126       "B::C",
4127       "C",
4128       "A :: B :: C ( int )",
4129       "B :: C ( int )",
4130       "C ( int )",
4131     };
4132 
4133     for (const char *s : syms)
4134       {
4135 	CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4136 		     EXPECT ("(anonymous namespace)::A::B::C"));
4137       }
4138   }
4139 
4140   {
4141     static const char expected[] = "ns2::tmpl<int>::foo2";
4142     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4143 		 EXPECT (expected));
4144     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4145 		 EXPECT (expected));
4146   }
4147 
4148   SELF_CHECK (!any_mismatch);
4149 
4150 #undef EXPECT
4151 #undef CHECK_MATCH
4152 }
4153 
4154 static void
4155 run_test ()
4156 {
4157   test_mapped_index_find_name_component_bounds ();
4158   test_dw2_expand_symtabs_matching_symbol ();
4159 }
4160 
4161 }} // namespace selftests::dw2_expand_symtabs_matching
4162 
4163 #endif /* GDB_SELF_TEST */
4164 
4165 /* If FILE_MATCHER is NULL or if PER_CU has
4166    dwarf2_per_cu_quick_data::MARK set (see
4167    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4168    EXPANSION_NOTIFY on it.  */
4169 
4170 static bool
4171 dw2_expand_symtabs_matching_one
4172   (dwarf2_per_cu_data *per_cu,
4173    dwarf2_per_objfile *per_objfile,
4174    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4175    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
4176 {
4177   if (file_matcher == NULL || per_cu->v.quick->mark)
4178     {
4179       bool symtab_was_null = !per_objfile->symtab_set_p (per_cu);
4180 
4181       compunit_symtab *symtab
4182 	= dw2_instantiate_symtab (per_cu, per_objfile, false);
4183       gdb_assert (symtab != nullptr);
4184 
4185       if (expansion_notify != NULL && symtab_was_null)
4186 	return expansion_notify (symtab);
4187     }
4188   return true;
4189 }
4190 
4191 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
4192    matched, to expand corresponding CUs that were marked.  IDX is the
4193    index of the symbol name that matched.  */
4194 
4195 static bool
4196 dw2_expand_marked_cus
4197   (dwarf2_per_objfile *per_objfile, offset_type idx,
4198    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4199    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4200    block_search_flags search_flags,
4201    search_domain kind)
4202 {
4203   offset_type vec_len, vec_idx;
4204   bool global_seen = false;
4205   mapped_index &index = *per_objfile->per_bfd->index_table;
4206 
4207   offset_view vec (index.constant_pool.slice (index.symbol_vec_index (idx)));
4208   vec_len = vec[0];
4209   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4210     {
4211       offset_type cu_index_and_attrs = vec[vec_idx + 1];
4212       /* This value is only valid for index versions >= 7.  */
4213       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4214       gdb_index_symbol_kind symbol_kind =
4215 	GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4216       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4217       /* Only check the symbol attributes if they're present.
4218 	 Indices prior to version 7 don't record them,
4219 	 and indices >= 7 may elide them for certain symbols
4220 	 (gold does this).  */
4221       int attrs_valid =
4222 	(index.version >= 7
4223 	 && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4224 
4225       /* Work around gold/15646.  */
4226       if (attrs_valid
4227 	  && !is_static
4228 	  && symbol_kind == GDB_INDEX_SYMBOL_KIND_TYPE)
4229 	{
4230 	  if (global_seen)
4231 	    continue;
4232 
4233 	  global_seen = true;
4234 	}
4235 
4236       /* Only check the symbol's kind if it has one.  */
4237       if (attrs_valid)
4238 	{
4239 	  if (is_static)
4240 	    {
4241 	      if ((search_flags & SEARCH_STATIC_BLOCK) == 0)
4242 		continue;
4243 	    }
4244 	  else
4245 	    {
4246 	      if ((search_flags & SEARCH_GLOBAL_BLOCK) == 0)
4247 		continue;
4248 	    }
4249 
4250 	  switch (kind)
4251 	    {
4252 	    case VARIABLES_DOMAIN:
4253 	      if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4254 		continue;
4255 	      break;
4256 	    case FUNCTIONS_DOMAIN:
4257 	      if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4258 		continue;
4259 	      break;
4260 	    case TYPES_DOMAIN:
4261 	      if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4262 		continue;
4263 	      break;
4264 	    case MODULES_DOMAIN:
4265 	      if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4266 		continue;
4267 	      break;
4268 	    default:
4269 	      break;
4270 	    }
4271 	}
4272 
4273       /* Don't crash on bad data.  */
4274       if (cu_index >= per_objfile->per_bfd->all_comp_units.size ())
4275 	{
4276 	  complaint (_(".gdb_index entry has bad CU index"
4277 		       " [in module %s]"), objfile_name (per_objfile->objfile));
4278 	  continue;
4279 	}
4280 
4281       dwarf2_per_cu_data *per_cu = per_objfile->per_bfd->get_cu (cu_index);
4282       if (!dw2_expand_symtabs_matching_one (per_cu, per_objfile, file_matcher,
4283 					    expansion_notify))
4284 	return false;
4285     }
4286 
4287   return true;
4288 }
4289 
4290 /* If FILE_MATCHER is non-NULL, set all the
4291    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
4292    that match FILE_MATCHER.  */
4293 
4294 static void
4295 dw_expand_symtabs_matching_file_matcher
4296   (dwarf2_per_objfile *per_objfile,
4297    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
4298 {
4299   if (file_matcher == NULL)
4300     return;
4301 
4302   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4303 					    htab_eq_pointer,
4304 					    NULL, xcalloc, xfree));
4305   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4306 						htab_eq_pointer,
4307 						NULL, xcalloc, xfree));
4308 
4309   /* The rule is CUs specify all the files, including those used by
4310      any TU, so there's no need to scan TUs here.  */
4311 
4312   for (const auto &per_cu : per_objfile->per_bfd->all_comp_units)
4313     {
4314       QUIT;
4315 
4316       if (per_cu->is_debug_types)
4317 	continue;
4318       per_cu->v.quick->mark = 0;
4319 
4320       /* We only need to look at symtabs not already expanded.  */
4321       if (per_objfile->symtab_set_p (per_cu.get ()))
4322 	continue;
4323 
4324       quick_file_names *file_data = dw2_get_file_names (per_cu.get (),
4325 							per_objfile);
4326       if (file_data == NULL)
4327 	continue;
4328 
4329       if (htab_find (visited_not_found.get (), file_data) != NULL)
4330 	continue;
4331       else if (htab_find (visited_found.get (), file_data) != NULL)
4332 	{
4333 	  per_cu->v.quick->mark = 1;
4334 	  continue;
4335 	}
4336 
4337       for (int j = 0; j < file_data->num_file_names; ++j)
4338 	{
4339 	  const char *this_real_name;
4340 
4341 	  if (file_matcher (file_data->file_names[j], false))
4342 	    {
4343 	      per_cu->v.quick->mark = 1;
4344 	      break;
4345 	    }
4346 
4347 	  /* Before we invoke realpath, which can get expensive when many
4348 	     files are involved, do a quick comparison of the basenames.  */
4349 	  if (!basenames_may_differ
4350 	      && !file_matcher (lbasename (file_data->file_names[j]),
4351 				true))
4352 	    continue;
4353 
4354 	  this_real_name = dw2_get_real_path (per_objfile, file_data, j);
4355 	  if (file_matcher (this_real_name, false))
4356 	    {
4357 	      per_cu->v.quick->mark = 1;
4358 	      break;
4359 	    }
4360 	}
4361 
4362       void **slot = htab_find_slot (per_cu->v.quick->mark
4363 				    ? visited_found.get ()
4364 				    : visited_not_found.get (),
4365 				    file_data, INSERT);
4366       *slot = file_data;
4367     }
4368 }
4369 
4370 bool
4371 dwarf2_gdb_index::expand_symtabs_matching
4372     (struct objfile *objfile,
4373      gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4374      const lookup_name_info *lookup_name,
4375      gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4376      gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4377      block_search_flags search_flags,
4378      domain_enum domain,
4379      enum search_domain kind)
4380 {
4381   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
4382 
4383   /* index_table is NULL if OBJF_READNOW.  */
4384   if (!per_objfile->per_bfd->index_table)
4385     return true;
4386 
4387   dw_expand_symtabs_matching_file_matcher (per_objfile, file_matcher);
4388 
4389   if (symbol_matcher == NULL && lookup_name == NULL)
4390     {
4391       for (dwarf2_per_cu_data *per_cu
4392 	     : all_comp_units_range (per_objfile->per_bfd))
4393 	{
4394 	  QUIT;
4395 
4396 	  if (!dw2_expand_symtabs_matching_one (per_cu, per_objfile,
4397 						file_matcher,
4398 						expansion_notify))
4399 	    return false;
4400 	}
4401       return true;
4402     }
4403 
4404   mapped_index &index = *per_objfile->per_bfd->index_table;
4405 
4406   bool result
4407     = dw2_expand_symtabs_matching_symbol (index, *lookup_name,
4408 					  symbol_matcher,
4409 					  [&] (offset_type idx)
4410     {
4411       if (!dw2_expand_marked_cus (per_objfile, idx, file_matcher,
4412 				  expansion_notify, search_flags, kind))
4413 	return false;
4414       return true;
4415     }, per_objfile);
4416 
4417   return result;
4418 }
4419 
4420 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4421    symtab.  */
4422 
4423 static struct compunit_symtab *
4424 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4425 					  CORE_ADDR pc)
4426 {
4427   int i;
4428 
4429   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4430       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4431     return cust;
4432 
4433   if (cust->includes == NULL)
4434     return NULL;
4435 
4436   for (i = 0; cust->includes[i]; ++i)
4437     {
4438       struct compunit_symtab *s = cust->includes[i];
4439 
4440       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4441       if (s != NULL)
4442 	return s;
4443     }
4444 
4445   return NULL;
4446 }
4447 
4448 struct compunit_symtab *
4449 dwarf2_base_index_functions::find_pc_sect_compunit_symtab
4450      (struct objfile *objfile,
4451       struct bound_minimal_symbol msymbol,
4452       CORE_ADDR pc,
4453       struct obj_section *section,
4454       int warn_if_readin)
4455 {
4456   struct dwarf2_per_cu_data *data;
4457   struct compunit_symtab *result;
4458 
4459   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
4460   if (per_objfile->per_bfd->index_addrmap == nullptr)
4461     return NULL;
4462 
4463   CORE_ADDR baseaddr = objfile->text_section_offset ();
4464   data = ((struct dwarf2_per_cu_data *)
4465 	  addrmap_find (per_objfile->per_bfd->index_addrmap,
4466 			pc - baseaddr));
4467   if (!data)
4468     return NULL;
4469 
4470   if (warn_if_readin && per_objfile->symtab_set_p (data))
4471     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4472 	     paddress (objfile->arch (), pc));
4473 
4474   result = recursively_find_pc_sect_compunit_symtab
4475     (dw2_instantiate_symtab (data, per_objfile, false), pc);
4476 
4477   gdb_assert (result != NULL);
4478   return result;
4479 }
4480 
4481 void
4482 dwarf2_base_index_functions::map_symbol_filenames
4483      (struct objfile *objfile,
4484       gdb::function_view<symbol_filename_ftype> fun,
4485       bool need_fullname)
4486 {
4487   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
4488 
4489   /* Use caches to ensure we only call FUN once for each filename.  */
4490   filename_seen_cache filenames_cache;
4491   std::unordered_set<quick_file_names *> qfn_cache;
4492 
4493   /* The rule is CUs specify all the files, including those used by any TU,
4494      so there's no need to scan TUs here.  We can ignore file names coming
4495      from already-expanded CUs.  It is possible that an expanded CU might
4496      reuse the file names data from a currently unexpanded CU, in this
4497      case we don't want to report the files from the unexpanded CU.  */
4498 
4499   for (const auto &per_cu : per_objfile->per_bfd->all_comp_units)
4500     {
4501       if (per_objfile->symtab_set_p (per_cu.get ()))
4502 	{
4503 	  if (per_cu->v.quick->file_names != nullptr)
4504 	    qfn_cache.insert (per_cu->v.quick->file_names);
4505 	}
4506     }
4507 
4508   for (dwarf2_per_cu_data *per_cu
4509 	 : all_comp_units_range (per_objfile->per_bfd))
4510     {
4511       /* We only need to look at symtabs not already expanded.  */
4512       if (per_cu->is_debug_types || per_objfile->symtab_set_p (per_cu))
4513 	continue;
4514 
4515       quick_file_names *file_data = dw2_get_file_names (per_cu, per_objfile);
4516       if (file_data == nullptr
4517 	  || qfn_cache.find (file_data) != qfn_cache.end ())
4518 	continue;
4519 
4520       for (int j = 0; j < file_data->num_file_names; ++j)
4521 	{
4522 	  const char *filename = file_data->file_names[j];
4523 	  filenames_cache.seen (filename);
4524 	}
4525     }
4526 
4527   filenames_cache.traverse ([&] (const char *filename)
4528     {
4529       gdb::unique_xmalloc_ptr<char> this_real_name;
4530 
4531       if (need_fullname)
4532 	this_real_name = gdb_realpath (filename);
4533       fun (filename, this_real_name.get ());
4534     });
4535 }
4536 
4537 bool
4538 dwarf2_base_index_functions::has_symbols (struct objfile *objfile)
4539 {
4540   return true;
4541 }
4542 
4543 /* See quick_symbol_functions::has_unexpanded_symtabs in quick-symbol.h.  */
4544 
4545 bool
4546 dwarf2_base_index_functions::has_unexpanded_symtabs (struct objfile *objfile)
4547 {
4548   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
4549 
4550   for (const auto &per_cu : per_objfile->per_bfd->all_comp_units)
4551     {
4552       /* Is this already expanded?  */
4553       if (per_objfile->symtab_set_p (per_cu.get ()))
4554 	continue;
4555 
4556       /* It has not yet been expanded.  */
4557       return true;
4558     }
4559 
4560   return false;
4561 }
4562 
4563 /* DWARF-5 debug_names reader.  */
4564 
4565 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
4566 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
4567 
4568 /* A helper function that reads the .debug_names section in SECTION
4569    and fills in MAP.  FILENAME is the name of the file containing the
4570    section; it is used for error reporting.
4571 
4572    Returns true if all went well, false otherwise.  */
4573 
4574 static bool
4575 read_debug_names_from_section (struct objfile *objfile,
4576 			       const char *filename,
4577 			       struct dwarf2_section_info *section,
4578 			       mapped_debug_names &map)
4579 {
4580   if (section->empty ())
4581     return false;
4582 
4583   /* Older elfutils strip versions could keep the section in the main
4584      executable while splitting it for the separate debug info file.  */
4585   if ((section->get_flags () & SEC_HAS_CONTENTS) == 0)
4586     return false;
4587 
4588   section->read (objfile);
4589 
4590   map.dwarf5_byte_order = gdbarch_byte_order (objfile->arch ());
4591 
4592   const gdb_byte *addr = section->buffer;
4593 
4594   bfd *const abfd = section->get_bfd_owner ();
4595 
4596   unsigned int bytes_read;
4597   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
4598   addr += bytes_read;
4599 
4600   map.dwarf5_is_dwarf64 = bytes_read != 4;
4601   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
4602   if (bytes_read + length != section->size)
4603     {
4604       /* There may be multiple per-CU indices.  */
4605       warning (_("Section .debug_names in %s length %s does not match "
4606 		 "section length %s, ignoring .debug_names."),
4607 	       filename, plongest (bytes_read + length),
4608 	       pulongest (section->size));
4609       return false;
4610     }
4611 
4612   /* The version number.  */
4613   uint16_t version = read_2_bytes (abfd, addr);
4614   addr += 2;
4615   if (version != 5)
4616     {
4617       warning (_("Section .debug_names in %s has unsupported version %d, "
4618 		 "ignoring .debug_names."),
4619 	       filename, version);
4620       return false;
4621     }
4622 
4623   /* Padding.  */
4624   uint16_t padding = read_2_bytes (abfd, addr);
4625   addr += 2;
4626   if (padding != 0)
4627     {
4628       warning (_("Section .debug_names in %s has unsupported padding %d, "
4629 		 "ignoring .debug_names."),
4630 	       filename, padding);
4631       return false;
4632     }
4633 
4634   /* comp_unit_count - The number of CUs in the CU list.  */
4635   map.cu_count = read_4_bytes (abfd, addr);
4636   addr += 4;
4637 
4638   /* local_type_unit_count - The number of TUs in the local TU
4639      list.  */
4640   map.tu_count = read_4_bytes (abfd, addr);
4641   addr += 4;
4642 
4643   /* foreign_type_unit_count - The number of TUs in the foreign TU
4644      list.  */
4645   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
4646   addr += 4;
4647   if (foreign_tu_count != 0)
4648     {
4649       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
4650 		 "ignoring .debug_names."),
4651 	       filename, static_cast<unsigned long> (foreign_tu_count));
4652       return false;
4653     }
4654 
4655   /* bucket_count - The number of hash buckets in the hash lookup
4656      table.  */
4657   map.bucket_count = read_4_bytes (abfd, addr);
4658   addr += 4;
4659 
4660   /* name_count - The number of unique names in the index.  */
4661   map.name_count = read_4_bytes (abfd, addr);
4662   addr += 4;
4663 
4664   /* abbrev_table_size - The size in bytes of the abbreviations
4665      table.  */
4666   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
4667   addr += 4;
4668 
4669   /* augmentation_string_size - The size in bytes of the augmentation
4670      string.  This value is rounded up to a multiple of 4.  */
4671   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
4672   addr += 4;
4673   map.augmentation_is_gdb = ((augmentation_string_size
4674 			      == sizeof (dwarf5_augmentation))
4675 			     && memcmp (addr, dwarf5_augmentation,
4676 					sizeof (dwarf5_augmentation)) == 0);
4677   augmentation_string_size += (-augmentation_string_size) & 3;
4678   addr += augmentation_string_size;
4679 
4680   /* List of CUs */
4681   map.cu_table_reordered = addr;
4682   addr += map.cu_count * map.offset_size;
4683 
4684   /* List of Local TUs */
4685   map.tu_table_reordered = addr;
4686   addr += map.tu_count * map.offset_size;
4687 
4688   /* Hash Lookup Table */
4689   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
4690   addr += map.bucket_count * 4;
4691   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
4692   addr += map.name_count * 4;
4693 
4694   /* Name Table */
4695   map.name_table_string_offs_reordered = addr;
4696   addr += map.name_count * map.offset_size;
4697   map.name_table_entry_offs_reordered = addr;
4698   addr += map.name_count * map.offset_size;
4699 
4700   const gdb_byte *abbrev_table_start = addr;
4701   for (;;)
4702     {
4703       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
4704       addr += bytes_read;
4705       if (index_num == 0)
4706 	break;
4707 
4708       const auto insertpair
4709 	= map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
4710       if (!insertpair.second)
4711 	{
4712 	  warning (_("Section .debug_names in %s has duplicate index %s, "
4713 		     "ignoring .debug_names."),
4714 		   filename, pulongest (index_num));
4715 	  return false;
4716 	}
4717       mapped_debug_names::index_val &indexval = insertpair.first->second;
4718       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
4719       addr += bytes_read;
4720 
4721       for (;;)
4722 	{
4723 	  mapped_debug_names::index_val::attr attr;
4724 	  attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
4725 	  addr += bytes_read;
4726 	  attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
4727 	  addr += bytes_read;
4728 	  if (attr.form == DW_FORM_implicit_const)
4729 	    {
4730 	      attr.implicit_const = read_signed_leb128 (abfd, addr,
4731 							&bytes_read);
4732 	      addr += bytes_read;
4733 	    }
4734 	  if (attr.dw_idx == 0 && attr.form == 0)
4735 	    break;
4736 	  indexval.attr_vec.push_back (std::move (attr));
4737 	}
4738     }
4739   if (addr != abbrev_table_start + abbrev_table_size)
4740     {
4741       warning (_("Section .debug_names in %s has abbreviation_table "
4742 		 "of size %s vs. written as %u, ignoring .debug_names."),
4743 	       filename, plongest (addr - abbrev_table_start),
4744 	       abbrev_table_size);
4745       return false;
4746     }
4747   map.entry_pool = addr;
4748 
4749   return true;
4750 }
4751 
4752 /* A helper for create_cus_from_debug_names that handles the MAP's CU
4753    list.  */
4754 
4755 static void
4756 create_cus_from_debug_names_list (dwarf2_per_bfd *per_bfd,
4757 				  const mapped_debug_names &map,
4758 				  dwarf2_section_info &section,
4759 				  bool is_dwz)
4760 {
4761   if (!map.augmentation_is_gdb)
4762     {
4763       for (uint32_t i = 0; i < map.cu_count; ++i)
4764 	{
4765 	  sect_offset sect_off
4766 	    = (sect_offset) (extract_unsigned_integer
4767 			     (map.cu_table_reordered + i * map.offset_size,
4768 			      map.offset_size,
4769 			      map.dwarf5_byte_order));
4770 	  /* We don't know the length of the CU, because the CU list in a
4771 	     .debug_names index can be incomplete, so we can't use the start
4772 	     of the next CU as end of this CU.  We create the CUs here with
4773 	     length 0, and in cutu_reader::cutu_reader we'll fill in the
4774 	     actual length.  */
4775 	  dwarf2_per_cu_data_up per_cu
4776 	    = create_cu_from_index_list (per_bfd, &section, is_dwz,
4777 					 sect_off, 0);
4778 	  per_bfd->all_comp_units.push_back (std::move (per_cu));
4779 	}
4780       return;
4781     }
4782 
4783   sect_offset sect_off_prev;
4784   for (uint32_t i = 0; i <= map.cu_count; ++i)
4785     {
4786       sect_offset sect_off_next;
4787       if (i < map.cu_count)
4788 	{
4789 	  sect_off_next
4790 	    = (sect_offset) (extract_unsigned_integer
4791 			     (map.cu_table_reordered + i * map.offset_size,
4792 			      map.offset_size,
4793 			      map.dwarf5_byte_order));
4794 	}
4795       else
4796 	sect_off_next = (sect_offset) section.size;
4797       if (i >= 1)
4798 	{
4799 	  const ULONGEST length = sect_off_next - sect_off_prev;
4800 	  dwarf2_per_cu_data_up per_cu
4801 	    = create_cu_from_index_list (per_bfd, &section, is_dwz,
4802 					 sect_off_prev, length);
4803 	  per_bfd->all_comp_units.push_back (std::move (per_cu));
4804 	}
4805       sect_off_prev = sect_off_next;
4806     }
4807 }
4808 
4809 /* Read the CU list from the mapped index, and use it to create all
4810    the CU objects for this dwarf2_per_objfile.  */
4811 
4812 static void
4813 create_cus_from_debug_names (dwarf2_per_bfd *per_bfd,
4814 			     const mapped_debug_names &map,
4815 			     const mapped_debug_names &dwz_map)
4816 {
4817   gdb_assert (per_bfd->all_comp_units.empty ());
4818   per_bfd->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
4819 
4820   create_cus_from_debug_names_list (per_bfd, map, per_bfd->info,
4821 				    false /* is_dwz */);
4822 
4823   if (dwz_map.cu_count == 0)
4824     return;
4825 
4826   dwz_file *dwz = dwarf2_get_dwz_file (per_bfd);
4827   create_cus_from_debug_names_list (per_bfd, dwz_map, dwz->info,
4828 				    true /* is_dwz */);
4829 }
4830 
4831 /* Read .debug_names.  If everything went ok, initialize the "quick"
4832    elements of all the CUs and return true.  Otherwise, return false.  */
4833 
4834 static bool
4835 dwarf2_read_debug_names (dwarf2_per_objfile *per_objfile)
4836 {
4837   std::unique_ptr<mapped_debug_names> map (new mapped_debug_names);
4838   mapped_debug_names dwz_map;
4839   struct objfile *objfile = per_objfile->objfile;
4840   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
4841 
4842   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
4843 				      &per_bfd->debug_names, *map))
4844     return false;
4845 
4846   /* Don't use the index if it's empty.  */
4847   if (map->name_count == 0)
4848     return false;
4849 
4850   /* If there is a .dwz file, read it so we can get its CU list as
4851      well.  */
4852   dwz_file *dwz = dwarf2_get_dwz_file (per_bfd);
4853   if (dwz != NULL)
4854     {
4855       if (!read_debug_names_from_section (objfile,
4856 					  bfd_get_filename (dwz->dwz_bfd.get ()),
4857 					  &dwz->debug_names, dwz_map))
4858 	{
4859 	  warning (_("could not read '.debug_names' section from %s; skipping"),
4860 		   bfd_get_filename (dwz->dwz_bfd.get ()));
4861 	  return false;
4862 	}
4863     }
4864 
4865   create_cus_from_debug_names (per_bfd, *map, dwz_map);
4866 
4867   if (map->tu_count != 0)
4868     {
4869       /* We can only handle a single .debug_types when we have an
4870 	 index.  */
4871       if (per_bfd->types.size () != 1)
4872 	return false;
4873 
4874       dwarf2_section_info *section = &per_bfd->types[0];
4875 
4876       create_signatured_type_table_from_debug_names
4877 	(per_objfile, *map, section, &per_bfd->abbrev);
4878     }
4879 
4880   create_addrmap_from_aranges (per_objfile, &per_bfd->debug_aranges);
4881 
4882   per_bfd->debug_names_table = std::move (map);
4883   per_bfd->using_index = 1;
4884   per_bfd->quick_file_names_table =
4885     create_quick_file_names_table (per_bfd->all_comp_units.size ());
4886 
4887   return true;
4888 }
4889 
4890 /* Type used to manage iterating over all CUs looking for a symbol for
4891    .debug_names.  */
4892 
4893 class dw2_debug_names_iterator
4894 {
4895 public:
4896   dw2_debug_names_iterator (const mapped_debug_names &map,
4897 			    block_search_flags block_index,
4898 			    domain_enum domain,
4899 			    const char *name, dwarf2_per_objfile *per_objfile)
4900     : m_map (map), m_block_index (block_index), m_domain (domain),
4901       m_addr (find_vec_in_debug_names (map, name, per_objfile)),
4902       m_per_objfile (per_objfile)
4903   {}
4904 
4905   dw2_debug_names_iterator (const mapped_debug_names &map,
4906 			    search_domain search, uint32_t namei,
4907 			    dwarf2_per_objfile *per_objfile,
4908 			    domain_enum domain = UNDEF_DOMAIN)
4909     : m_map (map),
4910       m_domain (domain),
4911       m_search (search),
4912       m_addr (find_vec_in_debug_names (map, namei, per_objfile)),
4913       m_per_objfile (per_objfile)
4914   {}
4915 
4916   dw2_debug_names_iterator (const mapped_debug_names &map,
4917 			    block_search_flags block_index, domain_enum domain,
4918 			    uint32_t namei, dwarf2_per_objfile *per_objfile)
4919     : m_map (map), m_block_index (block_index), m_domain (domain),
4920       m_addr (find_vec_in_debug_names (map, namei, per_objfile)),
4921       m_per_objfile (per_objfile)
4922   {}
4923 
4924   /* Return the next matching CU or NULL if there are no more.  */
4925   dwarf2_per_cu_data *next ();
4926 
4927 private:
4928   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
4929 						  const char *name,
4930 						  dwarf2_per_objfile *per_objfile);
4931   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
4932 						  uint32_t namei,
4933 						  dwarf2_per_objfile *per_objfile);
4934 
4935   /* The internalized form of .debug_names.  */
4936   const mapped_debug_names &m_map;
4937 
4938   /* Restrict the search to these blocks.  */
4939   block_search_flags m_block_index = (SEARCH_GLOBAL_BLOCK
4940 				      | SEARCH_STATIC_BLOCK);
4941 
4942   /* The kind of symbol we're looking for.  */
4943   const domain_enum m_domain = UNDEF_DOMAIN;
4944   const search_domain m_search = ALL_DOMAIN;
4945 
4946   /* The list of CUs from the index entry of the symbol, or NULL if
4947      not found.  */
4948   const gdb_byte *m_addr;
4949 
4950   dwarf2_per_objfile *m_per_objfile;
4951 };
4952 
4953 const char *
4954 mapped_debug_names::namei_to_name
4955   (uint32_t namei, dwarf2_per_objfile *per_objfile) const
4956 {
4957   const ULONGEST namei_string_offs
4958     = extract_unsigned_integer ((name_table_string_offs_reordered
4959 				 + namei * offset_size),
4960 				offset_size,
4961 				dwarf5_byte_order);
4962   return read_indirect_string_at_offset (per_objfile, namei_string_offs);
4963 }
4964 
4965 /* Find a slot in .debug_names for the object named NAME.  If NAME is
4966    found, return pointer to its pool data.  If NAME cannot be found,
4967    return NULL.  */
4968 
4969 const gdb_byte *
4970 dw2_debug_names_iterator::find_vec_in_debug_names
4971   (const mapped_debug_names &map, const char *name,
4972    dwarf2_per_objfile *per_objfile)
4973 {
4974   int (*cmp) (const char *, const char *);
4975 
4976   gdb::unique_xmalloc_ptr<char> without_params;
4977   if (current_language->la_language == language_cplus
4978       || current_language->la_language == language_fortran
4979       || current_language->la_language == language_d)
4980     {
4981       /* NAME is already canonical.  Drop any qualifiers as
4982 	 .debug_names does not contain any.  */
4983 
4984       if (strchr (name, '(') != NULL)
4985 	{
4986 	  without_params = cp_remove_params (name);
4987 	  if (without_params != NULL)
4988 	    name = without_params.get ();
4989 	}
4990     }
4991 
4992   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
4993 
4994   const uint32_t full_hash = dwarf5_djb_hash (name);
4995   uint32_t namei
4996     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
4997 				(map.bucket_table_reordered
4998 				 + (full_hash % map.bucket_count)), 4,
4999 				map.dwarf5_byte_order);
5000   if (namei == 0)
5001     return NULL;
5002   --namei;
5003   if (namei >= map.name_count)
5004     {
5005       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5006 		   "[in module %s]"),
5007 		 namei, map.name_count,
5008 		 objfile_name (per_objfile->objfile));
5009       return NULL;
5010     }
5011 
5012   for (;;)
5013     {
5014       const uint32_t namei_full_hash
5015 	= extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5016 				    (map.hash_table_reordered + namei), 4,
5017 				    map.dwarf5_byte_order);
5018       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5019 	return NULL;
5020 
5021       if (full_hash == namei_full_hash)
5022 	{
5023 	  const char *const namei_string = map.namei_to_name (namei, per_objfile);
5024 
5025 #if 0 /* An expensive sanity check.  */
5026 	  if (namei_full_hash != dwarf5_djb_hash (namei_string))
5027 	    {
5028 	      complaint (_("Wrong .debug_names hash for string at index %u "
5029 			   "[in module %s]"),
5030 			 namei, objfile_name (dwarf2_per_objfile->objfile));
5031 	      return NULL;
5032 	    }
5033 #endif
5034 
5035 	  if (cmp (namei_string, name) == 0)
5036 	    {
5037 	      const ULONGEST namei_entry_offs
5038 		= extract_unsigned_integer ((map.name_table_entry_offs_reordered
5039 					     + namei * map.offset_size),
5040 					    map.offset_size, map.dwarf5_byte_order);
5041 	      return map.entry_pool + namei_entry_offs;
5042 	    }
5043 	}
5044 
5045       ++namei;
5046       if (namei >= map.name_count)
5047 	return NULL;
5048     }
5049 }
5050 
5051 const gdb_byte *
5052 dw2_debug_names_iterator::find_vec_in_debug_names
5053   (const mapped_debug_names &map, uint32_t namei, dwarf2_per_objfile *per_objfile)
5054 {
5055   if (namei >= map.name_count)
5056     {
5057       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5058 		   "[in module %s]"),
5059 		 namei, map.name_count,
5060 		 objfile_name (per_objfile->objfile));
5061       return NULL;
5062     }
5063 
5064   const ULONGEST namei_entry_offs
5065     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5066 				 + namei * map.offset_size),
5067 				map.offset_size, map.dwarf5_byte_order);
5068   return map.entry_pool + namei_entry_offs;
5069 }
5070 
5071 /* See dw2_debug_names_iterator.  */
5072 
5073 dwarf2_per_cu_data *
5074 dw2_debug_names_iterator::next ()
5075 {
5076   if (m_addr == NULL)
5077     return NULL;
5078 
5079   dwarf2_per_bfd *per_bfd = m_per_objfile->per_bfd;
5080   struct objfile *objfile = m_per_objfile->objfile;
5081   bfd *const abfd = objfile->obfd;
5082 
5083  again:
5084 
5085   unsigned int bytes_read;
5086   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5087   m_addr += bytes_read;
5088   if (abbrev == 0)
5089     return NULL;
5090 
5091   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5092   if (indexval_it == m_map.abbrev_map.cend ())
5093     {
5094       complaint (_("Wrong .debug_names undefined abbrev code %s "
5095 		   "[in module %s]"),
5096 		 pulongest (abbrev), objfile_name (objfile));
5097       return NULL;
5098     }
5099   const mapped_debug_names::index_val &indexval = indexval_it->second;
5100   enum class symbol_linkage {
5101     unknown,
5102     static_,
5103     extern_,
5104   } symbol_linkage_ = symbol_linkage::unknown;
5105   dwarf2_per_cu_data *per_cu = NULL;
5106   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5107     {
5108       ULONGEST ull;
5109       switch (attr.form)
5110 	{
5111 	case DW_FORM_implicit_const:
5112 	  ull = attr.implicit_const;
5113 	  break;
5114 	case DW_FORM_flag_present:
5115 	  ull = 1;
5116 	  break;
5117 	case DW_FORM_udata:
5118 	  ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5119 	  m_addr += bytes_read;
5120 	  break;
5121 	case DW_FORM_ref4:
5122 	  ull = read_4_bytes (abfd, m_addr);
5123 	  m_addr += 4;
5124 	  break;
5125 	case DW_FORM_ref8:
5126 	  ull = read_8_bytes (abfd, m_addr);
5127 	  m_addr += 8;
5128 	  break;
5129 	case DW_FORM_ref_sig8:
5130 	  ull = read_8_bytes (abfd, m_addr);
5131 	  m_addr += 8;
5132 	  break;
5133 	default:
5134 	  complaint (_("Unsupported .debug_names form %s [in module %s]"),
5135 		     dwarf_form_name (attr.form),
5136 		     objfile_name (objfile));
5137 	  return NULL;
5138 	}
5139       switch (attr.dw_idx)
5140 	{
5141 	case DW_IDX_compile_unit:
5142 	  /* Don't crash on bad data.  */
5143 	  if (ull >= per_bfd->all_comp_units.size ())
5144 	    {
5145 	      complaint (_(".debug_names entry has bad CU index %s"
5146 			   " [in module %s]"),
5147 			 pulongest (ull),
5148 			 objfile_name (objfile));
5149 	      continue;
5150 	    }
5151 	  per_cu = per_bfd->get_cu (ull);
5152 	  break;
5153 	case DW_IDX_type_unit:
5154 	  /* Don't crash on bad data.  */
5155 	  if (ull >= per_bfd->tu_stats.nr_tus)
5156 	    {
5157 	      complaint (_(".debug_names entry has bad TU index %s"
5158 			   " [in module %s]"),
5159 			 pulongest (ull),
5160 			 objfile_name (objfile));
5161 	      continue;
5162 	    }
5163 	  per_cu = per_bfd->get_cu (ull + per_bfd->tu_stats.nr_tus);
5164 	  break;
5165 	case DW_IDX_die_offset:
5166 	  /* In a per-CU index (as opposed to a per-module index), index
5167 	     entries without CU attribute implicitly refer to the single CU.  */
5168 	  if (per_cu == NULL)
5169 	    per_cu = per_bfd->get_cu (0);
5170 	  break;
5171 	case DW_IDX_GNU_internal:
5172 	  if (!m_map.augmentation_is_gdb)
5173 	    break;
5174 	  symbol_linkage_ = symbol_linkage::static_;
5175 	  break;
5176 	case DW_IDX_GNU_external:
5177 	  if (!m_map.augmentation_is_gdb)
5178 	    break;
5179 	  symbol_linkage_ = symbol_linkage::extern_;
5180 	  break;
5181 	}
5182     }
5183 
5184   /* Skip if already read in.  */
5185   if (m_per_objfile->symtab_set_p (per_cu))
5186     goto again;
5187 
5188   /* Check static vs global.  */
5189   if (symbol_linkage_ != symbol_linkage::unknown)
5190     {
5191       if (symbol_linkage_ == symbol_linkage::static_)
5192 	{
5193 	  if ((m_block_index & SEARCH_STATIC_BLOCK) == 0)
5194 	    goto again;
5195 	}
5196       else
5197 	{
5198 	  if ((m_block_index & SEARCH_GLOBAL_BLOCK) == 0)
5199 	    goto again;
5200 	}
5201     }
5202 
5203   /* Match dw2_symtab_iter_next, symbol_kind
5204      and debug_names::psymbol_tag.  */
5205   switch (m_domain)
5206     {
5207     case VAR_DOMAIN:
5208       switch (indexval.dwarf_tag)
5209 	{
5210 	case DW_TAG_variable:
5211 	case DW_TAG_subprogram:
5212 	/* Some types are also in VAR_DOMAIN.  */
5213 	case DW_TAG_typedef:
5214 	case DW_TAG_structure_type:
5215 	  break;
5216 	default:
5217 	  goto again;
5218 	}
5219       break;
5220     case STRUCT_DOMAIN:
5221       switch (indexval.dwarf_tag)
5222 	{
5223 	case DW_TAG_typedef:
5224 	case DW_TAG_structure_type:
5225 	  break;
5226 	default:
5227 	  goto again;
5228 	}
5229       break;
5230     case LABEL_DOMAIN:
5231       switch (indexval.dwarf_tag)
5232 	{
5233 	case 0:
5234 	case DW_TAG_variable:
5235 	  break;
5236 	default:
5237 	  goto again;
5238 	}
5239       break;
5240     case MODULE_DOMAIN:
5241       switch (indexval.dwarf_tag)
5242 	{
5243 	case DW_TAG_module:
5244 	  break;
5245 	default:
5246 	  goto again;
5247 	}
5248       break;
5249     default:
5250       break;
5251     }
5252 
5253   /* Match dw2_expand_symtabs_matching, symbol_kind and
5254      debug_names::psymbol_tag.  */
5255   switch (m_search)
5256     {
5257     case VARIABLES_DOMAIN:
5258       switch (indexval.dwarf_tag)
5259 	{
5260 	case DW_TAG_variable:
5261 	  break;
5262 	default:
5263 	  goto again;
5264 	}
5265       break;
5266     case FUNCTIONS_DOMAIN:
5267       switch (indexval.dwarf_tag)
5268 	{
5269 	case DW_TAG_subprogram:
5270 	  break;
5271 	default:
5272 	  goto again;
5273 	}
5274       break;
5275     case TYPES_DOMAIN:
5276       switch (indexval.dwarf_tag)
5277 	{
5278 	case DW_TAG_typedef:
5279 	case DW_TAG_structure_type:
5280 	  break;
5281 	default:
5282 	  goto again;
5283 	}
5284       break;
5285     case MODULES_DOMAIN:
5286       switch (indexval.dwarf_tag)
5287 	{
5288 	case DW_TAG_module:
5289 	  break;
5290 	default:
5291 	  goto again;
5292 	}
5293     default:
5294       break;
5295     }
5296 
5297   return per_cu;
5298 }
5299 
5300 /* This dumps minimal information about .debug_names.  It is called
5301    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
5302    uses this to verify that .debug_names has been loaded.  */
5303 
5304 void
5305 dwarf2_debug_names_index::dump (struct objfile *objfile)
5306 {
5307   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
5308 
5309   gdb_assert (per_objfile->per_bfd->using_index);
5310   printf_filtered (".debug_names:");
5311   if (per_objfile->per_bfd->debug_names_table)
5312     printf_filtered (" exists\n");
5313   else
5314     printf_filtered (" faked for \"readnow\"\n");
5315   printf_filtered ("\n");
5316 }
5317 
5318 void
5319 dwarf2_debug_names_index::expand_matching_symbols
5320   (struct objfile *objfile,
5321    const lookup_name_info &name, domain_enum domain,
5322    int global,
5323    symbol_compare_ftype *ordered_compare)
5324 {
5325   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
5326 
5327   /* debug_names_table is NULL if OBJF_READNOW.  */
5328   if (!per_objfile->per_bfd->debug_names_table)
5329     return;
5330 
5331   mapped_debug_names &map = *per_objfile->per_bfd->debug_names_table;
5332   const block_search_flags block_flags
5333     = global ? SEARCH_GLOBAL_BLOCK : SEARCH_STATIC_BLOCK;
5334 
5335   const char *match_name = name.ada ().lookup_name ().c_str ();
5336   auto matcher = [&] (const char *symname)
5337     {
5338       if (ordered_compare == nullptr)
5339 	return true;
5340       return ordered_compare (symname, match_name) == 0;
5341     };
5342 
5343   dw2_expand_symtabs_matching_symbol (map, name, matcher,
5344 				      [&] (offset_type namei)
5345     {
5346       /* The name was matched, now expand corresponding CUs that were
5347 	 marked.  */
5348       dw2_debug_names_iterator iter (map, block_flags, domain, namei,
5349 				     per_objfile);
5350 
5351       struct dwarf2_per_cu_data *per_cu;
5352       while ((per_cu = iter.next ()) != NULL)
5353 	dw2_expand_symtabs_matching_one (per_cu, per_objfile, nullptr,
5354 					 nullptr);
5355       return true;
5356     }, per_objfile);
5357 }
5358 
5359 bool
5360 dwarf2_debug_names_index::expand_symtabs_matching
5361   (struct objfile *objfile,
5362    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5363    const lookup_name_info *lookup_name,
5364    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5365    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5366    block_search_flags search_flags,
5367    domain_enum domain,
5368    enum search_domain kind)
5369 {
5370   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
5371 
5372   /* debug_names_table is NULL if OBJF_READNOW.  */
5373   if (!per_objfile->per_bfd->debug_names_table)
5374     return true;
5375 
5376   dw_expand_symtabs_matching_file_matcher (per_objfile, file_matcher);
5377 
5378   if (symbol_matcher == NULL && lookup_name == NULL)
5379     {
5380       for (dwarf2_per_cu_data *per_cu
5381 	     : all_comp_units_range (per_objfile->per_bfd))
5382 	{
5383 	  QUIT;
5384 
5385 	  if (!dw2_expand_symtabs_matching_one (per_cu, per_objfile,
5386 						file_matcher,
5387 						expansion_notify))
5388 	    return false;
5389 	}
5390       return true;
5391     }
5392 
5393   mapped_debug_names &map = *per_objfile->per_bfd->debug_names_table;
5394 
5395   bool result
5396     = dw2_expand_symtabs_matching_symbol (map, *lookup_name,
5397 					  symbol_matcher,
5398 					  [&] (offset_type namei)
5399     {
5400       /* The name was matched, now expand corresponding CUs that were
5401 	 marked.  */
5402       dw2_debug_names_iterator iter (map, kind, namei, per_objfile, domain);
5403 
5404       struct dwarf2_per_cu_data *per_cu;
5405       while ((per_cu = iter.next ()) != NULL)
5406 	if (!dw2_expand_symtabs_matching_one (per_cu, per_objfile,
5407 					      file_matcher,
5408 					      expansion_notify))
5409 	  return false;
5410       return true;
5411     }, per_objfile);
5412 
5413   return result;
5414 }
5415 
5416 /* Get the content of the .gdb_index section of OBJ.  SECTION_OWNER should point
5417    to either a dwarf2_per_bfd or dwz_file object.  */
5418 
5419 template <typename T>
5420 static gdb::array_view<const gdb_byte>
5421 get_gdb_index_contents_from_section (objfile *obj, T *section_owner)
5422 {
5423   dwarf2_section_info *section = &section_owner->gdb_index;
5424 
5425   if (section->empty ())
5426     return {};
5427 
5428   /* Older elfutils strip versions could keep the section in the main
5429      executable while splitting it for the separate debug info file.  */
5430   if ((section->get_flags () & SEC_HAS_CONTENTS) == 0)
5431     return {};
5432 
5433   section->read (obj);
5434 
5435   /* dwarf2_section_info::size is a bfd_size_type, while
5436      gdb::array_view works with size_t.  On 32-bit hosts, with
5437      --enable-64-bit-bfd, bfd_size_type is a 64-bit type, while size_t
5438      is 32-bit.  So we need an explicit narrowing conversion here.
5439      This is fine, because it's impossible to allocate or mmap an
5440      array/buffer larger than what size_t can represent.  */
5441   return gdb::make_array_view (section->buffer, section->size);
5442 }
5443 
5444 /* Lookup the index cache for the contents of the index associated to
5445    DWARF2_OBJ.  */
5446 
5447 static gdb::array_view<const gdb_byte>
5448 get_gdb_index_contents_from_cache (objfile *obj, dwarf2_per_bfd *dwarf2_per_bfd)
5449 {
5450   const bfd_build_id *build_id = build_id_bfd_get (obj->obfd);
5451   if (build_id == nullptr)
5452     return {};
5453 
5454   return global_index_cache.lookup_gdb_index (build_id,
5455 					      &dwarf2_per_bfd->index_cache_res);
5456 }
5457 
5458 /* Same as the above, but for DWZ.  */
5459 
5460 static gdb::array_view<const gdb_byte>
5461 get_gdb_index_contents_from_cache_dwz (objfile *obj, dwz_file *dwz)
5462 {
5463   const bfd_build_id *build_id = build_id_bfd_get (dwz->dwz_bfd.get ());
5464   if (build_id == nullptr)
5465     return {};
5466 
5467   return global_index_cache.lookup_gdb_index (build_id, &dwz->index_cache_res);
5468 }
5469 
5470 /* See dwarf2/public.h.  */
5471 
5472 void
5473 dwarf2_initialize_objfile (struct objfile *objfile)
5474 {
5475   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
5476   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
5477 
5478   dwarf_read_debug_printf ("called");
5479 
5480   /* If we're about to read full symbols, don't bother with the
5481      indices.  In this case we also don't care if some other debug
5482      format is making psymtabs, because they are all about to be
5483      expanded anyway.  */
5484   if ((objfile->flags & OBJF_READNOW))
5485     {
5486       dwarf_read_debug_printf ("readnow requested");
5487 
5488       /* When using READNOW, the using_index flag (set below) indicates that
5489 	 PER_BFD was already initialized, when we loaded some other objfile.  */
5490       if (per_bfd->using_index)
5491 	{
5492 	  dwarf_read_debug_printf ("using_index already set");
5493 	  objfile->qf.push_front (make_dwarf_gdb_index ());
5494 	  return;
5495 	}
5496 
5497       per_bfd->using_index = 1;
5498       create_all_comp_units (per_objfile);
5499       per_bfd->quick_file_names_table
5500 	= create_quick_file_names_table (per_bfd->all_comp_units.size ());
5501 
5502       for (int i = 0; i < per_bfd->all_comp_units.size (); ++i)
5503 	{
5504 	  dwarf2_per_cu_data *per_cu = per_bfd->get_cu (i);
5505 
5506 	  per_cu->v.quick = OBSTACK_ZALLOC (&per_bfd->obstack,
5507 					    struct dwarf2_per_cu_quick_data);
5508 	}
5509 
5510       /* Arrange for gdb to see the "quick" functions.  However, these
5511 	 functions will be no-ops because we will have expanded all
5512 	 symtabs.  */
5513       objfile->qf.push_front (make_dwarf_gdb_index ());
5514       return;
5515     }
5516 
5517   /* Was a debug names index already read when we processed an objfile sharing
5518      PER_BFD?  */
5519   if (per_bfd->debug_names_table != nullptr)
5520     {
5521       dwarf_read_debug_printf ("re-using shared debug names table");
5522       objfile->qf.push_front (make_dwarf_debug_names ());
5523       return;
5524     }
5525 
5526   /* Was a GDB index already read when we processed an objfile sharing
5527      PER_BFD?  */
5528   if (per_bfd->index_table != nullptr)
5529     {
5530       dwarf_read_debug_printf ("re-using shared index table");
5531       objfile->qf.push_front (make_dwarf_gdb_index ());
5532       return;
5533     }
5534 
5535   /* There might already be partial symtabs built for this BFD.  This happens
5536      when loading the same binary twice with the index-cache enabled.  If so,
5537      don't try to read an index.  The objfile / per_objfile initialization will
5538      be completed in dwarf2_build_psymtabs, in the standard partial symtabs
5539      code path.  */
5540   if (per_bfd->partial_symtabs != nullptr)
5541     {
5542       dwarf_read_debug_printf ("re-using shared partial symtabs");
5543       objfile->qf.push_front (make_lazy_dwarf_reader ());
5544       return;
5545     }
5546 
5547   if (dwarf2_read_debug_names (per_objfile))
5548     {
5549       dwarf_read_debug_printf ("found debug names");
5550       objfile->qf.push_front (make_dwarf_debug_names ());
5551       return;
5552     }
5553 
5554   if (dwarf2_read_gdb_index (per_objfile,
5555 			     get_gdb_index_contents_from_section<struct dwarf2_per_bfd>,
5556 			     get_gdb_index_contents_from_section<dwz_file>))
5557     {
5558       dwarf_read_debug_printf ("found gdb index from file");
5559       objfile->qf.push_front (make_dwarf_gdb_index ());
5560       return;
5561     }
5562 
5563   /* ... otherwise, try to find the index in the index cache.  */
5564   if (dwarf2_read_gdb_index (per_objfile,
5565 			     get_gdb_index_contents_from_cache,
5566 			     get_gdb_index_contents_from_cache_dwz))
5567     {
5568       dwarf_read_debug_printf ("found gdb index from cache");
5569       global_index_cache.hit ();
5570       objfile->qf.push_front (make_dwarf_gdb_index ());
5571       return;
5572     }
5573 
5574   global_index_cache.miss ();
5575   objfile->qf.push_front (make_lazy_dwarf_reader ());
5576 }
5577 
5578 
5579 
5580 /* Build a partial symbol table.  */
5581 
5582 void
5583 dwarf2_build_psymtabs (struct objfile *objfile, psymbol_functions *psf)
5584 {
5585   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
5586   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
5587 
5588   if (per_bfd->partial_symtabs != nullptr)
5589     {
5590       /* Partial symbols were already read, so now we can simply
5591 	 attach them.  */
5592       if (psf == nullptr)
5593 	{
5594 	  psf = new psymbol_functions (per_bfd->partial_symtabs);
5595 	  objfile->qf.emplace_front (psf);
5596 	}
5597       else
5598 	psf->set_partial_symtabs (per_bfd->partial_symtabs);
5599       return;
5600     }
5601 
5602   if (psf == nullptr)
5603     {
5604       psf = new psymbol_functions;
5605       objfile->qf.emplace_front (psf);
5606     }
5607   const std::shared_ptr<psymtab_storage> &partial_symtabs
5608     = psf->get_partial_symtabs ();
5609 
5610   /* Set the local reference to partial symtabs, so that we don't try
5611      to read them again if reading another objfile with the same BFD.
5612      If we can't in fact share, this won't make a difference anyway as
5613      the dwarf2_per_bfd object won't be shared.  */
5614   per_bfd->partial_symtabs = partial_symtabs;
5615 
5616   try
5617     {
5618       /* This isn't really ideal: all the data we allocate on the
5619 	 objfile's obstack is still uselessly kept around.  However,
5620 	 freeing it seems unsafe.  */
5621       psymtab_discarder psymtabs (partial_symtabs.get ());
5622       dwarf2_build_psymtabs_hard (per_objfile);
5623       psymtabs.keep ();
5624 
5625       /* (maybe) store an index in the cache.  */
5626       global_index_cache.store (per_objfile);
5627     }
5628   catch (const gdb_exception_error &except)
5629     {
5630       exception_print (gdb_stderr, except);
5631     }
5632 }
5633 
5634 /* Find the base address of the compilation unit for range lists and
5635    location lists.  It will normally be specified by DW_AT_low_pc.
5636    In DWARF-3 draft 4, the base address could be overridden by
5637    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
5638    compilation units with discontinuous ranges.  */
5639 
5640 static void
5641 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
5642 {
5643   struct attribute *attr;
5644 
5645   cu->base_address.reset ();
5646 
5647   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
5648   if (attr != nullptr)
5649     cu->base_address = attr->as_address ();
5650   else
5651     {
5652       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
5653       if (attr != nullptr)
5654 	cu->base_address = attr->as_address ();
5655     }
5656 }
5657 
5658 /* Helper function that returns the proper abbrev section for
5659    THIS_CU.  */
5660 
5661 static struct dwarf2_section_info *
5662 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
5663 {
5664   struct dwarf2_section_info *abbrev;
5665   dwarf2_per_bfd *per_bfd = this_cu->per_bfd;
5666 
5667   if (this_cu->is_dwz)
5668     abbrev = &dwarf2_get_dwz_file (per_bfd, true)->abbrev;
5669   else
5670     abbrev = &per_bfd->abbrev;
5671 
5672   return abbrev;
5673 }
5674 
5675 /* Fetch the abbreviation table offset from a comp or type unit header.  */
5676 
5677 static sect_offset
5678 read_abbrev_offset (dwarf2_per_objfile *per_objfile,
5679 		    struct dwarf2_section_info *section,
5680 		    sect_offset sect_off)
5681 {
5682   bfd *abfd = section->get_bfd_owner ();
5683   const gdb_byte *info_ptr;
5684   unsigned int initial_length_size, offset_size;
5685   uint16_t version;
5686 
5687   section->read (per_objfile->objfile);
5688   info_ptr = section->buffer + to_underlying (sect_off);
5689   read_initial_length (abfd, info_ptr, &initial_length_size);
5690   offset_size = initial_length_size == 4 ? 4 : 8;
5691   info_ptr += initial_length_size;
5692 
5693   version = read_2_bytes (abfd, info_ptr);
5694   info_ptr += 2;
5695   if (version >= 5)
5696     {
5697       /* Skip unit type and address size.  */
5698       info_ptr += 2;
5699     }
5700 
5701   return (sect_offset) read_offset (abfd, info_ptr, offset_size);
5702 }
5703 
5704 /* A partial symtab that is used only for include files.  */
5705 struct dwarf2_include_psymtab : public partial_symtab
5706 {
5707   dwarf2_include_psymtab (const char *filename,
5708 			  psymtab_storage *partial_symtabs,
5709 			  objfile_per_bfd_storage *objfile_per_bfd)
5710     : partial_symtab (filename, partial_symtabs, objfile_per_bfd)
5711   {
5712   }
5713 
5714   void read_symtab (struct objfile *objfile) override
5715   {
5716     /* It's an include file, no symbols to read for it.
5717        Everything is in the includer symtab.  */
5718 
5719     /* The expansion of a dwarf2_include_psymtab is just a trigger for
5720        expansion of the includer psymtab.  We use the dependencies[0] field to
5721        model the includer.  But if we go the regular route of calling
5722        expand_psymtab here, and having expand_psymtab call expand_dependencies
5723        to expand the includer, we'll only use expand_psymtab on the includer
5724        (making it a non-toplevel psymtab), while if we expand the includer via
5725        another path, we'll use read_symtab (making it a toplevel psymtab).
5726        So, don't pretend a dwarf2_include_psymtab is an actual toplevel
5727        psymtab, and trigger read_symtab on the includer here directly.  */
5728     includer ()->read_symtab (objfile);
5729   }
5730 
5731   void expand_psymtab (struct objfile *objfile) override
5732   {
5733     /* This is not called by read_symtab, and should not be called by any
5734        expand_dependencies.  */
5735     gdb_assert (false);
5736   }
5737 
5738   bool readin_p (struct objfile *objfile) const override
5739   {
5740     return includer ()->readin_p (objfile);
5741   }
5742 
5743   compunit_symtab *get_compunit_symtab (struct objfile *objfile) const override
5744   {
5745     return nullptr;
5746   }
5747 
5748 private:
5749   partial_symtab *includer () const
5750   {
5751     /* An include psymtab has exactly one dependency: the psymtab that
5752        includes it.  */
5753     gdb_assert (this->number_of_dependencies == 1);
5754     return this->dependencies[0];
5755   }
5756 };
5757 
5758 /* Allocate a new partial symtab for file named NAME and mark this new
5759    partial symtab as being an include of PST.  */
5760 
5761 static void
5762 dwarf2_create_include_psymtab (dwarf2_per_bfd *per_bfd,
5763 			       const char *name,
5764 			       dwarf2_psymtab *pst,
5765 			       psymtab_storage *partial_symtabs,
5766 			       objfile_per_bfd_storage *objfile_per_bfd)
5767 {
5768   dwarf2_include_psymtab *subpst
5769     = new dwarf2_include_psymtab (name, partial_symtabs, objfile_per_bfd);
5770 
5771   if (!IS_ABSOLUTE_PATH (subpst->filename))
5772     subpst->dirname = pst->dirname;
5773 
5774   subpst->dependencies = per_bfd->partial_symtabs->allocate_dependencies (1);
5775   subpst->dependencies[0] = pst;
5776   subpst->number_of_dependencies = 1;
5777 }
5778 
5779 /* Read the Line Number Program data and extract the list of files
5780    included by the source file represented by PST.  Build an include
5781    partial symtab for each of these included files.  */
5782 
5783 static void
5784 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
5785 			       struct die_info *die,
5786 			       dwarf2_psymtab *pst)
5787 {
5788   line_header_up lh;
5789   struct attribute *attr;
5790 
5791   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
5792   if (attr != nullptr && attr->form_is_unsigned ())
5793     lh = dwarf_decode_line_header ((sect_offset) attr->as_unsigned (), cu);
5794   if (lh == NULL)
5795     return;  /* No linetable, so no includes.  */
5796 
5797   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  Also note
5798      that we pass in the raw text_low here; that is ok because we're
5799      only decoding the line table to make include partial symtabs, and
5800      so the addresses aren't really used.  */
5801   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst,
5802 		      pst->raw_text_low (), 1);
5803 }
5804 
5805 static hashval_t
5806 hash_signatured_type (const void *item)
5807 {
5808   const struct signatured_type *sig_type
5809     = (const struct signatured_type *) item;
5810 
5811   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
5812   return sig_type->signature;
5813 }
5814 
5815 static int
5816 eq_signatured_type (const void *item_lhs, const void *item_rhs)
5817 {
5818   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
5819   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
5820 
5821   return lhs->signature == rhs->signature;
5822 }
5823 
5824 /* Allocate a hash table for signatured types.  */
5825 
5826 static htab_up
5827 allocate_signatured_type_table ()
5828 {
5829   return htab_up (htab_create_alloc (41,
5830 				     hash_signatured_type,
5831 				     eq_signatured_type,
5832 				     NULL, xcalloc, xfree));
5833 }
5834 
5835 /* A helper for create_debug_types_hash_table.  Read types from SECTION
5836    and fill them into TYPES_HTAB.  It will process only type units,
5837    therefore DW_UT_type.  */
5838 
5839 static void
5840 create_debug_type_hash_table (dwarf2_per_objfile *per_objfile,
5841 			      struct dwo_file *dwo_file,
5842 			      dwarf2_section_info *section, htab_up &types_htab,
5843 			      rcuh_kind section_kind)
5844 {
5845   struct objfile *objfile = per_objfile->objfile;
5846   struct dwarf2_section_info *abbrev_section;
5847   bfd *abfd;
5848   const gdb_byte *info_ptr, *end_ptr;
5849 
5850   abbrev_section = &dwo_file->sections.abbrev;
5851 
5852   dwarf_read_debug_printf ("Reading %s for %s",
5853 			   section->get_name (),
5854 			   abbrev_section->get_file_name ());
5855 
5856   section->read (objfile);
5857   info_ptr = section->buffer;
5858 
5859   if (info_ptr == NULL)
5860     return;
5861 
5862   /* We can't set abfd until now because the section may be empty or
5863      not present, in which case the bfd is unknown.  */
5864   abfd = section->get_bfd_owner ();
5865 
5866   /* We don't use cutu_reader here because we don't need to read
5867      any dies: the signature is in the header.  */
5868 
5869   end_ptr = info_ptr + section->size;
5870   while (info_ptr < end_ptr)
5871     {
5872       signatured_type_up sig_type;
5873       struct dwo_unit *dwo_tu;
5874       void **slot;
5875       const gdb_byte *ptr = info_ptr;
5876       struct comp_unit_head header;
5877       unsigned int length;
5878 
5879       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
5880 
5881       /* Initialize it due to a false compiler warning.  */
5882       header.signature = -1;
5883       header.type_cu_offset_in_tu = (cu_offset) -1;
5884 
5885       /* We need to read the type's signature in order to build the hash
5886 	 table, but we don't need anything else just yet.  */
5887 
5888       ptr = read_and_check_comp_unit_head (per_objfile, &header, section,
5889 					   abbrev_section, ptr, section_kind);
5890 
5891       length = header.get_length ();
5892 
5893       /* Skip dummy type units.  */
5894       if (ptr >= info_ptr + length
5895 	  || peek_abbrev_code (abfd, ptr) == 0
5896 	  || (header.unit_type != DW_UT_type
5897 	      && header.unit_type != DW_UT_split_type))
5898 	{
5899 	  info_ptr += length;
5900 	  continue;
5901 	}
5902 
5903       if (types_htab == NULL)
5904 	types_htab = allocate_dwo_unit_table ();
5905 
5906       dwo_tu = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, dwo_unit);
5907       dwo_tu->dwo_file = dwo_file;
5908       dwo_tu->signature = header.signature;
5909       dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
5910       dwo_tu->section = section;
5911       dwo_tu->sect_off = sect_off;
5912       dwo_tu->length = length;
5913 
5914       slot = htab_find_slot (types_htab.get (), dwo_tu, INSERT);
5915       gdb_assert (slot != NULL);
5916       if (*slot != NULL)
5917 	complaint (_("debug type entry at offset %s is duplicate to"
5918 		     " the entry at offset %s, signature %s"),
5919 		   sect_offset_str (sect_off),
5920 		   sect_offset_str (dwo_tu->sect_off),
5921 		   hex_string (header.signature));
5922       *slot = dwo_tu;
5923 
5924       dwarf_read_debug_printf_v ("  offset %s, signature %s",
5925 				 sect_offset_str (sect_off),
5926 				 hex_string (header.signature));
5927 
5928       info_ptr += length;
5929     }
5930 }
5931 
5932 /* Create the hash table of all entries in the .debug_types
5933    (or .debug_types.dwo) section(s).
5934    DWO_FILE is a pointer to the DWO file object.
5935 
5936    The result is a pointer to the hash table or NULL if there are no types.
5937 
5938    Note: This function processes DWO files only, not DWP files.  */
5939 
5940 static void
5941 create_debug_types_hash_table (dwarf2_per_objfile *per_objfile,
5942 			       struct dwo_file *dwo_file,
5943 			       gdb::array_view<dwarf2_section_info> type_sections,
5944 			       htab_up &types_htab)
5945 {
5946   for (dwarf2_section_info &section : type_sections)
5947     create_debug_type_hash_table (per_objfile, dwo_file, &section, types_htab,
5948 				  rcuh_kind::TYPE);
5949 }
5950 
5951 /* Add an entry for signature SIG to dwarf2_per_objfile->per_bfd->signatured_types.
5952    If SLOT is non-NULL, it is the entry to use in the hash table.
5953    Otherwise we find one.  */
5954 
5955 static struct signatured_type *
5956 add_type_unit (dwarf2_per_objfile *per_objfile, ULONGEST sig, void **slot)
5957 {
5958   if (per_objfile->per_bfd->all_comp_units.size ()
5959       == per_objfile->per_bfd->all_comp_units.capacity ())
5960     ++per_objfile->per_bfd->tu_stats.nr_all_type_units_reallocs;
5961 
5962   signatured_type_up sig_type_holder
5963     = per_objfile->per_bfd->allocate_signatured_type (sig);
5964   signatured_type *sig_type = sig_type_holder.get ();
5965 
5966   per_objfile->per_bfd->all_comp_units.emplace_back
5967     (sig_type_holder.release ());
5968   if (per_objfile->per_bfd->using_index)
5969     {
5970       sig_type->v.quick =
5971 	OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack,
5972 			struct dwarf2_per_cu_quick_data);
5973     }
5974 
5975   if (slot == NULL)
5976     {
5977       slot = htab_find_slot (per_objfile->per_bfd->signatured_types.get (),
5978 			     sig_type, INSERT);
5979     }
5980   gdb_assert (*slot == NULL);
5981   *slot = sig_type;
5982   /* The rest of sig_type must be filled in by the caller.  */
5983   return sig_type;
5984 }
5985 
5986 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5987    Fill in SIG_ENTRY with DWO_ENTRY.  */
5988 
5989 static void
5990 fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile *per_objfile,
5991 				  struct signatured_type *sig_entry,
5992 				  struct dwo_unit *dwo_entry)
5993 {
5994   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
5995 
5996   /* Make sure we're not clobbering something we don't expect to.  */
5997   gdb_assert (! sig_entry->queued);
5998   gdb_assert (per_objfile->get_cu (sig_entry) == NULL);
5999   if (per_bfd->using_index)
6000     {
6001       gdb_assert (sig_entry->v.quick != NULL);
6002       gdb_assert (!per_objfile->symtab_set_p (sig_entry));
6003     }
6004   else
6005       gdb_assert (sig_entry->v.psymtab == NULL);
6006   gdb_assert (sig_entry->signature == dwo_entry->signature);
6007   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6008   gdb_assert (sig_entry->type_unit_group == NULL);
6009   gdb_assert (sig_entry->dwo_unit == NULL);
6010 
6011   sig_entry->section = dwo_entry->section;
6012   sig_entry->sect_off = dwo_entry->sect_off;
6013   sig_entry->length = dwo_entry->length;
6014   sig_entry->reading_dwo_directly = 1;
6015   sig_entry->per_bfd = per_bfd;
6016   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6017   sig_entry->dwo_unit = dwo_entry;
6018 }
6019 
6020 /* Subroutine of lookup_signatured_type.
6021    If we haven't read the TU yet, create the signatured_type data structure
6022    for a TU to be read in directly from a DWO file, bypassing the stub.
6023    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6024    using .gdb_index, then when reading a CU we want to stay in the DWO file
6025    containing that CU.  Otherwise we could end up reading several other DWO
6026    files (due to comdat folding) to process the transitive closure of all the
6027    mentioned TUs, and that can be slow.  The current DWO file will have every
6028    type signature that it needs.
6029    We only do this for .gdb_index because in the psymtab case we already have
6030    to read all the DWOs to build the type unit groups.  */
6031 
6032 static struct signatured_type *
6033 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6034 {
6035   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6036   struct dwo_file *dwo_file;
6037   struct dwo_unit find_dwo_entry, *dwo_entry;
6038   void **slot;
6039 
6040   gdb_assert (cu->dwo_unit && per_objfile->per_bfd->using_index);
6041 
6042   /* If TU skeletons have been removed then we may not have read in any
6043      TUs yet.  */
6044   if (per_objfile->per_bfd->signatured_types == NULL)
6045     per_objfile->per_bfd->signatured_types = allocate_signatured_type_table ();
6046 
6047   /* We only ever need to read in one copy of a signatured type.
6048      Use the global signatured_types array to do our own comdat-folding
6049      of types.  If this is the first time we're reading this TU, and
6050      the TU has an entry in .gdb_index, replace the recorded data from
6051      .gdb_index with this TU.  */
6052 
6053   signatured_type find_sig_entry (sig);
6054   slot = htab_find_slot (per_objfile->per_bfd->signatured_types.get (),
6055 			 &find_sig_entry, INSERT);
6056   signatured_type *sig_entry = (struct signatured_type *) *slot;
6057 
6058   /* We can get here with the TU already read, *or* in the process of being
6059      read.  Don't reassign the global entry to point to this DWO if that's
6060      the case.  Also note that if the TU is already being read, it may not
6061      have come from a DWO, the program may be a mix of Fission-compiled
6062      code and non-Fission-compiled code.  */
6063 
6064   /* Have we already tried to read this TU?
6065      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6066      needn't exist in the global table yet).  */
6067   if (sig_entry != NULL && sig_entry->tu_read)
6068     return sig_entry;
6069 
6070   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6071      dwo_unit of the TU itself.  */
6072   dwo_file = cu->dwo_unit->dwo_file;
6073 
6074   /* Ok, this is the first time we're reading this TU.  */
6075   if (dwo_file->tus == NULL)
6076     return NULL;
6077   find_dwo_entry.signature = sig;
6078   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus.get (),
6079 					     &find_dwo_entry);
6080   if (dwo_entry == NULL)
6081     return NULL;
6082 
6083   /* If the global table doesn't have an entry for this TU, add one.  */
6084   if (sig_entry == NULL)
6085     sig_entry = add_type_unit (per_objfile, sig, slot);
6086 
6087   fill_in_sig_entry_from_dwo_entry (per_objfile, sig_entry, dwo_entry);
6088   sig_entry->tu_read = 1;
6089   return sig_entry;
6090 }
6091 
6092 /* Subroutine of lookup_signatured_type.
6093    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6094    then try the DWP file.  If the TU stub (skeleton) has been removed then
6095    it won't be in .gdb_index.  */
6096 
6097 static struct signatured_type *
6098 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6099 {
6100   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6101   struct dwp_file *dwp_file = get_dwp_file (per_objfile);
6102   struct dwo_unit *dwo_entry;
6103   void **slot;
6104 
6105   gdb_assert (cu->dwo_unit && per_objfile->per_bfd->using_index);
6106   gdb_assert (dwp_file != NULL);
6107 
6108   /* If TU skeletons have been removed then we may not have read in any
6109      TUs yet.  */
6110   if (per_objfile->per_bfd->signatured_types == NULL)
6111     per_objfile->per_bfd->signatured_types = allocate_signatured_type_table ();
6112 
6113   signatured_type find_sig_entry (sig);
6114   slot = htab_find_slot (per_objfile->per_bfd->signatured_types.get (),
6115 			 &find_sig_entry, INSERT);
6116   signatured_type *sig_entry = (struct signatured_type *) *slot;
6117 
6118   /* Have we already tried to read this TU?
6119      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6120      needn't exist in the global table yet).  */
6121   if (sig_entry != NULL)
6122     return sig_entry;
6123 
6124   if (dwp_file->tus == NULL)
6125     return NULL;
6126   dwo_entry = lookup_dwo_unit_in_dwp (per_objfile, dwp_file, NULL, sig,
6127 				      1 /* is_debug_types */);
6128   if (dwo_entry == NULL)
6129     return NULL;
6130 
6131   sig_entry = add_type_unit (per_objfile, sig, slot);
6132   fill_in_sig_entry_from_dwo_entry (per_objfile, sig_entry, dwo_entry);
6133 
6134   return sig_entry;
6135 }
6136 
6137 /* Lookup a signature based type for DW_FORM_ref_sig8.
6138    Returns NULL if signature SIG is not present in the table.
6139    It is up to the caller to complain about this.  */
6140 
6141 static struct signatured_type *
6142 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6143 {
6144   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6145 
6146   if (cu->dwo_unit && per_objfile->per_bfd->using_index)
6147     {
6148       /* We're in a DWO/DWP file, and we're using .gdb_index.
6149 	 These cases require special processing.  */
6150       if (get_dwp_file (per_objfile) == NULL)
6151 	return lookup_dwo_signatured_type (cu, sig);
6152       else
6153 	return lookup_dwp_signatured_type (cu, sig);
6154     }
6155   else
6156     {
6157       if (per_objfile->per_bfd->signatured_types == NULL)
6158 	return NULL;
6159       signatured_type find_entry (sig);
6160       return ((struct signatured_type *)
6161 	      htab_find (per_objfile->per_bfd->signatured_types.get (),
6162 			 &find_entry));
6163     }
6164 }
6165 
6166 /* Low level DIE reading support.  */
6167 
6168 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
6169 
6170 static void
6171 init_cu_die_reader (struct die_reader_specs *reader,
6172 		    struct dwarf2_cu *cu,
6173 		    struct dwarf2_section_info *section,
6174 		    struct dwo_file *dwo_file,
6175 		    struct abbrev_table *abbrev_table)
6176 {
6177   gdb_assert (section->readin && section->buffer != NULL);
6178   reader->abfd = section->get_bfd_owner ();
6179   reader->cu = cu;
6180   reader->dwo_file = dwo_file;
6181   reader->die_section = section;
6182   reader->buffer = section->buffer;
6183   reader->buffer_end = section->buffer + section->size;
6184   reader->abbrev_table = abbrev_table;
6185 }
6186 
6187 /* Subroutine of cutu_reader to simplify it.
6188    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
6189    There's just a lot of work to do, and cutu_reader is big enough
6190    already.
6191 
6192    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
6193    from it to the DIE in the DWO.  If NULL we are skipping the stub.
6194    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
6195    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
6196    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
6197    STUB_COMP_DIR may be non-NULL.
6198    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE
6199    are filled in with the info of the DIE from the DWO file.
6200    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
6201    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
6202    kept around for at least as long as *RESULT_READER.
6203 
6204    The result is non-zero if a valid (non-dummy) DIE was found.  */
6205 
6206 static int
6207 read_cutu_die_from_dwo (dwarf2_cu *cu,
6208 			struct dwo_unit *dwo_unit,
6209 			struct die_info *stub_comp_unit_die,
6210 			const char *stub_comp_dir,
6211 			struct die_reader_specs *result_reader,
6212 			const gdb_byte **result_info_ptr,
6213 			struct die_info **result_comp_unit_die,
6214 			abbrev_table_up *result_dwo_abbrev_table)
6215 {
6216   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6217   dwarf2_per_cu_data *per_cu = cu->per_cu;
6218   struct objfile *objfile = per_objfile->objfile;
6219   bfd *abfd;
6220   const gdb_byte *begin_info_ptr, *info_ptr;
6221   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
6222   int i,num_extra_attrs;
6223   struct dwarf2_section_info *dwo_abbrev_section;
6224   struct die_info *comp_unit_die;
6225 
6226   /* At most one of these may be provided.  */
6227   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
6228 
6229   /* These attributes aren't processed until later:
6230      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
6231      DW_AT_comp_dir is used now, to find the DWO file, but it is also
6232      referenced later.  However, these attributes are found in the stub
6233      which we won't have later.  In order to not impose this complication
6234      on the rest of the code, we read them here and copy them to the
6235      DWO CU/TU die.  */
6236 
6237   stmt_list = NULL;
6238   low_pc = NULL;
6239   high_pc = NULL;
6240   ranges = NULL;
6241   comp_dir = NULL;
6242 
6243   if (stub_comp_unit_die != NULL)
6244     {
6245       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
6246 	 DWO file.  */
6247       if (!per_cu->is_debug_types)
6248 	stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
6249       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
6250       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
6251       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
6252       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
6253 
6254       cu->addr_base = stub_comp_unit_die->addr_base ();
6255 
6256       /* There should be a DW_AT_GNU_ranges_base attribute here (if needed).
6257          We need the value before we can process DW_AT_ranges values from the
6258          DWO.  */
6259       cu->gnu_ranges_base = stub_comp_unit_die->gnu_ranges_base ();
6260 
6261       /* For DWARF5: record the DW_AT_rnglists_base value from the skeleton.  If
6262          there are attributes of form DW_FORM_rnglistx in the skeleton, they'll
6263          need the rnglists base.  Attributes of form DW_FORM_rnglistx in the
6264          split unit don't use it, as the DWO has its own .debug_rnglists.dwo
6265          section.  */
6266       cu->rnglists_base = stub_comp_unit_die->rnglists_base ();
6267     }
6268   else if (stub_comp_dir != NULL)
6269     {
6270       /* Reconstruct the comp_dir attribute to simplify the code below.  */
6271       comp_dir = OBSTACK_ZALLOC (&cu->comp_unit_obstack, struct attribute);
6272       comp_dir->name = DW_AT_comp_dir;
6273       comp_dir->form = DW_FORM_string;
6274       comp_dir->set_string_noncanonical (stub_comp_dir);
6275     }
6276 
6277   /* Set up for reading the DWO CU/TU.  */
6278   cu->dwo_unit = dwo_unit;
6279   dwarf2_section_info *section = dwo_unit->section;
6280   section->read (objfile);
6281   abfd = section->get_bfd_owner ();
6282   begin_info_ptr = info_ptr = (section->buffer
6283 			       + to_underlying (dwo_unit->sect_off));
6284   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
6285 
6286   if (per_cu->is_debug_types)
6287     {
6288       signatured_type *sig_type = (struct signatured_type *) per_cu;
6289 
6290       info_ptr = read_and_check_comp_unit_head (per_objfile, &cu->header,
6291 						section, dwo_abbrev_section,
6292 						info_ptr, rcuh_kind::TYPE);
6293       /* This is not an assert because it can be caused by bad debug info.  */
6294       if (sig_type->signature != cu->header.signature)
6295 	{
6296 	  error (_("Dwarf Error: signature mismatch %s vs %s while reading"
6297 		   " TU at offset %s [in module %s]"),
6298 		 hex_string (sig_type->signature),
6299 		 hex_string (cu->header.signature),
6300 		 sect_offset_str (dwo_unit->sect_off),
6301 		 bfd_get_filename (abfd));
6302 	}
6303       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6304       /* For DWOs coming from DWP files, we don't know the CU length
6305 	 nor the type's offset in the TU until now.  */
6306       dwo_unit->length = cu->header.get_length ();
6307       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
6308 
6309       /* Establish the type offset that can be used to lookup the type.
6310 	 For DWO files, we don't know it until now.  */
6311       sig_type->type_offset_in_section
6312 	= dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
6313     }
6314   else
6315     {
6316       info_ptr = read_and_check_comp_unit_head (per_objfile, &cu->header,
6317 						section, dwo_abbrev_section,
6318 						info_ptr, rcuh_kind::COMPILE);
6319       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6320       /* For DWOs coming from DWP files, we don't know the CU length
6321 	 until now.  */
6322       dwo_unit->length = cu->header.get_length ();
6323     }
6324 
6325   dwo_abbrev_section->read (objfile);
6326   *result_dwo_abbrev_table
6327     = abbrev_table::read (dwo_abbrev_section, cu->header.abbrev_sect_off);
6328   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
6329 		      result_dwo_abbrev_table->get ());
6330 
6331   /* Read in the die, but leave space to copy over the attributes
6332      from the stub.  This has the benefit of simplifying the rest of
6333      the code - all the work to maintain the illusion of a single
6334      DW_TAG_{compile,type}_unit DIE is done here.  */
6335   num_extra_attrs = ((stmt_list != NULL)
6336 		     + (low_pc != NULL)
6337 		     + (high_pc != NULL)
6338 		     + (ranges != NULL)
6339 		     + (comp_dir != NULL));
6340   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
6341 			      num_extra_attrs);
6342 
6343   /* Copy over the attributes from the stub to the DIE we just read in.  */
6344   comp_unit_die = *result_comp_unit_die;
6345   i = comp_unit_die->num_attrs;
6346   if (stmt_list != NULL)
6347     comp_unit_die->attrs[i++] = *stmt_list;
6348   if (low_pc != NULL)
6349     comp_unit_die->attrs[i++] = *low_pc;
6350   if (high_pc != NULL)
6351     comp_unit_die->attrs[i++] = *high_pc;
6352   if (ranges != NULL)
6353     comp_unit_die->attrs[i++] = *ranges;
6354   if (comp_dir != NULL)
6355     comp_unit_die->attrs[i++] = *comp_dir;
6356   comp_unit_die->num_attrs += num_extra_attrs;
6357 
6358   if (dwarf_die_debug)
6359     {
6360       fprintf_unfiltered (gdb_stdlog,
6361 			  "Read die from %s@0x%x of %s:\n",
6362 			  section->get_name (),
6363 			  (unsigned) (begin_info_ptr - section->buffer),
6364 			  bfd_get_filename (abfd));
6365       dump_die (comp_unit_die, dwarf_die_debug);
6366     }
6367 
6368   /* Skip dummy compilation units.  */
6369   if (info_ptr >= begin_info_ptr + dwo_unit->length
6370       || peek_abbrev_code (abfd, info_ptr) == 0)
6371     return 0;
6372 
6373   *result_info_ptr = info_ptr;
6374   return 1;
6375 }
6376 
6377 /* Return the signature of the compile unit, if found. In DWARF 4 and before,
6378    the signature is in the DW_AT_GNU_dwo_id attribute. In DWARF 5 and later, the
6379    signature is part of the header.  */
6380 static gdb::optional<ULONGEST>
6381 lookup_dwo_id (struct dwarf2_cu *cu, struct die_info* comp_unit_die)
6382 {
6383   if (cu->header.version >= 5)
6384     return cu->header.signature;
6385   struct attribute *attr;
6386   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
6387   if (attr == nullptr || !attr->form_is_unsigned ())
6388     return gdb::optional<ULONGEST> ();
6389   return attr->as_unsigned ();
6390 }
6391 
6392 /* Subroutine of cutu_reader to simplify it.
6393    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
6394    Returns NULL if the specified DWO unit cannot be found.  */
6395 
6396 static struct dwo_unit *
6397 lookup_dwo_unit (dwarf2_cu *cu, die_info *comp_unit_die, const char *dwo_name)
6398 {
6399   dwarf2_per_cu_data *per_cu = cu->per_cu;
6400   struct dwo_unit *dwo_unit;
6401   const char *comp_dir;
6402 
6403   gdb_assert (cu != NULL);
6404 
6405   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
6406   dwo_name = dwarf2_dwo_name (comp_unit_die, cu);
6407   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6408 
6409   if (per_cu->is_debug_types)
6410     dwo_unit = lookup_dwo_type_unit (cu, dwo_name, comp_dir);
6411   else
6412     {
6413       gdb::optional<ULONGEST> signature = lookup_dwo_id (cu, comp_unit_die);
6414 
6415       if (!signature.has_value ())
6416 	error (_("Dwarf Error: missing dwo_id for dwo_name %s"
6417 		 " [in module %s]"),
6418 	       dwo_name, bfd_get_filename (per_cu->per_bfd->obfd));
6419 
6420       dwo_unit = lookup_dwo_comp_unit (cu, dwo_name, comp_dir, *signature);
6421     }
6422 
6423   return dwo_unit;
6424 }
6425 
6426 /* Subroutine of cutu_reader to simplify it.
6427    See it for a description of the parameters.
6428    Read a TU directly from a DWO file, bypassing the stub.  */
6429 
6430 void
6431 cutu_reader::init_tu_and_read_dwo_dies (dwarf2_per_cu_data *this_cu,
6432 					dwarf2_per_objfile *per_objfile,
6433 					dwarf2_cu *existing_cu)
6434 {
6435   struct signatured_type *sig_type;
6436 
6437   /* Verify we can do the following downcast, and that we have the
6438      data we need.  */
6439   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
6440   sig_type = (struct signatured_type *) this_cu;
6441   gdb_assert (sig_type->dwo_unit != NULL);
6442 
6443   dwarf2_cu *cu;
6444 
6445   if (existing_cu != nullptr)
6446     {
6447       cu = existing_cu;
6448       gdb_assert (cu->dwo_unit == sig_type->dwo_unit);
6449       /* There's no need to do the rereading_dwo_cu handling that
6450 	 cutu_reader does since we don't read the stub.  */
6451     }
6452   else
6453     {
6454       /* If an existing_cu is provided, a dwarf2_cu must not exist for this_cu
6455 	 in per_objfile yet.  */
6456       gdb_assert (per_objfile->get_cu (this_cu) == nullptr);
6457       m_new_cu.reset (new dwarf2_cu (this_cu, per_objfile));
6458       cu = m_new_cu.get ();
6459     }
6460 
6461   /* A future optimization, if needed, would be to use an existing
6462      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
6463      could share abbrev tables.  */
6464 
6465   if (read_cutu_die_from_dwo (cu, sig_type->dwo_unit,
6466 			      NULL /* stub_comp_unit_die */,
6467 			      sig_type->dwo_unit->dwo_file->comp_dir,
6468 			      this, &info_ptr,
6469 			      &comp_unit_die,
6470 			      &m_dwo_abbrev_table) == 0)
6471     {
6472       /* Dummy die.  */
6473       dummy_p = true;
6474     }
6475 }
6476 
6477 /* Initialize a CU (or TU) and read its DIEs.
6478    If the CU defers to a DWO file, read the DWO file as well.
6479 
6480    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
6481    Otherwise the table specified in the comp unit header is read in and used.
6482    This is an optimization for when we already have the abbrev table.
6483 
6484    If EXISTING_CU is non-NULL, then use it.  Otherwise, a new CU is
6485    allocated.  */
6486 
6487 cutu_reader::cutu_reader (dwarf2_per_cu_data *this_cu,
6488 			  dwarf2_per_objfile *per_objfile,
6489 			  struct abbrev_table *abbrev_table,
6490 			  dwarf2_cu *existing_cu,
6491 			  bool skip_partial)
6492   : die_reader_specs {},
6493     m_this_cu (this_cu)
6494 {
6495   struct objfile *objfile = per_objfile->objfile;
6496   struct dwarf2_section_info *section = this_cu->section;
6497   bfd *abfd = section->get_bfd_owner ();
6498   const gdb_byte *begin_info_ptr;
6499   struct signatured_type *sig_type = NULL;
6500   struct dwarf2_section_info *abbrev_section;
6501   /* Non-zero if CU currently points to a DWO file and we need to
6502      reread it.  When this happens we need to reread the skeleton die
6503      before we can reread the DWO file (this only applies to CUs, not TUs).  */
6504   int rereading_dwo_cu = 0;
6505 
6506   if (dwarf_die_debug)
6507     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
6508 			this_cu->is_debug_types ? "type" : "comp",
6509 			sect_offset_str (this_cu->sect_off));
6510 
6511   /* If we're reading a TU directly from a DWO file, including a virtual DWO
6512      file (instead of going through the stub), short-circuit all of this.  */
6513   if (this_cu->reading_dwo_directly)
6514     {
6515       /* Narrow down the scope of possibilities to have to understand.  */
6516       gdb_assert (this_cu->is_debug_types);
6517       gdb_assert (abbrev_table == NULL);
6518       init_tu_and_read_dwo_dies (this_cu, per_objfile, existing_cu);
6519       return;
6520     }
6521 
6522   /* This is cheap if the section is already read in.  */
6523   section->read (objfile);
6524 
6525   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6526 
6527   abbrev_section = get_abbrev_section_for_cu (this_cu);
6528 
6529   dwarf2_cu *cu;
6530 
6531   if (existing_cu != nullptr)
6532     {
6533       cu = existing_cu;
6534       /* If this CU is from a DWO file we need to start over, we need to
6535 	 refetch the attributes from the skeleton CU.
6536 	 This could be optimized by retrieving those attributes from when we
6537 	 were here the first time: the previous comp_unit_die was stored in
6538 	 comp_unit_obstack.  But there's no data yet that we need this
6539 	 optimization.  */
6540       if (cu->dwo_unit != NULL)
6541 	rereading_dwo_cu = 1;
6542     }
6543   else
6544     {
6545       /* If an existing_cu is provided, a dwarf2_cu must not exist for this_cu
6546 	 in per_objfile yet.  */
6547       gdb_assert (per_objfile->get_cu (this_cu) == nullptr);
6548       m_new_cu.reset (new dwarf2_cu (this_cu, per_objfile));
6549       cu = m_new_cu.get ();
6550     }
6551 
6552   /* Get the header.  */
6553   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
6554     {
6555       /* We already have the header, there's no need to read it in again.  */
6556       info_ptr += to_underlying (cu->header.first_die_cu_offset);
6557     }
6558   else
6559     {
6560       if (this_cu->is_debug_types)
6561 	{
6562 	  info_ptr = read_and_check_comp_unit_head (per_objfile, &cu->header,
6563 						    section, abbrev_section,
6564 						    info_ptr, rcuh_kind::TYPE);
6565 
6566 	  /* Since per_cu is the first member of struct signatured_type,
6567 	     we can go from a pointer to one to a pointer to the other.  */
6568 	  sig_type = (struct signatured_type *) this_cu;
6569 	  gdb_assert (sig_type->signature == cu->header.signature);
6570 	  gdb_assert (sig_type->type_offset_in_tu
6571 		      == cu->header.type_cu_offset_in_tu);
6572 	  gdb_assert (this_cu->sect_off == cu->header.sect_off);
6573 
6574 	  /* LENGTH has not been set yet for type units if we're
6575 	     using .gdb_index.  */
6576 	  this_cu->length = cu->header.get_length ();
6577 
6578 	  /* Establish the type offset that can be used to lookup the type.  */
6579 	  sig_type->type_offset_in_section =
6580 	    this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
6581 
6582 	  this_cu->dwarf_version = cu->header.version;
6583 	}
6584       else
6585 	{
6586 	  info_ptr = read_and_check_comp_unit_head (per_objfile, &cu->header,
6587 						    section, abbrev_section,
6588 						    info_ptr,
6589 						    rcuh_kind::COMPILE);
6590 
6591 	  gdb_assert (this_cu->sect_off == cu->header.sect_off);
6592 	  if (this_cu->length == 0)
6593 	    this_cu->length = cu->header.get_length ();
6594 	  else
6595 	    gdb_assert (this_cu->length == cu->header.get_length ());
6596 	  this_cu->dwarf_version = cu->header.version;
6597 	}
6598     }
6599 
6600   /* Skip dummy compilation units.  */
6601   if (info_ptr >= begin_info_ptr + this_cu->length
6602       || peek_abbrev_code (abfd, info_ptr) == 0)
6603     {
6604       dummy_p = true;
6605       return;
6606     }
6607 
6608   /* If we don't have them yet, read the abbrevs for this compilation unit.
6609      And if we need to read them now, make sure they're freed when we're
6610      done.  */
6611   if (abbrev_table != NULL)
6612     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
6613   else
6614     {
6615       abbrev_section->read (objfile);
6616       m_abbrev_table_holder
6617 	= abbrev_table::read (abbrev_section, cu->header.abbrev_sect_off);
6618       abbrev_table = m_abbrev_table_holder.get ();
6619     }
6620 
6621   /* Read the top level CU/TU die.  */
6622   init_cu_die_reader (this, cu, section, NULL, abbrev_table);
6623   info_ptr = read_full_die (this, &comp_unit_die, info_ptr);
6624 
6625   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
6626     {
6627       dummy_p = true;
6628       return;
6629     }
6630 
6631   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
6632      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
6633      table from the DWO file and pass the ownership over to us.  It will be
6634      referenced from READER, so we must make sure to free it after we're done
6635      with READER.
6636 
6637      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
6638      DWO CU, that this test will fail (the attribute will not be present).  */
6639   const char *dwo_name = dwarf2_dwo_name (comp_unit_die, cu);
6640   if (dwo_name != nullptr)
6641     {
6642       struct dwo_unit *dwo_unit;
6643       struct die_info *dwo_comp_unit_die;
6644 
6645       if (comp_unit_die->has_children)
6646 	{
6647 	  complaint (_("compilation unit with DW_AT_GNU_dwo_name"
6648 		       " has children (offset %s) [in module %s]"),
6649 		     sect_offset_str (this_cu->sect_off),
6650 		     bfd_get_filename (abfd));
6651 	}
6652       dwo_unit = lookup_dwo_unit (cu, comp_unit_die, dwo_name);
6653       if (dwo_unit != NULL)
6654 	{
6655 	  if (read_cutu_die_from_dwo (cu, dwo_unit,
6656 				      comp_unit_die, NULL,
6657 				      this, &info_ptr,
6658 				      &dwo_comp_unit_die,
6659 				      &m_dwo_abbrev_table) == 0)
6660 	    {
6661 	      /* Dummy die.  */
6662 	      dummy_p = true;
6663 	      return;
6664 	    }
6665 	  comp_unit_die = dwo_comp_unit_die;
6666 	}
6667       else
6668 	{
6669 	  /* Yikes, we couldn't find the rest of the DIE, we only have
6670 	     the stub.  A complaint has already been logged.  There's
6671 	     not much more we can do except pass on the stub DIE to
6672 	     die_reader_func.  We don't want to throw an error on bad
6673 	     debug info.  */
6674 	}
6675     }
6676 }
6677 
6678 void
6679 cutu_reader::keep ()
6680 {
6681   /* Done, clean up.  */
6682   gdb_assert (!dummy_p);
6683   if (m_new_cu != NULL)
6684     {
6685       /* Save this dwarf2_cu in the per_objfile.  The per_objfile owns it
6686 	 now.  */
6687       dwarf2_per_objfile *per_objfile = m_new_cu->per_objfile;
6688       per_objfile->set_cu (m_this_cu, m_new_cu.release ());
6689     }
6690 }
6691 
6692 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name (DW_AT_dwo_name)
6693    if present. DWO_FILE, if non-NULL, is the DWO file to read (the caller is
6694    assumed to have already done the lookup to find the DWO file).
6695 
6696    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
6697    THIS_CU->is_debug_types, but nothing else.
6698 
6699    We fill in THIS_CU->length.
6700 
6701    THIS_CU->cu is always freed when done.
6702    This is done in order to not leave THIS_CU->cu in a state where we have
6703    to care whether it refers to the "main" CU or the DWO CU.
6704 
6705    When parent_cu is passed, it is used to provide a default value for
6706    str_offsets_base and addr_base from the parent.  */
6707 
6708 cutu_reader::cutu_reader (dwarf2_per_cu_data *this_cu,
6709 			  dwarf2_per_objfile *per_objfile,
6710 			  struct dwarf2_cu *parent_cu,
6711 			  struct dwo_file *dwo_file)
6712   : die_reader_specs {},
6713     m_this_cu (this_cu)
6714 {
6715   struct objfile *objfile = per_objfile->objfile;
6716   struct dwarf2_section_info *section = this_cu->section;
6717   bfd *abfd = section->get_bfd_owner ();
6718   struct dwarf2_section_info *abbrev_section;
6719   const gdb_byte *begin_info_ptr, *info_ptr;
6720 
6721   if (dwarf_die_debug)
6722     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
6723 			this_cu->is_debug_types ? "type" : "comp",
6724 			sect_offset_str (this_cu->sect_off));
6725 
6726   gdb_assert (per_objfile->get_cu (this_cu) == nullptr);
6727 
6728   abbrev_section = (dwo_file != NULL
6729 		    ? &dwo_file->sections.abbrev
6730 		    : get_abbrev_section_for_cu (this_cu));
6731 
6732   /* This is cheap if the section is already read in.  */
6733   section->read (objfile);
6734 
6735   m_new_cu.reset (new dwarf2_cu (this_cu, per_objfile));
6736 
6737   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6738   info_ptr = read_and_check_comp_unit_head (per_objfile, &m_new_cu->header,
6739 					    section, abbrev_section, info_ptr,
6740 					    (this_cu->is_debug_types
6741 					     ? rcuh_kind::TYPE
6742 					     : rcuh_kind::COMPILE));
6743 
6744   if (parent_cu != nullptr)
6745     {
6746       m_new_cu->str_offsets_base = parent_cu->str_offsets_base;
6747       m_new_cu->addr_base = parent_cu->addr_base;
6748     }
6749   this_cu->length = m_new_cu->header.get_length ();
6750 
6751   /* Skip dummy compilation units.  */
6752   if (info_ptr >= begin_info_ptr + this_cu->length
6753       || peek_abbrev_code (abfd, info_ptr) == 0)
6754     {
6755       dummy_p = true;
6756       return;
6757     }
6758 
6759   abbrev_section->read (objfile);
6760   m_abbrev_table_holder
6761     = abbrev_table::read (abbrev_section, m_new_cu->header.abbrev_sect_off);
6762 
6763   init_cu_die_reader (this, m_new_cu.get (), section, dwo_file,
6764 		      m_abbrev_table_holder.get ());
6765   info_ptr = read_full_die (this, &comp_unit_die, info_ptr);
6766 }
6767 
6768 
6769 /* Type Unit Groups.
6770 
6771    Type Unit Groups are a way to collapse the set of all TUs (type units) into
6772    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
6773    so that all types coming from the same compilation (.o file) are grouped
6774    together.  A future step could be to put the types in the same symtab as
6775    the CU the types ultimately came from.  */
6776 
6777 static hashval_t
6778 hash_type_unit_group (const void *item)
6779 {
6780   const struct type_unit_group *tu_group
6781     = (const struct type_unit_group *) item;
6782 
6783   return hash_stmt_list_entry (&tu_group->hash);
6784 }
6785 
6786 static int
6787 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6788 {
6789   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6790   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6791 
6792   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6793 }
6794 
6795 /* Allocate a hash table for type unit groups.  */
6796 
6797 static htab_up
6798 allocate_type_unit_groups_table ()
6799 {
6800   return htab_up (htab_create_alloc (3,
6801 				     hash_type_unit_group,
6802 				     eq_type_unit_group,
6803 				     htab_delete_entry<type_unit_group>,
6804 				     xcalloc, xfree));
6805 }
6806 
6807 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6808    partial symtabs.  We combine several TUs per psymtab to not let the size
6809    of any one psymtab grow too big.  */
6810 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6811 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6812 
6813 /* Helper routine for get_type_unit_group.
6814    Create the type_unit_group object used to hold one or more TUs.  */
6815 
6816 static std::unique_ptr<type_unit_group>
6817 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6818 {
6819   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6820   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
6821 
6822   std::unique_ptr<type_unit_group> tu_group (new type_unit_group);
6823   tu_group->per_bfd = per_bfd;
6824 
6825   if (per_bfd->using_index)
6826     {
6827       tu_group->v.quick = OBSTACK_ZALLOC (&per_bfd->obstack,
6828 					  struct dwarf2_per_cu_quick_data);
6829     }
6830   else
6831     {
6832       unsigned int line_offset = to_underlying (line_offset_struct);
6833       dwarf2_psymtab *pst;
6834       std::string name;
6835 
6836       /* Give the symtab a useful name for debug purposes.  */
6837       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6838 	name = string_printf ("<type_units_%d>",
6839 			      (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6840       else
6841 	name = string_printf ("<type_units_at_0x%x>", line_offset);
6842 
6843       pst = create_partial_symtab (tu_group.get (), per_objfile,
6844 				   name.c_str ());
6845       pst->anonymous = true;
6846     }
6847 
6848   tu_group->hash.dwo_unit = cu->dwo_unit;
6849   tu_group->hash.line_sect_off = line_offset_struct;
6850 
6851   return tu_group;
6852 }
6853 
6854 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6855    STMT_LIST is a DW_AT_stmt_list attribute.  */
6856 
6857 static struct type_unit_group *
6858 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6859 {
6860   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6861   struct tu_stats *tu_stats = &per_objfile->per_bfd->tu_stats;
6862   struct type_unit_group *tu_group;
6863   void **slot;
6864   unsigned int line_offset;
6865   struct type_unit_group type_unit_group_for_lookup;
6866 
6867   if (per_objfile->per_bfd->type_unit_groups == NULL)
6868     per_objfile->per_bfd->type_unit_groups = allocate_type_unit_groups_table ();
6869 
6870   /* Do we need to create a new group, or can we use an existing one?  */
6871 
6872   if (stmt_list != nullptr && stmt_list->form_is_unsigned ())
6873     {
6874       line_offset = stmt_list->as_unsigned ();
6875       ++tu_stats->nr_symtab_sharers;
6876     }
6877   else
6878     {
6879       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6880 	 We can do various things here like create one group per TU or
6881 	 spread them over multiple groups to split up the expansion work.
6882 	 To avoid worst case scenarios (too many groups or too large groups)
6883 	 we, umm, group them in bunches.  */
6884       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6885 		     | (tu_stats->nr_stmt_less_type_units
6886 			/ NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6887       ++tu_stats->nr_stmt_less_type_units;
6888     }
6889 
6890   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6891   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6892   slot = htab_find_slot (per_objfile->per_bfd->type_unit_groups.get (),
6893 			 &type_unit_group_for_lookup, INSERT);
6894   if (*slot == nullptr)
6895     {
6896       sect_offset line_offset_struct = (sect_offset) line_offset;
6897       std::unique_ptr<type_unit_group> grp
6898 	= create_type_unit_group (cu, line_offset_struct);
6899       *slot = grp.release ();
6900       ++tu_stats->nr_symtabs;
6901     }
6902 
6903   tu_group = (struct type_unit_group *) *slot;
6904   gdb_assert (tu_group != nullptr);
6905   return tu_group;
6906 }
6907 
6908 /* Partial symbol tables.  */
6909 
6910 /* Create a psymtab named NAME and assign it to PER_CU.
6911 
6912    The caller must fill in the following details:
6913    dirname, textlow, texthigh.  */
6914 
6915 static dwarf2_psymtab *
6916 create_partial_symtab (dwarf2_per_cu_data *per_cu,
6917 		       dwarf2_per_objfile *per_objfile,
6918 		       const char *name)
6919 {
6920   dwarf2_psymtab *pst
6921     = new dwarf2_psymtab (name, per_objfile->per_bfd->partial_symtabs.get (),
6922 			  per_objfile->objfile->per_bfd, per_cu);
6923 
6924   pst->psymtabs_addrmap_supported = true;
6925 
6926   /* This is the glue that links PST into GDB's symbol API.  */
6927   per_cu->v.psymtab = pst;
6928 
6929   return pst;
6930 }
6931 
6932 /* DIE reader function for process_psymtab_comp_unit.  */
6933 
6934 static void
6935 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6936 				  const gdb_byte *info_ptr,
6937 				  struct die_info *comp_unit_die,
6938 				  enum language pretend_language)
6939 {
6940   struct dwarf2_cu *cu = reader->cu;
6941   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6942   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
6943   struct objfile *objfile = per_objfile->objfile;
6944   struct gdbarch *gdbarch = objfile->arch ();
6945   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6946   CORE_ADDR baseaddr;
6947   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6948   dwarf2_psymtab *pst;
6949   enum pc_bounds_kind cu_bounds_kind;
6950   const char *filename;
6951 
6952   gdb_assert (! per_cu->is_debug_types);
6953 
6954   prepare_one_comp_unit (cu, comp_unit_die, pretend_language);
6955 
6956   /* Allocate a new partial symbol table structure.  */
6957   gdb::unique_xmalloc_ptr<char> debug_filename;
6958   static const char artificial[] = "<artificial>";
6959   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
6960   if (filename == NULL)
6961     filename = "";
6962   else if (strcmp (filename, artificial) == 0)
6963     {
6964       debug_filename.reset (concat (artificial, "@",
6965 				    sect_offset_str (per_cu->sect_off),
6966 				    (char *) NULL));
6967       filename = debug_filename.get ();
6968     }
6969 
6970   pst = create_partial_symtab (per_cu, per_objfile, filename);
6971 
6972   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6973   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6974 
6975   baseaddr = objfile->text_section_offset ();
6976 
6977   dwarf2_find_base_address (comp_unit_die, cu);
6978 
6979   /* Possibly set the default values of LOWPC and HIGHPC from
6980      `DW_AT_ranges'.  */
6981   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6982 					 &best_highpc, cu, pst);
6983   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6984     {
6985       CORE_ADDR low
6986 	= (gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr)
6987 	   - baseaddr);
6988       CORE_ADDR high
6989 	= (gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr)
6990 	   - baseaddr - 1);
6991       /* Store the contiguous range if it is not empty; it can be
6992 	 empty for CUs with no code.  */
6993       addrmap_set_empty (per_bfd->partial_symtabs->psymtabs_addrmap,
6994 			 low, high, pst);
6995     }
6996 
6997   /* Check if comp unit has_children.
6998      If so, read the rest of the partial symbols from this comp unit.
6999      If not, there's no more debug_info for this comp unit.  */
7000   if (comp_unit_die->has_children)
7001     {
7002       struct partial_die_info *first_die;
7003       CORE_ADDR lowpc, highpc;
7004 
7005       lowpc = ((CORE_ADDR) -1);
7006       highpc = ((CORE_ADDR) 0);
7007 
7008       first_die = load_partial_dies (reader, info_ptr, 1);
7009 
7010       scan_partial_symbols (first_die, &lowpc, &highpc,
7011 			    cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7012 
7013       /* If we didn't find a lowpc, set it to highpc to avoid
7014 	 complaints from `maint check'.	 */
7015       if (lowpc == ((CORE_ADDR) -1))
7016 	lowpc = highpc;
7017 
7018       /* If the compilation unit didn't have an explicit address range,
7019 	 then use the information extracted from its child dies.  */
7020       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7021 	{
7022 	  best_lowpc = lowpc;
7023 	  best_highpc = highpc;
7024 	}
7025     }
7026   pst->set_text_low (gdbarch_adjust_dwarf2_addr (gdbarch,
7027 						 best_lowpc + baseaddr)
7028 		     - baseaddr);
7029   pst->set_text_high (gdbarch_adjust_dwarf2_addr (gdbarch,
7030 						  best_highpc + baseaddr)
7031 		      - baseaddr);
7032 
7033   pst->end ();
7034 
7035   if (!cu->per_cu->imported_symtabs_empty ())
7036     {
7037       int i;
7038       int len = cu->per_cu->imported_symtabs_size ();
7039 
7040       /* Fill in 'dependencies' here; we fill in 'users' in a
7041 	 post-pass.  */
7042       pst->number_of_dependencies = len;
7043       pst->dependencies
7044 	= per_bfd->partial_symtabs->allocate_dependencies (len);
7045       for (i = 0; i < len; ++i)
7046 	{
7047 	  pst->dependencies[i]
7048 	    = cu->per_cu->imported_symtabs->at (i)->v.psymtab;
7049 	}
7050 
7051       cu->per_cu->imported_symtabs_free ();
7052     }
7053 
7054   /* Get the list of files included in the current compilation unit,
7055      and build a psymtab for each of them.  */
7056   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
7057 
7058   dwarf_read_debug_printf ("Psymtab for %s unit @%s: %s - %s"
7059 			   ", %d global, %d static syms",
7060 			   per_cu->is_debug_types ? "type" : "comp",
7061 			   sect_offset_str (per_cu->sect_off),
7062 			   paddress (gdbarch, pst->text_low (objfile)),
7063 			   paddress (gdbarch, pst->text_high (objfile)),
7064 			   (int) pst->global_psymbols.size (),
7065 			   (int) pst->static_psymbols.size ());
7066 }
7067 
7068 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
7069    Process compilation unit THIS_CU for a psymtab.  */
7070 
7071 static void
7072 process_psymtab_comp_unit (dwarf2_per_cu_data *this_cu,
7073 			   dwarf2_per_objfile *per_objfile,
7074 			   bool want_partial_unit,
7075 			   enum language pretend_language)
7076 {
7077   /* If this compilation unit was already read in, free the
7078      cached copy in order to read it in again.	This is
7079      necessary because we skipped some symbols when we first
7080      read in the compilation unit (see load_partial_dies).
7081      This problem could be avoided, but the benefit is unclear.  */
7082   per_objfile->remove_cu (this_cu);
7083 
7084   cutu_reader reader (this_cu, per_objfile, nullptr, nullptr, false);
7085 
7086   if (reader.comp_unit_die == nullptr)
7087     return;
7088 
7089   switch (reader.comp_unit_die->tag)
7090     {
7091     case DW_TAG_compile_unit:
7092       this_cu->unit_type = DW_UT_compile;
7093       break;
7094     case DW_TAG_partial_unit:
7095       this_cu->unit_type = DW_UT_partial;
7096       break;
7097     case DW_TAG_type_unit:
7098       this_cu->unit_type = DW_UT_type;
7099       break;
7100     default:
7101       error (_("Dwarf Error: unexpected tag '%s' at offset %s [in module %s]"),
7102 	     dwarf_tag_name (reader.comp_unit_die->tag),
7103 	     sect_offset_str (reader.cu->per_cu->sect_off),
7104 	     objfile_name (per_objfile->objfile));
7105     }
7106 
7107   if (reader.dummy_p)
7108     {
7109       /* Nothing.  */
7110     }
7111   else if (this_cu->is_debug_types)
7112     build_type_psymtabs_reader (&reader, reader.info_ptr,
7113 				reader.comp_unit_die);
7114   else if (want_partial_unit
7115 	   || reader.comp_unit_die->tag != DW_TAG_partial_unit)
7116     process_psymtab_comp_unit_reader (&reader, reader.info_ptr,
7117 				      reader.comp_unit_die,
7118 				      pretend_language);
7119 
7120   /* Age out any secondary CUs.  */
7121   per_objfile->age_comp_units ();
7122 }
7123 
7124 /* Reader function for build_type_psymtabs.  */
7125 
7126 static void
7127 build_type_psymtabs_reader (const struct die_reader_specs *reader,
7128 			    const gdb_byte *info_ptr,
7129 			    struct die_info *type_unit_die)
7130 {
7131   dwarf2_per_objfile *per_objfile = reader->cu->per_objfile;
7132   struct dwarf2_cu *cu = reader->cu;
7133   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7134   struct signatured_type *sig_type;
7135   struct type_unit_group *tu_group;
7136   struct attribute *attr;
7137   struct partial_die_info *first_die;
7138   CORE_ADDR lowpc, highpc;
7139   dwarf2_psymtab *pst;
7140 
7141   gdb_assert (per_cu->is_debug_types);
7142   sig_type = (struct signatured_type *) per_cu;
7143 
7144   if (! type_unit_die->has_children)
7145     return;
7146 
7147   attr = type_unit_die->attr (DW_AT_stmt_list);
7148   tu_group = get_type_unit_group (cu, attr);
7149 
7150   if (tu_group->tus == nullptr)
7151     tu_group->tus = new std::vector<signatured_type *>;
7152   tu_group->tus->push_back (sig_type);
7153 
7154   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
7155   pst = create_partial_symtab (per_cu, per_objfile, "");
7156   pst->anonymous = true;
7157 
7158   first_die = load_partial_dies (reader, info_ptr, 1);
7159 
7160   lowpc = (CORE_ADDR) -1;
7161   highpc = (CORE_ADDR) 0;
7162   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
7163 
7164   pst->end ();
7165 }
7166 
7167 /* Struct used to sort TUs by their abbreviation table offset.  */
7168 
7169 struct tu_abbrev_offset
7170 {
7171   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
7172   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
7173   {}
7174 
7175   /* This is used when sorting.  */
7176   bool operator< (const tu_abbrev_offset &other) const
7177   {
7178     return abbrev_offset < other.abbrev_offset;
7179   }
7180 
7181   signatured_type *sig_type;
7182   sect_offset abbrev_offset;
7183 };
7184 
7185 /* Efficiently read all the type units.
7186 
7187    The efficiency is because we sort TUs by the abbrev table they use and
7188    only read each abbrev table once.  In one program there are 200K TUs
7189    sharing 8K abbrev tables.
7190 
7191    The main purpose of this function is to support building the
7192    dwarf2_per_objfile->per_bfd->type_unit_groups table.
7193    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
7194    can collapse the search space by grouping them by stmt_list.
7195    The savings can be significant, in the same program from above the 200K TUs
7196    share 8K stmt_list tables.
7197 
7198    FUNC is expected to call get_type_unit_group, which will create the
7199    struct type_unit_group if necessary and add it to
7200    dwarf2_per_objfile->per_bfd->type_unit_groups.  */
7201 
7202 static void
7203 build_type_psymtabs (dwarf2_per_objfile *per_objfile)
7204 {
7205   struct tu_stats *tu_stats = &per_objfile->per_bfd->tu_stats;
7206   abbrev_table_up abbrev_table;
7207   sect_offset abbrev_offset;
7208 
7209   /* It's up to the caller to not call us multiple times.  */
7210   gdb_assert (per_objfile->per_bfd->type_unit_groups == NULL);
7211 
7212   if (per_objfile->per_bfd->tu_stats.nr_tus == 0)
7213     return;
7214 
7215   /* TUs typically share abbrev tables, and there can be way more TUs than
7216      abbrev tables.  Sort by abbrev table to reduce the number of times we
7217      read each abbrev table in.
7218      Alternatives are to punt or to maintain a cache of abbrev tables.
7219      This is simpler and efficient enough for now.
7220 
7221      Later we group TUs by their DW_AT_stmt_list value (as this defines the
7222      symtab to use).  Typically TUs with the same abbrev offset have the same
7223      stmt_list value too so in practice this should work well.
7224 
7225      The basic algorithm here is:
7226 
7227       sort TUs by abbrev table
7228       for each TU with same abbrev table:
7229 	read abbrev table if first user
7230 	read TU top level DIE
7231 	  [IWBN if DWO skeletons had DW_AT_stmt_list]
7232 	call FUNC  */
7233 
7234   dwarf_read_debug_printf ("Building type unit groups ...");
7235 
7236   /* Sort in a separate table to maintain the order of all_comp_units
7237      for .gdb_index: TU indices directly index all_type_units.  */
7238   std::vector<tu_abbrev_offset> sorted_by_abbrev;
7239   sorted_by_abbrev.reserve (per_objfile->per_bfd->tu_stats.nr_tus);
7240 
7241   for (const auto &cu : per_objfile->per_bfd->all_comp_units)
7242     {
7243       if (cu->is_debug_types)
7244 	{
7245 	  auto sig_type = static_cast<signatured_type *> (cu.get ());
7246 	  sorted_by_abbrev.emplace_back
7247 	    (sig_type, read_abbrev_offset (per_objfile, sig_type->section,
7248 					   sig_type->sect_off));
7249 	}
7250     }
7251 
7252   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end ());
7253 
7254   abbrev_offset = (sect_offset) ~(unsigned) 0;
7255 
7256   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
7257     {
7258       /* Switch to the next abbrev table if necessary.  */
7259       if (abbrev_table == NULL
7260 	  || tu.abbrev_offset != abbrev_offset)
7261 	{
7262 	  abbrev_offset = tu.abbrev_offset;
7263 	  per_objfile->per_bfd->abbrev.read (per_objfile->objfile);
7264 	  abbrev_table =
7265 	    abbrev_table::read (&per_objfile->per_bfd->abbrev, abbrev_offset);
7266 	  ++tu_stats->nr_uniq_abbrev_tables;
7267 	}
7268 
7269       cutu_reader reader (tu.sig_type, per_objfile,
7270 			  abbrev_table.get (), nullptr, false);
7271       if (!reader.dummy_p)
7272 	build_type_psymtabs_reader (&reader, reader.info_ptr,
7273 				    reader.comp_unit_die);
7274     }
7275 }
7276 
7277 /* Print collected type unit statistics.  */
7278 
7279 static void
7280 print_tu_stats (dwarf2_per_objfile *per_objfile)
7281 {
7282   struct tu_stats *tu_stats = &per_objfile->per_bfd->tu_stats;
7283 
7284   dwarf_read_debug_printf ("Type unit statistics:");
7285   dwarf_read_debug_printf ("  %d TUs", tu_stats->nr_tus);
7286   dwarf_read_debug_printf ("  %d uniq abbrev tables",
7287 			   tu_stats->nr_uniq_abbrev_tables);
7288   dwarf_read_debug_printf ("  %d symtabs from stmt_list entries",
7289 			   tu_stats->nr_symtabs);
7290   dwarf_read_debug_printf ("  %d symtab sharers",
7291 			   tu_stats->nr_symtab_sharers);
7292   dwarf_read_debug_printf ("  %d type units without a stmt_list",
7293 			   tu_stats->nr_stmt_less_type_units);
7294   dwarf_read_debug_printf ("  %d all_type_units reallocs",
7295 			   tu_stats->nr_all_type_units_reallocs);
7296 }
7297 
7298 /* Traversal function for build_type_psymtabs.  */
7299 
7300 static int
7301 build_type_psymtab_dependencies (void **slot, void *info)
7302 {
7303   dwarf2_per_objfile *per_objfile = (dwarf2_per_objfile *) info;
7304   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
7305   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
7306   dwarf2_psymtab *pst = tu_group->v.psymtab;
7307   int len = (tu_group->tus == nullptr) ? 0 : tu_group->tus->size ();
7308   int i;
7309 
7310   gdb_assert (len > 0);
7311   gdb_assert (tu_group->type_unit_group_p ());
7312 
7313   pst->number_of_dependencies = len;
7314   pst->dependencies = per_bfd->partial_symtabs->allocate_dependencies (len);
7315   for (i = 0; i < len; ++i)
7316     {
7317       struct signatured_type *iter = tu_group->tus->at (i);
7318       gdb_assert (iter->is_debug_types);
7319       pst->dependencies[i] = iter->v.psymtab;
7320       iter->type_unit_group = tu_group;
7321     }
7322 
7323   delete tu_group->tus;
7324   tu_group->tus = nullptr;
7325 
7326   return 1;
7327 }
7328 
7329 /* Traversal function for process_skeletonless_type_unit.
7330    Read a TU in a DWO file and build partial symbols for it.  */
7331 
7332 static int
7333 process_skeletonless_type_unit (void **slot, void *info)
7334 {
7335   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
7336   dwarf2_per_objfile *per_objfile = (dwarf2_per_objfile *) info;
7337 
7338   /* If this TU doesn't exist in the global table, add it and read it in.  */
7339 
7340   if (per_objfile->per_bfd->signatured_types == NULL)
7341     per_objfile->per_bfd->signatured_types = allocate_signatured_type_table ();
7342 
7343   signatured_type find_entry (dwo_unit->signature);
7344   slot = htab_find_slot (per_objfile->per_bfd->signatured_types.get (),
7345 			 &find_entry, INSERT);
7346   /* If we've already seen this type there's nothing to do.  What's happening
7347      is we're doing our own version of comdat-folding here.  */
7348   if (*slot != NULL)
7349     return 1;
7350 
7351   /* This does the job that create_all_comp_units would have done for
7352      this TU.  */
7353   signatured_type *entry
7354     = add_type_unit (per_objfile, dwo_unit->signature, slot);
7355   fill_in_sig_entry_from_dwo_entry (per_objfile, entry, dwo_unit);
7356   *slot = entry;
7357 
7358   /* This does the job that build_type_psymtabs would have done.  */
7359   cutu_reader reader (entry, per_objfile, nullptr, nullptr, false);
7360   if (!reader.dummy_p)
7361     build_type_psymtabs_reader (&reader, reader.info_ptr,
7362 				reader.comp_unit_die);
7363 
7364   return 1;
7365 }
7366 
7367 /* Traversal function for process_skeletonless_type_units.  */
7368 
7369 static int
7370 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
7371 {
7372   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
7373 
7374   if (dwo_file->tus != NULL)
7375     htab_traverse_noresize (dwo_file->tus.get (),
7376 			    process_skeletonless_type_unit, info);
7377 
7378   return 1;
7379 }
7380 
7381 /* Scan all TUs of DWO files, verifying we've processed them.
7382    This is needed in case a TU was emitted without its skeleton.
7383    Note: This can't be done until we know what all the DWO files are.  */
7384 
7385 static void
7386 process_skeletonless_type_units (dwarf2_per_objfile *per_objfile)
7387 {
7388   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
7389   if (get_dwp_file (per_objfile) == NULL
7390       && per_objfile->per_bfd->dwo_files != NULL)
7391     {
7392       htab_traverse_noresize (per_objfile->per_bfd->dwo_files.get (),
7393 			      process_dwo_file_for_skeletonless_type_units,
7394 			      per_objfile);
7395     }
7396 }
7397 
7398 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
7399 
7400 static void
7401 set_partial_user (dwarf2_per_objfile *per_objfile)
7402 {
7403   for (const auto &per_cu : per_objfile->per_bfd->all_comp_units)
7404     {
7405       dwarf2_psymtab *pst = per_cu->v.psymtab;
7406 
7407       if (pst == NULL)
7408 	continue;
7409 
7410       for (int j = 0; j < pst->number_of_dependencies; ++j)
7411 	{
7412 	  /* Set the 'user' field only if it is not already set.  */
7413 	  if (pst->dependencies[j]->user == NULL)
7414 	    pst->dependencies[j]->user = pst;
7415 	}
7416     }
7417 }
7418 
7419 /* Build the partial symbol table by doing a quick pass through the
7420    .debug_info and .debug_abbrev sections.  */
7421 
7422 static void
7423 dwarf2_build_psymtabs_hard (dwarf2_per_objfile *per_objfile)
7424 {
7425   struct objfile *objfile = per_objfile->objfile;
7426   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
7427 
7428   dwarf_read_debug_printf ("Building psymtabs of objfile %s ...",
7429 			   objfile_name (objfile));
7430 
7431   scoped_restore restore_reading_psyms
7432     = make_scoped_restore (&per_bfd->reading_partial_symbols, true);
7433 
7434   per_bfd->info.read (objfile);
7435 
7436   /* Any cached compilation units will be linked by the per-objfile
7437      read_in_chain.  Make sure to free them when we're done.  */
7438   free_cached_comp_units freer (per_objfile);
7439 
7440   create_all_comp_units (per_objfile);
7441   build_type_psymtabs (per_objfile);
7442 
7443   /* Create a temporary address map on a temporary obstack.  We later
7444      copy this to the final obstack.  */
7445   auto_obstack temp_obstack;
7446 
7447   scoped_restore save_psymtabs_addrmap
7448     = make_scoped_restore (&per_bfd->partial_symtabs->psymtabs_addrmap,
7449 			   addrmap_create_mutable (&temp_obstack));
7450 
7451   for (const auto &per_cu : per_bfd->all_comp_units)
7452     {
7453       if (per_cu->v.psymtab != NULL)
7454 	/* In case a forward DW_TAG_imported_unit has read the CU already.  */
7455 	continue;
7456       process_psymtab_comp_unit (per_cu.get (), per_objfile, false,
7457 				 language_minimal);
7458     }
7459 
7460   /* This has to wait until we read the CUs, we need the list of DWOs.  */
7461   process_skeletonless_type_units (per_objfile);
7462 
7463   /* Now that all TUs have been processed we can fill in the dependencies.  */
7464   if (per_bfd->type_unit_groups != NULL)
7465     {
7466       htab_traverse_noresize (per_bfd->type_unit_groups.get (),
7467 			      build_type_psymtab_dependencies, per_objfile);
7468     }
7469 
7470   if (dwarf_read_debug > 0)
7471     print_tu_stats (per_objfile);
7472 
7473   set_partial_user (per_objfile);
7474 
7475   per_bfd->partial_symtabs->psymtabs_addrmap
7476     = addrmap_create_fixed (per_bfd->partial_symtabs->psymtabs_addrmap,
7477 			    per_bfd->partial_symtabs->obstack ());
7478   /* At this point we want to keep the address map.  */
7479   save_psymtabs_addrmap.release ();
7480 
7481   dwarf_read_debug_printf ("Done building psymtabs of %s",
7482 			   objfile_name (objfile));
7483 }
7484 
7485 /* Load the partial DIEs for a secondary CU into memory.
7486    This is also used when rereading a primary CU with load_all_dies.  */
7487 
7488 static void
7489 load_partial_comp_unit (dwarf2_per_cu_data *this_cu,
7490 			dwarf2_per_objfile *per_objfile,
7491 			dwarf2_cu *existing_cu)
7492 {
7493   cutu_reader reader (this_cu, per_objfile, nullptr, existing_cu, false);
7494 
7495   if (!reader.dummy_p)
7496     {
7497       prepare_one_comp_unit (reader.cu, reader.comp_unit_die,
7498 			     language_minimal);
7499 
7500       /* Check if comp unit has_children.
7501 	 If so, read the rest of the partial symbols from this comp unit.
7502 	 If not, there's no more debug_info for this comp unit.  */
7503       if (reader.comp_unit_die->has_children)
7504 	load_partial_dies (&reader, reader.info_ptr, 0);
7505 
7506       reader.keep ();
7507     }
7508 }
7509 
7510 static void
7511 read_comp_units_from_section (dwarf2_per_objfile *per_objfile,
7512 			      struct dwarf2_section_info *section,
7513 			      struct dwarf2_section_info *abbrev_section,
7514 			      unsigned int is_dwz,
7515 			      htab_up &types_htab,
7516 			      rcuh_kind section_kind)
7517 {
7518   const gdb_byte *info_ptr;
7519   struct objfile *objfile = per_objfile->objfile;
7520 
7521   dwarf_read_debug_printf ("Reading %s for %s",
7522 			   section->get_name (),
7523 			   section->get_file_name ());
7524 
7525   section->read (objfile);
7526 
7527   info_ptr = section->buffer;
7528 
7529   while (info_ptr < section->buffer + section->size)
7530     {
7531       dwarf2_per_cu_data_up this_cu;
7532 
7533       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
7534 
7535       comp_unit_head cu_header;
7536       read_and_check_comp_unit_head (per_objfile, &cu_header, section,
7537 				     abbrev_section, info_ptr,
7538 				     section_kind);
7539 
7540       /* Save the compilation unit for later lookup.  */
7541       if (cu_header.unit_type != DW_UT_type)
7542 	this_cu = per_objfile->per_bfd->allocate_per_cu ();
7543       else
7544 	{
7545 	  if (types_htab == nullptr)
7546 	    types_htab = allocate_signatured_type_table ();
7547 
7548 	  auto sig_type = per_objfile->per_bfd->allocate_signatured_type
7549 	    (cu_header.signature);
7550 	  signatured_type *sig_ptr = sig_type.get ();
7551 	  sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
7552 	  this_cu.reset (sig_type.release ());
7553 
7554 	  void **slot = htab_find_slot (types_htab.get (), sig_ptr, INSERT);
7555 	  gdb_assert (slot != nullptr);
7556 	  if (*slot != nullptr)
7557 	    complaint (_("debug type entry at offset %s is duplicate to"
7558 			 " the entry at offset %s, signature %s"),
7559 		       sect_offset_str (sect_off),
7560 		       sect_offset_str (sig_ptr->sect_off),
7561 		       hex_string (sig_ptr->signature));
7562 	  *slot = sig_ptr;
7563 	}
7564       this_cu->sect_off = sect_off;
7565       this_cu->length = cu_header.length + cu_header.initial_length_size;
7566       this_cu->is_dwz = is_dwz;
7567       this_cu->section = section;
7568 
7569       info_ptr = info_ptr + this_cu->length;
7570       per_objfile->per_bfd->all_comp_units.push_back (std::move (this_cu));
7571     }
7572 }
7573 
7574 /* Create a list of all compilation units in OBJFILE.
7575    This is only done for -readnow and building partial symtabs.  */
7576 
7577 static void
7578 create_all_comp_units (dwarf2_per_objfile *per_objfile)
7579 {
7580   htab_up types_htab;
7581 
7582   read_comp_units_from_section (per_objfile, &per_objfile->per_bfd->info,
7583 				&per_objfile->per_bfd->abbrev, 0,
7584 				types_htab, rcuh_kind::COMPILE);
7585   for (dwarf2_section_info &section : per_objfile->per_bfd->types)
7586     read_comp_units_from_section (per_objfile, &section,
7587 				  &per_objfile->per_bfd->abbrev, 0,
7588 				  types_htab, rcuh_kind::TYPE);
7589 
7590   dwz_file *dwz = dwarf2_get_dwz_file (per_objfile->per_bfd);
7591   if (dwz != NULL)
7592     read_comp_units_from_section (per_objfile, &dwz->info, &dwz->abbrev, 1,
7593 				  types_htab, rcuh_kind::COMPILE);
7594 
7595   per_objfile->per_bfd->signatured_types = std::move (types_htab);
7596 }
7597 
7598 /* Process all loaded DIEs for compilation unit CU, starting at
7599    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
7600    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
7601    DW_AT_ranges).  See the comments of add_partial_subprogram on how
7602    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
7603 
7604 static void
7605 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
7606 		      CORE_ADDR *highpc, int set_addrmap,
7607 		      struct dwarf2_cu *cu)
7608 {
7609   struct partial_die_info *pdi;
7610 
7611   /* Now, march along the PDI's, descending into ones which have
7612      interesting children but skipping the children of the other ones,
7613      until we reach the end of the compilation unit.  */
7614 
7615   pdi = first_die;
7616 
7617   while (pdi != NULL)
7618     {
7619       pdi->fixup (cu);
7620 
7621       /* Anonymous namespaces or modules have no name but have interesting
7622 	 children, so we need to look at them.  Ditto for anonymous
7623 	 enums.  */
7624 
7625       if (pdi->raw_name != NULL || pdi->tag == DW_TAG_namespace
7626 	  || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
7627 	  || pdi->tag == DW_TAG_imported_unit
7628 	  || pdi->tag == DW_TAG_inlined_subroutine)
7629 	{
7630 	  switch (pdi->tag)
7631 	    {
7632 	    case DW_TAG_subprogram:
7633 	    case DW_TAG_inlined_subroutine:
7634 	      add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7635 	      if (cu->per_cu->lang == language_cplus)
7636 		scan_partial_symbols (pdi->die_child, lowpc, highpc,
7637 				      set_addrmap, cu);
7638 	      break;
7639 	    case DW_TAG_constant:
7640 	    case DW_TAG_variable:
7641 	    case DW_TAG_typedef:
7642 	    case DW_TAG_union_type:
7643 	      if (!pdi->is_declaration
7644 		  || (pdi->tag == DW_TAG_variable && pdi->is_external))
7645 		{
7646 		  add_partial_symbol (pdi, cu);
7647 		}
7648 	      break;
7649 	    case DW_TAG_class_type:
7650 	    case DW_TAG_interface_type:
7651 	    case DW_TAG_structure_type:
7652 	      if (!pdi->is_declaration)
7653 		{
7654 		  add_partial_symbol (pdi, cu);
7655 		}
7656 	      if ((cu->per_cu->lang == language_rust
7657 		   || cu->per_cu->lang == language_cplus)
7658 		  && pdi->has_children)
7659 		scan_partial_symbols (pdi->die_child, lowpc, highpc,
7660 				      set_addrmap, cu);
7661 	      break;
7662 	    case DW_TAG_enumeration_type:
7663 	      if (!pdi->is_declaration)
7664 		add_partial_enumeration (pdi, cu);
7665 	      break;
7666 	    case DW_TAG_base_type:
7667 	    case DW_TAG_subrange_type:
7668 	      /* File scope base type definitions are added to the partial
7669 		 symbol table.  */
7670 	      add_partial_symbol (pdi, cu);
7671 	      break;
7672 	    case DW_TAG_namespace:
7673 	      add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
7674 	      break;
7675 	    case DW_TAG_module:
7676 	      if (!pdi->is_declaration)
7677 		add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
7678 	      break;
7679 	    case DW_TAG_imported_unit:
7680 	      {
7681 		struct dwarf2_per_cu_data *per_cu;
7682 
7683 		/* For now we don't handle imported units in type units.  */
7684 		if (cu->per_cu->is_debug_types)
7685 		  {
7686 		    error (_("Dwarf Error: DW_TAG_imported_unit is not"
7687 			     " supported in type units [in module %s]"),
7688 			   objfile_name (cu->per_objfile->objfile));
7689 		  }
7690 
7691 		per_cu = dwarf2_find_containing_comp_unit
7692 			   (pdi->d.sect_off, pdi->is_dwz, cu->per_objfile);
7693 
7694 		/* Go read the partial unit, if needed.  */
7695 		if (per_cu->v.psymtab == NULL)
7696 		  process_psymtab_comp_unit (per_cu, cu->per_objfile, true,
7697 					     cu->per_cu->lang);
7698 
7699 		cu->per_cu->imported_symtabs_push (per_cu);
7700 	      }
7701 	      break;
7702 	    case DW_TAG_imported_declaration:
7703 	      add_partial_symbol (pdi, cu);
7704 	      break;
7705 	    default:
7706 	      break;
7707 	    }
7708 	}
7709 
7710       /* If the die has a sibling, skip to the sibling.  */
7711 
7712       pdi = pdi->die_sibling;
7713     }
7714 }
7715 
7716 /* Functions used to compute the fully scoped name of a partial DIE.
7717 
7718    Normally, this is simple.  For C++, the parent DIE's fully scoped
7719    name is concatenated with "::" and the partial DIE's name.
7720    Enumerators are an exception; they use the scope of their parent
7721    enumeration type, i.e. the name of the enumeration type is not
7722    prepended to the enumerator.
7723 
7724    There are two complexities.  One is DW_AT_specification; in this
7725    case "parent" means the parent of the target of the specification,
7726    instead of the direct parent of the DIE.  The other is compilers
7727    which do not emit DW_TAG_namespace; in this case we try to guess
7728    the fully qualified name of structure types from their members'
7729    linkage names.  This must be done using the DIE's children rather
7730    than the children of any DW_AT_specification target.  We only need
7731    to do this for structures at the top level, i.e. if the target of
7732    any DW_AT_specification (if any; otherwise the DIE itself) does not
7733    have a parent.  */
7734 
7735 /* Compute the scope prefix associated with PDI's parent, in
7736    compilation unit CU.  The result will be allocated on CU's
7737    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7738    field.  NULL is returned if no prefix is necessary.  */
7739 static const char *
7740 partial_die_parent_scope (struct partial_die_info *pdi,
7741 			  struct dwarf2_cu *cu)
7742 {
7743   const char *grandparent_scope;
7744   struct partial_die_info *parent, *real_pdi;
7745 
7746   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7747      then this means the parent of the specification DIE.  */
7748 
7749   real_pdi = pdi;
7750   while (real_pdi->has_specification)
7751     {
7752       auto res = find_partial_die (real_pdi->spec_offset,
7753 				   real_pdi->spec_is_dwz, cu);
7754       real_pdi = res.pdi;
7755       cu = res.cu;
7756     }
7757 
7758   parent = real_pdi->die_parent;
7759   if (parent == NULL)
7760     return NULL;
7761 
7762   if (parent->scope_set)
7763     return parent->scope;
7764 
7765   parent->fixup (cu);
7766 
7767   grandparent_scope = partial_die_parent_scope (parent, cu);
7768 
7769   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7770      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7771      Work around this problem here.  */
7772   if (cu->per_cu->lang == language_cplus
7773       && parent->tag == DW_TAG_namespace
7774       && strcmp (parent->name (cu), "::") == 0
7775       && grandparent_scope == NULL)
7776     {
7777       parent->scope = NULL;
7778       parent->scope_set = 1;
7779       return NULL;
7780     }
7781 
7782   /* Nested subroutines in Fortran get a prefix.  */
7783   if (pdi->tag == DW_TAG_enumerator)
7784     /* Enumerators should not get the name of the enumeration as a prefix.  */
7785     parent->scope = grandparent_scope;
7786   else if (parent->tag == DW_TAG_namespace
7787       || parent->tag == DW_TAG_module
7788       || parent->tag == DW_TAG_structure_type
7789       || parent->tag == DW_TAG_class_type
7790       || parent->tag == DW_TAG_interface_type
7791       || parent->tag == DW_TAG_union_type
7792       || parent->tag == DW_TAG_enumeration_type
7793       || (cu->per_cu->lang == language_fortran
7794 	  && parent->tag == DW_TAG_subprogram
7795 	  && pdi->tag == DW_TAG_subprogram))
7796     {
7797       if (grandparent_scope == NULL)
7798 	parent->scope = parent->name (cu);
7799       else
7800 	parent->scope = typename_concat (&cu->comp_unit_obstack,
7801 					 grandparent_scope,
7802 					 parent->name (cu), 0, cu);
7803     }
7804   else
7805     {
7806       /* FIXME drow/2004-04-01: What should we be doing with
7807 	 function-local names?  For partial symbols, we should probably be
7808 	 ignoring them.  */
7809       complaint (_("unhandled containing DIE tag %s for DIE at %s"),
7810 		 dwarf_tag_name (parent->tag),
7811 		 sect_offset_str (pdi->sect_off));
7812       parent->scope = grandparent_scope;
7813     }
7814 
7815   parent->scope_set = 1;
7816   return parent->scope;
7817 }
7818 
7819 /* Return the fully scoped name associated with PDI, from compilation unit
7820    CU.  The result will be allocated with malloc.  */
7821 
7822 static gdb::unique_xmalloc_ptr<char>
7823 partial_die_full_name (struct partial_die_info *pdi,
7824 		       struct dwarf2_cu *cu)
7825 {
7826   const char *parent_scope;
7827 
7828   /* If this is a template instantiation, we can not work out the
7829      template arguments from partial DIEs.  So, unfortunately, we have
7830      to go through the full DIEs.  At least any work we do building
7831      types here will be reused if full symbols are loaded later.  */
7832   if (pdi->has_template_arguments)
7833     {
7834       pdi->fixup (cu);
7835 
7836       if (pdi->name (cu) != NULL && strchr (pdi->name (cu), '<') == NULL)
7837 	{
7838 	  struct die_info *die;
7839 	  struct attribute attr;
7840 	  struct dwarf2_cu *ref_cu = cu;
7841 
7842 	  /* DW_FORM_ref_addr is using section offset.  */
7843 	  attr.name = (enum dwarf_attribute) 0;
7844 	  attr.form = DW_FORM_ref_addr;
7845 	  attr.u.unsnd = to_underlying (pdi->sect_off);
7846 	  die = follow_die_ref (NULL, &attr, &ref_cu);
7847 
7848 	  return make_unique_xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7849 	}
7850     }
7851 
7852   parent_scope = partial_die_parent_scope (pdi, cu);
7853   if (parent_scope == NULL)
7854     return NULL;
7855   else
7856     return gdb::unique_xmalloc_ptr<char> (typename_concat (NULL, parent_scope,
7857 							   pdi->name (cu),
7858 							   0, cu));
7859 }
7860 
7861 static void
7862 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7863 {
7864   dwarf2_per_objfile *per_objfile = cu->per_objfile;
7865   struct objfile *objfile = per_objfile->objfile;
7866   struct gdbarch *gdbarch = objfile->arch ();
7867   CORE_ADDR addr = 0;
7868   const char *actual_name = NULL;
7869   CORE_ADDR baseaddr;
7870 
7871   baseaddr = objfile->text_section_offset ();
7872 
7873   gdb::unique_xmalloc_ptr<char> built_actual_name
7874     = partial_die_full_name (pdi, cu);
7875   if (built_actual_name != NULL)
7876     actual_name = built_actual_name.get ();
7877 
7878   if (actual_name == NULL)
7879     actual_name = pdi->name (cu);
7880 
7881   partial_symbol psymbol;
7882   memset (&psymbol, 0, sizeof (psymbol));
7883   psymbol.ginfo.set_language (cu->per_cu->lang,
7884 			      &objfile->objfile_obstack);
7885   psymbol.ginfo.set_section_index (-1);
7886 
7887   /* The code below indicates that the psymbol should be installed by
7888      setting this.  */
7889   gdb::optional<psymbol_placement> where;
7890 
7891   switch (pdi->tag)
7892     {
7893     case DW_TAG_inlined_subroutine:
7894     case DW_TAG_subprogram:
7895       addr = (gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr)
7896 	      - baseaddr);
7897       if (pdi->is_external
7898 	  || cu->per_cu->lang == language_ada
7899 	  || (cu->per_cu->lang == language_fortran
7900 	      && pdi->die_parent != NULL
7901 	      && pdi->die_parent->tag == DW_TAG_subprogram))
7902 	{
7903 	  /* Normally, only "external" DIEs are part of the global scope.
7904 	     But in Ada and Fortran, we want to be able to access nested
7905 	     procedures globally.  So all Ada and Fortran subprograms are
7906 	     stored in the global scope.  */
7907 	  where = psymbol_placement::GLOBAL;
7908 	}
7909       else
7910 	where = psymbol_placement::STATIC;
7911 
7912       psymbol.domain = VAR_DOMAIN;
7913       psymbol.aclass = LOC_BLOCK;
7914       psymbol.ginfo.set_section_index (SECT_OFF_TEXT (objfile));
7915       psymbol.ginfo.value.address = addr;
7916 
7917       if (pdi->main_subprogram && actual_name != NULL)
7918 	set_objfile_main_name (objfile, actual_name, cu->per_cu->lang);
7919       break;
7920     case DW_TAG_constant:
7921       psymbol.domain = VAR_DOMAIN;
7922       psymbol.aclass = LOC_STATIC;
7923       where = (pdi->is_external
7924 	       ? psymbol_placement::GLOBAL
7925 	       : psymbol_placement::STATIC);
7926       break;
7927     case DW_TAG_variable:
7928       if (pdi->d.locdesc)
7929 	addr = decode_locdesc (pdi->d.locdesc, cu);
7930 
7931       if (pdi->d.locdesc
7932 	  && addr == 0
7933 	  && !per_objfile->per_bfd->has_section_at_zero)
7934 	{
7935 	  /* A global or static variable may also have been stripped
7936 	     out by the linker if unused, in which case its address
7937 	     will be nullified; do not add such variables into partial
7938 	     symbol table then.  */
7939 	}
7940       else if (pdi->is_external)
7941 	{
7942 	  /* Global Variable.
7943 	     Don't enter into the minimal symbol tables as there is
7944 	     a minimal symbol table entry from the ELF symbols already.
7945 	     Enter into partial symbol table if it has a location
7946 	     descriptor or a type.
7947 	     If the location descriptor is missing, new_symbol will create
7948 	     a LOC_UNRESOLVED symbol, the address of the variable will then
7949 	     be determined from the minimal symbol table whenever the variable
7950 	     is referenced.
7951 	     The address for the partial symbol table entry is not
7952 	     used by GDB, but it comes in handy for debugging partial symbol
7953 	     table building.  */
7954 
7955 	  if (pdi->d.locdesc || pdi->has_type)
7956 	    {
7957 	      psymbol.domain = VAR_DOMAIN;
7958 	      psymbol.aclass = LOC_STATIC;
7959 	      psymbol.ginfo.set_section_index (SECT_OFF_TEXT (objfile));
7960 	      psymbol.ginfo.value.address = addr;
7961 	      where = psymbol_placement::GLOBAL;
7962 	    }
7963 	}
7964       else
7965 	{
7966 	  int has_loc = pdi->d.locdesc != NULL;
7967 
7968 	  /* Static Variable.  Skip symbols whose value we cannot know (those
7969 	     without location descriptors or constant values).  */
7970 	  if (!has_loc && !pdi->has_const_value)
7971 	    return;
7972 
7973 	  psymbol.domain = VAR_DOMAIN;
7974 	  psymbol.aclass = LOC_STATIC;
7975 	  psymbol.ginfo.set_section_index (SECT_OFF_TEXT (objfile));
7976 	  if (has_loc)
7977 	    psymbol.ginfo.value.address = addr;
7978 	  where = psymbol_placement::STATIC;
7979 	}
7980       break;
7981     case DW_TAG_array_type:
7982     case DW_TAG_typedef:
7983     case DW_TAG_base_type:
7984     case DW_TAG_subrange_type:
7985       psymbol.domain = VAR_DOMAIN;
7986       psymbol.aclass = LOC_TYPEDEF;
7987       where = psymbol_placement::STATIC;
7988       break;
7989     case DW_TAG_imported_declaration:
7990     case DW_TAG_namespace:
7991       psymbol.domain = VAR_DOMAIN;
7992       psymbol.aclass = LOC_TYPEDEF;
7993       where = psymbol_placement::GLOBAL;
7994       break;
7995     case DW_TAG_module:
7996       /* With Fortran 77 there might be a "BLOCK DATA" module
7997 	 available without any name.  If so, we skip the module as it
7998 	 doesn't bring any value.  */
7999       if (actual_name != nullptr)
8000 	{
8001 	  psymbol.domain = MODULE_DOMAIN;
8002 	  psymbol.aclass = LOC_TYPEDEF;
8003 	  where = psymbol_placement::GLOBAL;
8004 	}
8005       break;
8006     case DW_TAG_class_type:
8007     case DW_TAG_interface_type:
8008     case DW_TAG_structure_type:
8009     case DW_TAG_union_type:
8010     case DW_TAG_enumeration_type:
8011       /* Skip external references.  The DWARF standard says in the section
8012 	 about "Structure, Union, and Class Type Entries": "An incomplete
8013 	 structure, union or class type is represented by a structure,
8014 	 union or class entry that does not have a byte size attribute
8015 	 and that has a DW_AT_declaration attribute."  */
8016       if (!pdi->has_byte_size && pdi->is_declaration)
8017 	return;
8018 
8019       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8020 	 static vs. global.  */
8021       psymbol.domain = STRUCT_DOMAIN;
8022       psymbol.aclass = LOC_TYPEDEF;
8023       where = (cu->per_cu->lang == language_cplus
8024 	       ? psymbol_placement::GLOBAL
8025 	       : psymbol_placement::STATIC);
8026       break;
8027     case DW_TAG_enumerator:
8028       psymbol.domain = VAR_DOMAIN;
8029       psymbol.aclass = LOC_CONST;
8030       where = (cu->per_cu->lang == language_cplus
8031 	       ? psymbol_placement::GLOBAL
8032 	       : psymbol_placement::STATIC);
8033       break;
8034     default:
8035       break;
8036     }
8037 
8038   if (where.has_value ())
8039     {
8040       if (built_actual_name != nullptr)
8041 	actual_name = objfile->intern (actual_name);
8042       if (pdi->linkage_name == nullptr
8043 	  || cu->per_cu->lang == language_ada)
8044 	psymbol.ginfo.set_linkage_name (actual_name);
8045       else
8046 	{
8047 	  psymbol.ginfo.set_demangled_name (actual_name,
8048 					    &objfile->objfile_obstack);
8049 	  psymbol.ginfo.set_linkage_name (pdi->linkage_name);
8050 	}
8051       cu->per_cu->v.psymtab->add_psymbol
8052 	(psymbol, *where, per_objfile->per_bfd->partial_symtabs.get (),
8053 	 objfile);
8054     }
8055 }
8056 
8057 /* Read a partial die corresponding to a namespace; also, add a symbol
8058    corresponding to that namespace to the symbol table.  NAMESPACE is
8059    the name of the enclosing namespace.  */
8060 
8061 static void
8062 add_partial_namespace (struct partial_die_info *pdi,
8063 		       CORE_ADDR *lowpc, CORE_ADDR *highpc,
8064 		       int set_addrmap, struct dwarf2_cu *cu)
8065 {
8066   /* Add a symbol for the namespace.  */
8067 
8068   add_partial_symbol (pdi, cu);
8069 
8070   /* Now scan partial symbols in that namespace.  */
8071 
8072   if (pdi->has_children)
8073     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8074 }
8075 
8076 /* Read a partial die corresponding to a Fortran module.  */
8077 
8078 static void
8079 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
8080 		    CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
8081 {
8082   /* Add a symbol for the namespace.  */
8083 
8084   add_partial_symbol (pdi, cu);
8085 
8086   /* Now scan partial symbols in that module.  */
8087 
8088   if (pdi->has_children)
8089     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8090 }
8091 
8092 /* Read a partial die corresponding to a subprogram or an inlined
8093    subprogram and create a partial symbol for that subprogram.
8094    When the CU language allows it, this routine also defines a partial
8095    symbol for each nested subprogram that this subprogram contains.
8096    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
8097    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
8098 
8099    PDI may also be a lexical block, in which case we simply search
8100    recursively for subprograms defined inside that lexical block.
8101    Again, this is only performed when the CU language allows this
8102    type of definitions.  */
8103 
8104 static void
8105 add_partial_subprogram (struct partial_die_info *pdi,
8106 			CORE_ADDR *lowpc, CORE_ADDR *highpc,
8107 			int set_addrmap, struct dwarf2_cu *cu)
8108 {
8109   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
8110     {
8111       if (pdi->has_pc_info)
8112 	{
8113 	  if (pdi->lowpc < *lowpc)
8114 	    *lowpc = pdi->lowpc;
8115 	  if (pdi->highpc > *highpc)
8116 	    *highpc = pdi->highpc;
8117 	  if (set_addrmap)
8118 	    {
8119 	      struct objfile *objfile = cu->per_objfile->objfile;
8120 	      dwarf2_per_bfd *per_bfd = cu->per_objfile->per_bfd;
8121 	      struct gdbarch *gdbarch = objfile->arch ();
8122 	      CORE_ADDR baseaddr;
8123 	      CORE_ADDR this_highpc;
8124 	      CORE_ADDR this_lowpc;
8125 
8126 	      baseaddr = objfile->text_section_offset ();
8127 	      this_lowpc
8128 		= (gdbarch_adjust_dwarf2_addr (gdbarch,
8129 					       pdi->lowpc + baseaddr)
8130 		   - baseaddr);
8131 	      this_highpc
8132 		= (gdbarch_adjust_dwarf2_addr (gdbarch,
8133 					       pdi->highpc + baseaddr)
8134 		   - baseaddr);
8135 	      addrmap_set_empty (per_bfd->partial_symtabs->psymtabs_addrmap,
8136 				 this_lowpc, this_highpc - 1,
8137 				 cu->per_cu->v.psymtab);
8138 	    }
8139 	}
8140 
8141       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
8142 	{
8143 	  if (!pdi->is_declaration)
8144 	    /* Ignore subprogram DIEs that do not have a name, they are
8145 	       illegal.  Do not emit a complaint at this point, we will
8146 	       do so when we convert this psymtab into a symtab.  */
8147 	    if (pdi->name (cu))
8148 	      add_partial_symbol (pdi, cu);
8149 	}
8150     }
8151 
8152   if (! pdi->has_children)
8153     return;
8154 
8155   if (cu->per_cu->lang == language_ada
8156       || cu->per_cu->lang == language_fortran)
8157     {
8158       pdi = pdi->die_child;
8159       while (pdi != NULL)
8160 	{
8161 	  pdi->fixup (cu);
8162 	  if (pdi->tag == DW_TAG_subprogram
8163 	      || pdi->tag == DW_TAG_inlined_subroutine
8164 	      || pdi->tag == DW_TAG_lexical_block)
8165 	    add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8166 	  pdi = pdi->die_sibling;
8167 	}
8168     }
8169 }
8170 
8171 /* Read a partial die corresponding to an enumeration type.  */
8172 
8173 static void
8174 add_partial_enumeration (struct partial_die_info *enum_pdi,
8175 			 struct dwarf2_cu *cu)
8176 {
8177   struct partial_die_info *pdi;
8178 
8179   if (enum_pdi->name (cu) != NULL)
8180     add_partial_symbol (enum_pdi, cu);
8181 
8182   pdi = enum_pdi->die_child;
8183   while (pdi)
8184     {
8185       if (pdi->tag != DW_TAG_enumerator || pdi->raw_name == NULL)
8186 	complaint (_("malformed enumerator DIE ignored"));
8187       else
8188 	add_partial_symbol (pdi, cu);
8189       pdi = pdi->die_sibling;
8190     }
8191 }
8192 
8193 /* Return the initial uleb128 in the die at INFO_PTR.  */
8194 
8195 static unsigned int
8196 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
8197 {
8198   unsigned int bytes_read;
8199 
8200   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8201 }
8202 
8203 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
8204    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
8205 
8206    Return the corresponding abbrev, or NULL if the number is zero (indicating
8207    an empty DIE).  In either case *BYTES_READ will be set to the length of
8208    the initial number.  */
8209 
8210 static const struct abbrev_info *
8211 peek_die_abbrev (const die_reader_specs &reader,
8212 		 const gdb_byte *info_ptr, unsigned int *bytes_read)
8213 {
8214   dwarf2_cu *cu = reader.cu;
8215   bfd *abfd = reader.abfd;
8216   unsigned int abbrev_number
8217     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
8218 
8219   if (abbrev_number == 0)
8220     return NULL;
8221 
8222   const abbrev_info *abbrev
8223     = reader.abbrev_table->lookup_abbrev (abbrev_number);
8224   if (!abbrev)
8225     {
8226       error (_("Dwarf Error: Could not find abbrev number %d in %s"
8227 	       " at offset %s [in module %s]"),
8228 	     abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
8229 	     sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
8230     }
8231 
8232   return abbrev;
8233 }
8234 
8235 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8236    Returns a pointer to the end of a series of DIEs, terminated by an empty
8237    DIE.  Any children of the skipped DIEs will also be skipped.  */
8238 
8239 static const gdb_byte *
8240 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
8241 {
8242   while (1)
8243     {
8244       unsigned int bytes_read;
8245       const abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr,
8246 						   &bytes_read);
8247 
8248       if (abbrev == NULL)
8249 	return info_ptr + bytes_read;
8250       else
8251 	info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
8252     }
8253 }
8254 
8255 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8256    INFO_PTR should point just after the initial uleb128 of a DIE, and the
8257    abbrev corresponding to that skipped uleb128 should be passed in
8258    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
8259    children.  */
8260 
8261 static const gdb_byte *
8262 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
8263 	      const struct abbrev_info *abbrev)
8264 {
8265   unsigned int bytes_read;
8266   struct attribute attr;
8267   bfd *abfd = reader->abfd;
8268   struct dwarf2_cu *cu = reader->cu;
8269   const gdb_byte *buffer = reader->buffer;
8270   const gdb_byte *buffer_end = reader->buffer_end;
8271   unsigned int form, i;
8272 
8273   for (i = 0; i < abbrev->num_attrs; i++)
8274     {
8275       /* The only abbrev we care about is DW_AT_sibling.  */
8276       if (abbrev->attrs[i].name == DW_AT_sibling)
8277 	{
8278 	  read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
8279 	  if (attr.form == DW_FORM_ref_addr)
8280 	    complaint (_("ignoring absolute DW_AT_sibling"));
8281 	  else
8282 	    {
8283 	      sect_offset off = attr.get_ref_die_offset ();
8284 	      const gdb_byte *sibling_ptr = buffer + to_underlying (off);
8285 
8286 	      if (sibling_ptr < info_ptr)
8287 		complaint (_("DW_AT_sibling points backwards"));
8288 	      else if (sibling_ptr > reader->buffer_end)
8289 		reader->die_section->overflow_complaint ();
8290 	      else
8291 		return sibling_ptr;
8292 	    }
8293 	}
8294 
8295       /* If it isn't DW_AT_sibling, skip this attribute.  */
8296       form = abbrev->attrs[i].form;
8297     skip_attribute:
8298       switch (form)
8299 	{
8300 	case DW_FORM_ref_addr:
8301 	  /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
8302 	     and later it is offset sized.  */
8303 	  if (cu->header.version == 2)
8304 	    info_ptr += cu->header.addr_size;
8305 	  else
8306 	    info_ptr += cu->header.offset_size;
8307 	  break;
8308 	case DW_FORM_GNU_ref_alt:
8309 	  info_ptr += cu->header.offset_size;
8310 	  break;
8311 	case DW_FORM_addr:
8312 	  info_ptr += cu->header.addr_size;
8313 	  break;
8314 	case DW_FORM_data1:
8315 	case DW_FORM_ref1:
8316 	case DW_FORM_flag:
8317 	case DW_FORM_strx1:
8318 	  info_ptr += 1;
8319 	  break;
8320 	case DW_FORM_flag_present:
8321 	case DW_FORM_implicit_const:
8322 	  break;
8323 	case DW_FORM_data2:
8324 	case DW_FORM_ref2:
8325 	case DW_FORM_strx2:
8326 	  info_ptr += 2;
8327 	  break;
8328 	case DW_FORM_strx3:
8329 	  info_ptr += 3;
8330 	  break;
8331 	case DW_FORM_data4:
8332 	case DW_FORM_ref4:
8333 	case DW_FORM_strx4:
8334 	  info_ptr += 4;
8335 	  break;
8336 	case DW_FORM_data8:
8337 	case DW_FORM_ref8:
8338 	case DW_FORM_ref_sig8:
8339 	  info_ptr += 8;
8340 	  break;
8341 	case DW_FORM_data16:
8342 	  info_ptr += 16;
8343 	  break;
8344 	case DW_FORM_string:
8345 	  read_direct_string (abfd, info_ptr, &bytes_read);
8346 	  info_ptr += bytes_read;
8347 	  break;
8348 	case DW_FORM_sec_offset:
8349 	case DW_FORM_strp:
8350 	case DW_FORM_GNU_strp_alt:
8351 	  info_ptr += cu->header.offset_size;
8352 	  break;
8353 	case DW_FORM_exprloc:
8354 	case DW_FORM_block:
8355 	  info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8356 	  info_ptr += bytes_read;
8357 	  break;
8358 	case DW_FORM_block1:
8359 	  info_ptr += 1 + read_1_byte (abfd, info_ptr);
8360 	  break;
8361 	case DW_FORM_block2:
8362 	  info_ptr += 2 + read_2_bytes (abfd, info_ptr);
8363 	  break;
8364 	case DW_FORM_block4:
8365 	  info_ptr += 4 + read_4_bytes (abfd, info_ptr);
8366 	  break;
8367 	case DW_FORM_addrx:
8368 	case DW_FORM_strx:
8369 	case DW_FORM_sdata:
8370 	case DW_FORM_udata:
8371 	case DW_FORM_ref_udata:
8372 	case DW_FORM_GNU_addr_index:
8373 	case DW_FORM_GNU_str_index:
8374 	case DW_FORM_rnglistx:
8375 	case DW_FORM_loclistx:
8376 	  info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
8377 	  break;
8378 	case DW_FORM_indirect:
8379 	  form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8380 	  info_ptr += bytes_read;
8381 	  /* We need to continue parsing from here, so just go back to
8382 	     the top.  */
8383 	  goto skip_attribute;
8384 
8385 	default:
8386 	  error (_("Dwarf Error: Cannot handle %s "
8387 		   "in DWARF reader [in module %s]"),
8388 		 dwarf_form_name (form),
8389 		 bfd_get_filename (abfd));
8390 	}
8391     }
8392 
8393   if (abbrev->has_children)
8394     return skip_children (reader, info_ptr);
8395   else
8396     return info_ptr;
8397 }
8398 
8399 /* Locate ORIG_PDI's sibling.
8400    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
8401 
8402 static const gdb_byte *
8403 locate_pdi_sibling (const struct die_reader_specs *reader,
8404 		    struct partial_die_info *orig_pdi,
8405 		    const gdb_byte *info_ptr)
8406 {
8407   /* Do we know the sibling already?  */
8408 
8409   if (orig_pdi->sibling)
8410     return orig_pdi->sibling;
8411 
8412   /* Are there any children to deal with?  */
8413 
8414   if (!orig_pdi->has_children)
8415     return info_ptr;
8416 
8417   /* Skip the children the long way.  */
8418 
8419   return skip_children (reader, info_ptr);
8420 }
8421 
8422 /* Expand this partial symbol table into a full symbol table.  SELF is
8423    not NULL.  */
8424 
8425 void
8426 dwarf2_psymtab::read_symtab (struct objfile *objfile)
8427 {
8428   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
8429 
8430   gdb_assert (!per_objfile->symtab_set_p (per_cu_data));
8431 
8432   /* If this psymtab is constructed from a debug-only objfile, the
8433      has_section_at_zero flag will not necessarily be correct.  We
8434      can get the correct value for this flag by looking at the data
8435      associated with the (presumably stripped) associated objfile.  */
8436   if (objfile->separate_debug_objfile_backlink)
8437     {
8438       dwarf2_per_objfile *per_objfile_backlink
8439 	= get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
8440 
8441       per_objfile->per_bfd->has_section_at_zero
8442 	= per_objfile_backlink->per_bfd->has_section_at_zero;
8443     }
8444 
8445   expand_psymtab (objfile);
8446 
8447   process_cu_includes (per_objfile);
8448 }
8449 
8450 /* Reading in full CUs.  */
8451 
8452 /* Add PER_CU to the queue.  */
8453 
8454 static void
8455 queue_comp_unit (dwarf2_per_cu_data *per_cu,
8456 		 dwarf2_per_objfile *per_objfile,
8457 		 enum language pretend_language)
8458 {
8459   per_cu->queued = 1;
8460 
8461   gdb_assert (per_objfile->per_bfd->queue.has_value ());
8462   per_cu->per_bfd->queue->emplace (per_cu, per_objfile, pretend_language);
8463 }
8464 
8465 /* If PER_CU is not yet expanded of queued for expansion, add it to the queue.
8466 
8467    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
8468    dependency.
8469 
8470    Return true if maybe_queue_comp_unit requires the caller to load the CU's
8471    DIEs, false otherwise.
8472 
8473    Explanation: there is an invariant that if a CU is queued for expansion
8474    (present in `dwarf2_per_bfd::queue`), then its DIEs are loaded
8475    (a dwarf2_cu object exists for this CU, and `dwarf2_per_objfile::get_cu`
8476    returns non-nullptr).  If the CU gets enqueued by this function but its DIEs
8477    are not yet loaded, the the caller must load the CU's DIEs to ensure the
8478    invariant is respected.
8479 
8480    The caller is therefore not required to load the CU's DIEs (we return false)
8481    if:
8482 
8483      - the CU is already expanded, and therefore does not get enqueued
8484      - the CU gets enqueued for expansion, but its DIEs are already loaded
8485 
8486    Note that the caller should not use this function's return value as an
8487    indicator of whether the CU's DIEs are loaded right now, it should check
8488    that by calling `dwarf2_per_objfile::get_cu` instead.  */
8489 
8490 static int
8491 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
8492 		       dwarf2_per_cu_data *per_cu,
8493 		       dwarf2_per_objfile *per_objfile,
8494 		       enum language pretend_language)
8495 {
8496   /* We may arrive here during partial symbol reading, if we need full
8497      DIEs to process an unusual case (e.g. template arguments).  Do
8498      not queue PER_CU, just tell our caller to load its DIEs.  */
8499   if (per_cu->per_bfd->reading_partial_symbols)
8500     {
8501       dwarf2_cu *cu = per_objfile->get_cu (per_cu);
8502 
8503       if (cu == NULL || cu->dies == NULL)
8504 	return 1;
8505       return 0;
8506     }
8507 
8508   /* Mark the dependence relation so that we don't flush PER_CU
8509      too early.  */
8510   if (dependent_cu != NULL)
8511     dependent_cu->add_dependence (per_cu);
8512 
8513   /* If it's already on the queue, we have nothing to do.  */
8514   if (per_cu->queued)
8515     {
8516       /* Verify the invariant that if a CU is queued for expansion, its DIEs are
8517 	 loaded.  */
8518       gdb_assert (per_objfile->get_cu (per_cu) != nullptr);
8519 
8520       /* If the CU is queued for expansion, it should not already be
8521 	 expanded.  */
8522       gdb_assert (!per_objfile->symtab_set_p (per_cu));
8523 
8524       /* The DIEs are already loaded, the caller doesn't need to do it.  */
8525       return 0;
8526     }
8527 
8528   bool queued = false;
8529   if (!per_objfile->symtab_set_p (per_cu))
8530     {
8531       /* Add it to the queue.  */
8532       queue_comp_unit (per_cu, per_objfile,  pretend_language);
8533       queued = true;
8534     }
8535 
8536   /* If the compilation unit is already loaded, just mark it as
8537      used.  */
8538   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
8539   if (cu != nullptr)
8540     cu->last_used = 0;
8541 
8542   /* Ask the caller to load the CU's DIEs if the CU got enqueued for expansion
8543      and the DIEs are not already loaded.  */
8544   return queued && cu == nullptr;
8545 }
8546 
8547 /* Process the queue.  */
8548 
8549 static void
8550 process_queue (dwarf2_per_objfile *per_objfile)
8551 {
8552   dwarf_read_debug_printf ("Expanding one or more symtabs of objfile %s ...",
8553 			   objfile_name (per_objfile->objfile));
8554 
8555   /* The queue starts out with one item, but following a DIE reference
8556      may load a new CU, adding it to the end of the queue.  */
8557   while (!per_objfile->per_bfd->queue->empty ())
8558     {
8559       dwarf2_queue_item &item = per_objfile->per_bfd->queue->front ();
8560       dwarf2_per_cu_data *per_cu = item.per_cu;
8561 
8562       if (!per_objfile->symtab_set_p (per_cu))
8563 	{
8564 	  dwarf2_cu *cu = per_objfile->get_cu (per_cu);
8565 
8566 	  /* Skip dummy CUs.  */
8567 	  if (cu != nullptr)
8568 	    {
8569 	      unsigned int debug_print_threshold;
8570 	      char buf[100];
8571 
8572 	      if (per_cu->is_debug_types)
8573 		{
8574 		  struct signatured_type *sig_type =
8575 		    (struct signatured_type *) per_cu;
8576 
8577 		  sprintf (buf, "TU %s at offset %s",
8578 			   hex_string (sig_type->signature),
8579 			   sect_offset_str (per_cu->sect_off));
8580 		  /* There can be 100s of TUs.
8581 		     Only print them in verbose mode.  */
8582 		  debug_print_threshold = 2;
8583 		}
8584 	      else
8585 		{
8586 		  sprintf (buf, "CU at offset %s",
8587 			   sect_offset_str (per_cu->sect_off));
8588 		  debug_print_threshold = 1;
8589 		}
8590 
8591 	      if (dwarf_read_debug >= debug_print_threshold)
8592 		dwarf_read_debug_printf ("Expanding symtab of %s", buf);
8593 
8594 	      if (per_cu->is_debug_types)
8595 		process_full_type_unit (cu, item.pretend_language);
8596 	      else
8597 		process_full_comp_unit (cu, item.pretend_language);
8598 
8599 	      if (dwarf_read_debug >= debug_print_threshold)
8600 		dwarf_read_debug_printf ("Done expanding %s", buf);
8601 	    }
8602 	}
8603 
8604       per_cu->queued = 0;
8605       per_objfile->per_bfd->queue->pop ();
8606     }
8607 
8608   dwarf_read_debug_printf ("Done expanding symtabs of %s.",
8609 			   objfile_name (per_objfile->objfile));
8610 }
8611 
8612 /* Read in full symbols for PST, and anything it depends on.  */
8613 
8614 void
8615 dwarf2_psymtab::expand_psymtab (struct objfile *objfile)
8616 {
8617   gdb_assert (!readin_p (objfile));
8618 
8619   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
8620   free_cached_comp_units freer (per_objfile);
8621   expand_dependencies (objfile);
8622 
8623   dw2_do_instantiate_symtab (per_cu_data, per_objfile, false);
8624   gdb_assert (get_compunit_symtab (objfile) != nullptr);
8625 }
8626 
8627 /* See psympriv.h.  */
8628 
8629 bool
8630 dwarf2_psymtab::readin_p (struct objfile *objfile) const
8631 {
8632   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
8633   return per_objfile->symtab_set_p (per_cu_data);
8634 }
8635 
8636 /* See psympriv.h.  */
8637 
8638 compunit_symtab *
8639 dwarf2_psymtab::get_compunit_symtab (struct objfile *objfile) const
8640 {
8641   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
8642   return per_objfile->get_symtab (per_cu_data);
8643 }
8644 
8645 /* Trivial hash function for die_info: the hash value of a DIE
8646    is its offset in .debug_info for this objfile.  */
8647 
8648 static hashval_t
8649 die_hash (const void *item)
8650 {
8651   const struct die_info *die = (const struct die_info *) item;
8652 
8653   return to_underlying (die->sect_off);
8654 }
8655 
8656 /* Trivial comparison function for die_info structures: two DIEs
8657    are equal if they have the same offset.  */
8658 
8659 static int
8660 die_eq (const void *item_lhs, const void *item_rhs)
8661 {
8662   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
8663   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
8664 
8665   return die_lhs->sect_off == die_rhs->sect_off;
8666 }
8667 
8668 /* Load the DIEs associated with PER_CU into memory.
8669 
8670    In some cases, the caller, while reading partial symbols, will need to load
8671    the full symbols for the CU for some reason.  It will already have a
8672    dwarf2_cu object for THIS_CU and pass it as EXISTING_CU, so it can be re-used
8673    rather than creating a new one.  */
8674 
8675 static void
8676 load_full_comp_unit (dwarf2_per_cu_data *this_cu,
8677 		     dwarf2_per_objfile *per_objfile,
8678 		     dwarf2_cu *existing_cu,
8679 		     bool skip_partial,
8680 		     enum language pretend_language)
8681 {
8682   gdb_assert (! this_cu->is_debug_types);
8683 
8684   cutu_reader reader (this_cu, per_objfile, NULL, existing_cu, skip_partial);
8685   if (reader.dummy_p)
8686     return;
8687 
8688   struct dwarf2_cu *cu = reader.cu;
8689   const gdb_byte *info_ptr = reader.info_ptr;
8690 
8691   gdb_assert (cu->die_hash == NULL);
8692   cu->die_hash =
8693     htab_create_alloc_ex (cu->header.length / 12,
8694 			  die_hash,
8695 			  die_eq,
8696 			  NULL,
8697 			  &cu->comp_unit_obstack,
8698 			  hashtab_obstack_allocate,
8699 			  dummy_obstack_deallocate);
8700 
8701   if (reader.comp_unit_die->has_children)
8702     reader.comp_unit_die->child
8703       = read_die_and_siblings (&reader, reader.info_ptr,
8704 			       &info_ptr, reader.comp_unit_die);
8705   cu->dies = reader.comp_unit_die;
8706   /* comp_unit_die is not stored in die_hash, no need.  */
8707 
8708   /* We try not to read any attributes in this function, because not
8709      all CUs needed for references have been loaded yet, and symbol
8710      table processing isn't initialized.  But we have to set the CU language,
8711      or we won't be able to build types correctly.
8712      Similarly, if we do not read the producer, we can not apply
8713      producer-specific interpretation.  */
8714   prepare_one_comp_unit (cu, cu->dies, pretend_language);
8715 
8716   reader.keep ();
8717 }
8718 
8719 /* Add a DIE to the delayed physname list.  */
8720 
8721 static void
8722 add_to_method_list (struct type *type, int fnfield_index, int index,
8723 		    const char *name, struct die_info *die,
8724 		    struct dwarf2_cu *cu)
8725 {
8726   struct delayed_method_info mi;
8727   mi.type = type;
8728   mi.fnfield_index = fnfield_index;
8729   mi.index = index;
8730   mi.name = name;
8731   mi.die = die;
8732   cu->method_list.push_back (mi);
8733 }
8734 
8735 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
8736    "const" / "volatile".  If so, decrements LEN by the length of the
8737    modifier and return true.  Otherwise return false.  */
8738 
8739 template<size_t N>
8740 static bool
8741 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
8742 {
8743   size_t mod_len = sizeof (mod) - 1;
8744   if (len > mod_len && startswith (physname + (len - mod_len), mod))
8745     {
8746       len -= mod_len;
8747       return true;
8748     }
8749   return false;
8750 }
8751 
8752 /* Compute the physnames of any methods on the CU's method list.
8753 
8754    The computation of method physnames is delayed in order to avoid the
8755    (bad) condition that one of the method's formal parameters is of an as yet
8756    incomplete type.  */
8757 
8758 static void
8759 compute_delayed_physnames (struct dwarf2_cu *cu)
8760 {
8761   /* Only C++ delays computing physnames.  */
8762   if (cu->method_list.empty ())
8763     return;
8764   gdb_assert (cu->per_cu->lang == language_cplus);
8765 
8766   for (const delayed_method_info &mi : cu->method_list)
8767     {
8768       const char *physname;
8769       struct fn_fieldlist *fn_flp
8770 	= &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
8771       physname = dwarf2_physname (mi.name, mi.die, cu);
8772       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
8773 	= physname ? physname : "";
8774 
8775       /* Since there's no tag to indicate whether a method is a
8776 	 const/volatile overload, extract that information out of the
8777 	 demangled name.  */
8778       if (physname != NULL)
8779 	{
8780 	  size_t len = strlen (physname);
8781 
8782 	  while (1)
8783 	    {
8784 	      if (physname[len] == ')') /* shortcut */
8785 		break;
8786 	      else if (check_modifier (physname, len, " const"))
8787 		TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
8788 	      else if (check_modifier (physname, len, " volatile"))
8789 		TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
8790 	      else
8791 		break;
8792 	    }
8793 	}
8794     }
8795 
8796   /* The list is no longer needed.  */
8797   cu->method_list.clear ();
8798 }
8799 
8800 /* Go objects should be embedded in a DW_TAG_module DIE,
8801    and it's not clear if/how imported objects will appear.
8802    To keep Go support simple until that's worked out,
8803    go back through what we've read and create something usable.
8804    We could do this while processing each DIE, and feels kinda cleaner,
8805    but that way is more invasive.
8806    This is to, for example, allow the user to type "p var" or "b main"
8807    without having to specify the package name, and allow lookups
8808    of module.object to work in contexts that use the expression
8809    parser.  */
8810 
8811 static void
8812 fixup_go_packaging (struct dwarf2_cu *cu)
8813 {
8814   gdb::unique_xmalloc_ptr<char> package_name;
8815   struct pending *list;
8816   int i;
8817 
8818   for (list = *cu->get_builder ()->get_global_symbols ();
8819        list != NULL;
8820        list = list->next)
8821     {
8822       for (i = 0; i < list->nsyms; ++i)
8823 	{
8824 	  struct symbol *sym = list->symbol[i];
8825 
8826 	  if (sym->language () == language_go
8827 	      && SYMBOL_CLASS (sym) == LOC_BLOCK)
8828 	    {
8829 	      gdb::unique_xmalloc_ptr<char> this_package_name
8830 		(go_symbol_package_name (sym));
8831 
8832 	      if (this_package_name == NULL)
8833 		continue;
8834 	      if (package_name == NULL)
8835 		package_name = std::move (this_package_name);
8836 	      else
8837 		{
8838 		  struct objfile *objfile = cu->per_objfile->objfile;
8839 		  if (strcmp (package_name.get (), this_package_name.get ()) != 0)
8840 		    complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
8841 			       (symbol_symtab (sym) != NULL
8842 				? symtab_to_filename_for_display
8843 				    (symbol_symtab (sym))
8844 				: objfile_name (objfile)),
8845 			       this_package_name.get (), package_name.get ());
8846 		}
8847 	    }
8848 	}
8849     }
8850 
8851   if (package_name != NULL)
8852     {
8853       struct objfile *objfile = cu->per_objfile->objfile;
8854       const char *saved_package_name = objfile->intern (package_name.get ());
8855       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
8856 				     saved_package_name);
8857       struct symbol *sym;
8858 
8859       sym = new (&objfile->objfile_obstack) symbol;
8860       sym->set_language (language_go, &objfile->objfile_obstack);
8861       sym->compute_and_set_names (saved_package_name, false, objfile->per_bfd);
8862       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8863 	 e.g., "main" finds the "main" module and not C's main().  */
8864       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8865       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8866       SYMBOL_TYPE (sym) = type;
8867 
8868       add_symbol_to_list (sym, cu->get_builder ()->get_global_symbols ());
8869     }
8870 }
8871 
8872 /* Allocate a fully-qualified name consisting of the two parts on the
8873    obstack.  */
8874 
8875 static const char *
8876 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
8877 {
8878   return obconcat (obstack, p1, "::", p2, (char *) NULL);
8879 }
8880 
8881 /* A helper that allocates a variant part to attach to a Rust enum
8882    type.  OBSTACK is where the results should be allocated.  TYPE is
8883    the type we're processing.  DISCRIMINANT_INDEX is the index of the
8884    discriminant.  It must be the index of one of the fields of TYPE,
8885    or -1 to mean there is no discriminant (univariant enum).
8886    DEFAULT_INDEX is the index of the default field; or -1 if there is
8887    no default.  RANGES is indexed by "effective" field number (the
8888    field index, but omitting the discriminant and default fields) and
8889    must hold the discriminant values used by the variants.  Note that
8890    RANGES must have a lifetime at least as long as OBSTACK -- either
8891    already allocated on it, or static.  */
8892 
8893 static void
8894 alloc_rust_variant (struct obstack *obstack, struct type *type,
8895 		    int discriminant_index, int default_index,
8896 		    gdb::array_view<discriminant_range> ranges)
8897 {
8898   /* When DISCRIMINANT_INDEX == -1, we have a univariant enum.  */
8899   gdb_assert (discriminant_index == -1
8900 	      || (discriminant_index >= 0
8901 		  && discriminant_index < type->num_fields ()));
8902   gdb_assert (default_index == -1
8903 	      || (default_index >= 0 && default_index < type->num_fields ()));
8904 
8905   /* We have one variant for each non-discriminant field.  */
8906   int n_variants = type->num_fields ();
8907   if (discriminant_index != -1)
8908     --n_variants;
8909 
8910   variant *variants = new (obstack) variant[n_variants];
8911   int var_idx = 0;
8912   int range_idx = 0;
8913   for (int i = 0; i < type->num_fields (); ++i)
8914     {
8915       if (i == discriminant_index)
8916 	continue;
8917 
8918       variants[var_idx].first_field = i;
8919       variants[var_idx].last_field = i + 1;
8920 
8921       /* The default field does not need a range, but other fields do.
8922 	 We skipped the discriminant above.  */
8923       if (i != default_index)
8924 	{
8925 	  variants[var_idx].discriminants = ranges.slice (range_idx, 1);
8926 	  ++range_idx;
8927 	}
8928 
8929       ++var_idx;
8930     }
8931 
8932   gdb_assert (range_idx == ranges.size ());
8933   gdb_assert (var_idx == n_variants);
8934 
8935   variant_part *part = new (obstack) variant_part;
8936   part->discriminant_index = discriminant_index;
8937   /* If there is no discriminant, then whether it is signed is of no
8938      consequence.  */
8939   part->is_unsigned
8940     = (discriminant_index == -1
8941        ? false
8942        : type->field (discriminant_index).type ()->is_unsigned ());
8943   part->variants = gdb::array_view<variant> (variants, n_variants);
8944 
8945   void *storage = obstack_alloc (obstack, sizeof (gdb::array_view<variant_part>));
8946   gdb::array_view<variant_part> *prop_value
8947     = new (storage) gdb::array_view<variant_part> (part, 1);
8948 
8949   struct dynamic_prop prop;
8950   prop.set_variant_parts (prop_value);
8951 
8952   type->add_dyn_prop (DYN_PROP_VARIANT_PARTS, prop);
8953 }
8954 
8955 /* Some versions of rustc emitted enums in an unusual way.
8956 
8957    Ordinary enums were emitted as unions.  The first element of each
8958    structure in the union was named "RUST$ENUM$DISR".  This element
8959    held the discriminant.
8960 
8961    These versions of Rust also implemented the "non-zero"
8962    optimization.  When the enum had two values, and one is empty and
8963    the other holds a pointer that cannot be zero, the pointer is used
8964    as the discriminant, with a zero value meaning the empty variant.
8965    Here, the union's first member is of the form
8966    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
8967    where the fieldnos are the indices of the fields that should be
8968    traversed in order to find the field (which may be several fields deep)
8969    and the variantname is the name of the variant of the case when the
8970    field is zero.
8971 
8972    This function recognizes whether TYPE is of one of these forms,
8973    and, if so, smashes it to be a variant type.  */
8974 
8975 static void
8976 quirk_rust_enum (struct type *type, struct objfile *objfile)
8977 {
8978   gdb_assert (type->code () == TYPE_CODE_UNION);
8979 
8980   /* We don't need to deal with empty enums.  */
8981   if (type->num_fields () == 0)
8982     return;
8983 
8984 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
8985   if (type->num_fields () == 1
8986       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
8987     {
8988       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
8989 
8990       /* Decode the field name to find the offset of the
8991 	 discriminant.  */
8992       ULONGEST bit_offset = 0;
8993       struct type *field_type = type->field (0).type ();
8994       while (name[0] >= '0' && name[0] <= '9')
8995 	{
8996 	  char *tail;
8997 	  unsigned long index = strtoul (name, &tail, 10);
8998 	  name = tail;
8999 	  if (*name != '$'
9000 	      || index >= field_type->num_fields ()
9001 	      || (TYPE_FIELD_LOC_KIND (field_type, index)
9002 		  != FIELD_LOC_KIND_BITPOS))
9003 	    {
9004 	      complaint (_("Could not parse Rust enum encoding string \"%s\""
9005 			   "[in module %s]"),
9006 			 TYPE_FIELD_NAME (type, 0),
9007 			 objfile_name (objfile));
9008 	      return;
9009 	    }
9010 	  ++name;
9011 
9012 	  bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9013 	  field_type = field_type->field (index).type ();
9014 	}
9015 
9016       /* Smash this type to be a structure type.  We have to do this
9017 	 because the type has already been recorded.  */
9018       type->set_code (TYPE_CODE_STRUCT);
9019       type->set_num_fields (3);
9020       /* Save the field we care about.  */
9021       struct field saved_field = type->field (0);
9022       type->set_fields
9023 	((struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field)));
9024 
9025       /* Put the discriminant at index 0.  */
9026       type->field (0).set_type (field_type);
9027       TYPE_FIELD_ARTIFICIAL (type, 0) = 1;
9028       TYPE_FIELD_NAME (type, 0) = "<<discriminant>>";
9029       SET_FIELD_BITPOS (type->field (0), bit_offset);
9030 
9031       /* The order of fields doesn't really matter, so put the real
9032 	 field at index 1 and the data-less field at index 2.  */
9033       type->field (1) = saved_field;
9034       TYPE_FIELD_NAME (type, 1)
9035 	= rust_last_path_segment (type->field (1).type ()->name ());
9036       type->field (1).type ()->set_name
9037 	(rust_fully_qualify (&objfile->objfile_obstack, type->name (),
9038 			     TYPE_FIELD_NAME (type, 1)));
9039 
9040       const char *dataless_name
9041 	= rust_fully_qualify (&objfile->objfile_obstack, type->name (),
9042 			      name);
9043       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
9044 					      dataless_name);
9045       type->field (2).set_type (dataless_type);
9046       /* NAME points into the original discriminant name, which
9047 	 already has the correct lifetime.  */
9048       TYPE_FIELD_NAME (type, 2) = name;
9049       SET_FIELD_BITPOS (type->field (2), 0);
9050 
9051       /* Indicate that this is a variant type.  */
9052       static discriminant_range ranges[1] = { { 0, 0 } };
9053       alloc_rust_variant (&objfile->objfile_obstack, type, 0, 1, ranges);
9054     }
9055   /* A union with a single anonymous field is probably an old-style
9056      univariant enum.  */
9057   else if (type->num_fields () == 1 && streq (TYPE_FIELD_NAME (type, 0), ""))
9058     {
9059       /* Smash this type to be a structure type.  We have to do this
9060 	 because the type has already been recorded.  */
9061       type->set_code (TYPE_CODE_STRUCT);
9062 
9063       struct type *field_type = type->field (0).type ();
9064       const char *variant_name
9065 	= rust_last_path_segment (field_type->name ());
9066       TYPE_FIELD_NAME (type, 0) = variant_name;
9067       field_type->set_name
9068 	(rust_fully_qualify (&objfile->objfile_obstack,
9069 			     type->name (), variant_name));
9070 
9071       alloc_rust_variant (&objfile->objfile_obstack, type, -1, 0, {});
9072     }
9073   else
9074     {
9075       struct type *disr_type = nullptr;
9076       for (int i = 0; i < type->num_fields (); ++i)
9077 	{
9078 	  disr_type = type->field (i).type ();
9079 
9080 	  if (disr_type->code () != TYPE_CODE_STRUCT)
9081 	    {
9082 	      /* All fields of a true enum will be structs.  */
9083 	      return;
9084 	    }
9085 	  else if (disr_type->num_fields () == 0)
9086 	    {
9087 	      /* Could be data-less variant, so keep going.  */
9088 	      disr_type = nullptr;
9089 	    }
9090 	  else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
9091 			   "RUST$ENUM$DISR") != 0)
9092 	    {
9093 	      /* Not a Rust enum.  */
9094 	      return;
9095 	    }
9096 	  else
9097 	    {
9098 	      /* Found one.  */
9099 	      break;
9100 	    }
9101 	}
9102 
9103       /* If we got here without a discriminant, then it's probably
9104 	 just a union.  */
9105       if (disr_type == nullptr)
9106 	return;
9107 
9108       /* Smash this type to be a structure type.  We have to do this
9109 	 because the type has already been recorded.  */
9110       type->set_code (TYPE_CODE_STRUCT);
9111 
9112       /* Make space for the discriminant field.  */
9113       struct field *disr_field = &disr_type->field (0);
9114       field *new_fields
9115 	= (struct field *) TYPE_ZALLOC (type, ((type->num_fields () + 1)
9116 					       * sizeof (struct field)));
9117       memcpy (new_fields + 1, type->fields (),
9118 	      type->num_fields () * sizeof (struct field));
9119       type->set_fields (new_fields);
9120       type->set_num_fields (type->num_fields () + 1);
9121 
9122       /* Install the discriminant at index 0 in the union.  */
9123       type->field (0) = *disr_field;
9124       TYPE_FIELD_ARTIFICIAL (type, 0) = 1;
9125       TYPE_FIELD_NAME (type, 0) = "<<discriminant>>";
9126 
9127       /* We need a way to find the correct discriminant given a
9128 	 variant name.  For convenience we build a map here.  */
9129       struct type *enum_type = disr_field->type ();
9130       std::unordered_map<std::string, ULONGEST> discriminant_map;
9131       for (int i = 0; i < enum_type->num_fields (); ++i)
9132 	{
9133 	  if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
9134 	    {
9135 	      const char *name
9136 		= rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
9137 	      discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
9138 	    }
9139 	}
9140 
9141       int n_fields = type->num_fields ();
9142       /* We don't need a range entry for the discriminant, but we do
9143 	 need one for every other field, as there is no default
9144 	 variant.  */
9145       discriminant_range *ranges = XOBNEWVEC (&objfile->objfile_obstack,
9146 					      discriminant_range,
9147 					      n_fields - 1);
9148       /* Skip the discriminant here.  */
9149       for (int i = 1; i < n_fields; ++i)
9150 	{
9151 	  /* Find the final word in the name of this variant's type.
9152 	     That name can be used to look up the correct
9153 	     discriminant.  */
9154 	  const char *variant_name
9155 	    = rust_last_path_segment (type->field (i).type ()->name ());
9156 
9157 	  auto iter = discriminant_map.find (variant_name);
9158 	  if (iter != discriminant_map.end ())
9159 	    {
9160 	      ranges[i - 1].low = iter->second;
9161 	      ranges[i - 1].high = iter->second;
9162 	    }
9163 
9164 	  /* In Rust, each element should have the size of the
9165 	     enclosing enum.  */
9166 	  TYPE_LENGTH (type->field (i).type ()) = TYPE_LENGTH (type);
9167 
9168 	  /* Remove the discriminant field, if it exists.  */
9169 	  struct type *sub_type = type->field (i).type ();
9170 	  if (sub_type->num_fields () > 0)
9171 	    {
9172 	      sub_type->set_num_fields (sub_type->num_fields () - 1);
9173 	      sub_type->set_fields (sub_type->fields () + 1);
9174 	    }
9175 	  TYPE_FIELD_NAME (type, i) = variant_name;
9176 	  sub_type->set_name
9177 	    (rust_fully_qualify (&objfile->objfile_obstack,
9178 				 type->name (), variant_name));
9179 	}
9180 
9181       /* Indicate that this is a variant type.  */
9182       alloc_rust_variant (&objfile->objfile_obstack, type, 0, -1,
9183 			  gdb::array_view<discriminant_range> (ranges,
9184 							       n_fields - 1));
9185     }
9186 }
9187 
9188 /* Rewrite some Rust unions to be structures with variants parts.  */
9189 
9190 static void
9191 rust_union_quirks (struct dwarf2_cu *cu)
9192 {
9193   gdb_assert (cu->per_cu->lang == language_rust);
9194   for (type *type_ : cu->rust_unions)
9195     quirk_rust_enum (type_, cu->per_objfile->objfile);
9196   /* We don't need this any more.  */
9197   cu->rust_unions.clear ();
9198 }
9199 
9200 /* See read.h.  */
9201 
9202 type_unit_group_unshareable *
9203 dwarf2_per_objfile::get_type_unit_group_unshareable (type_unit_group *tu_group)
9204 {
9205   auto iter = this->m_type_units.find (tu_group);
9206   if (iter != this->m_type_units.end ())
9207     return iter->second.get ();
9208 
9209   type_unit_group_unshareable_up uniq (new type_unit_group_unshareable);
9210   type_unit_group_unshareable *result = uniq.get ();
9211   this->m_type_units[tu_group] = std::move (uniq);
9212   return result;
9213 }
9214 
9215 struct type *
9216 dwarf2_per_objfile::get_type_for_signatured_type
9217   (signatured_type *sig_type) const
9218 {
9219   auto iter = this->m_type_map.find (sig_type);
9220   if (iter == this->m_type_map.end ())
9221     return nullptr;
9222 
9223   return iter->second;
9224 }
9225 
9226 void dwarf2_per_objfile::set_type_for_signatured_type
9227   (signatured_type *sig_type, struct type *type)
9228 {
9229   gdb_assert (this->m_type_map.find (sig_type) == this->m_type_map.end ());
9230 
9231   this->m_type_map[sig_type] = type;
9232 }
9233 
9234 /* A helper function for computing the list of all symbol tables
9235    included by PER_CU.  */
9236 
9237 static void
9238 recursively_compute_inclusions (std::vector<compunit_symtab *> *result,
9239 				htab_t all_children, htab_t all_type_symtabs,
9240 				dwarf2_per_cu_data *per_cu,
9241 				dwarf2_per_objfile *per_objfile,
9242 				struct compunit_symtab *immediate_parent)
9243 {
9244   void **slot = htab_find_slot (all_children, per_cu, INSERT);
9245   if (*slot != NULL)
9246     {
9247       /* This inclusion and its children have been processed.  */
9248       return;
9249     }
9250 
9251   *slot = per_cu;
9252 
9253   /* Only add a CU if it has a symbol table.  */
9254   compunit_symtab *cust = per_objfile->get_symtab (per_cu);
9255   if (cust != NULL)
9256     {
9257       /* If this is a type unit only add its symbol table if we haven't
9258 	 seen it yet (type unit per_cu's can share symtabs).  */
9259       if (per_cu->is_debug_types)
9260 	{
9261 	  slot = htab_find_slot (all_type_symtabs, cust, INSERT);
9262 	  if (*slot == NULL)
9263 	    {
9264 	      *slot = cust;
9265 	      result->push_back (cust);
9266 	      if (cust->user == NULL)
9267 		cust->user = immediate_parent;
9268 	    }
9269 	}
9270       else
9271 	{
9272 	  result->push_back (cust);
9273 	  if (cust->user == NULL)
9274 	    cust->user = immediate_parent;
9275 	}
9276     }
9277 
9278   if (!per_cu->imported_symtabs_empty ())
9279     for (dwarf2_per_cu_data *ptr : *per_cu->imported_symtabs)
9280       {
9281 	recursively_compute_inclusions (result, all_children,
9282 					all_type_symtabs, ptr, per_objfile,
9283 					cust);
9284       }
9285 }
9286 
9287 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
9288    PER_CU.  */
9289 
9290 static void
9291 compute_compunit_symtab_includes (dwarf2_per_cu_data *per_cu,
9292 				  dwarf2_per_objfile *per_objfile)
9293 {
9294   gdb_assert (! per_cu->is_debug_types);
9295 
9296   if (!per_cu->imported_symtabs_empty ())
9297     {
9298       int len;
9299       std::vector<compunit_symtab *> result_symtabs;
9300       compunit_symtab *cust = per_objfile->get_symtab (per_cu);
9301 
9302       /* If we don't have a symtab, we can just skip this case.  */
9303       if (cust == NULL)
9304 	return;
9305 
9306       htab_up all_children (htab_create_alloc (1, htab_hash_pointer,
9307 					       htab_eq_pointer,
9308 					       NULL, xcalloc, xfree));
9309       htab_up all_type_symtabs (htab_create_alloc (1, htab_hash_pointer,
9310 						   htab_eq_pointer,
9311 						   NULL, xcalloc, xfree));
9312 
9313       for (dwarf2_per_cu_data *ptr : *per_cu->imported_symtabs)
9314 	{
9315 	  recursively_compute_inclusions (&result_symtabs, all_children.get (),
9316 					  all_type_symtabs.get (), ptr,
9317 					  per_objfile, cust);
9318 	}
9319 
9320       /* Now we have a transitive closure of all the included symtabs.  */
9321       len = result_symtabs.size ();
9322       cust->includes
9323 	= XOBNEWVEC (&per_objfile->objfile->objfile_obstack,
9324 		     struct compunit_symtab *, len + 1);
9325       memcpy (cust->includes, result_symtabs.data (),
9326 	      len * sizeof (compunit_symtab *));
9327       cust->includes[len] = NULL;
9328     }
9329 }
9330 
9331 /* Compute the 'includes' field for the symtabs of all the CUs we just
9332    read.  */
9333 
9334 static void
9335 process_cu_includes (dwarf2_per_objfile *per_objfile)
9336 {
9337   for (dwarf2_per_cu_data *iter : per_objfile->per_bfd->just_read_cus)
9338     {
9339       if (! iter->is_debug_types)
9340 	compute_compunit_symtab_includes (iter, per_objfile);
9341     }
9342 
9343   per_objfile->per_bfd->just_read_cus.clear ();
9344 }
9345 
9346 /* Generate full symbol information for CU, whose DIEs have
9347    already been loaded into memory.  */
9348 
9349 static void
9350 process_full_comp_unit (dwarf2_cu *cu, enum language pretend_language)
9351 {
9352   dwarf2_per_objfile *per_objfile = cu->per_objfile;
9353   struct objfile *objfile = per_objfile->objfile;
9354   struct gdbarch *gdbarch = objfile->arch ();
9355   CORE_ADDR lowpc, highpc;
9356   struct compunit_symtab *cust;
9357   CORE_ADDR baseaddr;
9358   struct block *static_block;
9359   CORE_ADDR addr;
9360 
9361   baseaddr = objfile->text_section_offset ();
9362 
9363   /* Clear the list here in case something was left over.  */
9364   cu->method_list.clear ();
9365 
9366   dwarf2_find_base_address (cu->dies, cu);
9367 
9368   /* Before we start reading the top-level DIE, ensure it has a valid tag
9369      type.  */
9370   switch (cu->dies->tag)
9371     {
9372     case DW_TAG_compile_unit:
9373     case DW_TAG_partial_unit:
9374     case DW_TAG_type_unit:
9375       break;
9376     default:
9377       error (_("Dwarf Error: unexpected tag '%s' at offset %s [in module %s]"),
9378 	     dwarf_tag_name (cu->dies->tag),
9379 	     sect_offset_str (cu->per_cu->sect_off),
9380 	     objfile_name (per_objfile->objfile));
9381     }
9382 
9383   /* Do line number decoding in read_file_scope () */
9384   process_die (cu->dies, cu);
9385 
9386   /* For now fudge the Go package.  */
9387   if (cu->per_cu->lang == language_go)
9388     fixup_go_packaging (cu);
9389 
9390   /* Now that we have processed all the DIEs in the CU, all the types
9391      should be complete, and it should now be safe to compute all of the
9392      physnames.  */
9393   compute_delayed_physnames (cu);
9394 
9395   if (cu->per_cu->lang == language_rust)
9396     rust_union_quirks (cu);
9397 
9398   /* Some compilers don't define a DW_AT_high_pc attribute for the
9399      compilation unit.  If the DW_AT_high_pc is missing, synthesize
9400      it, by scanning the DIE's below the compilation unit.  */
9401   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
9402 
9403   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
9404   static_block = cu->get_builder ()->end_symtab_get_static_block (addr, 0, 1);
9405 
9406   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
9407      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
9408      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
9409      addrmap to help ensure it has an accurate map of pc values belonging to
9410      this comp unit.  */
9411   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
9412 
9413   cust = cu->get_builder ()->end_symtab_from_static_block (static_block,
9414 						    SECT_OFF_TEXT (objfile),
9415 						    0);
9416 
9417   if (cust != NULL)
9418     {
9419       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
9420 
9421       /* Set symtab language to language from DW_AT_language.  If the
9422 	 compilation is from a C file generated by language preprocessors, do
9423 	 not set the language if it was already deduced by start_subfile.  */
9424       if (!(cu->per_cu->lang == language_c
9425 	    && COMPUNIT_FILETABS (cust)->language != language_unknown))
9426 	COMPUNIT_FILETABS (cust)->language = cu->per_cu->lang;
9427 
9428       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
9429 	 produce DW_AT_location with location lists but it can be possibly
9430 	 invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
9431 	 there were bugs in prologue debug info, fixed later in GCC-4.5
9432 	 by "unwind info for epilogues" patch (which is not directly related).
9433 
9434 	 For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
9435 	 needed, it would be wrong due to missing DW_AT_producer there.
9436 
9437 	 Still one can confuse GDB by using non-standard GCC compilation
9438 	 options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
9439 	 */
9440       if (cu->has_loclist && gcc_4_minor >= 5)
9441 	cust->locations_valid = 1;
9442 
9443       if (gcc_4_minor >= 5)
9444 	cust->epilogue_unwind_valid = 1;
9445 
9446       cust->call_site_htab = cu->call_site_htab;
9447     }
9448 
9449   per_objfile->set_symtab (cu->per_cu, cust);
9450 
9451   /* Push it for inclusion processing later.  */
9452   per_objfile->per_bfd->just_read_cus.push_back (cu->per_cu);
9453 
9454   /* Not needed any more.  */
9455   cu->reset_builder ();
9456 }
9457 
9458 /* Generate full symbol information for type unit CU, whose DIEs have
9459    already been loaded into memory.  */
9460 
9461 static void
9462 process_full_type_unit (dwarf2_cu *cu,
9463 			enum language pretend_language)
9464 {
9465   dwarf2_per_objfile *per_objfile = cu->per_objfile;
9466   struct objfile *objfile = per_objfile->objfile;
9467   struct compunit_symtab *cust;
9468   struct signatured_type *sig_type;
9469 
9470   gdb_assert (cu->per_cu->is_debug_types);
9471   sig_type = (struct signatured_type *) cu->per_cu;
9472 
9473   /* Clear the list here in case something was left over.  */
9474   cu->method_list.clear ();
9475 
9476   /* The symbol tables are set up in read_type_unit_scope.  */
9477   process_die (cu->dies, cu);
9478 
9479   /* For now fudge the Go package.  */
9480   if (cu->per_cu->lang == language_go)
9481     fixup_go_packaging (cu);
9482 
9483   /* Now that we have processed all the DIEs in the CU, all the types
9484      should be complete, and it should now be safe to compute all of the
9485      physnames.  */
9486   compute_delayed_physnames (cu);
9487 
9488   if (cu->per_cu->lang == language_rust)
9489     rust_union_quirks (cu);
9490 
9491   /* TUs share symbol tables.
9492      If this is the first TU to use this symtab, complete the construction
9493      of it with end_expandable_symtab.  Otherwise, complete the addition of
9494      this TU's symbols to the existing symtab.  */
9495   type_unit_group_unshareable *tug_unshare =
9496     per_objfile->get_type_unit_group_unshareable (sig_type->type_unit_group);
9497   if (tug_unshare->compunit_symtab == NULL)
9498     {
9499       buildsym_compunit *builder = cu->get_builder ();
9500       cust = builder->end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
9501       tug_unshare->compunit_symtab = cust;
9502 
9503       if (cust != NULL)
9504 	{
9505 	  /* Set symtab language to language from DW_AT_language.  If the
9506 	     compilation is from a C file generated by language preprocessors,
9507 	     do not set the language if it was already deduced by
9508 	     start_subfile.  */
9509 	  if (!(cu->per_cu->lang == language_c
9510 		&& COMPUNIT_FILETABS (cust)->language != language_c))
9511 	    COMPUNIT_FILETABS (cust)->language = cu->per_cu->lang;
9512 	}
9513     }
9514   else
9515     {
9516       cu->get_builder ()->augment_type_symtab ();
9517       cust = tug_unshare->compunit_symtab;
9518     }
9519 
9520   per_objfile->set_symtab (cu->per_cu, cust);
9521 
9522   /* Not needed any more.  */
9523   cu->reset_builder ();
9524 }
9525 
9526 /* Process an imported unit DIE.  */
9527 
9528 static void
9529 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
9530 {
9531   struct attribute *attr;
9532 
9533   /* For now we don't handle imported units in type units.  */
9534   if (cu->per_cu->is_debug_types)
9535     {
9536       error (_("Dwarf Error: DW_TAG_imported_unit is not"
9537 	       " supported in type units [in module %s]"),
9538 	     objfile_name (cu->per_objfile->objfile));
9539     }
9540 
9541   attr = dwarf2_attr (die, DW_AT_import, cu);
9542   if (attr != NULL)
9543     {
9544       sect_offset sect_off = attr->get_ref_die_offset ();
9545       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
9546       dwarf2_per_objfile *per_objfile = cu->per_objfile;
9547       dwarf2_per_cu_data *per_cu
9548 	= dwarf2_find_containing_comp_unit (sect_off, is_dwz, per_objfile);
9549 
9550       /* We're importing a C++ compilation unit with tag DW_TAG_compile_unit
9551 	 into another compilation unit, at root level.  Regard this as a hint,
9552 	 and ignore it.  */
9553       if (die->parent && die->parent->parent == NULL
9554 	  && per_cu->unit_type == DW_UT_compile
9555 	  && per_cu->lang == language_cplus)
9556 	return;
9557 
9558       /* If necessary, add it to the queue and load its DIEs.  */
9559       if (maybe_queue_comp_unit (cu, per_cu, per_objfile,
9560 				 cu->per_cu->lang))
9561 	load_full_comp_unit (per_cu, per_objfile, per_objfile->get_cu (per_cu),
9562 			     false, cu->per_cu->lang);
9563 
9564       cu->per_cu->imported_symtabs_push (per_cu);
9565     }
9566 }
9567 
9568 /* RAII object that represents a process_die scope: i.e.,
9569    starts/finishes processing a DIE.  */
9570 class process_die_scope
9571 {
9572 public:
9573   process_die_scope (die_info *die, dwarf2_cu *cu)
9574     : m_die (die), m_cu (cu)
9575   {
9576     /* We should only be processing DIEs not already in process.  */
9577     gdb_assert (!m_die->in_process);
9578     m_die->in_process = true;
9579   }
9580 
9581   ~process_die_scope ()
9582   {
9583     m_die->in_process = false;
9584 
9585     /* If we're done processing the DIE for the CU that owns the line
9586        header, we don't need the line header anymore.  */
9587     if (m_cu->line_header_die_owner == m_die)
9588       {
9589 	delete m_cu->line_header;
9590 	m_cu->line_header = NULL;
9591 	m_cu->line_header_die_owner = NULL;
9592       }
9593   }
9594 
9595 private:
9596   die_info *m_die;
9597   dwarf2_cu *m_cu;
9598 };
9599 
9600 /* Process a die and its children.  */
9601 
9602 static void
9603 process_die (struct die_info *die, struct dwarf2_cu *cu)
9604 {
9605   process_die_scope scope (die, cu);
9606 
9607   switch (die->tag)
9608     {
9609     case DW_TAG_padding:
9610       break;
9611     case DW_TAG_compile_unit:
9612     case DW_TAG_partial_unit:
9613       read_file_scope (die, cu);
9614       break;
9615     case DW_TAG_type_unit:
9616       read_type_unit_scope (die, cu);
9617       break;
9618     case DW_TAG_subprogram:
9619       /* Nested subprograms in Fortran get a prefix.  */
9620       if (cu->per_cu->lang == language_fortran
9621 	  && die->parent != NULL
9622 	  && die->parent->tag == DW_TAG_subprogram)
9623 	cu->processing_has_namespace_info = true;
9624       /* Fall through.  */
9625     case DW_TAG_inlined_subroutine:
9626       read_func_scope (die, cu);
9627       break;
9628     case DW_TAG_lexical_block:
9629     case DW_TAG_try_block:
9630     case DW_TAG_catch_block:
9631       read_lexical_block_scope (die, cu);
9632       break;
9633     case DW_TAG_call_site:
9634     case DW_TAG_GNU_call_site:
9635       read_call_site_scope (die, cu);
9636       break;
9637     case DW_TAG_class_type:
9638     case DW_TAG_interface_type:
9639     case DW_TAG_structure_type:
9640     case DW_TAG_union_type:
9641       process_structure_scope (die, cu);
9642       break;
9643     case DW_TAG_enumeration_type:
9644       process_enumeration_scope (die, cu);
9645       break;
9646 
9647     /* These dies have a type, but processing them does not create
9648        a symbol or recurse to process the children.  Therefore we can
9649        read them on-demand through read_type_die.  */
9650     case DW_TAG_subroutine_type:
9651     case DW_TAG_set_type:
9652     case DW_TAG_pointer_type:
9653     case DW_TAG_ptr_to_member_type:
9654     case DW_TAG_reference_type:
9655     case DW_TAG_rvalue_reference_type:
9656     case DW_TAG_string_type:
9657       break;
9658 
9659     case DW_TAG_array_type:
9660       /* We only need to handle this case for Ada -- in other
9661 	 languages, it's normal for the compiler to emit a typedef
9662 	 instead.  */
9663       if (cu->per_cu->lang != language_ada)
9664 	break;
9665       /* FALLTHROUGH */
9666     case DW_TAG_base_type:
9667     case DW_TAG_subrange_type:
9668     case DW_TAG_typedef:
9669       /* Add a typedef symbol for the type definition, if it has a
9670 	 DW_AT_name.  */
9671       new_symbol (die, read_type_die (die, cu), cu);
9672       break;
9673     case DW_TAG_common_block:
9674       read_common_block (die, cu);
9675       break;
9676     case DW_TAG_common_inclusion:
9677       break;
9678     case DW_TAG_namespace:
9679       cu->processing_has_namespace_info = true;
9680       read_namespace (die, cu);
9681       break;
9682     case DW_TAG_module:
9683       cu->processing_has_namespace_info = true;
9684       read_module (die, cu);
9685       break;
9686     case DW_TAG_imported_declaration:
9687       cu->processing_has_namespace_info = true;
9688       if (read_namespace_alias (die, cu))
9689 	break;
9690       /* The declaration is not a global namespace alias.  */
9691       /* Fall through.  */
9692     case DW_TAG_imported_module:
9693       cu->processing_has_namespace_info = true;
9694       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
9695 				 || cu->per_cu->lang != language_fortran))
9696 	complaint (_("Tag '%s' has unexpected children"),
9697 		   dwarf_tag_name (die->tag));
9698       read_import_statement (die, cu);
9699       break;
9700 
9701     case DW_TAG_imported_unit:
9702       process_imported_unit_die (die, cu);
9703       break;
9704 
9705     case DW_TAG_variable:
9706       read_variable (die, cu);
9707       break;
9708 
9709     default:
9710       new_symbol (die, NULL, cu);
9711       break;
9712     }
9713 }
9714 
9715 /* DWARF name computation.  */
9716 
9717 /* A helper function for dwarf2_compute_name which determines whether DIE
9718    needs to have the name of the scope prepended to the name listed in the
9719    die.  */
9720 
9721 static int
9722 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
9723 {
9724   struct attribute *attr;
9725 
9726   switch (die->tag)
9727     {
9728     case DW_TAG_namespace:
9729     case DW_TAG_typedef:
9730     case DW_TAG_class_type:
9731     case DW_TAG_interface_type:
9732     case DW_TAG_structure_type:
9733     case DW_TAG_union_type:
9734     case DW_TAG_enumeration_type:
9735     case DW_TAG_enumerator:
9736     case DW_TAG_subprogram:
9737     case DW_TAG_inlined_subroutine:
9738     case DW_TAG_member:
9739     case DW_TAG_imported_declaration:
9740       return 1;
9741 
9742     case DW_TAG_variable:
9743     case DW_TAG_constant:
9744       /* We only need to prefix "globally" visible variables.  These include
9745 	 any variable marked with DW_AT_external or any variable that
9746 	 lives in a namespace.  [Variables in anonymous namespaces
9747 	 require prefixing, but they are not DW_AT_external.]  */
9748 
9749       if (dwarf2_attr (die, DW_AT_specification, cu))
9750 	{
9751 	  struct dwarf2_cu *spec_cu = cu;
9752 
9753 	  return die_needs_namespace (die_specification (die, &spec_cu),
9754 				      spec_cu);
9755 	}
9756 
9757       attr = dwarf2_attr (die, DW_AT_external, cu);
9758       if (attr == NULL && die->parent->tag != DW_TAG_namespace
9759 	  && die->parent->tag != DW_TAG_module)
9760 	return 0;
9761       /* A variable in a lexical block of some kind does not need a
9762 	 namespace, even though in C++ such variables may be external
9763 	 and have a mangled name.  */
9764       if (die->parent->tag ==  DW_TAG_lexical_block
9765 	  || die->parent->tag ==  DW_TAG_try_block
9766 	  || die->parent->tag ==  DW_TAG_catch_block
9767 	  || die->parent->tag == DW_TAG_subprogram)
9768 	return 0;
9769       return 1;
9770 
9771     default:
9772       return 0;
9773     }
9774 }
9775 
9776 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
9777    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9778    defined for the given DIE.  */
9779 
9780 static struct attribute *
9781 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
9782 {
9783   struct attribute *attr;
9784 
9785   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
9786   if (attr == NULL)
9787     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
9788 
9789   return attr;
9790 }
9791 
9792 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
9793    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9794    defined for the given DIE.  */
9795 
9796 static const char *
9797 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
9798 {
9799   const char *linkage_name;
9800 
9801   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
9802   if (linkage_name == NULL)
9803     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
9804 
9805   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
9806      See https://github.com/rust-lang/rust/issues/32925.  */
9807   if (cu->per_cu->lang == language_rust && linkage_name != NULL
9808       && strchr (linkage_name, '{') != NULL)
9809     linkage_name = NULL;
9810 
9811   return linkage_name;
9812 }
9813 
9814 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
9815    compute the physname for the object, which include a method's:
9816    - formal parameters (C++),
9817    - receiver type (Go),
9818 
9819    The term "physname" is a bit confusing.
9820    For C++, for example, it is the demangled name.
9821    For Go, for example, it's the mangled name.
9822 
9823    For Ada, return the DIE's linkage name rather than the fully qualified
9824    name.  PHYSNAME is ignored..
9825 
9826    The result is allocated on the objfile->per_bfd's obstack and
9827    canonicalized.  */
9828 
9829 static const char *
9830 dwarf2_compute_name (const char *name,
9831 		     struct die_info *die, struct dwarf2_cu *cu,
9832 		     int physname)
9833 {
9834   struct objfile *objfile = cu->per_objfile->objfile;
9835 
9836   if (name == NULL)
9837     name = dwarf2_name (die, cu);
9838 
9839   enum language lang = cu->per_cu->lang;
9840 
9841   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
9842      but otherwise compute it by typename_concat inside GDB.
9843      FIXME: Actually this is not really true, or at least not always true.
9844      It's all very confusing.  compute_and_set_names doesn't try to demangle
9845      Fortran names because there is no mangling standard.  So new_symbol
9846      will set the demangled name to the result of dwarf2_full_name, and it is
9847      the demangled name that GDB uses if it exists.  */
9848   if (lang == language_ada
9849       || (lang == language_fortran && physname))
9850     {
9851       /* For Ada unit, we prefer the linkage name over the name, as
9852 	 the former contains the exported name, which the user expects
9853 	 to be able to reference.  Ideally, we want the user to be able
9854 	 to reference this entity using either natural or linkage name,
9855 	 but we haven't started looking at this enhancement yet.  */
9856       const char *linkage_name = dw2_linkage_name (die, cu);
9857 
9858       if (linkage_name != NULL)
9859 	return linkage_name;
9860     }
9861 
9862   /* These are the only languages we know how to qualify names in.  */
9863   if (name != NULL
9864       && (lang == language_cplus
9865 	  || lang == language_fortran || lang == language_d
9866 	  || lang == language_rust))
9867     {
9868       if (die_needs_namespace (die, cu))
9869 	{
9870 	  const char *prefix;
9871 	  const char *canonical_name = NULL;
9872 
9873 	  string_file buf;
9874 
9875 	  prefix = determine_prefix (die, cu);
9876 	  if (*prefix != '\0')
9877 	    {
9878 	      gdb::unique_xmalloc_ptr<char> prefixed_name
9879 		(typename_concat (NULL, prefix, name, physname, cu));
9880 
9881 	      buf.puts (prefixed_name.get ());
9882 	    }
9883 	  else
9884 	    buf.puts (name);
9885 
9886 	  /* Template parameters may be specified in the DIE's DW_AT_name, or
9887 	     as children with DW_TAG_template_type_param or
9888 	     DW_TAG_value_type_param.  If the latter, add them to the name
9889 	     here.  If the name already has template parameters, then
9890 	     skip this step; some versions of GCC emit both, and
9891 	     it is more efficient to use the pre-computed name.
9892 
9893 	     Something to keep in mind about this process: it is very
9894 	     unlikely, or in some cases downright impossible, to produce
9895 	     something that will match the mangled name of a function.
9896 	     If the definition of the function has the same debug info,
9897 	     we should be able to match up with it anyway.  But fallbacks
9898 	     using the minimal symbol, for instance to find a method
9899 	     implemented in a stripped copy of libstdc++, will not work.
9900 	     If we do not have debug info for the definition, we will have to
9901 	     match them up some other way.
9902 
9903 	     When we do name matching there is a related problem with function
9904 	     templates; two instantiated function templates are allowed to
9905 	     differ only by their return types, which we do not add here.  */
9906 
9907 	  if (lang == language_cplus && strchr (name, '<') == NULL)
9908 	    {
9909 	      struct attribute *attr;
9910 	      struct die_info *child;
9911 	      int first = 1;
9912 
9913 	      die->building_fullname = 1;
9914 
9915 	      for (child = die->child; child != NULL; child = child->sibling)
9916 		{
9917 		  struct type *type;
9918 		  LONGEST value;
9919 		  const gdb_byte *bytes;
9920 		  struct dwarf2_locexpr_baton *baton;
9921 		  struct value *v;
9922 
9923 		  if (child->tag != DW_TAG_template_type_param
9924 		      && child->tag != DW_TAG_template_value_param)
9925 		    continue;
9926 
9927 		  if (first)
9928 		    {
9929 		      buf.puts ("<");
9930 		      first = 0;
9931 		    }
9932 		  else
9933 		    buf.puts (", ");
9934 
9935 		  attr = dwarf2_attr (child, DW_AT_type, cu);
9936 		  if (attr == NULL)
9937 		    {
9938 		      complaint (_("template parameter missing DW_AT_type"));
9939 		      buf.puts ("UNKNOWN_TYPE");
9940 		      continue;
9941 		    }
9942 		  type = die_type (child, cu);
9943 
9944 		  if (child->tag == DW_TAG_template_type_param)
9945 		    {
9946 		      cu->language_defn->print_type (type, "", &buf, -1, 0,
9947 						     &type_print_raw_options);
9948 		      continue;
9949 		    }
9950 
9951 		  attr = dwarf2_attr (child, DW_AT_const_value, cu);
9952 		  if (attr == NULL)
9953 		    {
9954 		      complaint (_("template parameter missing "
9955 				   "DW_AT_const_value"));
9956 		      buf.puts ("UNKNOWN_VALUE");
9957 		      continue;
9958 		    }
9959 
9960 		  dwarf2_const_value_attr (attr, type, name,
9961 					   &cu->comp_unit_obstack, cu,
9962 					   &value, &bytes, &baton);
9963 
9964 		  if (type->has_no_signedness ())
9965 		    /* GDB prints characters as NUMBER 'CHAR'.  If that's
9966 		       changed, this can use value_print instead.  */
9967 		    cu->language_defn->printchar (value, type, &buf);
9968 		  else
9969 		    {
9970 		      struct value_print_options opts;
9971 
9972 		      if (baton != NULL)
9973 			v = dwarf2_evaluate_loc_desc (type, NULL,
9974 						      baton->data,
9975 						      baton->size,
9976 						      baton->per_cu,
9977 						      baton->per_objfile);
9978 		      else if (bytes != NULL)
9979 			{
9980 			  v = allocate_value (type);
9981 			  memcpy (value_contents_writeable (v), bytes,
9982 				  TYPE_LENGTH (type));
9983 			}
9984 		      else
9985 			v = value_from_longest (type, value);
9986 
9987 		      /* Specify decimal so that we do not depend on
9988 			 the radix.  */
9989 		      get_formatted_print_options (&opts, 'd');
9990 		      opts.raw = 1;
9991 		      value_print (v, &buf, &opts);
9992 		      release_value (v);
9993 		    }
9994 		}
9995 
9996 	      die->building_fullname = 0;
9997 
9998 	      if (!first)
9999 		{
10000 		  /* Close the argument list, with a space if necessary
10001 		     (nested templates).  */
10002 		  if (!buf.empty () && buf.string ().back () == '>')
10003 		    buf.puts (" >");
10004 		  else
10005 		    buf.puts (">");
10006 		}
10007 	    }
10008 
10009 	  /* For C++ methods, append formal parameter type
10010 	     information, if PHYSNAME.  */
10011 
10012 	  if (physname && die->tag == DW_TAG_subprogram
10013 	      && lang == language_cplus)
10014 	    {
10015 	      struct type *type = read_type_die (die, cu);
10016 
10017 	      c_type_print_args (type, &buf, 1, lang,
10018 				 &type_print_raw_options);
10019 
10020 	      if (lang == language_cplus)
10021 		{
10022 		  /* Assume that an artificial first parameter is
10023 		     "this", but do not crash if it is not.  RealView
10024 		     marks unnamed (and thus unused) parameters as
10025 		     artificial; there is no way to differentiate
10026 		     the two cases.  */
10027 		  if (type->num_fields () > 0
10028 		      && TYPE_FIELD_ARTIFICIAL (type, 0)
10029 		      && type->field (0).type ()->code () == TYPE_CODE_PTR
10030 		      && TYPE_CONST (TYPE_TARGET_TYPE (type->field (0).type ())))
10031 		    buf.puts (" const");
10032 		}
10033 	    }
10034 
10035 	  const std::string &intermediate_name = buf.string ();
10036 
10037 	  if (lang == language_cplus)
10038 	    canonical_name
10039 	      = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10040 					  objfile);
10041 
10042 	  /* If we only computed INTERMEDIATE_NAME, or if
10043 	     INTERMEDIATE_NAME is already canonical, then we need to
10044 	     intern it.  */
10045 	  if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10046 	    name = objfile->intern (intermediate_name);
10047 	  else
10048 	    name = canonical_name;
10049 	}
10050     }
10051 
10052   return name;
10053 }
10054 
10055 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10056    If scope qualifiers are appropriate they will be added.  The result
10057    will be allocated on the storage_obstack, or NULL if the DIE does
10058    not have a name.  NAME may either be from a previous call to
10059    dwarf2_name or NULL.
10060 
10061    The output string will be canonicalized (if C++).  */
10062 
10063 static const char *
10064 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10065 {
10066   return dwarf2_compute_name (name, die, cu, 0);
10067 }
10068 
10069 /* Construct a physname for the given DIE in CU.  NAME may either be
10070    from a previous call to dwarf2_name or NULL.  The result will be
10071    allocated on the objfile_objstack or NULL if the DIE does not have a
10072    name.
10073 
10074    The output string will be canonicalized (if C++).  */
10075 
10076 static const char *
10077 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10078 {
10079   struct objfile *objfile = cu->per_objfile->objfile;
10080   const char *retval, *mangled = NULL, *canon = NULL;
10081   int need_copy = 1;
10082 
10083   /* In this case dwarf2_compute_name is just a shortcut not building anything
10084      on its own.  */
10085   if (!die_needs_namespace (die, cu))
10086     return dwarf2_compute_name (name, die, cu, 1);
10087 
10088   if (cu->per_cu->lang != language_rust)
10089     mangled = dw2_linkage_name (die, cu);
10090 
10091   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
10092      has computed.  */
10093   gdb::unique_xmalloc_ptr<char> demangled;
10094   if (mangled != NULL)
10095     {
10096       if (cu->language_defn->store_sym_names_in_linkage_form_p ())
10097 	{
10098 	  /* Do nothing (do not demangle the symbol name).  */
10099 	}
10100       else
10101 	{
10102 	  /* Use DMGL_RET_DROP for C++ template functions to suppress
10103 	     their return type.  It is easier for GDB users to search
10104 	     for such functions as `name(params)' than `long name(params)'.
10105 	     In such case the minimal symbol names do not match the full
10106 	     symbol names but for template functions there is never a need
10107 	     to look up their definition from their declaration so
10108 	     the only disadvantage remains the minimal symbol variant
10109 	     `long name(params)' does not have the proper inferior type.  */
10110 	  demangled.reset (gdb_demangle (mangled,
10111 					 (DMGL_PARAMS | DMGL_ANSI
10112 					  | DMGL_RET_DROP)));
10113 	}
10114       if (demangled)
10115 	canon = demangled.get ();
10116       else
10117 	{
10118 	  canon = mangled;
10119 	  need_copy = 0;
10120 	}
10121     }
10122 
10123   if (canon == NULL || check_physname)
10124     {
10125       const char *physname = dwarf2_compute_name (name, die, cu, 1);
10126 
10127       if (canon != NULL && strcmp (physname, canon) != 0)
10128 	{
10129 	  /* It may not mean a bug in GDB.  The compiler could also
10130 	     compute DW_AT_linkage_name incorrectly.  But in such case
10131 	     GDB would need to be bug-to-bug compatible.  */
10132 
10133 	  complaint (_("Computed physname <%s> does not match demangled <%s> "
10134 		       "(from linkage <%s>) - DIE at %s [in module %s]"),
10135 		     physname, canon, mangled, sect_offset_str (die->sect_off),
10136 		     objfile_name (objfile));
10137 
10138 	  /* Prefer DW_AT_linkage_name (in the CANON form) - when it
10139 	     is available here - over computed PHYSNAME.  It is safer
10140 	     against both buggy GDB and buggy compilers.  */
10141 
10142 	  retval = canon;
10143 	}
10144       else
10145 	{
10146 	  retval = physname;
10147 	  need_copy = 0;
10148 	}
10149     }
10150   else
10151     retval = canon;
10152 
10153   if (need_copy)
10154     retval = objfile->intern (retval);
10155 
10156   return retval;
10157 }
10158 
10159 /* Inspect DIE in CU for a namespace alias.  If one exists, record
10160    a new symbol for it.
10161 
10162    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
10163 
10164 static int
10165 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
10166 {
10167   struct attribute *attr;
10168 
10169   /* If the die does not have a name, this is not a namespace
10170      alias.  */
10171   attr = dwarf2_attr (die, DW_AT_name, cu);
10172   if (attr != NULL)
10173     {
10174       int num;
10175       struct die_info *d = die;
10176       struct dwarf2_cu *imported_cu = cu;
10177 
10178       /* If the compiler has nested DW_AT_imported_declaration DIEs,
10179 	 keep inspecting DIEs until we hit the underlying import.  */
10180 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
10181       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
10182 	{
10183 	  attr = dwarf2_attr (d, DW_AT_import, cu);
10184 	  if (attr == NULL)
10185 	    break;
10186 
10187 	  d = follow_die_ref (d, attr, &imported_cu);
10188 	  if (d->tag != DW_TAG_imported_declaration)
10189 	    break;
10190 	}
10191 
10192       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
10193 	{
10194 	  complaint (_("DIE at %s has too many recursively imported "
10195 		       "declarations"), sect_offset_str (d->sect_off));
10196 	  return 0;
10197 	}
10198 
10199       if (attr != NULL)
10200 	{
10201 	  struct type *type;
10202 	  sect_offset sect_off = attr->get_ref_die_offset ();
10203 
10204 	  type = get_die_type_at_offset (sect_off, cu->per_cu, cu->per_objfile);
10205 	  if (type != NULL && type->code () == TYPE_CODE_NAMESPACE)
10206 	    {
10207 	      /* This declaration is a global namespace alias.  Add
10208 		 a symbol for it whose type is the aliased namespace.  */
10209 	      new_symbol (die, type, cu);
10210 	      return 1;
10211 	    }
10212 	}
10213     }
10214 
10215   return 0;
10216 }
10217 
10218 /* Return the using directives repository (global or local?) to use in the
10219    current context for CU.
10220 
10221    For Ada, imported declarations can materialize renamings, which *may* be
10222    global.  However it is impossible (for now?) in DWARF to distinguish
10223    "external" imported declarations and "static" ones.  As all imported
10224    declarations seem to be static in all other languages, make them all CU-wide
10225    global only in Ada.  */
10226 
10227 static struct using_direct **
10228 using_directives (struct dwarf2_cu *cu)
10229 {
10230   if (cu->per_cu->lang == language_ada
10231       && cu->get_builder ()->outermost_context_p ())
10232     return cu->get_builder ()->get_global_using_directives ();
10233   else
10234     return cu->get_builder ()->get_local_using_directives ();
10235 }
10236 
10237 /* Read the import statement specified by the given die and record it.  */
10238 
10239 static void
10240 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
10241 {
10242   struct objfile *objfile = cu->per_objfile->objfile;
10243   struct attribute *import_attr;
10244   struct die_info *imported_die, *child_die;
10245   struct dwarf2_cu *imported_cu;
10246   const char *imported_name;
10247   const char *imported_name_prefix;
10248   const char *canonical_name;
10249   const char *import_alias;
10250   const char *imported_declaration = NULL;
10251   const char *import_prefix;
10252   std::vector<const char *> excludes;
10253 
10254   import_attr = dwarf2_attr (die, DW_AT_import, cu);
10255   if (import_attr == NULL)
10256     {
10257       complaint (_("Tag '%s' has no DW_AT_import"),
10258 		 dwarf_tag_name (die->tag));
10259       return;
10260     }
10261 
10262   imported_cu = cu;
10263   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
10264   imported_name = dwarf2_name (imported_die, imported_cu);
10265   if (imported_name == NULL)
10266     {
10267       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
10268 
10269 	The import in the following code:
10270 	namespace A
10271 	  {
10272 	    typedef int B;
10273 	  }
10274 
10275 	int main ()
10276 	  {
10277 	    using A::B;
10278 	    B b;
10279 	    return b;
10280 	  }
10281 
10282 	...
10283 	 <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
10284 	    <52>   DW_AT_decl_file   : 1
10285 	    <53>   DW_AT_decl_line   : 6
10286 	    <54>   DW_AT_import      : <0x75>
10287 	 <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
10288 	    <59>   DW_AT_name        : B
10289 	    <5b>   DW_AT_decl_file   : 1
10290 	    <5c>   DW_AT_decl_line   : 2
10291 	    <5d>   DW_AT_type        : <0x6e>
10292 	...
10293 	 <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
10294 	    <76>   DW_AT_byte_size   : 4
10295 	    <77>   DW_AT_encoding    : 5        (signed)
10296 
10297 	imports the wrong die ( 0x75 instead of 0x58 ).
10298 	This case will be ignored until the gcc bug is fixed.  */
10299       return;
10300     }
10301 
10302   /* Figure out the local name after import.  */
10303   import_alias = dwarf2_name (die, cu);
10304 
10305   /* Figure out where the statement is being imported to.  */
10306   import_prefix = determine_prefix (die, cu);
10307 
10308   /* Figure out what the scope of the imported die is and prepend it
10309      to the name of the imported die.  */
10310   imported_name_prefix = determine_prefix (imported_die, imported_cu);
10311 
10312   if (imported_die->tag != DW_TAG_namespace
10313       && imported_die->tag != DW_TAG_module)
10314     {
10315       imported_declaration = imported_name;
10316       canonical_name = imported_name_prefix;
10317     }
10318   else if (strlen (imported_name_prefix) > 0)
10319     canonical_name = obconcat (&objfile->objfile_obstack,
10320 			       imported_name_prefix,
10321 			       (cu->per_cu->lang == language_d
10322 				? "."
10323 				: "::"),
10324 			       imported_name, (char *) NULL);
10325   else
10326     canonical_name = imported_name;
10327 
10328   if (die->tag == DW_TAG_imported_module
10329       && cu->per_cu->lang == language_fortran)
10330     for (child_die = die->child; child_die && child_die->tag;
10331 	 child_die = child_die->sibling)
10332       {
10333 	/* DWARF-4: A Fortran use statement with a “rename list” may be
10334 	   represented by an imported module entry with an import attribute
10335 	   referring to the module and owned entries corresponding to those
10336 	   entities that are renamed as part of being imported.  */
10337 
10338 	if (child_die->tag != DW_TAG_imported_declaration)
10339 	  {
10340 	    complaint (_("child DW_TAG_imported_declaration expected "
10341 			 "- DIE at %s [in module %s]"),
10342 		       sect_offset_str (child_die->sect_off),
10343 		       objfile_name (objfile));
10344 	    continue;
10345 	  }
10346 
10347 	import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
10348 	if (import_attr == NULL)
10349 	  {
10350 	    complaint (_("Tag '%s' has no DW_AT_import"),
10351 		       dwarf_tag_name (child_die->tag));
10352 	    continue;
10353 	  }
10354 
10355 	imported_cu = cu;
10356 	imported_die = follow_die_ref_or_sig (child_die, import_attr,
10357 					      &imported_cu);
10358 	imported_name = dwarf2_name (imported_die, imported_cu);
10359 	if (imported_name == NULL)
10360 	  {
10361 	    complaint (_("child DW_TAG_imported_declaration has unknown "
10362 			 "imported name - DIE at %s [in module %s]"),
10363 		       sect_offset_str (child_die->sect_off),
10364 		       objfile_name (objfile));
10365 	    continue;
10366 	  }
10367 
10368 	excludes.push_back (imported_name);
10369 
10370 	process_die (child_die, cu);
10371       }
10372 
10373   add_using_directive (using_directives (cu),
10374 		       import_prefix,
10375 		       canonical_name,
10376 		       import_alias,
10377 		       imported_declaration,
10378 		       excludes,
10379 		       0,
10380 		       &objfile->objfile_obstack);
10381 }
10382 
10383 /* ICC<14 does not output the required DW_AT_declaration on incomplete
10384    types, but gives them a size of zero.  Starting with version 14,
10385    ICC is compatible with GCC.  */
10386 
10387 static bool
10388 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
10389 {
10390   if (!cu->checked_producer)
10391     check_producer (cu);
10392 
10393   return cu->producer_is_icc_lt_14;
10394 }
10395 
10396 /* ICC generates a DW_AT_type for C void functions.  This was observed on
10397    ICC 14.0.5.212, and appears to be against the DWARF spec (V5 3.3.2)
10398    which says that void functions should not have a DW_AT_type.  */
10399 
10400 static bool
10401 producer_is_icc (struct dwarf2_cu *cu)
10402 {
10403   if (!cu->checked_producer)
10404     check_producer (cu);
10405 
10406   return cu->producer_is_icc;
10407 }
10408 
10409 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
10410    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
10411    this, it was first present in GCC release 4.3.0.  */
10412 
10413 static bool
10414 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
10415 {
10416   if (!cu->checked_producer)
10417     check_producer (cu);
10418 
10419   return cu->producer_is_gcc_lt_4_3;
10420 }
10421 
10422 static file_and_directory
10423 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
10424 {
10425   file_and_directory res;
10426 
10427   /* Find the filename.  Do not use dwarf2_name here, since the filename
10428      is not a source language identifier.  */
10429   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
10430   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
10431 
10432   if (res.comp_dir == NULL
10433       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
10434       && IS_ABSOLUTE_PATH (res.name))
10435     {
10436       res.comp_dir_storage = ldirname (res.name);
10437       if (!res.comp_dir_storage.empty ())
10438 	res.comp_dir = res.comp_dir_storage.c_str ();
10439     }
10440   if (res.comp_dir != NULL)
10441     {
10442       /* Irix 6.2 native cc prepends <machine>.: to the compilation
10443 	 directory, get rid of it.  */
10444       const char *cp = strchr (res.comp_dir, ':');
10445 
10446       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
10447 	res.comp_dir = cp + 1;
10448     }
10449 
10450   if (res.name == NULL)
10451     res.name = "<unknown>";
10452 
10453   return res;
10454 }
10455 
10456 /* Handle DW_AT_stmt_list for a compilation unit.
10457    DIE is the DW_TAG_compile_unit die for CU.
10458    COMP_DIR is the compilation directory.  LOWPC is passed to
10459    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
10460 
10461 static void
10462 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
10463 			const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
10464 {
10465   dwarf2_per_objfile *per_objfile = cu->per_objfile;
10466   struct attribute *attr;
10467   struct line_header line_header_local;
10468   hashval_t line_header_local_hash;
10469   void **slot;
10470   int decode_mapping;
10471 
10472   gdb_assert (! cu->per_cu->is_debug_types);
10473 
10474   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
10475   if (attr == NULL || !attr->form_is_unsigned ())
10476     return;
10477 
10478   sect_offset line_offset = (sect_offset) attr->as_unsigned ();
10479 
10480   /* The line header hash table is only created if needed (it exists to
10481      prevent redundant reading of the line table for partial_units).
10482      If we're given a partial_unit, we'll need it.  If we're given a
10483      compile_unit, then use the line header hash table if it's already
10484      created, but don't create one just yet.  */
10485 
10486   if (per_objfile->line_header_hash == NULL
10487       && die->tag == DW_TAG_partial_unit)
10488     {
10489       per_objfile->line_header_hash
10490 	.reset (htab_create_alloc (127, line_header_hash_voidp,
10491 				   line_header_eq_voidp,
10492 				   htab_delete_entry<line_header>,
10493 				   xcalloc, xfree));
10494     }
10495 
10496   line_header_local.sect_off = line_offset;
10497   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
10498   line_header_local_hash = line_header_hash (&line_header_local);
10499   if (per_objfile->line_header_hash != NULL)
10500     {
10501       slot = htab_find_slot_with_hash (per_objfile->line_header_hash.get (),
10502 				       &line_header_local,
10503 				       line_header_local_hash, NO_INSERT);
10504 
10505       /* For DW_TAG_compile_unit we need info like symtab::linetable which
10506 	 is not present in *SLOT (since if there is something in *SLOT then
10507 	 it will be for a partial_unit).  */
10508       if (die->tag == DW_TAG_partial_unit && slot != NULL)
10509 	{
10510 	  gdb_assert (*slot != NULL);
10511 	  cu->line_header = (struct line_header *) *slot;
10512 	  return;
10513 	}
10514     }
10515 
10516   /* dwarf_decode_line_header does not yet provide sufficient information.
10517      We always have to call also dwarf_decode_lines for it.  */
10518   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
10519   if (lh == NULL)
10520     return;
10521 
10522   cu->line_header = lh.release ();
10523   cu->line_header_die_owner = die;
10524 
10525   if (per_objfile->line_header_hash == NULL)
10526     slot = NULL;
10527   else
10528     {
10529       slot = htab_find_slot_with_hash (per_objfile->line_header_hash.get (),
10530 				       &line_header_local,
10531 				       line_header_local_hash, INSERT);
10532       gdb_assert (slot != NULL);
10533     }
10534   if (slot != NULL && *slot == NULL)
10535     {
10536       /* This newly decoded line number information unit will be owned
10537 	 by line_header_hash hash table.  */
10538       *slot = cu->line_header;
10539       cu->line_header_die_owner = NULL;
10540     }
10541   else
10542     {
10543       /* We cannot free any current entry in (*slot) as that struct line_header
10544 	 may be already used by multiple CUs.  Create only temporary decoded
10545 	 line_header for this CU - it may happen at most once for each line
10546 	 number information unit.  And if we're not using line_header_hash
10547 	 then this is what we want as well.  */
10548       gdb_assert (die->tag != DW_TAG_partial_unit);
10549     }
10550   decode_mapping = (die->tag != DW_TAG_partial_unit);
10551   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
10552 		      decode_mapping);
10553 
10554 }
10555 
10556 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
10557 
10558 static void
10559 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
10560 {
10561   dwarf2_per_objfile *per_objfile = cu->per_objfile;
10562   struct objfile *objfile = per_objfile->objfile;
10563   struct gdbarch *gdbarch = objfile->arch ();
10564   CORE_ADDR lowpc = ((CORE_ADDR) -1);
10565   CORE_ADDR highpc = ((CORE_ADDR) 0);
10566   struct attribute *attr;
10567   struct die_info *child_die;
10568   CORE_ADDR baseaddr;
10569 
10570   prepare_one_comp_unit (cu, die, cu->per_cu->lang);
10571   baseaddr = objfile->text_section_offset ();
10572 
10573   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
10574 
10575   /* If we didn't find a lowpc, set it to highpc to avoid complaints
10576      from finish_block.  */
10577   if (lowpc == ((CORE_ADDR) -1))
10578     lowpc = highpc;
10579   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
10580 
10581   file_and_directory fnd = find_file_and_directory (die, cu);
10582 
10583   cu->start_symtab (fnd.name, fnd.comp_dir, lowpc);
10584 
10585   gdb_assert (per_objfile->sym_cu == nullptr);
10586   scoped_restore restore_sym_cu
10587     = make_scoped_restore (&per_objfile->sym_cu, cu);
10588 
10589   /* Decode line number information if present.  We do this before
10590      processing child DIEs, so that the line header table is available
10591      for DW_AT_decl_file.  */
10592   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
10593 
10594   /* Process all dies in compilation unit.  */
10595   if (die->child != NULL)
10596     {
10597       child_die = die->child;
10598       while (child_die && child_die->tag)
10599 	{
10600 	  process_die (child_die, cu);
10601 	  child_die = child_die->sibling;
10602 	}
10603     }
10604   per_objfile->sym_cu = nullptr;
10605 
10606   /* Decode macro information, if present.  Dwarf 2 macro information
10607      refers to information in the line number info statement program
10608      header, so we can only read it if we've read the header
10609      successfully.  */
10610   attr = dwarf2_attr (die, DW_AT_macros, cu);
10611   if (attr == NULL)
10612     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
10613   if (attr != nullptr && attr->form_is_unsigned () && cu->line_header)
10614     {
10615       if (dwarf2_attr (die, DW_AT_macro_info, cu))
10616 	complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
10617 
10618       dwarf_decode_macros (cu, attr->as_unsigned (), 1);
10619     }
10620   else
10621     {
10622       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
10623       if (attr != nullptr && attr->form_is_unsigned () && cu->line_header)
10624 	{
10625 	  unsigned int macro_offset = attr->as_unsigned ();
10626 
10627 	  dwarf_decode_macros (cu, macro_offset, 0);
10628 	}
10629     }
10630 }
10631 
10632 void
10633 dwarf2_cu::setup_type_unit_groups (struct die_info *die)
10634 {
10635   struct type_unit_group *tu_group;
10636   int first_time;
10637   struct attribute *attr;
10638   unsigned int i;
10639   struct signatured_type *sig_type;
10640 
10641   gdb_assert (per_cu->is_debug_types);
10642   sig_type = (struct signatured_type *) per_cu;
10643 
10644   attr = dwarf2_attr (die, DW_AT_stmt_list, this);
10645 
10646   /* If we're using .gdb_index (includes -readnow) then
10647      per_cu->type_unit_group may not have been set up yet.  */
10648   if (sig_type->type_unit_group == NULL)
10649     sig_type->type_unit_group = get_type_unit_group (this, attr);
10650   tu_group = sig_type->type_unit_group;
10651 
10652   /* If we've already processed this stmt_list there's no real need to
10653      do it again, we could fake it and just recreate the part we need
10654      (file name,index -> symtab mapping).  If data shows this optimization
10655      is useful we can do it then.  */
10656   type_unit_group_unshareable *tug_unshare
10657     = per_objfile->get_type_unit_group_unshareable (tu_group);
10658   first_time = tug_unshare->compunit_symtab == NULL;
10659 
10660   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
10661      debug info.  */
10662   line_header_up lh;
10663   if (attr != NULL && attr->form_is_unsigned ())
10664     {
10665       sect_offset line_offset = (sect_offset) attr->as_unsigned ();
10666       lh = dwarf_decode_line_header (line_offset, this);
10667     }
10668   if (lh == NULL)
10669     {
10670       if (first_time)
10671 	start_symtab ("", NULL, 0);
10672       else
10673 	{
10674 	  gdb_assert (tug_unshare->symtabs == NULL);
10675 	  gdb_assert (m_builder == nullptr);
10676 	  struct compunit_symtab *cust = tug_unshare->compunit_symtab;
10677 	  m_builder.reset (new struct buildsym_compunit
10678 			   (COMPUNIT_OBJFILE (cust), "",
10679 			    COMPUNIT_DIRNAME (cust),
10680 			    compunit_language (cust),
10681 			    0, cust));
10682 	  list_in_scope = get_builder ()->get_file_symbols ();
10683 	}
10684       return;
10685     }
10686 
10687   line_header = lh.release ();
10688   line_header_die_owner = die;
10689 
10690   if (first_time)
10691     {
10692       struct compunit_symtab *cust = start_symtab ("", NULL, 0);
10693 
10694       /* Note: We don't assign tu_group->compunit_symtab yet because we're
10695 	 still initializing it, and our caller (a few levels up)
10696 	 process_full_type_unit still needs to know if this is the first
10697 	 time.  */
10698 
10699       tug_unshare->symtabs
10700 	= XOBNEWVEC (&COMPUNIT_OBJFILE (cust)->objfile_obstack,
10701 		     struct symtab *, line_header->file_names_size ());
10702 
10703       auto &file_names = line_header->file_names ();
10704       for (i = 0; i < file_names.size (); ++i)
10705 	{
10706 	  file_entry &fe = file_names[i];
10707 	  dwarf2_start_subfile (this, fe.name,
10708 				fe.include_dir (line_header));
10709 	  buildsym_compunit *b = get_builder ();
10710 	  if (b->get_current_subfile ()->symtab == NULL)
10711 	    {
10712 	      /* NOTE: start_subfile will recognize when it's been
10713 		 passed a file it has already seen.  So we can't
10714 		 assume there's a simple mapping from
10715 		 cu->line_header->file_names to subfiles, plus
10716 		 cu->line_header->file_names may contain dups.  */
10717 	      b->get_current_subfile ()->symtab
10718 		= allocate_symtab (cust, b->get_current_subfile ()->name);
10719 	    }
10720 
10721 	  fe.symtab = b->get_current_subfile ()->symtab;
10722 	  tug_unshare->symtabs[i] = fe.symtab;
10723 	}
10724     }
10725   else
10726     {
10727       gdb_assert (m_builder == nullptr);
10728       struct compunit_symtab *cust = tug_unshare->compunit_symtab;
10729       m_builder.reset (new struct buildsym_compunit
10730 		       (COMPUNIT_OBJFILE (cust), "",
10731 			COMPUNIT_DIRNAME (cust),
10732 			compunit_language (cust),
10733 			0, cust));
10734       list_in_scope = get_builder ()->get_file_symbols ();
10735 
10736       auto &file_names = line_header->file_names ();
10737       for (i = 0; i < file_names.size (); ++i)
10738 	{
10739 	  file_entry &fe = file_names[i];
10740 	  fe.symtab = tug_unshare->symtabs[i];
10741 	}
10742     }
10743 
10744   /* The main symtab is allocated last.  Type units don't have DW_AT_name
10745      so they don't have a "real" (so to speak) symtab anyway.
10746      There is later code that will assign the main symtab to all symbols
10747      that don't have one.  We need to handle the case of a symbol with a
10748      missing symtab (DW_AT_decl_file) anyway.  */
10749 }
10750 
10751 /* Process DW_TAG_type_unit.
10752    For TUs we want to skip the first top level sibling if it's not the
10753    actual type being defined by this TU.  In this case the first top
10754    level sibling is there to provide context only.  */
10755 
10756 static void
10757 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
10758 {
10759   struct die_info *child_die;
10760 
10761   prepare_one_comp_unit (cu, die, language_minimal);
10762 
10763   /* Initialize (or reinitialize) the machinery for building symtabs.
10764      We do this before processing child DIEs, so that the line header table
10765      is available for DW_AT_decl_file.  */
10766   cu->setup_type_unit_groups (die);
10767 
10768   if (die->child != NULL)
10769     {
10770       child_die = die->child;
10771       while (child_die && child_die->tag)
10772 	{
10773 	  process_die (child_die, cu);
10774 	  child_die = child_die->sibling;
10775 	}
10776     }
10777 }
10778 
10779 /* DWO/DWP files.
10780 
10781    http://gcc.gnu.org/wiki/DebugFission
10782    http://gcc.gnu.org/wiki/DebugFissionDWP
10783 
10784    To simplify handling of both DWO files ("object" files with the DWARF info)
10785    and DWP files (a file with the DWOs packaged up into one file), we treat
10786    DWP files as having a collection of virtual DWO files.  */
10787 
10788 static hashval_t
10789 hash_dwo_file (const void *item)
10790 {
10791   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
10792   hashval_t hash;
10793 
10794   hash = htab_hash_string (dwo_file->dwo_name);
10795   if (dwo_file->comp_dir != NULL)
10796     hash += htab_hash_string (dwo_file->comp_dir);
10797   return hash;
10798 }
10799 
10800 static int
10801 eq_dwo_file (const void *item_lhs, const void *item_rhs)
10802 {
10803   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
10804   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
10805 
10806   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
10807     return 0;
10808   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
10809     return lhs->comp_dir == rhs->comp_dir;
10810   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
10811 }
10812 
10813 /* Allocate a hash table for DWO files.  */
10814 
10815 static htab_up
10816 allocate_dwo_file_hash_table ()
10817 {
10818   return htab_up (htab_create_alloc (41,
10819 				     hash_dwo_file,
10820 				     eq_dwo_file,
10821 				     htab_delete_entry<dwo_file>,
10822 				     xcalloc, xfree));
10823 }
10824 
10825 /* Lookup DWO file DWO_NAME.  */
10826 
10827 static void **
10828 lookup_dwo_file_slot (dwarf2_per_objfile *per_objfile,
10829 		      const char *dwo_name,
10830 		      const char *comp_dir)
10831 {
10832   struct dwo_file find_entry;
10833   void **slot;
10834 
10835   if (per_objfile->per_bfd->dwo_files == NULL)
10836     per_objfile->per_bfd->dwo_files = allocate_dwo_file_hash_table ();
10837 
10838   find_entry.dwo_name = dwo_name;
10839   find_entry.comp_dir = comp_dir;
10840   slot = htab_find_slot (per_objfile->per_bfd->dwo_files.get (), &find_entry,
10841 			 INSERT);
10842 
10843   return slot;
10844 }
10845 
10846 static hashval_t
10847 hash_dwo_unit (const void *item)
10848 {
10849   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
10850 
10851   /* This drops the top 32 bits of the id, but is ok for a hash.  */
10852   return dwo_unit->signature;
10853 }
10854 
10855 static int
10856 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
10857 {
10858   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
10859   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
10860 
10861   /* The signature is assumed to be unique within the DWO file.
10862      So while object file CU dwo_id's always have the value zero,
10863      that's OK, assuming each object file DWO file has only one CU,
10864      and that's the rule for now.  */
10865   return lhs->signature == rhs->signature;
10866 }
10867 
10868 /* Allocate a hash table for DWO CUs,TUs.
10869    There is one of these tables for each of CUs,TUs for each DWO file.  */
10870 
10871 static htab_up
10872 allocate_dwo_unit_table ()
10873 {
10874   /* Start out with a pretty small number.
10875      Generally DWO files contain only one CU and maybe some TUs.  */
10876   return htab_up (htab_create_alloc (3,
10877 				     hash_dwo_unit,
10878 				     eq_dwo_unit,
10879 				     NULL, xcalloc, xfree));
10880 }
10881 
10882 /* die_reader_func for create_dwo_cu.  */
10883 
10884 static void
10885 create_dwo_cu_reader (const struct die_reader_specs *reader,
10886 		      const gdb_byte *info_ptr,
10887 		      struct die_info *comp_unit_die,
10888 		      struct dwo_file *dwo_file,
10889 		      struct dwo_unit *dwo_unit)
10890 {
10891   struct dwarf2_cu *cu = reader->cu;
10892   sect_offset sect_off = cu->per_cu->sect_off;
10893   struct dwarf2_section_info *section = cu->per_cu->section;
10894 
10895   gdb::optional<ULONGEST> signature = lookup_dwo_id (cu, comp_unit_die);
10896   if (!signature.has_value ())
10897     {
10898       complaint (_("Dwarf Error: debug entry at offset %s is missing"
10899 		   " its dwo_id [in module %s]"),
10900 		 sect_offset_str (sect_off), dwo_file->dwo_name);
10901       return;
10902     }
10903 
10904   dwo_unit->dwo_file = dwo_file;
10905   dwo_unit->signature = *signature;
10906   dwo_unit->section = section;
10907   dwo_unit->sect_off = sect_off;
10908   dwo_unit->length = cu->per_cu->length;
10909 
10910   dwarf_read_debug_printf ("  offset %s, dwo_id %s",
10911 			   sect_offset_str (sect_off),
10912 			   hex_string (dwo_unit->signature));
10913 }
10914 
10915 /* Create the dwo_units for the CUs in a DWO_FILE.
10916    Note: This function processes DWO files only, not DWP files.  */
10917 
10918 static void
10919 create_cus_hash_table (dwarf2_per_objfile *per_objfile,
10920 		       dwarf2_cu *cu, struct dwo_file &dwo_file,
10921 		       dwarf2_section_info &section, htab_up &cus_htab)
10922 {
10923   struct objfile *objfile = per_objfile->objfile;
10924   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
10925   const gdb_byte *info_ptr, *end_ptr;
10926 
10927   section.read (objfile);
10928   info_ptr = section.buffer;
10929 
10930   if (info_ptr == NULL)
10931     return;
10932 
10933   dwarf_read_debug_printf ("Reading %s for %s:",
10934 			   section.get_name (),
10935 			   section.get_file_name ());
10936 
10937   end_ptr = info_ptr + section.size;
10938   while (info_ptr < end_ptr)
10939     {
10940       struct dwarf2_per_cu_data per_cu;
10941       struct dwo_unit read_unit {};
10942       struct dwo_unit *dwo_unit;
10943       void **slot;
10944       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
10945 
10946       per_cu.per_bfd = per_bfd;
10947       per_cu.is_debug_types = 0;
10948       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
10949       per_cu.section = &section;
10950 
10951       cutu_reader reader (&per_cu, per_objfile, cu, &dwo_file);
10952       if (!reader.dummy_p)
10953 	create_dwo_cu_reader (&reader, reader.info_ptr, reader.comp_unit_die,
10954 			      &dwo_file, &read_unit);
10955       info_ptr += per_cu.length;
10956 
10957       // If the unit could not be parsed, skip it.
10958       if (read_unit.dwo_file == NULL)
10959 	continue;
10960 
10961       if (cus_htab == NULL)
10962 	cus_htab = allocate_dwo_unit_table ();
10963 
10964       dwo_unit = OBSTACK_ZALLOC (&per_bfd->obstack,
10965 				 struct dwo_unit);
10966       *dwo_unit = read_unit;
10967       slot = htab_find_slot (cus_htab.get (), dwo_unit, INSERT);
10968       gdb_assert (slot != NULL);
10969       if (*slot != NULL)
10970 	{
10971 	  const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
10972 	  sect_offset dup_sect_off = dup_cu->sect_off;
10973 
10974 	  complaint (_("debug cu entry at offset %s is duplicate to"
10975 		       " the entry at offset %s, signature %s"),
10976 		     sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
10977 		     hex_string (dwo_unit->signature));
10978 	}
10979       *slot = (void *)dwo_unit;
10980     }
10981 }
10982 
10983 /* DWP file .debug_{cu,tu}_index section format:
10984    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
10985    [ref: http://dwarfstd.org/doc/DWARF5.pdf, sect 7.3.5 "DWARF Package Files"]
10986 
10987    DWP Versions 1 & 2 are older, pre-standard format versions.  The first
10988    officially standard DWP format was published with DWARF v5 and is called
10989    Version 5.  There are no versions 3 or 4.
10990 
10991    DWP Version 1:
10992 
10993    Both index sections have the same format, and serve to map a 64-bit
10994    signature to a set of section numbers.  Each section begins with a header,
10995    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
10996    indexes, and a pool of 32-bit section numbers.  The index sections will be
10997    aligned at 8-byte boundaries in the file.
10998 
10999    The index section header consists of:
11000 
11001     V, 32 bit version number
11002     -, 32 bits unused
11003     N, 32 bit number of compilation units or type units in the index
11004     M, 32 bit number of slots in the hash table
11005 
11006    Numbers are recorded using the byte order of the application binary.
11007 
11008    The hash table begins at offset 16 in the section, and consists of an array
11009    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11010    order of the application binary).  Unused slots in the hash table are 0.
11011    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11012 
11013    The parallel table begins immediately after the hash table
11014    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11015    array of 32-bit indexes (using the byte order of the application binary),
11016    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11017    table contains a 32-bit index into the pool of section numbers.  For unused
11018    hash table slots, the corresponding entry in the parallel table will be 0.
11019 
11020    The pool of section numbers begins immediately following the hash table
11021    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11022    section numbers consists of an array of 32-bit words (using the byte order
11023    of the application binary).  Each item in the array is indexed starting
11024    from 0.  The hash table entry provides the index of the first section
11025    number in the set.  Additional section numbers in the set follow, and the
11026    set is terminated by a 0 entry (section number 0 is not used in ELF).
11027 
11028    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11029    section must be the first entry in the set, and the .debug_abbrev.dwo must
11030    be the second entry. Other members of the set may follow in any order.
11031 
11032    ---
11033 
11034    DWP Versions 2 and 5:
11035 
11036    DWP Versions 2 and 5 combine all the .debug_info, etc. sections into one,
11037    and the entries in the index tables are now offsets into these sections.
11038    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
11039    section.
11040 
11041    Index Section Contents:
11042     Header
11043     Hash Table of Signatures   dwp_hash_table.hash_table
11044     Parallel Table of Indices  dwp_hash_table.unit_table
11045     Table of Section Offsets   dwp_hash_table.{v2|v5}.{section_ids,offsets}
11046     Table of Section Sizes     dwp_hash_table.{v2|v5}.sizes
11047 
11048    The index section header consists of:
11049 
11050     V, 32 bit version number
11051     L, 32 bit number of columns in the table of section offsets
11052     N, 32 bit number of compilation units or type units in the index
11053     M, 32 bit number of slots in the hash table
11054 
11055    Numbers are recorded using the byte order of the application binary.
11056 
11057    The hash table has the same format as version 1.
11058    The parallel table of indices has the same format as version 1,
11059    except that the entries are origin-1 indices into the table of sections
11060    offsets and the table of section sizes.
11061 
11062    The table of offsets begins immediately following the parallel table
11063    (at offset 16 + 12 * M from the beginning of the section).  The table is
11064    a two-dimensional array of 32-bit words (using the byte order of the
11065    application binary), with L columns and N+1 rows, in row-major order.
11066    Each row in the array is indexed starting from 0.  The first row provides
11067    a key to the remaining rows: each column in this row provides an identifier
11068    for a debug section, and the offsets in the same column of subsequent rows
11069    refer to that section.  The section identifiers for Version 2 are:
11070 
11071     DW_SECT_INFO         1  .debug_info.dwo
11072     DW_SECT_TYPES        2  .debug_types.dwo
11073     DW_SECT_ABBREV       3  .debug_abbrev.dwo
11074     DW_SECT_LINE         4  .debug_line.dwo
11075     DW_SECT_LOC          5  .debug_loc.dwo
11076     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
11077     DW_SECT_MACINFO      7  .debug_macinfo.dwo
11078     DW_SECT_MACRO        8  .debug_macro.dwo
11079 
11080    The section identifiers for Version 5 are:
11081 
11082     DW_SECT_INFO_V5         1  .debug_info.dwo
11083     DW_SECT_RESERVED_V5     2  --
11084     DW_SECT_ABBREV_V5       3  .debug_abbrev.dwo
11085     DW_SECT_LINE_V5         4  .debug_line.dwo
11086     DW_SECT_LOCLISTS_V5     5  .debug_loclists.dwo
11087     DW_SECT_STR_OFFSETS_V5  6  .debug_str_offsets.dwo
11088     DW_SECT_MACRO_V5        7  .debug_macro.dwo
11089     DW_SECT_RNGLISTS_V5     8  .debug_rnglists.dwo
11090 
11091    The offsets provided by the CU and TU index sections are the base offsets
11092    for the contributions made by each CU or TU to the corresponding section
11093    in the package file.  Each CU and TU header contains an abbrev_offset
11094    field, used to find the abbreviations table for that CU or TU within the
11095    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
11096    be interpreted as relative to the base offset given in the index section.
11097    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
11098    should be interpreted as relative to the base offset for .debug_line.dwo,
11099    and offsets into other debug sections obtained from DWARF attributes should
11100    also be interpreted as relative to the corresponding base offset.
11101 
11102    The table of sizes begins immediately following the table of offsets.
11103    Like the table of offsets, it is a two-dimensional array of 32-bit words,
11104    with L columns and N rows, in row-major order.  Each row in the array is
11105    indexed starting from 1 (row 0 is shared by the two tables).
11106 
11107    ---
11108 
11109    Hash table lookup is handled the same in version 1 and 2:
11110 
11111    We assume that N and M will not exceed 2^32 - 1.
11112    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
11113 
11114    Given a 64-bit compilation unit signature or a type signature S, an entry
11115    in the hash table is located as follows:
11116 
11117    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
11118       the low-order k bits all set to 1.
11119 
11120    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
11121 
11122    3) If the hash table entry at index H matches the signature, use that
11123       entry.  If the hash table entry at index H is unused (all zeroes),
11124       terminate the search: the signature is not present in the table.
11125 
11126    4) Let H = (H + H') modulo M. Repeat at Step 3.
11127 
11128    Because M > N and H' and M are relatively prime, the search is guaranteed
11129    to stop at an unused slot or find the match.  */
11130 
11131 /* Create a hash table to map DWO IDs to their CU/TU entry in
11132    .debug_{info,types}.dwo in DWP_FILE.
11133    Returns NULL if there isn't one.
11134    Note: This function processes DWP files only, not DWO files.  */
11135 
11136 static struct dwp_hash_table *
11137 create_dwp_hash_table (dwarf2_per_objfile *per_objfile,
11138 		       struct dwp_file *dwp_file, int is_debug_types)
11139 {
11140   struct objfile *objfile = per_objfile->objfile;
11141   bfd *dbfd = dwp_file->dbfd.get ();
11142   const gdb_byte *index_ptr, *index_end;
11143   struct dwarf2_section_info *index;
11144   uint32_t version, nr_columns, nr_units, nr_slots;
11145   struct dwp_hash_table *htab;
11146 
11147   if (is_debug_types)
11148     index = &dwp_file->sections.tu_index;
11149   else
11150     index = &dwp_file->sections.cu_index;
11151 
11152   if (index->empty ())
11153     return NULL;
11154   index->read (objfile);
11155 
11156   index_ptr = index->buffer;
11157   index_end = index_ptr + index->size;
11158 
11159   /* For Version 5, the version is really 2 bytes of data & 2 bytes of padding.
11160      For now it's safe to just read 4 bytes (particularly as it's difficult to
11161      tell if you're dealing with Version 5 before you've read the version).   */
11162   version = read_4_bytes (dbfd, index_ptr);
11163   index_ptr += 4;
11164   if (version == 2 || version == 5)
11165     nr_columns = read_4_bytes (dbfd, index_ptr);
11166   else
11167     nr_columns = 0;
11168   index_ptr += 4;
11169   nr_units = read_4_bytes (dbfd, index_ptr);
11170   index_ptr += 4;
11171   nr_slots = read_4_bytes (dbfd, index_ptr);
11172   index_ptr += 4;
11173 
11174   if (version != 1 && version != 2 && version != 5)
11175     {
11176       error (_("Dwarf Error: unsupported DWP file version (%s)"
11177 	       " [in module %s]"),
11178 	     pulongest (version), dwp_file->name);
11179     }
11180   if (nr_slots != (nr_slots & -nr_slots))
11181     {
11182       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
11183 	       " is not power of 2 [in module %s]"),
11184 	     pulongest (nr_slots), dwp_file->name);
11185     }
11186 
11187   htab = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, struct dwp_hash_table);
11188   htab->version = version;
11189   htab->nr_columns = nr_columns;
11190   htab->nr_units = nr_units;
11191   htab->nr_slots = nr_slots;
11192   htab->hash_table = index_ptr;
11193   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
11194 
11195   /* Exit early if the table is empty.  */
11196   if (nr_slots == 0 || nr_units == 0
11197       || (version == 2 && nr_columns == 0)
11198       || (version == 5 && nr_columns == 0))
11199     {
11200       /* All must be zero.  */
11201       if (nr_slots != 0 || nr_units != 0
11202 	  || (version == 2 && nr_columns != 0)
11203 	  || (version == 5 && nr_columns != 0))
11204 	{
11205 	  complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
11206 		       " all zero [in modules %s]"),
11207 		     dwp_file->name);
11208 	}
11209       return htab;
11210     }
11211 
11212   if (version == 1)
11213     {
11214       htab->section_pool.v1.indices =
11215 	htab->unit_table + sizeof (uint32_t) * nr_slots;
11216       /* It's harder to decide whether the section is too small in v1.
11217 	 V1 is deprecated anyway so we punt.  */
11218     }
11219   else if (version == 2)
11220     {
11221       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
11222       int *ids = htab->section_pool.v2.section_ids;
11223       size_t sizeof_ids = sizeof (htab->section_pool.v2.section_ids);
11224       /* Reverse map for error checking.  */
11225       int ids_seen[DW_SECT_MAX + 1];
11226       int i;
11227 
11228       if (nr_columns < 2)
11229 	{
11230 	  error (_("Dwarf Error: bad DWP hash table, too few columns"
11231 		   " in section table [in module %s]"),
11232 		 dwp_file->name);
11233 	}
11234       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
11235 	{
11236 	  error (_("Dwarf Error: bad DWP hash table, too many columns"
11237 		   " in section table [in module %s]"),
11238 		 dwp_file->name);
11239 	}
11240       memset (ids, 255, sizeof_ids);
11241       memset (ids_seen, 255, sizeof (ids_seen));
11242       for (i = 0; i < nr_columns; ++i)
11243 	{
11244 	  int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
11245 
11246 	  if (id < DW_SECT_MIN || id > DW_SECT_MAX)
11247 	    {
11248 	      error (_("Dwarf Error: bad DWP hash table, bad section id %d"
11249 		       " in section table [in module %s]"),
11250 		     id, dwp_file->name);
11251 	    }
11252 	  if (ids_seen[id] != -1)
11253 	    {
11254 	      error (_("Dwarf Error: bad DWP hash table, duplicate section"
11255 		       " id %d in section table [in module %s]"),
11256 		     id, dwp_file->name);
11257 	    }
11258 	  ids_seen[id] = i;
11259 	  ids[i] = id;
11260 	}
11261       /* Must have exactly one info or types section.  */
11262       if (((ids_seen[DW_SECT_INFO] != -1)
11263 	   + (ids_seen[DW_SECT_TYPES] != -1))
11264 	  != 1)
11265 	{
11266 	  error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
11267 		   " DWO info/types section [in module %s]"),
11268 		 dwp_file->name);
11269 	}
11270       /* Must have an abbrev section.  */
11271       if (ids_seen[DW_SECT_ABBREV] == -1)
11272 	{
11273 	  error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
11274 		   " section [in module %s]"),
11275 		 dwp_file->name);
11276 	}
11277       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
11278       htab->section_pool.v2.sizes =
11279 	htab->section_pool.v2.offsets + (sizeof (uint32_t)
11280 					 * nr_units * nr_columns);
11281       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
11282 					  * nr_units * nr_columns))
11283 	  > index_end)
11284 	{
11285 	  error (_("Dwarf Error: DWP index section is corrupt (too small)"
11286 		   " [in module %s]"),
11287 		 dwp_file->name);
11288 	}
11289     }
11290   else /* version == 5  */
11291     {
11292       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
11293       int *ids = htab->section_pool.v5.section_ids;
11294       size_t sizeof_ids = sizeof (htab->section_pool.v5.section_ids);
11295       /* Reverse map for error checking.  */
11296       int ids_seen[DW_SECT_MAX_V5 + 1];
11297 
11298       if (nr_columns < 2)
11299 	{
11300 	  error (_("Dwarf Error: bad DWP hash table, too few columns"
11301 		   " in section table [in module %s]"),
11302 		 dwp_file->name);
11303 	}
11304       if (nr_columns > MAX_NR_V5_DWO_SECTIONS)
11305 	{
11306 	  error (_("Dwarf Error: bad DWP hash table, too many columns"
11307 		   " in section table [in module %s]"),
11308 		 dwp_file->name);
11309 	}
11310       memset (ids, 255, sizeof_ids);
11311       memset (ids_seen, 255, sizeof (ids_seen));
11312       for (int i = 0; i < nr_columns; ++i)
11313 	{
11314 	  int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
11315 
11316 	  if (id < DW_SECT_MIN || id > DW_SECT_MAX_V5)
11317 	    {
11318 	      error (_("Dwarf Error: bad DWP hash table, bad section id %d"
11319 		       " in section table [in module %s]"),
11320 		     id, dwp_file->name);
11321 	    }
11322 	  if (ids_seen[id] != -1)
11323 	    {
11324 	      error (_("Dwarf Error: bad DWP hash table, duplicate section"
11325 		       " id %d in section table [in module %s]"),
11326 		     id, dwp_file->name);
11327 	    }
11328 	  ids_seen[id] = i;
11329 	  ids[i] = id;
11330 	}
11331       /* Must have seen an info section.  */
11332       if (ids_seen[DW_SECT_INFO_V5] == -1)
11333 	{
11334 	  error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
11335 		   " DWO info/types section [in module %s]"),
11336 		 dwp_file->name);
11337 	}
11338       /* Must have an abbrev section.  */
11339       if (ids_seen[DW_SECT_ABBREV_V5] == -1)
11340 	{
11341 	  error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
11342 		   " section [in module %s]"),
11343 		 dwp_file->name);
11344 	}
11345       htab->section_pool.v5.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
11346       htab->section_pool.v5.sizes
11347 	= htab->section_pool.v5.offsets + (sizeof (uint32_t)
11348 					 * nr_units * nr_columns);
11349       if ((htab->section_pool.v5.sizes + (sizeof (uint32_t)
11350 					  * nr_units * nr_columns))
11351 	  > index_end)
11352 	{
11353 	  error (_("Dwarf Error: DWP index section is corrupt (too small)"
11354 		   " [in module %s]"),
11355 		 dwp_file->name);
11356 	}
11357     }
11358 
11359   return htab;
11360 }
11361 
11362 /* Update SECTIONS with the data from SECTP.
11363 
11364    This function is like the other "locate" section routines, but in
11365    this context the sections to read comes from the DWP V1 hash table,
11366    not the full ELF section table.
11367 
11368    The result is non-zero for success, or zero if an error was found.  */
11369 
11370 static int
11371 locate_v1_virtual_dwo_sections (asection *sectp,
11372 				struct virtual_v1_dwo_sections *sections)
11373 {
11374   const struct dwop_section_names *names = &dwop_section_names;
11375 
11376   if (names->abbrev_dwo.matches (sectp->name))
11377     {
11378       /* There can be only one.  */
11379       if (sections->abbrev.s.section != NULL)
11380 	return 0;
11381       sections->abbrev.s.section = sectp;
11382       sections->abbrev.size = bfd_section_size (sectp);
11383     }
11384   else if (names->info_dwo.matches (sectp->name)
11385 	   || names->types_dwo.matches (sectp->name))
11386     {
11387       /* There can be only one.  */
11388       if (sections->info_or_types.s.section != NULL)
11389 	return 0;
11390       sections->info_or_types.s.section = sectp;
11391       sections->info_or_types.size = bfd_section_size (sectp);
11392     }
11393   else if (names->line_dwo.matches (sectp->name))
11394     {
11395       /* There can be only one.  */
11396       if (sections->line.s.section != NULL)
11397 	return 0;
11398       sections->line.s.section = sectp;
11399       sections->line.size = bfd_section_size (sectp);
11400     }
11401   else if (names->loc_dwo.matches (sectp->name))
11402     {
11403       /* There can be only one.  */
11404       if (sections->loc.s.section != NULL)
11405 	return 0;
11406       sections->loc.s.section = sectp;
11407       sections->loc.size = bfd_section_size (sectp);
11408     }
11409   else if (names->macinfo_dwo.matches (sectp->name))
11410     {
11411       /* There can be only one.  */
11412       if (sections->macinfo.s.section != NULL)
11413 	return 0;
11414       sections->macinfo.s.section = sectp;
11415       sections->macinfo.size = bfd_section_size (sectp);
11416     }
11417   else if (names->macro_dwo.matches (sectp->name))
11418     {
11419       /* There can be only one.  */
11420       if (sections->macro.s.section != NULL)
11421 	return 0;
11422       sections->macro.s.section = sectp;
11423       sections->macro.size = bfd_section_size (sectp);
11424     }
11425   else if (names->str_offsets_dwo.matches (sectp->name))
11426     {
11427       /* There can be only one.  */
11428       if (sections->str_offsets.s.section != NULL)
11429 	return 0;
11430       sections->str_offsets.s.section = sectp;
11431       sections->str_offsets.size = bfd_section_size (sectp);
11432     }
11433   else
11434     {
11435       /* No other kind of section is valid.  */
11436       return 0;
11437     }
11438 
11439   return 1;
11440 }
11441 
11442 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11443    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11444    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11445    This is for DWP version 1 files.  */
11446 
11447 static struct dwo_unit *
11448 create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile *per_objfile,
11449 			   struct dwp_file *dwp_file,
11450 			   uint32_t unit_index,
11451 			   const char *comp_dir,
11452 			   ULONGEST signature, int is_debug_types)
11453 {
11454   const struct dwp_hash_table *dwp_htab =
11455     is_debug_types ? dwp_file->tus : dwp_file->cus;
11456   bfd *dbfd = dwp_file->dbfd.get ();
11457   const char *kind = is_debug_types ? "TU" : "CU";
11458   struct dwo_file *dwo_file;
11459   struct dwo_unit *dwo_unit;
11460   struct virtual_v1_dwo_sections sections;
11461   void **dwo_file_slot;
11462   int i;
11463 
11464   gdb_assert (dwp_file->version == 1);
11465 
11466   dwarf_read_debug_printf ("Reading %s %s/%s in DWP V1 file: %s",
11467 			   kind, pulongest (unit_index), hex_string (signature),
11468 			   dwp_file->name);
11469 
11470   /* Fetch the sections of this DWO unit.
11471      Put a limit on the number of sections we look for so that bad data
11472      doesn't cause us to loop forever.  */
11473 
11474 #define MAX_NR_V1_DWO_SECTIONS \
11475   (1 /* .debug_info or .debug_types */ \
11476    + 1 /* .debug_abbrev */ \
11477    + 1 /* .debug_line */ \
11478    + 1 /* .debug_loc */ \
11479    + 1 /* .debug_str_offsets */ \
11480    + 1 /* .debug_macro or .debug_macinfo */ \
11481    + 1 /* trailing zero */)
11482 
11483   memset (&sections, 0, sizeof (sections));
11484 
11485   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
11486     {
11487       asection *sectp;
11488       uint32_t section_nr =
11489 	read_4_bytes (dbfd,
11490 		      dwp_htab->section_pool.v1.indices
11491 		      + (unit_index + i) * sizeof (uint32_t));
11492 
11493       if (section_nr == 0)
11494 	break;
11495       if (section_nr >= dwp_file->num_sections)
11496 	{
11497 	  error (_("Dwarf Error: bad DWP hash table, section number too large"
11498 		   " [in module %s]"),
11499 		 dwp_file->name);
11500 	}
11501 
11502       sectp = dwp_file->elf_sections[section_nr];
11503       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
11504 	{
11505 	  error (_("Dwarf Error: bad DWP hash table, invalid section found"
11506 		   " [in module %s]"),
11507 		 dwp_file->name);
11508 	}
11509     }
11510 
11511   if (i < 2
11512       || sections.info_or_types.empty ()
11513       || sections.abbrev.empty ())
11514     {
11515       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
11516 	       " [in module %s]"),
11517 	     dwp_file->name);
11518     }
11519   if (i == MAX_NR_V1_DWO_SECTIONS)
11520     {
11521       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
11522 	       " [in module %s]"),
11523 	     dwp_file->name);
11524     }
11525 
11526   /* It's easier for the rest of the code if we fake a struct dwo_file and
11527      have dwo_unit "live" in that.  At least for now.
11528 
11529      The DWP file can be made up of a random collection of CUs and TUs.
11530      However, for each CU + set of TUs that came from the same original DWO
11531      file, we can combine them back into a virtual DWO file to save space
11532      (fewer struct dwo_file objects to allocate).  Remember that for really
11533      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
11534 
11535   std::string virtual_dwo_name =
11536     string_printf ("virtual-dwo/%d-%d-%d-%d",
11537 		   sections.abbrev.get_id (),
11538 		   sections.line.get_id (),
11539 		   sections.loc.get_id (),
11540 		   sections.str_offsets.get_id ());
11541   /* Can we use an existing virtual DWO file?  */
11542   dwo_file_slot = lookup_dwo_file_slot (per_objfile, virtual_dwo_name.c_str (),
11543 					comp_dir);
11544   /* Create one if necessary.  */
11545   if (*dwo_file_slot == NULL)
11546     {
11547       dwarf_read_debug_printf ("Creating virtual DWO: %s",
11548 			       virtual_dwo_name.c_str ());
11549 
11550       dwo_file = new struct dwo_file;
11551       dwo_file->dwo_name = per_objfile->objfile->intern (virtual_dwo_name);
11552       dwo_file->comp_dir = comp_dir;
11553       dwo_file->sections.abbrev = sections.abbrev;
11554       dwo_file->sections.line = sections.line;
11555       dwo_file->sections.loc = sections.loc;
11556       dwo_file->sections.macinfo = sections.macinfo;
11557       dwo_file->sections.macro = sections.macro;
11558       dwo_file->sections.str_offsets = sections.str_offsets;
11559       /* The "str" section is global to the entire DWP file.  */
11560       dwo_file->sections.str = dwp_file->sections.str;
11561       /* The info or types section is assigned below to dwo_unit,
11562 	 there's no need to record it in dwo_file.
11563 	 Also, we can't simply record type sections in dwo_file because
11564 	 we record a pointer into the vector in dwo_unit.  As we collect more
11565 	 types we'll grow the vector and eventually have to reallocate space
11566 	 for it, invalidating all copies of pointers into the previous
11567 	 contents.  */
11568       *dwo_file_slot = dwo_file;
11569     }
11570   else
11571     {
11572       dwarf_read_debug_printf ("Using existing virtual DWO: %s",
11573 			       virtual_dwo_name.c_str ());
11574 
11575       dwo_file = (struct dwo_file *) *dwo_file_slot;
11576     }
11577 
11578   dwo_unit = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, struct dwo_unit);
11579   dwo_unit->dwo_file = dwo_file;
11580   dwo_unit->signature = signature;
11581   dwo_unit->section =
11582     XOBNEW (&per_objfile->per_bfd->obstack, struct dwarf2_section_info);
11583   *dwo_unit->section = sections.info_or_types;
11584   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11585 
11586   return dwo_unit;
11587 }
11588 
11589 /* Subroutine of create_dwo_unit_in_dwp_v2 and create_dwo_unit_in_dwp_v5 to
11590    simplify them.  Given a pointer to the containing section SECTION, and
11591    OFFSET,SIZE of the piece within that section used by a TU/CU, return a
11592    virtual section of just that piece.  */
11593 
11594 static struct dwarf2_section_info
11595 create_dwp_v2_or_v5_section (dwarf2_per_objfile *per_objfile,
11596 			     struct dwarf2_section_info *section,
11597 			     bfd_size_type offset, bfd_size_type size)
11598 {
11599   struct dwarf2_section_info result;
11600   asection *sectp;
11601 
11602   gdb_assert (section != NULL);
11603   gdb_assert (!section->is_virtual);
11604 
11605   memset (&result, 0, sizeof (result));
11606   result.s.containing_section = section;
11607   result.is_virtual = true;
11608 
11609   if (size == 0)
11610     return result;
11611 
11612   sectp = section->get_bfd_section ();
11613 
11614   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
11615      bounds of the real section.  This is a pretty-rare event, so just
11616      flag an error (easier) instead of a warning and trying to cope.  */
11617   if (sectp == NULL
11618       || offset + size > bfd_section_size (sectp))
11619     {
11620       error (_("Dwarf Error: Bad DWP V2 or V5 section info, doesn't fit"
11621 	       " in section %s [in module %s]"),
11622 	     sectp ? bfd_section_name (sectp) : "<unknown>",
11623 	     objfile_name (per_objfile->objfile));
11624     }
11625 
11626   result.virtual_offset = offset;
11627   result.size = size;
11628   return result;
11629 }
11630 
11631 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11632    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11633    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11634    This is for DWP version 2 files.  */
11635 
11636 static struct dwo_unit *
11637 create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile *per_objfile,
11638 			   struct dwp_file *dwp_file,
11639 			   uint32_t unit_index,
11640 			   const char *comp_dir,
11641 			   ULONGEST signature, int is_debug_types)
11642 {
11643   const struct dwp_hash_table *dwp_htab =
11644     is_debug_types ? dwp_file->tus : dwp_file->cus;
11645   bfd *dbfd = dwp_file->dbfd.get ();
11646   const char *kind = is_debug_types ? "TU" : "CU";
11647   struct dwo_file *dwo_file;
11648   struct dwo_unit *dwo_unit;
11649   struct virtual_v2_or_v5_dwo_sections sections;
11650   void **dwo_file_slot;
11651   int i;
11652 
11653   gdb_assert (dwp_file->version == 2);
11654 
11655   dwarf_read_debug_printf ("Reading %s %s/%s in DWP V2 file: %s",
11656 			   kind, pulongest (unit_index), hex_string (signature),
11657 			   dwp_file->name);
11658 
11659   /* Fetch the section offsets of this DWO unit.  */
11660 
11661   memset (&sections, 0, sizeof (sections));
11662 
11663   for (i = 0; i < dwp_htab->nr_columns; ++i)
11664     {
11665       uint32_t offset = read_4_bytes (dbfd,
11666 				      dwp_htab->section_pool.v2.offsets
11667 				      + (((unit_index - 1) * dwp_htab->nr_columns
11668 					  + i)
11669 					 * sizeof (uint32_t)));
11670       uint32_t size = read_4_bytes (dbfd,
11671 				    dwp_htab->section_pool.v2.sizes
11672 				    + (((unit_index - 1) * dwp_htab->nr_columns
11673 					+ i)
11674 				       * sizeof (uint32_t)));
11675 
11676       switch (dwp_htab->section_pool.v2.section_ids[i])
11677 	{
11678 	case DW_SECT_INFO:
11679 	case DW_SECT_TYPES:
11680 	  sections.info_or_types_offset = offset;
11681 	  sections.info_or_types_size = size;
11682 	  break;
11683 	case DW_SECT_ABBREV:
11684 	  sections.abbrev_offset = offset;
11685 	  sections.abbrev_size = size;
11686 	  break;
11687 	case DW_SECT_LINE:
11688 	  sections.line_offset = offset;
11689 	  sections.line_size = size;
11690 	  break;
11691 	case DW_SECT_LOC:
11692 	  sections.loc_offset = offset;
11693 	  sections.loc_size = size;
11694 	  break;
11695 	case DW_SECT_STR_OFFSETS:
11696 	  sections.str_offsets_offset = offset;
11697 	  sections.str_offsets_size = size;
11698 	  break;
11699 	case DW_SECT_MACINFO:
11700 	  sections.macinfo_offset = offset;
11701 	  sections.macinfo_size = size;
11702 	  break;
11703 	case DW_SECT_MACRO:
11704 	  sections.macro_offset = offset;
11705 	  sections.macro_size = size;
11706 	  break;
11707 	}
11708     }
11709 
11710   /* It's easier for the rest of the code if we fake a struct dwo_file and
11711      have dwo_unit "live" in that.  At least for now.
11712 
11713      The DWP file can be made up of a random collection of CUs and TUs.
11714      However, for each CU + set of TUs that came from the same original DWO
11715      file, we can combine them back into a virtual DWO file to save space
11716      (fewer struct dwo_file objects to allocate).  Remember that for really
11717      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
11718 
11719   std::string virtual_dwo_name =
11720     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
11721 		   (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
11722 		   (long) (sections.line_size ? sections.line_offset : 0),
11723 		   (long) (sections.loc_size ? sections.loc_offset : 0),
11724 		   (long) (sections.str_offsets_size
11725 			   ? sections.str_offsets_offset : 0));
11726   /* Can we use an existing virtual DWO file?  */
11727   dwo_file_slot = lookup_dwo_file_slot (per_objfile, virtual_dwo_name.c_str (),
11728 					comp_dir);
11729   /* Create one if necessary.  */
11730   if (*dwo_file_slot == NULL)
11731     {
11732       dwarf_read_debug_printf ("Creating virtual DWO: %s",
11733 			       virtual_dwo_name.c_str ());
11734 
11735       dwo_file = new struct dwo_file;
11736       dwo_file->dwo_name = per_objfile->objfile->intern (virtual_dwo_name);
11737       dwo_file->comp_dir = comp_dir;
11738       dwo_file->sections.abbrev =
11739 	create_dwp_v2_or_v5_section (per_objfile, &dwp_file->sections.abbrev,
11740 				     sections.abbrev_offset,
11741 				     sections.abbrev_size);
11742       dwo_file->sections.line =
11743 	create_dwp_v2_or_v5_section (per_objfile, &dwp_file->sections.line,
11744 				     sections.line_offset,
11745 				     sections.line_size);
11746       dwo_file->sections.loc =
11747 	create_dwp_v2_or_v5_section (per_objfile, &dwp_file->sections.loc,
11748 				     sections.loc_offset, sections.loc_size);
11749       dwo_file->sections.macinfo =
11750 	create_dwp_v2_or_v5_section (per_objfile, &dwp_file->sections.macinfo,
11751 				     sections.macinfo_offset,
11752 				     sections.macinfo_size);
11753       dwo_file->sections.macro =
11754 	create_dwp_v2_or_v5_section (per_objfile, &dwp_file->sections.macro,
11755 				     sections.macro_offset,
11756 				     sections.macro_size);
11757       dwo_file->sections.str_offsets =
11758 	create_dwp_v2_or_v5_section (per_objfile,
11759 				     &dwp_file->sections.str_offsets,
11760 				     sections.str_offsets_offset,
11761 				     sections.str_offsets_size);
11762       /* The "str" section is global to the entire DWP file.  */
11763       dwo_file->sections.str = dwp_file->sections.str;
11764       /* The info or types section is assigned below to dwo_unit,
11765 	 there's no need to record it in dwo_file.
11766 	 Also, we can't simply record type sections in dwo_file because
11767 	 we record a pointer into the vector in dwo_unit.  As we collect more
11768 	 types we'll grow the vector and eventually have to reallocate space
11769 	 for it, invalidating all copies of pointers into the previous
11770 	 contents.  */
11771       *dwo_file_slot = dwo_file;
11772     }
11773   else
11774     {
11775       dwarf_read_debug_printf ("Using existing virtual DWO: %s",
11776 			       virtual_dwo_name.c_str ());
11777 
11778       dwo_file = (struct dwo_file *) *dwo_file_slot;
11779     }
11780 
11781   dwo_unit = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, struct dwo_unit);
11782   dwo_unit->dwo_file = dwo_file;
11783   dwo_unit->signature = signature;
11784   dwo_unit->section =
11785     XOBNEW (&per_objfile->per_bfd->obstack, struct dwarf2_section_info);
11786   *dwo_unit->section = create_dwp_v2_or_v5_section
11787 			 (per_objfile,
11788 			  is_debug_types
11789 			  ? &dwp_file->sections.types
11790 			  : &dwp_file->sections.info,
11791 			  sections.info_or_types_offset,
11792 			  sections.info_or_types_size);
11793   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11794 
11795   return dwo_unit;
11796 }
11797 
11798 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11799    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11800    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11801    This is for DWP version 5 files.  */
11802 
11803 static struct dwo_unit *
11804 create_dwo_unit_in_dwp_v5 (dwarf2_per_objfile *per_objfile,
11805 			   struct dwp_file *dwp_file,
11806 			   uint32_t unit_index,
11807 			   const char *comp_dir,
11808 			   ULONGEST signature, int is_debug_types)
11809 {
11810   const struct dwp_hash_table *dwp_htab
11811     = is_debug_types ? dwp_file->tus : dwp_file->cus;
11812   bfd *dbfd = dwp_file->dbfd.get ();
11813   const char *kind = is_debug_types ? "TU" : "CU";
11814   struct dwo_file *dwo_file;
11815   struct dwo_unit *dwo_unit;
11816   struct virtual_v2_or_v5_dwo_sections sections {};
11817   void **dwo_file_slot;
11818 
11819   gdb_assert (dwp_file->version == 5);
11820 
11821   dwarf_read_debug_printf ("Reading %s %s/%s in DWP V5 file: %s",
11822 			   kind, pulongest (unit_index), hex_string (signature),
11823 			   dwp_file->name);
11824 
11825   /* Fetch the section offsets of this DWO unit.  */
11826 
11827   /*  memset (&sections, 0, sizeof (sections)); */
11828 
11829   for (int i = 0; i < dwp_htab->nr_columns; ++i)
11830     {
11831       uint32_t offset = read_4_bytes (dbfd,
11832 				      dwp_htab->section_pool.v5.offsets
11833 				      + (((unit_index - 1)
11834 					  * dwp_htab->nr_columns
11835 					  + i)
11836 					 * sizeof (uint32_t)));
11837       uint32_t size = read_4_bytes (dbfd,
11838 				    dwp_htab->section_pool.v5.sizes
11839 				    + (((unit_index - 1) * dwp_htab->nr_columns
11840 					+ i)
11841 				       * sizeof (uint32_t)));
11842 
11843       switch (dwp_htab->section_pool.v5.section_ids[i])
11844 	{
11845 	  case DW_SECT_ABBREV_V5:
11846 	    sections.abbrev_offset = offset;
11847 	    sections.abbrev_size = size;
11848 	    break;
11849 	  case DW_SECT_INFO_V5:
11850 	    sections.info_or_types_offset = offset;
11851 	    sections.info_or_types_size = size;
11852 	    break;
11853 	  case DW_SECT_LINE_V5:
11854 	    sections.line_offset = offset;
11855 	    sections.line_size = size;
11856 	    break;
11857 	  case DW_SECT_LOCLISTS_V5:
11858 	    sections.loclists_offset = offset;
11859 	    sections.loclists_size = size;
11860 	    break;
11861 	  case DW_SECT_MACRO_V5:
11862 	    sections.macro_offset = offset;
11863 	    sections.macro_size = size;
11864 	    break;
11865 	  case DW_SECT_RNGLISTS_V5:
11866 	    sections.rnglists_offset = offset;
11867 	    sections.rnglists_size = size;
11868 	    break;
11869 	  case DW_SECT_STR_OFFSETS_V5:
11870 	    sections.str_offsets_offset = offset;
11871 	    sections.str_offsets_size = size;
11872 	    break;
11873 	  case DW_SECT_RESERVED_V5:
11874 	  default:
11875 	    break;
11876 	}
11877     }
11878 
11879   /* It's easier for the rest of the code if we fake a struct dwo_file and
11880      have dwo_unit "live" in that.  At least for now.
11881 
11882      The DWP file can be made up of a random collection of CUs and TUs.
11883      However, for each CU + set of TUs that came from the same original DWO
11884      file, we can combine them back into a virtual DWO file to save space
11885      (fewer struct dwo_file objects to allocate).  Remember that for really
11886      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
11887 
11888   std::string virtual_dwo_name =
11889     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld-%ld-%ld",
11890 		 (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
11891 		 (long) (sections.line_size ? sections.line_offset : 0),
11892 		 (long) (sections.loclists_size ? sections.loclists_offset : 0),
11893 		 (long) (sections.str_offsets_size
11894 			    ? sections.str_offsets_offset : 0),
11895 		 (long) (sections.macro_size ? sections.macro_offset : 0),
11896 		 (long) (sections.rnglists_size ? sections.rnglists_offset: 0));
11897   /* Can we use an existing virtual DWO file?  */
11898   dwo_file_slot = lookup_dwo_file_slot (per_objfile,
11899 					virtual_dwo_name.c_str (),
11900 					comp_dir);
11901   /* Create one if necessary.  */
11902   if (*dwo_file_slot == NULL)
11903     {
11904       dwarf_read_debug_printf ("Creating virtual DWO: %s",
11905 			       virtual_dwo_name.c_str ());
11906 
11907       dwo_file = new struct dwo_file;
11908       dwo_file->dwo_name = per_objfile->objfile->intern (virtual_dwo_name);
11909       dwo_file->comp_dir = comp_dir;
11910       dwo_file->sections.abbrev =
11911 	create_dwp_v2_or_v5_section (per_objfile,
11912 				     &dwp_file->sections.abbrev,
11913 				     sections.abbrev_offset,
11914 				     sections.abbrev_size);
11915       dwo_file->sections.line =
11916 	create_dwp_v2_or_v5_section (per_objfile,
11917 				     &dwp_file->sections.line,
11918 				     sections.line_offset, sections.line_size);
11919       dwo_file->sections.macro =
11920 	create_dwp_v2_or_v5_section (per_objfile,
11921 				     &dwp_file->sections.macro,
11922 				     sections.macro_offset,
11923 				     sections.macro_size);
11924       dwo_file->sections.loclists =
11925 	create_dwp_v2_or_v5_section (per_objfile,
11926 				     &dwp_file->sections.loclists,
11927 				     sections.loclists_offset,
11928 				     sections.loclists_size);
11929       dwo_file->sections.rnglists =
11930 	create_dwp_v2_or_v5_section (per_objfile,
11931 				     &dwp_file->sections.rnglists,
11932 				     sections.rnglists_offset,
11933 				     sections.rnglists_size);
11934       dwo_file->sections.str_offsets =
11935 	create_dwp_v2_or_v5_section (per_objfile,
11936 				     &dwp_file->sections.str_offsets,
11937 				     sections.str_offsets_offset,
11938 				     sections.str_offsets_size);
11939       /* The "str" section is global to the entire DWP file.  */
11940       dwo_file->sections.str = dwp_file->sections.str;
11941       /* The info or types section is assigned below to dwo_unit,
11942 	 there's no need to record it in dwo_file.
11943 	 Also, we can't simply record type sections in dwo_file because
11944 	 we record a pointer into the vector in dwo_unit.  As we collect more
11945 	 types we'll grow the vector and eventually have to reallocate space
11946 	 for it, invalidating all copies of pointers into the previous
11947 	 contents.  */
11948       *dwo_file_slot = dwo_file;
11949     }
11950   else
11951     {
11952       dwarf_read_debug_printf ("Using existing virtual DWO: %s",
11953 			       virtual_dwo_name.c_str ());
11954 
11955       dwo_file = (struct dwo_file *) *dwo_file_slot;
11956     }
11957 
11958   dwo_unit = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, struct dwo_unit);
11959   dwo_unit->dwo_file = dwo_file;
11960   dwo_unit->signature = signature;
11961   dwo_unit->section
11962     = XOBNEW (&per_objfile->per_bfd->obstack, struct dwarf2_section_info);
11963   *dwo_unit->section = create_dwp_v2_or_v5_section (per_objfile,
11964 					      &dwp_file->sections.info,
11965 					      sections.info_or_types_offset,
11966 					      sections.info_or_types_size);
11967   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11968 
11969   return dwo_unit;
11970 }
11971 
11972 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
11973    Returns NULL if the signature isn't found.  */
11974 
11975 static struct dwo_unit *
11976 lookup_dwo_unit_in_dwp (dwarf2_per_objfile *per_objfile,
11977 			struct dwp_file *dwp_file, const char *comp_dir,
11978 			ULONGEST signature, int is_debug_types)
11979 {
11980   const struct dwp_hash_table *dwp_htab =
11981     is_debug_types ? dwp_file->tus : dwp_file->cus;
11982   bfd *dbfd = dwp_file->dbfd.get ();
11983   uint32_t mask = dwp_htab->nr_slots - 1;
11984   uint32_t hash = signature & mask;
11985   uint32_t hash2 = ((signature >> 32) & mask) | 1;
11986   unsigned int i;
11987   void **slot;
11988   struct dwo_unit find_dwo_cu;
11989 
11990   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
11991   find_dwo_cu.signature = signature;
11992   slot = htab_find_slot (is_debug_types
11993 			 ? dwp_file->loaded_tus.get ()
11994 			 : dwp_file->loaded_cus.get (),
11995 			 &find_dwo_cu, INSERT);
11996 
11997   if (*slot != NULL)
11998     return (struct dwo_unit *) *slot;
11999 
12000   /* Use a for loop so that we don't loop forever on bad debug info.  */
12001   for (i = 0; i < dwp_htab->nr_slots; ++i)
12002     {
12003       ULONGEST signature_in_table;
12004 
12005       signature_in_table =
12006 	read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12007       if (signature_in_table == signature)
12008 	{
12009 	  uint32_t unit_index =
12010 	    read_4_bytes (dbfd,
12011 			  dwp_htab->unit_table + hash * sizeof (uint32_t));
12012 
12013 	  if (dwp_file->version == 1)
12014 	    {
12015 	      *slot = create_dwo_unit_in_dwp_v1 (per_objfile, dwp_file,
12016 						 unit_index, comp_dir,
12017 						 signature, is_debug_types);
12018 	    }
12019 	  else if (dwp_file->version == 2)
12020 	    {
12021 	      *slot = create_dwo_unit_in_dwp_v2 (per_objfile, dwp_file,
12022 						 unit_index, comp_dir,
12023 						 signature, is_debug_types);
12024 	    }
12025 	  else /* version == 5  */
12026 	    {
12027 	      *slot = create_dwo_unit_in_dwp_v5 (per_objfile, dwp_file,
12028 						 unit_index, comp_dir,
12029 						 signature, is_debug_types);
12030 	    }
12031 	  return (struct dwo_unit *) *slot;
12032 	}
12033       if (signature_in_table == 0)
12034 	return NULL;
12035       hash = (hash + hash2) & mask;
12036     }
12037 
12038   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12039 	   " [in module %s]"),
12040 	 dwp_file->name);
12041 }
12042 
12043 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12044    Open the file specified by FILE_NAME and hand it off to BFD for
12045    preliminary analysis.  Return a newly initialized bfd *, which
12046    includes a canonicalized copy of FILE_NAME.
12047    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12048    SEARCH_CWD is true if the current directory is to be searched.
12049    It will be searched before debug-file-directory.
12050    If successful, the file is added to the bfd include table of the
12051    objfile's bfd (see gdb_bfd_record_inclusion).
12052    If unable to find/open the file, return NULL.
12053    NOTE: This function is derived from symfile_bfd_open.  */
12054 
12055 static gdb_bfd_ref_ptr
12056 try_open_dwop_file (dwarf2_per_objfile *per_objfile,
12057 		    const char *file_name, int is_dwp, int search_cwd)
12058 {
12059   int desc;
12060   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12061      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12062      to debug_file_directory.  */
12063   const char *search_path;
12064   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12065 
12066   gdb::unique_xmalloc_ptr<char> search_path_holder;
12067   if (search_cwd)
12068     {
12069       if (*debug_file_directory != '\0')
12070 	{
12071 	  search_path_holder.reset (concat (".", dirname_separator_string,
12072 					    debug_file_directory,
12073 					    (char *) NULL));
12074 	  search_path = search_path_holder.get ();
12075 	}
12076       else
12077 	search_path = ".";
12078     }
12079   else
12080     search_path = debug_file_directory;
12081 
12082   /* Add the path for the executable binary to the list of search paths.  */
12083   std::string objfile_dir = ldirname (objfile_name (per_objfile->objfile));
12084   search_path_holder.reset (concat (objfile_dir.c_str (),
12085 				    dirname_separator_string,
12086 				    search_path, nullptr));
12087   search_path = search_path_holder.get ();
12088 
12089   openp_flags flags = OPF_RETURN_REALPATH;
12090   if (is_dwp)
12091     flags |= OPF_SEARCH_IN_PATH;
12092 
12093   gdb::unique_xmalloc_ptr<char> absolute_name;
12094   desc = openp (search_path, flags, file_name,
12095 		O_RDONLY | O_BINARY, &absolute_name);
12096   if (desc < 0)
12097     return NULL;
12098 
12099   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12100 					 gnutarget, desc));
12101   if (sym_bfd == NULL)
12102     return NULL;
12103   bfd_set_cacheable (sym_bfd.get (), 1);
12104 
12105   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12106     return NULL;
12107 
12108   /* Success.  Record the bfd as having been included by the objfile's bfd.
12109      This is important because things like demangled_names_hash lives in the
12110      objfile's per_bfd space and may have references to things like symbol
12111      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12112   gdb_bfd_record_inclusion (per_objfile->objfile->obfd, sym_bfd.get ());
12113 
12114   return sym_bfd;
12115 }
12116 
12117 /* Try to open DWO file FILE_NAME.
12118    COMP_DIR is the DW_AT_comp_dir attribute.
12119    The result is the bfd handle of the file.
12120    If there is a problem finding or opening the file, return NULL.
12121    Upon success, the canonicalized path of the file is stored in the bfd,
12122    same as symfile_bfd_open.  */
12123 
12124 static gdb_bfd_ref_ptr
12125 open_dwo_file (dwarf2_per_objfile *per_objfile,
12126 	       const char *file_name, const char *comp_dir)
12127 {
12128   if (IS_ABSOLUTE_PATH (file_name))
12129     return try_open_dwop_file (per_objfile, file_name,
12130 			       0 /*is_dwp*/, 0 /*search_cwd*/);
12131 
12132   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12133 
12134   if (comp_dir != NULL)
12135     {
12136       gdb::unique_xmalloc_ptr<char> path_to_try
12137 	(concat (comp_dir, SLASH_STRING, file_name, (char *) NULL));
12138 
12139       /* NOTE: If comp_dir is a relative path, this will also try the
12140 	 search path, which seems useful.  */
12141       gdb_bfd_ref_ptr abfd (try_open_dwop_file (per_objfile, path_to_try.get (),
12142 						0 /*is_dwp*/,
12143 						1 /*search_cwd*/));
12144       if (abfd != NULL)
12145 	return abfd;
12146     }
12147 
12148   /* That didn't work, try debug-file-directory, which, despite its name,
12149      is a list of paths.  */
12150 
12151   if (*debug_file_directory == '\0')
12152     return NULL;
12153 
12154   return try_open_dwop_file (per_objfile, file_name,
12155 			     0 /*is_dwp*/, 1 /*search_cwd*/);
12156 }
12157 
12158 /* This function is mapped across the sections and remembers the offset and
12159    size of each of the DWO debugging sections we are interested in.  */
12160 
12161 static void
12162 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp,
12163 			    dwo_sections *dwo_sections)
12164 {
12165   const struct dwop_section_names *names = &dwop_section_names;
12166 
12167   if (names->abbrev_dwo.matches (sectp->name))
12168     {
12169       dwo_sections->abbrev.s.section = sectp;
12170       dwo_sections->abbrev.size = bfd_section_size (sectp);
12171     }
12172   else if (names->info_dwo.matches (sectp->name))
12173     {
12174       dwo_sections->info.s.section = sectp;
12175       dwo_sections->info.size = bfd_section_size (sectp);
12176     }
12177   else if (names->line_dwo.matches (sectp->name))
12178     {
12179       dwo_sections->line.s.section = sectp;
12180       dwo_sections->line.size = bfd_section_size (sectp);
12181     }
12182   else if (names->loc_dwo.matches (sectp->name))
12183     {
12184       dwo_sections->loc.s.section = sectp;
12185       dwo_sections->loc.size = bfd_section_size (sectp);
12186     }
12187   else if (names->loclists_dwo.matches (sectp->name))
12188     {
12189       dwo_sections->loclists.s.section = sectp;
12190       dwo_sections->loclists.size = bfd_section_size (sectp);
12191     }
12192   else if (names->macinfo_dwo.matches (sectp->name))
12193     {
12194       dwo_sections->macinfo.s.section = sectp;
12195       dwo_sections->macinfo.size = bfd_section_size (sectp);
12196     }
12197   else if (names->macro_dwo.matches (sectp->name))
12198     {
12199       dwo_sections->macro.s.section = sectp;
12200       dwo_sections->macro.size = bfd_section_size (sectp);
12201     }
12202   else if (names->rnglists_dwo.matches (sectp->name))
12203     {
12204       dwo_sections->rnglists.s.section = sectp;
12205       dwo_sections->rnglists.size = bfd_section_size (sectp);
12206     }
12207   else if (names->str_dwo.matches (sectp->name))
12208     {
12209       dwo_sections->str.s.section = sectp;
12210       dwo_sections->str.size = bfd_section_size (sectp);
12211     }
12212   else if (names->str_offsets_dwo.matches (sectp->name))
12213     {
12214       dwo_sections->str_offsets.s.section = sectp;
12215       dwo_sections->str_offsets.size = bfd_section_size (sectp);
12216     }
12217   else if (names->types_dwo.matches (sectp->name))
12218     {
12219       struct dwarf2_section_info type_section;
12220 
12221       memset (&type_section, 0, sizeof (type_section));
12222       type_section.s.section = sectp;
12223       type_section.size = bfd_section_size (sectp);
12224       dwo_sections->types.push_back (type_section);
12225     }
12226 }
12227 
12228 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12229    by PER_CU.  This is for the non-DWP case.
12230    The result is NULL if DWO_NAME can't be found.  */
12231 
12232 static struct dwo_file *
12233 open_and_init_dwo_file (dwarf2_cu *cu, const char *dwo_name,
12234 			const char *comp_dir)
12235 {
12236   dwarf2_per_objfile *per_objfile = cu->per_objfile;
12237 
12238   gdb_bfd_ref_ptr dbfd = open_dwo_file (per_objfile, dwo_name, comp_dir);
12239   if (dbfd == NULL)
12240     {
12241       dwarf_read_debug_printf ("DWO file not found: %s", dwo_name);
12242 
12243       return NULL;
12244     }
12245 
12246   dwo_file_up dwo_file (new struct dwo_file);
12247   dwo_file->dwo_name = dwo_name;
12248   dwo_file->comp_dir = comp_dir;
12249   dwo_file->dbfd = std::move (dbfd);
12250 
12251   for (asection *sec : gdb_bfd_sections (dwo_file->dbfd))
12252     dwarf2_locate_dwo_sections (dwo_file->dbfd.get (), sec,
12253 				&dwo_file->sections);
12254 
12255   create_cus_hash_table (per_objfile, cu, *dwo_file, dwo_file->sections.info,
12256 			 dwo_file->cus);
12257 
12258   if (cu->per_cu->dwarf_version < 5)
12259     {
12260       create_debug_types_hash_table (per_objfile, dwo_file.get (),
12261 				     dwo_file->sections.types, dwo_file->tus);
12262     }
12263   else
12264     {
12265       create_debug_type_hash_table (per_objfile, dwo_file.get (),
12266 				    &dwo_file->sections.info, dwo_file->tus,
12267 				    rcuh_kind::COMPILE);
12268     }
12269 
12270   dwarf_read_debug_printf ("DWO file found: %s", dwo_name);
12271 
12272   return dwo_file.release ();
12273 }
12274 
12275 /* This function is mapped across the sections and remembers the offset and
12276    size of each of the DWP debugging sections common to version 1 and 2 that
12277    we are interested in.  */
12278 
12279 static void
12280 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12281 				   dwp_file *dwp_file)
12282 {
12283   const struct dwop_section_names *names = &dwop_section_names;
12284   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12285 
12286   /* Record the ELF section number for later lookup: this is what the
12287      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12288   gdb_assert (elf_section_nr < dwp_file->num_sections);
12289   dwp_file->elf_sections[elf_section_nr] = sectp;
12290 
12291   /* Look for specific sections that we need.  */
12292   if (names->str_dwo.matches (sectp->name))
12293     {
12294       dwp_file->sections.str.s.section = sectp;
12295       dwp_file->sections.str.size = bfd_section_size (sectp);
12296     }
12297   else if (names->cu_index.matches (sectp->name))
12298     {
12299       dwp_file->sections.cu_index.s.section = sectp;
12300       dwp_file->sections.cu_index.size = bfd_section_size (sectp);
12301     }
12302   else if (names->tu_index.matches (sectp->name))
12303     {
12304       dwp_file->sections.tu_index.s.section = sectp;
12305       dwp_file->sections.tu_index.size = bfd_section_size (sectp);
12306     }
12307 }
12308 
12309 /* This function is mapped across the sections and remembers the offset and
12310    size of each of the DWP version 2 debugging sections that we are interested
12311    in.  This is split into a separate function because we don't know if we
12312    have version 1 or 2 or 5 until we parse the cu_index/tu_index sections.  */
12313 
12314 static void
12315 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12316 {
12317   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12318   const struct dwop_section_names *names = &dwop_section_names;
12319   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12320 
12321   /* Record the ELF section number for later lookup: this is what the
12322      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12323   gdb_assert (elf_section_nr < dwp_file->num_sections);
12324   dwp_file->elf_sections[elf_section_nr] = sectp;
12325 
12326   /* Look for specific sections that we need.  */
12327   if (names->abbrev_dwo.matches (sectp->name))
12328     {
12329       dwp_file->sections.abbrev.s.section = sectp;
12330       dwp_file->sections.abbrev.size = bfd_section_size (sectp);
12331     }
12332   else if (names->info_dwo.matches (sectp->name))
12333     {
12334       dwp_file->sections.info.s.section = sectp;
12335       dwp_file->sections.info.size = bfd_section_size (sectp);
12336     }
12337   else if (names->line_dwo.matches (sectp->name))
12338     {
12339       dwp_file->sections.line.s.section = sectp;
12340       dwp_file->sections.line.size = bfd_section_size (sectp);
12341     }
12342   else if (names->loc_dwo.matches (sectp->name))
12343     {
12344       dwp_file->sections.loc.s.section = sectp;
12345       dwp_file->sections.loc.size = bfd_section_size (sectp);
12346     }
12347   else if (names->macinfo_dwo.matches (sectp->name))
12348     {
12349       dwp_file->sections.macinfo.s.section = sectp;
12350       dwp_file->sections.macinfo.size = bfd_section_size (sectp);
12351     }
12352   else if (names->macro_dwo.matches (sectp->name))
12353     {
12354       dwp_file->sections.macro.s.section = sectp;
12355       dwp_file->sections.macro.size = bfd_section_size (sectp);
12356     }
12357   else if (names->str_offsets_dwo.matches (sectp->name))
12358     {
12359       dwp_file->sections.str_offsets.s.section = sectp;
12360       dwp_file->sections.str_offsets.size = bfd_section_size (sectp);
12361     }
12362   else if (names->types_dwo.matches (sectp->name))
12363     {
12364       dwp_file->sections.types.s.section = sectp;
12365       dwp_file->sections.types.size = bfd_section_size (sectp);
12366     }
12367 }
12368 
12369 /* This function is mapped across the sections and remembers the offset and
12370    size of each of the DWP version 5 debugging sections that we are interested
12371    in.  This is split into a separate function because we don't know if we
12372    have version 1 or 2 or 5 until we parse the cu_index/tu_index sections.  */
12373 
12374 static void
12375 dwarf2_locate_v5_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12376 {
12377   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12378   const struct dwop_section_names *names = &dwop_section_names;
12379   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12380 
12381   /* Record the ELF section number for later lookup: this is what the
12382      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12383   gdb_assert (elf_section_nr < dwp_file->num_sections);
12384   dwp_file->elf_sections[elf_section_nr] = sectp;
12385 
12386   /* Look for specific sections that we need.  */
12387   if (names->abbrev_dwo.matches (sectp->name))
12388     {
12389       dwp_file->sections.abbrev.s.section = sectp;
12390       dwp_file->sections.abbrev.size = bfd_section_size (sectp);
12391     }
12392   else if (names->info_dwo.matches (sectp->name))
12393     {
12394       dwp_file->sections.info.s.section = sectp;
12395       dwp_file->sections.info.size = bfd_section_size (sectp);
12396     }
12397   else if (names->line_dwo.matches (sectp->name))
12398    {
12399      dwp_file->sections.line.s.section = sectp;
12400      dwp_file->sections.line.size = bfd_section_size (sectp);
12401     }
12402   else if (names->loclists_dwo.matches (sectp->name))
12403     {
12404       dwp_file->sections.loclists.s.section = sectp;
12405       dwp_file->sections.loclists.size = bfd_section_size (sectp);
12406     }
12407   else if (names->macro_dwo.matches (sectp->name))
12408     {
12409       dwp_file->sections.macro.s.section = sectp;
12410       dwp_file->sections.macro.size = bfd_section_size (sectp);
12411     }
12412   else if (names->rnglists_dwo.matches (sectp->name))
12413     {
12414       dwp_file->sections.rnglists.s.section = sectp;
12415       dwp_file->sections.rnglists.size = bfd_section_size (sectp);
12416     }
12417   else if (names->str_offsets_dwo.matches (sectp->name))
12418     {
12419       dwp_file->sections.str_offsets.s.section = sectp;
12420       dwp_file->sections.str_offsets.size = bfd_section_size (sectp);
12421     }
12422 }
12423 
12424 /* Hash function for dwp_file loaded CUs/TUs.  */
12425 
12426 static hashval_t
12427 hash_dwp_loaded_cutus (const void *item)
12428 {
12429   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
12430 
12431   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
12432   return dwo_unit->signature;
12433 }
12434 
12435 /* Equality function for dwp_file loaded CUs/TUs.  */
12436 
12437 static int
12438 eq_dwp_loaded_cutus (const void *a, const void *b)
12439 {
12440   const struct dwo_unit *dua = (const struct dwo_unit *) a;
12441   const struct dwo_unit *dub = (const struct dwo_unit *) b;
12442 
12443   return dua->signature == dub->signature;
12444 }
12445 
12446 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
12447 
12448 static htab_up
12449 allocate_dwp_loaded_cutus_table ()
12450 {
12451   return htab_up (htab_create_alloc (3,
12452 				     hash_dwp_loaded_cutus,
12453 				     eq_dwp_loaded_cutus,
12454 				     NULL, xcalloc, xfree));
12455 }
12456 
12457 /* Try to open DWP file FILE_NAME.
12458    The result is the bfd handle of the file.
12459    If there is a problem finding or opening the file, return NULL.
12460    Upon success, the canonicalized path of the file is stored in the bfd,
12461    same as symfile_bfd_open.  */
12462 
12463 static gdb_bfd_ref_ptr
12464 open_dwp_file (dwarf2_per_objfile *per_objfile, const char *file_name)
12465 {
12466   gdb_bfd_ref_ptr abfd (try_open_dwop_file (per_objfile, file_name,
12467 					    1 /*is_dwp*/,
12468 					    1 /*search_cwd*/));
12469   if (abfd != NULL)
12470     return abfd;
12471 
12472   /* Work around upstream bug 15652.
12473      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
12474      [Whether that's a "bug" is debatable, but it is getting in our way.]
12475      We have no real idea where the dwp file is, because gdb's realpath-ing
12476      of the executable's path may have discarded the needed info.
12477      [IWBN if the dwp file name was recorded in the executable, akin to
12478      .gnu_debuglink, but that doesn't exist yet.]
12479      Strip the directory from FILE_NAME and search again.  */
12480   if (*debug_file_directory != '\0')
12481     {
12482       /* Don't implicitly search the current directory here.
12483 	 If the user wants to search "." to handle this case,
12484 	 it must be added to debug-file-directory.  */
12485       return try_open_dwop_file (per_objfile, lbasename (file_name),
12486 				 1 /*is_dwp*/,
12487 				 0 /*search_cwd*/);
12488     }
12489 
12490   return NULL;
12491 }
12492 
12493 /* Initialize the use of the DWP file for the current objfile.
12494    By convention the name of the DWP file is ${objfile}.dwp.
12495    The result is NULL if it can't be found.  */
12496 
12497 static std::unique_ptr<struct dwp_file>
12498 open_and_init_dwp_file (dwarf2_per_objfile *per_objfile)
12499 {
12500   struct objfile *objfile = per_objfile->objfile;
12501 
12502   /* Try to find first .dwp for the binary file before any symbolic links
12503      resolving.  */
12504 
12505   /* If the objfile is a debug file, find the name of the real binary
12506      file and get the name of dwp file from there.  */
12507   std::string dwp_name;
12508   if (objfile->separate_debug_objfile_backlink != NULL)
12509     {
12510       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
12511       const char *backlink_basename = lbasename (backlink->original_name);
12512 
12513       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
12514     }
12515   else
12516     dwp_name = objfile->original_name;
12517 
12518   dwp_name += ".dwp";
12519 
12520   gdb_bfd_ref_ptr dbfd (open_dwp_file (per_objfile, dwp_name.c_str ()));
12521   if (dbfd == NULL
12522       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
12523     {
12524       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
12525       dwp_name = objfile_name (objfile);
12526       dwp_name += ".dwp";
12527       dbfd = open_dwp_file (per_objfile, dwp_name.c_str ());
12528     }
12529 
12530   if (dbfd == NULL)
12531     {
12532       dwarf_read_debug_printf ("DWP file not found: %s", dwp_name.c_str ());
12533 
12534       return std::unique_ptr<dwp_file> ();
12535     }
12536 
12537   const char *name = bfd_get_filename (dbfd.get ());
12538   std::unique_ptr<struct dwp_file> dwp_file
12539     (new struct dwp_file (name, std::move (dbfd)));
12540 
12541   dwp_file->num_sections = elf_numsections (dwp_file->dbfd);
12542   dwp_file->elf_sections =
12543     OBSTACK_CALLOC (&per_objfile->per_bfd->obstack,
12544 		    dwp_file->num_sections, asection *);
12545 
12546   for (asection *sec : gdb_bfd_sections (dwp_file->dbfd))
12547     dwarf2_locate_common_dwp_sections (dwp_file->dbfd.get (), sec,
12548 				       dwp_file.get ());
12549 
12550   dwp_file->cus = create_dwp_hash_table (per_objfile, dwp_file.get (), 0);
12551 
12552   dwp_file->tus = create_dwp_hash_table (per_objfile, dwp_file.get (), 1);
12553 
12554   /* The DWP file version is stored in the hash table.  Oh well.  */
12555   if (dwp_file->cus && dwp_file->tus
12556       && dwp_file->cus->version != dwp_file->tus->version)
12557     {
12558       /* Technically speaking, we should try to limp along, but this is
12559 	 pretty bizarre.  We use pulongest here because that's the established
12560 	 portability solution (e.g, we cannot use %u for uint32_t).  */
12561       error (_("Dwarf Error: DWP file CU version %s doesn't match"
12562 	       " TU version %s [in DWP file %s]"),
12563 	     pulongest (dwp_file->cus->version),
12564 	     pulongest (dwp_file->tus->version), dwp_name.c_str ());
12565     }
12566 
12567   if (dwp_file->cus)
12568     dwp_file->version = dwp_file->cus->version;
12569   else if (dwp_file->tus)
12570     dwp_file->version = dwp_file->tus->version;
12571   else
12572     dwp_file->version = 2;
12573 
12574   for (asection *sec : gdb_bfd_sections (dwp_file->dbfd))
12575     {
12576       if (dwp_file->version == 2)
12577 	dwarf2_locate_v2_dwp_sections (dwp_file->dbfd.get (), sec,
12578 				       dwp_file.get ());
12579       else
12580 	dwarf2_locate_v5_dwp_sections (dwp_file->dbfd.get (), sec,
12581 				       dwp_file.get ());
12582     }
12583 
12584   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table ();
12585   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table ();
12586 
12587   dwarf_read_debug_printf ("DWP file found: %s", dwp_file->name);
12588   dwarf_read_debug_printf ("    %s CUs, %s TUs",
12589 			   pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
12590 			   pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
12591 
12592   return dwp_file;
12593 }
12594 
12595 /* Wrapper around open_and_init_dwp_file, only open it once.  */
12596 
12597 static struct dwp_file *
12598 get_dwp_file (dwarf2_per_objfile *per_objfile)
12599 {
12600   if (!per_objfile->per_bfd->dwp_checked)
12601     {
12602       per_objfile->per_bfd->dwp_file = open_and_init_dwp_file (per_objfile);
12603       per_objfile->per_bfd->dwp_checked = 1;
12604     }
12605   return per_objfile->per_bfd->dwp_file.get ();
12606 }
12607 
12608 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
12609    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
12610    or in the DWP file for the objfile, referenced by THIS_UNIT.
12611    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
12612    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
12613 
12614    This is called, for example, when wanting to read a variable with a
12615    complex location.  Therefore we don't want to do file i/o for every call.
12616    Therefore we don't want to look for a DWO file on every call.
12617    Therefore we first see if we've already seen SIGNATURE in a DWP file,
12618    then we check if we've already seen DWO_NAME, and only THEN do we check
12619    for a DWO file.
12620 
12621    The result is a pointer to the dwo_unit object or NULL if we didn't find it
12622    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
12623 
12624 static struct dwo_unit *
12625 lookup_dwo_cutu (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir,
12626 		 ULONGEST signature, int is_debug_types)
12627 {
12628   dwarf2_per_objfile *per_objfile = cu->per_objfile;
12629   struct objfile *objfile = per_objfile->objfile;
12630   const char *kind = is_debug_types ? "TU" : "CU";
12631   void **dwo_file_slot;
12632   struct dwo_file *dwo_file;
12633   struct dwp_file *dwp_file;
12634 
12635   /* First see if there's a DWP file.
12636      If we have a DWP file but didn't find the DWO inside it, don't
12637      look for the original DWO file.  It makes gdb behave differently
12638      depending on whether one is debugging in the build tree.  */
12639 
12640   dwp_file = get_dwp_file (per_objfile);
12641   if (dwp_file != NULL)
12642     {
12643       const struct dwp_hash_table *dwp_htab =
12644 	is_debug_types ? dwp_file->tus : dwp_file->cus;
12645 
12646       if (dwp_htab != NULL)
12647 	{
12648 	  struct dwo_unit *dwo_cutu =
12649 	    lookup_dwo_unit_in_dwp (per_objfile, dwp_file, comp_dir, signature,
12650 				    is_debug_types);
12651 
12652 	  if (dwo_cutu != NULL)
12653 	    {
12654 	      dwarf_read_debug_printf ("Virtual DWO %s %s found: @%s",
12655 				       kind, hex_string (signature),
12656 				       host_address_to_string (dwo_cutu));
12657 
12658 	      return dwo_cutu;
12659 	    }
12660 	}
12661     }
12662   else
12663     {
12664       /* No DWP file, look for the DWO file.  */
12665 
12666       dwo_file_slot = lookup_dwo_file_slot (per_objfile, dwo_name, comp_dir);
12667       if (*dwo_file_slot == NULL)
12668 	{
12669 	  /* Read in the file and build a table of the CUs/TUs it contains.  */
12670 	  *dwo_file_slot = open_and_init_dwo_file (cu, dwo_name, comp_dir);
12671 	}
12672       /* NOTE: This will be NULL if unable to open the file.  */
12673       dwo_file = (struct dwo_file *) *dwo_file_slot;
12674 
12675       if (dwo_file != NULL)
12676 	{
12677 	  struct dwo_unit *dwo_cutu = NULL;
12678 
12679 	  if (is_debug_types && dwo_file->tus)
12680 	    {
12681 	      struct dwo_unit find_dwo_cutu;
12682 
12683 	      memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12684 	      find_dwo_cutu.signature = signature;
12685 	      dwo_cutu
12686 		= (struct dwo_unit *) htab_find (dwo_file->tus.get (),
12687 						 &find_dwo_cutu);
12688 	    }
12689 	  else if (!is_debug_types && dwo_file->cus)
12690 	    {
12691 	      struct dwo_unit find_dwo_cutu;
12692 
12693 	      memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12694 	      find_dwo_cutu.signature = signature;
12695 	      dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus.get (),
12696 						       &find_dwo_cutu);
12697 	    }
12698 
12699 	  if (dwo_cutu != NULL)
12700 	    {
12701 	      dwarf_read_debug_printf ("DWO %s %s(%s) found: @%s",
12702 				       kind, dwo_name, hex_string (signature),
12703 				       host_address_to_string (dwo_cutu));
12704 
12705 	      return dwo_cutu;
12706 	    }
12707 	}
12708     }
12709 
12710   /* We didn't find it.  This could mean a dwo_id mismatch, or
12711      someone deleted the DWO/DWP file, or the search path isn't set up
12712      correctly to find the file.  */
12713 
12714   dwarf_read_debug_printf ("DWO %s %s(%s) not found",
12715 			   kind, dwo_name, hex_string (signature));
12716 
12717   /* This is a warning and not a complaint because it can be caused by
12718      pilot error (e.g., user accidentally deleting the DWO).  */
12719   {
12720     /* Print the name of the DWP file if we looked there, helps the user
12721        better diagnose the problem.  */
12722     std::string dwp_text;
12723 
12724     if (dwp_file != NULL)
12725       dwp_text = string_printf (" [in DWP file %s]",
12726 				lbasename (dwp_file->name));
12727 
12728     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
12729 	       " [in module %s]"),
12730 	     kind, dwo_name, hex_string (signature), dwp_text.c_str (), kind,
12731 	     sect_offset_str (cu->per_cu->sect_off), objfile_name (objfile));
12732   }
12733   return NULL;
12734 }
12735 
12736 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
12737    See lookup_dwo_cutu_unit for details.  */
12738 
12739 static struct dwo_unit *
12740 lookup_dwo_comp_unit (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir,
12741 		      ULONGEST signature)
12742 {
12743   gdb_assert (!cu->per_cu->is_debug_types);
12744 
12745   return lookup_dwo_cutu (cu, dwo_name, comp_dir, signature, 0);
12746 }
12747 
12748 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
12749    See lookup_dwo_cutu_unit for details.  */
12750 
12751 static struct dwo_unit *
12752 lookup_dwo_type_unit (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir)
12753 {
12754   gdb_assert (cu->per_cu->is_debug_types);
12755 
12756   signatured_type *sig_type = (signatured_type *) cu->per_cu;
12757 
12758   return lookup_dwo_cutu (cu, dwo_name, comp_dir, sig_type->signature, 1);
12759 }
12760 
12761 /* Traversal function for queue_and_load_all_dwo_tus.  */
12762 
12763 static int
12764 queue_and_load_dwo_tu (void **slot, void *info)
12765 {
12766   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
12767   dwarf2_cu *cu = (dwarf2_cu *) info;
12768   ULONGEST signature = dwo_unit->signature;
12769   signatured_type *sig_type = lookup_dwo_signatured_type (cu, signature);
12770 
12771   if (sig_type != NULL)
12772     {
12773       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
12774 	 a real dependency of PER_CU on SIG_TYPE.  That is detected later
12775 	 while processing PER_CU.  */
12776       if (maybe_queue_comp_unit (NULL, sig_type, cu->per_objfile,
12777 				 cu->per_cu->lang))
12778 	load_full_type_unit (sig_type, cu->per_objfile);
12779       cu->per_cu->imported_symtabs_push (sig_type);
12780     }
12781 
12782   return 1;
12783 }
12784 
12785 /* Queue all TUs contained in the DWO of CU to be read in.
12786    The DWO may have the only definition of the type, though it may not be
12787    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
12788    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
12789 
12790 static void
12791 queue_and_load_all_dwo_tus (dwarf2_cu *cu)
12792 {
12793   struct dwo_unit *dwo_unit;
12794   struct dwo_file *dwo_file;
12795 
12796   gdb_assert (cu != nullptr);
12797   gdb_assert (!cu->per_cu->is_debug_types);
12798   gdb_assert (get_dwp_file (cu->per_objfile) == nullptr);
12799 
12800   dwo_unit = cu->dwo_unit;
12801   gdb_assert (dwo_unit != NULL);
12802 
12803   dwo_file = dwo_unit->dwo_file;
12804   if (dwo_file->tus != NULL)
12805     htab_traverse_noresize (dwo_file->tus.get (), queue_and_load_dwo_tu, cu);
12806 }
12807 
12808 /* Read in various DIEs.  */
12809 
12810 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
12811    Inherit only the children of the DW_AT_abstract_origin DIE not being
12812    already referenced by DW_AT_abstract_origin from the children of the
12813    current DIE.  */
12814 
12815 static void
12816 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
12817 {
12818   struct die_info *child_die;
12819   sect_offset *offsetp;
12820   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
12821   struct die_info *origin_die;
12822   /* Iterator of the ORIGIN_DIE children.  */
12823   struct die_info *origin_child_die;
12824   struct attribute *attr;
12825   struct dwarf2_cu *origin_cu;
12826   struct pending **origin_previous_list_in_scope;
12827 
12828   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12829   if (!attr)
12830     return;
12831 
12832   /* Note that following die references may follow to a die in a
12833      different cu.  */
12834 
12835   origin_cu = cu;
12836   origin_die = follow_die_ref (die, attr, &origin_cu);
12837 
12838   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
12839      symbols in.  */
12840   origin_previous_list_in_scope = origin_cu->list_in_scope;
12841   origin_cu->list_in_scope = cu->list_in_scope;
12842 
12843   if (die->tag != origin_die->tag
12844       && !(die->tag == DW_TAG_inlined_subroutine
12845 	   && origin_die->tag == DW_TAG_subprogram))
12846     complaint (_("DIE %s and its abstract origin %s have different tags"),
12847 	       sect_offset_str (die->sect_off),
12848 	       sect_offset_str (origin_die->sect_off));
12849 
12850   /* Find if the concrete and abstract trees are structurally the
12851      same.  This is a shallow traversal and it is not bullet-proof;
12852      the compiler can trick the debugger into believing that the trees
12853      are isomorphic, whereas they actually are not.  However, the
12854      likelyhood of this happening is pretty low, and a full-fledged
12855      check would be an overkill.  */
12856   bool are_isomorphic = true;
12857   die_info *concrete_child = die->child;
12858   die_info *abstract_child = origin_die->child;
12859   while (concrete_child != nullptr || abstract_child != nullptr)
12860     {
12861       if (concrete_child == nullptr
12862 	  || abstract_child == nullptr
12863 	  || concrete_child->tag != abstract_child->tag)
12864 	{
12865 	  are_isomorphic = false;
12866 	  break;
12867 	}
12868 
12869       concrete_child = concrete_child->sibling;
12870       abstract_child = abstract_child->sibling;
12871     }
12872 
12873   /* Walk the origin's children in parallel to the concrete children.
12874      This helps match an origin child in case the debug info misses
12875      DW_AT_abstract_origin attributes.  Keep in mind that the abstract
12876      origin tree may not have the same tree structure as the concrete
12877      DIE, though.  */
12878   die_info *corresponding_abstract_child
12879     = are_isomorphic ? origin_die->child : nullptr;
12880 
12881   std::vector<sect_offset> offsets;
12882 
12883   for (child_die = die->child;
12884        child_die && child_die->tag;
12885        child_die = child_die->sibling)
12886     {
12887       struct die_info *child_origin_die;
12888       struct dwarf2_cu *child_origin_cu;
12889 
12890       /* We are trying to process concrete instance entries:
12891 	 DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
12892 	 it's not relevant to our analysis here. i.e. detecting DIEs that are
12893 	 present in the abstract instance but not referenced in the concrete
12894 	 one.  */
12895       if (child_die->tag == DW_TAG_call_site
12896 	  || child_die->tag == DW_TAG_GNU_call_site)
12897 	{
12898 	  if (are_isomorphic)
12899 	    corresponding_abstract_child
12900 	      = corresponding_abstract_child->sibling;
12901 	  continue;
12902 	}
12903 
12904       /* For each CHILD_DIE, find the corresponding child of
12905 	 ORIGIN_DIE.  If there is more than one layer of
12906 	 DW_AT_abstract_origin, follow them all; there shouldn't be,
12907 	 but GCC versions at least through 4.4 generate this (GCC PR
12908 	 40573).  */
12909       child_origin_die = child_die;
12910       child_origin_cu = cu;
12911       while (1)
12912 	{
12913 	  attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
12914 			      child_origin_cu);
12915 	  if (attr == NULL)
12916 	    break;
12917 	  child_origin_die = follow_die_ref (child_origin_die, attr,
12918 					     &child_origin_cu);
12919 	}
12920 
12921       /* If missing DW_AT_abstract_origin, try the corresponding child
12922 	 of the origin.  Clang emits such lexical scopes.  */
12923       if (child_origin_die == child_die
12924 	  && dwarf2_attr (child_die, DW_AT_abstract_origin, cu) == nullptr
12925 	  && are_isomorphic
12926 	  && child_die->tag == DW_TAG_lexical_block)
12927 	child_origin_die = corresponding_abstract_child;
12928 
12929       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
12930 	 counterpart may exist.  */
12931       if (child_origin_die != child_die)
12932 	{
12933 	  if (child_die->tag != child_origin_die->tag
12934 	      && !(child_die->tag == DW_TAG_inlined_subroutine
12935 		   && child_origin_die->tag == DW_TAG_subprogram))
12936 	    complaint (_("Child DIE %s and its abstract origin %s have "
12937 			 "different tags"),
12938 		       sect_offset_str (child_die->sect_off),
12939 		       sect_offset_str (child_origin_die->sect_off));
12940 	  if (child_origin_die->parent != origin_die)
12941 	    complaint (_("Child DIE %s and its abstract origin %s have "
12942 			 "different parents"),
12943 		       sect_offset_str (child_die->sect_off),
12944 		       sect_offset_str (child_origin_die->sect_off));
12945 	  else
12946 	    offsets.push_back (child_origin_die->sect_off);
12947 	}
12948 
12949       if (are_isomorphic)
12950 	corresponding_abstract_child = corresponding_abstract_child->sibling;
12951     }
12952   std::sort (offsets.begin (), offsets.end ());
12953   sect_offset *offsets_end = offsets.data () + offsets.size ();
12954   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
12955     if (offsetp[-1] == *offsetp)
12956       complaint (_("Multiple children of DIE %s refer "
12957 		   "to DIE %s as their abstract origin"),
12958 		 sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
12959 
12960   offsetp = offsets.data ();
12961   origin_child_die = origin_die->child;
12962   while (origin_child_die && origin_child_die->tag)
12963     {
12964       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
12965       while (offsetp < offsets_end
12966 	     && *offsetp < origin_child_die->sect_off)
12967 	offsetp++;
12968       if (offsetp >= offsets_end
12969 	  || *offsetp > origin_child_die->sect_off)
12970 	{
12971 	  /* Found that ORIGIN_CHILD_DIE is really not referenced.
12972 	     Check whether we're already processing ORIGIN_CHILD_DIE.
12973 	     This can happen with mutually referenced abstract_origins.
12974 	     PR 16581.  */
12975 	  if (!origin_child_die->in_process)
12976 	    process_die (origin_child_die, origin_cu);
12977 	}
12978       origin_child_die = origin_child_die->sibling;
12979     }
12980   origin_cu->list_in_scope = origin_previous_list_in_scope;
12981 
12982   if (cu != origin_cu)
12983     compute_delayed_physnames (origin_cu);
12984 }
12985 
12986 static void
12987 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
12988 {
12989   struct objfile *objfile = cu->per_objfile->objfile;
12990   struct gdbarch *gdbarch = objfile->arch ();
12991   struct context_stack *newobj;
12992   CORE_ADDR lowpc;
12993   CORE_ADDR highpc;
12994   struct die_info *child_die;
12995   struct attribute *attr, *call_line, *call_file;
12996   const char *name;
12997   CORE_ADDR baseaddr;
12998   struct block *block;
12999   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13000   std::vector<struct symbol *> template_args;
13001   struct template_symbol *templ_func = NULL;
13002 
13003   if (inlined_func)
13004     {
13005       /* If we do not have call site information, we can't show the
13006 	 caller of this inlined function.  That's too confusing, so
13007 	 only use the scope for local variables.  */
13008       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13009       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13010       if (call_line == NULL || call_file == NULL)
13011 	{
13012 	  read_lexical_block_scope (die, cu);
13013 	  return;
13014 	}
13015     }
13016 
13017   baseaddr = objfile->text_section_offset ();
13018 
13019   name = dwarf2_name (die, cu);
13020 
13021   /* Ignore functions with missing or empty names.  These are actually
13022      illegal according to the DWARF standard.  */
13023   if (name == NULL)
13024     {
13025       complaint (_("missing name for subprogram DIE at %s"),
13026 		 sect_offset_str (die->sect_off));
13027       return;
13028     }
13029 
13030   /* Ignore functions with missing or invalid low and high pc attributes.  */
13031   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13032       <= PC_BOUNDS_INVALID)
13033     {
13034       attr = dwarf2_attr (die, DW_AT_external, cu);
13035       if (attr == nullptr || !attr->as_boolean ())
13036 	complaint (_("cannot get low and high bounds "
13037 		     "for subprogram DIE at %s"),
13038 		   sect_offset_str (die->sect_off));
13039       return;
13040     }
13041 
13042   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13043   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13044 
13045   /* If we have any template arguments, then we must allocate a
13046      different sort of symbol.  */
13047   for (child_die = die->child; child_die; child_die = child_die->sibling)
13048     {
13049       if (child_die->tag == DW_TAG_template_type_param
13050 	  || child_die->tag == DW_TAG_template_value_param)
13051 	{
13052 	  templ_func = new (&objfile->objfile_obstack) template_symbol;
13053 	  templ_func->subclass = SYMBOL_TEMPLATE;
13054 	  break;
13055 	}
13056     }
13057 
13058   gdb_assert (cu->get_builder () != nullptr);
13059   newobj = cu->get_builder ()->push_context (0, lowpc);
13060   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13061 			     (struct symbol *) templ_func);
13062 
13063   if (dwarf2_flag_true_p (die, DW_AT_main_subprogram, cu))
13064     set_objfile_main_name (objfile, newobj->name->linkage_name (),
13065 			   cu->per_cu->lang);
13066 
13067   /* If there is a location expression for DW_AT_frame_base, record
13068      it.  */
13069   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13070   if (attr != nullptr)
13071     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13072 
13073   /* If there is a location for the static link, record it.  */
13074   newobj->static_link = NULL;
13075   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13076   if (attr != nullptr)
13077     {
13078       newobj->static_link
13079 	= XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13080       attr_to_dynamic_prop (attr, die, cu, newobj->static_link,
13081 			    cu->addr_type ());
13082     }
13083 
13084   cu->list_in_scope = cu->get_builder ()->get_local_symbols ();
13085 
13086   if (die->child != NULL)
13087     {
13088       child_die = die->child;
13089       while (child_die && child_die->tag)
13090 	{
13091 	  if (child_die->tag == DW_TAG_template_type_param
13092 	      || child_die->tag == DW_TAG_template_value_param)
13093 	    {
13094 	      struct symbol *arg = new_symbol (child_die, NULL, cu);
13095 
13096 	      if (arg != NULL)
13097 		template_args.push_back (arg);
13098 	    }
13099 	  else
13100 	    process_die (child_die, cu);
13101 	  child_die = child_die->sibling;
13102 	}
13103     }
13104 
13105   inherit_abstract_dies (die, cu);
13106 
13107   /* If we have a DW_AT_specification, we might need to import using
13108      directives from the context of the specification DIE.  See the
13109      comment in determine_prefix.  */
13110   if (cu->per_cu->lang == language_cplus
13111       && dwarf2_attr (die, DW_AT_specification, cu))
13112     {
13113       struct dwarf2_cu *spec_cu = cu;
13114       struct die_info *spec_die = die_specification (die, &spec_cu);
13115 
13116       while (spec_die)
13117 	{
13118 	  child_die = spec_die->child;
13119 	  while (child_die && child_die->tag)
13120 	    {
13121 	      if (child_die->tag == DW_TAG_imported_module)
13122 		process_die (child_die, spec_cu);
13123 	      child_die = child_die->sibling;
13124 	    }
13125 
13126 	  /* In some cases, GCC generates specification DIEs that
13127 	     themselves contain DW_AT_specification attributes.  */
13128 	  spec_die = die_specification (spec_die, &spec_cu);
13129 	}
13130     }
13131 
13132   struct context_stack cstk = cu->get_builder ()->pop_context ();
13133   /* Make a block for the local symbols within.  */
13134   block = cu->get_builder ()->finish_block (cstk.name, cstk.old_blocks,
13135 				     cstk.static_link, lowpc, highpc);
13136 
13137   /* For C++, set the block's scope.  */
13138   if ((cu->per_cu->lang == language_cplus
13139        || cu->per_cu->lang == language_fortran
13140        || cu->per_cu->lang == language_d
13141        || cu->per_cu->lang == language_rust)
13142       && cu->processing_has_namespace_info)
13143     block_set_scope (block, determine_prefix (die, cu),
13144 		     &objfile->objfile_obstack);
13145 
13146   /* If we have address ranges, record them.  */
13147   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13148 
13149   gdbarch_make_symbol_special (gdbarch, cstk.name, objfile);
13150 
13151   /* Attach template arguments to function.  */
13152   if (!template_args.empty ())
13153     {
13154       gdb_assert (templ_func != NULL);
13155 
13156       templ_func->n_template_arguments = template_args.size ();
13157       templ_func->template_arguments
13158 	= XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13159 		     templ_func->n_template_arguments);
13160       memcpy (templ_func->template_arguments,
13161 	      template_args.data (),
13162 	      (templ_func->n_template_arguments * sizeof (struct symbol *)));
13163 
13164       /* Make sure that the symtab is set on the new symbols.  Even
13165 	 though they don't appear in this symtab directly, other parts
13166 	 of gdb assume that symbols do, and this is reasonably
13167 	 true.  */
13168       for (symbol *sym : template_args)
13169 	symbol_set_symtab (sym, symbol_symtab (templ_func));
13170     }
13171 
13172   /* In C++, we can have functions nested inside functions (e.g., when
13173      a function declares a class that has methods).  This means that
13174      when we finish processing a function scope, we may need to go
13175      back to building a containing block's symbol lists.  */
13176   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13177   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13178 
13179   /* If we've finished processing a top-level function, subsequent
13180      symbols go in the file symbol list.  */
13181   if (cu->get_builder ()->outermost_context_p ())
13182     cu->list_in_scope = cu->get_builder ()->get_file_symbols ();
13183 }
13184 
13185 /* Process all the DIES contained within a lexical block scope.  Start
13186    a new scope, process the dies, and then close the scope.  */
13187 
13188 static void
13189 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13190 {
13191   struct objfile *objfile = cu->per_objfile->objfile;
13192   struct gdbarch *gdbarch = objfile->arch ();
13193   CORE_ADDR lowpc, highpc;
13194   struct die_info *child_die;
13195   CORE_ADDR baseaddr;
13196 
13197   baseaddr = objfile->text_section_offset ();
13198 
13199   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13200   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13201      as multiple lexical blocks?  Handling children in a sane way would
13202      be nasty.  Might be easier to properly extend generic blocks to
13203      describe ranges.  */
13204   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13205     {
13206     case PC_BOUNDS_NOT_PRESENT:
13207       /* DW_TAG_lexical_block has no attributes, process its children as if
13208 	 there was no wrapping by that DW_TAG_lexical_block.
13209 	 GCC does no longer produces such DWARF since GCC r224161.  */
13210       for (child_die = die->child;
13211 	   child_die != NULL && child_die->tag;
13212 	   child_die = child_die->sibling)
13213 	{
13214 	  /* We might already be processing this DIE.  This can happen
13215 	     in an unusual circumstance -- where a subroutine A
13216 	     appears lexically in another subroutine B, but A actually
13217 	     inlines B.  The recursion is broken here, rather than in
13218 	     inherit_abstract_dies, because it seems better to simply
13219 	     drop concrete children here.  */
13220 	  if (!child_die->in_process)
13221 	    process_die (child_die, cu);
13222 	}
13223       return;
13224     case PC_BOUNDS_INVALID:
13225       return;
13226     }
13227   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13228   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13229 
13230   cu->get_builder ()->push_context (0, lowpc);
13231   if (die->child != NULL)
13232     {
13233       child_die = die->child;
13234       while (child_die && child_die->tag)
13235 	{
13236 	  process_die (child_die, cu);
13237 	  child_die = child_die->sibling;
13238 	}
13239     }
13240   inherit_abstract_dies (die, cu);
13241   struct context_stack cstk = cu->get_builder ()->pop_context ();
13242 
13243   if (*cu->get_builder ()->get_local_symbols () != NULL
13244       || (*cu->get_builder ()->get_local_using_directives ()) != NULL)
13245     {
13246       struct block *block
13247 	= cu->get_builder ()->finish_block (0, cstk.old_blocks, NULL,
13248 				     cstk.start_addr, highpc);
13249 
13250       /* Note that recording ranges after traversing children, as we
13251 	 do here, means that recording a parent's ranges entails
13252 	 walking across all its children's ranges as they appear in
13253 	 the address map, which is quadratic behavior.
13254 
13255 	 It would be nicer to record the parent's ranges before
13256 	 traversing its children, simply overriding whatever you find
13257 	 there.  But since we don't even decide whether to create a
13258 	 block until after we've traversed its children, that's hard
13259 	 to do.  */
13260       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13261     }
13262   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13263   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13264 }
13265 
13266 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13267 
13268 static void
13269 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13270 {
13271   dwarf2_per_objfile *per_objfile = cu->per_objfile;
13272   struct objfile *objfile = per_objfile->objfile;
13273   struct gdbarch *gdbarch = objfile->arch ();
13274   CORE_ADDR pc, baseaddr;
13275   struct attribute *attr;
13276   struct call_site *call_site, call_site_local;
13277   void **slot;
13278   int nparams;
13279   struct die_info *child_die;
13280 
13281   baseaddr = objfile->text_section_offset ();
13282 
13283   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13284   if (attr == NULL)
13285     {
13286       /* This was a pre-DWARF-5 GNU extension alias
13287 	 for DW_AT_call_return_pc.  */
13288       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13289     }
13290   if (!attr)
13291     {
13292       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13293 		   "DIE %s [in module %s]"),
13294 		 sect_offset_str (die->sect_off), objfile_name (objfile));
13295       return;
13296     }
13297   pc = attr->as_address () + baseaddr;
13298   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13299 
13300   if (cu->call_site_htab == NULL)
13301     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13302 					       NULL, &objfile->objfile_obstack,
13303 					       hashtab_obstack_allocate, NULL);
13304   call_site_local.pc = pc;
13305   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13306   if (*slot != NULL)
13307     {
13308       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13309 		   "DIE %s [in module %s]"),
13310 		 paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13311 		 objfile_name (objfile));
13312       return;
13313     }
13314 
13315   /* Count parameters at the caller.  */
13316 
13317   nparams = 0;
13318   for (child_die = die->child; child_die && child_die->tag;
13319        child_die = child_die->sibling)
13320     {
13321       if (child_die->tag != DW_TAG_call_site_parameter
13322 	  && child_die->tag != DW_TAG_GNU_call_site_parameter)
13323 	{
13324 	  complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13325 		       "DW_TAG_call_site child DIE %s [in module %s]"),
13326 		     child_die->tag, sect_offset_str (child_die->sect_off),
13327 		     objfile_name (objfile));
13328 	  continue;
13329 	}
13330 
13331       nparams++;
13332     }
13333 
13334   call_site
13335     = ((struct call_site *)
13336        obstack_alloc (&objfile->objfile_obstack,
13337 		      sizeof (*call_site)
13338 		      + (sizeof (*call_site->parameter) * (nparams - 1))));
13339   *slot = call_site;
13340   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13341   call_site->pc = pc;
13342 
13343   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13344       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13345     {
13346       struct die_info *func_die;
13347 
13348       /* Skip also over DW_TAG_inlined_subroutine.  */
13349       for (func_die = die->parent;
13350 	   func_die && func_die->tag != DW_TAG_subprogram
13351 	   && func_die->tag != DW_TAG_subroutine_type;
13352 	   func_die = func_die->parent);
13353 
13354       /* DW_AT_call_all_calls is a superset
13355 	 of DW_AT_call_all_tail_calls.  */
13356       if (func_die
13357 	  && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13358 	  && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13359 	  && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13360 	  && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13361 	{
13362 	  /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13363 	     not complete.  But keep CALL_SITE for look ups via call_site_htab,
13364 	     both the initial caller containing the real return address PC and
13365 	     the final callee containing the current PC of a chain of tail
13366 	     calls do not need to have the tail call list complete.  But any
13367 	     function candidate for a virtual tail call frame searched via
13368 	     TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13369 	     determined unambiguously.  */
13370 	}
13371       else
13372 	{
13373 	  struct type *func_type = NULL;
13374 
13375 	  if (func_die)
13376 	    func_type = get_die_type (func_die, cu);
13377 	  if (func_type != NULL)
13378 	    {
13379 	      gdb_assert (func_type->code () == TYPE_CODE_FUNC);
13380 
13381 	      /* Enlist this call site to the function.  */
13382 	      call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13383 	      TYPE_TAIL_CALL_LIST (func_type) = call_site;
13384 	    }
13385 	  else
13386 	    complaint (_("Cannot find function owning DW_TAG_call_site "
13387 			 "DIE %s [in module %s]"),
13388 		       sect_offset_str (die->sect_off), objfile_name (objfile));
13389 	}
13390     }
13391 
13392   attr = dwarf2_attr (die, DW_AT_call_target, cu);
13393   if (attr == NULL)
13394     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
13395   if (attr == NULL)
13396     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
13397   if (attr == NULL)
13398     {
13399       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
13400       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13401     }
13402   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
13403   if (!attr || (attr->form_is_block () && attr->as_block ()->size == 0))
13404     /* Keep NULL DWARF_BLOCK.  */;
13405   else if (attr->form_is_block ())
13406     {
13407       struct dwarf2_locexpr_baton *dlbaton;
13408       struct dwarf_block *block = attr->as_block ();
13409 
13410       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
13411       dlbaton->data = block->data;
13412       dlbaton->size = block->size;
13413       dlbaton->per_objfile = per_objfile;
13414       dlbaton->per_cu = cu->per_cu;
13415 
13416       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
13417     }
13418   else if (attr->form_is_ref ())
13419     {
13420       struct dwarf2_cu *target_cu = cu;
13421       struct die_info *target_die;
13422 
13423       target_die = follow_die_ref (die, attr, &target_cu);
13424       gdb_assert (target_cu->per_objfile->objfile == objfile);
13425       if (die_is_declaration (target_die, target_cu))
13426 	{
13427 	  const char *target_physname;
13428 
13429 	  /* Prefer the mangled name; otherwise compute the demangled one.  */
13430 	  target_physname = dw2_linkage_name (target_die, target_cu);
13431 	  if (target_physname == NULL)
13432 	    target_physname = dwarf2_physname (NULL, target_die, target_cu);
13433 	  if (target_physname == NULL)
13434 	    complaint (_("DW_AT_call_target target DIE has invalid "
13435 			 "physname, for referencing DIE %s [in module %s]"),
13436 		       sect_offset_str (die->sect_off), objfile_name (objfile));
13437 	  else
13438 	    SET_FIELD_PHYSNAME (call_site->target, target_physname);
13439 	}
13440       else
13441 	{
13442 	  CORE_ADDR lowpc;
13443 
13444 	  /* DW_AT_entry_pc should be preferred.  */
13445 	  if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
13446 	      <= PC_BOUNDS_INVALID)
13447 	    complaint (_("DW_AT_call_target target DIE has invalid "
13448 			 "low pc, for referencing DIE %s [in module %s]"),
13449 		       sect_offset_str (die->sect_off), objfile_name (objfile));
13450 	  else
13451 	    {
13452 	      lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13453 	      SET_FIELD_PHYSADDR (call_site->target, lowpc);
13454 	    }
13455 	}
13456     }
13457   else
13458     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
13459 		 "block nor reference, for DIE %s [in module %s]"),
13460 	       sect_offset_str (die->sect_off), objfile_name (objfile));
13461 
13462   call_site->per_cu = cu->per_cu;
13463   call_site->per_objfile = per_objfile;
13464 
13465   for (child_die = die->child;
13466        child_die && child_die->tag;
13467        child_die = child_die->sibling)
13468     {
13469       struct call_site_parameter *parameter;
13470       struct attribute *loc, *origin;
13471 
13472       if (child_die->tag != DW_TAG_call_site_parameter
13473 	  && child_die->tag != DW_TAG_GNU_call_site_parameter)
13474 	{
13475 	  /* Already printed the complaint above.  */
13476 	  continue;
13477 	}
13478 
13479       gdb_assert (call_site->parameter_count < nparams);
13480       parameter = &call_site->parameter[call_site->parameter_count];
13481 
13482       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
13483 	 specifies DW_TAG_formal_parameter.  Value of the data assumed for the
13484 	 register is contained in DW_AT_call_value.  */
13485 
13486       loc = dwarf2_attr (child_die, DW_AT_location, cu);
13487       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
13488       if (origin == NULL)
13489 	{
13490 	  /* This was a pre-DWARF-5 GNU extension alias
13491 	     for DW_AT_call_parameter.  */
13492 	  origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
13493 	}
13494       if (loc == NULL && origin != NULL && origin->form_is_ref ())
13495 	{
13496 	  parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
13497 
13498 	  sect_offset sect_off = origin->get_ref_die_offset ();
13499 	  if (!cu->header.offset_in_cu_p (sect_off))
13500 	    {
13501 	      /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
13502 		 binding can be done only inside one CU.  Such referenced DIE
13503 		 therefore cannot be even moved to DW_TAG_partial_unit.  */
13504 	      complaint (_("DW_AT_call_parameter offset is not in CU for "
13505 			   "DW_TAG_call_site child DIE %s [in module %s]"),
13506 			 sect_offset_str (child_die->sect_off),
13507 			 objfile_name (objfile));
13508 	      continue;
13509 	    }
13510 	  parameter->u.param_cu_off
13511 	    = (cu_offset) (sect_off - cu->header.sect_off);
13512 	}
13513       else if (loc == NULL || origin != NULL || !loc->form_is_block ())
13514 	{
13515 	  complaint (_("No DW_FORM_block* DW_AT_location for "
13516 		       "DW_TAG_call_site child DIE %s [in module %s]"),
13517 		     sect_offset_str (child_die->sect_off), objfile_name (objfile));
13518 	  continue;
13519 	}
13520       else
13521 	{
13522 	  struct dwarf_block *block = loc->as_block ();
13523 
13524 	  parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
13525 	    (block->data, &block->data[block->size]);
13526 	  if (parameter->u.dwarf_reg != -1)
13527 	    parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
13528 	  else if (dwarf_block_to_sp_offset (gdbarch, block->data,
13529 				    &block->data[block->size],
13530 					     &parameter->u.fb_offset))
13531 	    parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
13532 	  else
13533 	    {
13534 	      complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
13535 			   "for DW_FORM_block* DW_AT_location is supported for "
13536 			   "DW_TAG_call_site child DIE %s "
13537 			   "[in module %s]"),
13538 			 sect_offset_str (child_die->sect_off),
13539 			 objfile_name (objfile));
13540 	      continue;
13541 	    }
13542 	}
13543 
13544       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
13545       if (attr == NULL)
13546 	attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
13547       if (attr == NULL || !attr->form_is_block ())
13548 	{
13549 	  complaint (_("No DW_FORM_block* DW_AT_call_value for "
13550 		       "DW_TAG_call_site child DIE %s [in module %s]"),
13551 		     sect_offset_str (child_die->sect_off),
13552 		     objfile_name (objfile));
13553 	  continue;
13554 	}
13555 
13556       struct dwarf_block *block = attr->as_block ();
13557       parameter->value = block->data;
13558       parameter->value_size = block->size;
13559 
13560       /* Parameters are not pre-cleared by memset above.  */
13561       parameter->data_value = NULL;
13562       parameter->data_value_size = 0;
13563       call_site->parameter_count++;
13564 
13565       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
13566       if (attr == NULL)
13567 	attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
13568       if (attr != nullptr)
13569 	{
13570 	  if (!attr->form_is_block ())
13571 	    complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
13572 			 "DW_TAG_call_site child DIE %s [in module %s]"),
13573 		       sect_offset_str (child_die->sect_off),
13574 		       objfile_name (objfile));
13575 	  else
13576 	    {
13577 	      block = attr->as_block ();
13578 	      parameter->data_value = block->data;
13579 	      parameter->data_value_size = block->size;
13580 	    }
13581 	}
13582     }
13583 }
13584 
13585 /* Helper function for read_variable.  If DIE represents a virtual
13586    table, then return the type of the concrete object that is
13587    associated with the virtual table.  Otherwise, return NULL.  */
13588 
13589 static struct type *
13590 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
13591 {
13592   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
13593   if (attr == NULL)
13594     return NULL;
13595 
13596   /* Find the type DIE.  */
13597   struct die_info *type_die = NULL;
13598   struct dwarf2_cu *type_cu = cu;
13599 
13600   if (attr->form_is_ref ())
13601     type_die = follow_die_ref (die, attr, &type_cu);
13602   if (type_die == NULL)
13603     return NULL;
13604 
13605   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
13606     return NULL;
13607   return die_containing_type (type_die, type_cu);
13608 }
13609 
13610 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
13611 
13612 static void
13613 read_variable (struct die_info *die, struct dwarf2_cu *cu)
13614 {
13615   struct rust_vtable_symbol *storage = NULL;
13616 
13617   if (cu->per_cu->lang == language_rust)
13618     {
13619       struct type *containing_type = rust_containing_type (die, cu);
13620 
13621       if (containing_type != NULL)
13622 	{
13623 	  struct objfile *objfile = cu->per_objfile->objfile;
13624 
13625 	  storage = new (&objfile->objfile_obstack) rust_vtable_symbol;
13626 	  storage->concrete_type = containing_type;
13627 	  storage->subclass = SYMBOL_RUST_VTABLE;
13628 	}
13629     }
13630 
13631   struct symbol *res = new_symbol (die, NULL, cu, storage);
13632   struct attribute *abstract_origin
13633     = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13634   struct attribute *loc = dwarf2_attr (die, DW_AT_location, cu);
13635   if (res == NULL && loc && abstract_origin)
13636     {
13637       /* We have a variable without a name, but with a location and an abstract
13638 	 origin.  This may be a concrete instance of an abstract variable
13639 	 referenced from an DW_OP_GNU_variable_value, so save it to find it back
13640 	 later.  */
13641       struct dwarf2_cu *origin_cu = cu;
13642       struct die_info *origin_die
13643 	= follow_die_ref (die, abstract_origin, &origin_cu);
13644       dwarf2_per_objfile *per_objfile = cu->per_objfile;
13645       per_objfile->per_bfd->abstract_to_concrete
13646 	[origin_die->sect_off].push_back (die->sect_off);
13647     }
13648 }
13649 
13650 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
13651    reading .debug_rnglists.
13652    Callback's type should be:
13653     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
13654    Return true if the attributes are present and valid, otherwise,
13655    return false.  */
13656 
13657 template <typename Callback>
13658 static bool
13659 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
13660 			 dwarf_tag tag, Callback &&callback)
13661 {
13662   dwarf2_per_objfile *per_objfile = cu->per_objfile;
13663   struct objfile *objfile = per_objfile->objfile;
13664   bfd *obfd = objfile->obfd;
13665   /* Base address selection entry.  */
13666   gdb::optional<CORE_ADDR> base;
13667   const gdb_byte *buffer;
13668   bool overflow = false;
13669   ULONGEST addr_index;
13670   struct dwarf2_section_info *rnglists_section;
13671 
13672   base = cu->base_address;
13673   rnglists_section = cu_debug_rnglists_section (cu, tag);
13674   rnglists_section->read (objfile);
13675 
13676   if (offset >= rnglists_section->size)
13677     {
13678       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
13679 		 offset);
13680       return false;
13681     }
13682   buffer = rnglists_section->buffer + offset;
13683 
13684   while (1)
13685     {
13686       /* Initialize it due to a false compiler warning.  */
13687       CORE_ADDR range_beginning = 0, range_end = 0;
13688       const gdb_byte *buf_end = (rnglists_section->buffer
13689 				 + rnglists_section->size);
13690       unsigned int bytes_read;
13691 
13692       if (buffer == buf_end)
13693 	{
13694 	  overflow = true;
13695 	  break;
13696 	}
13697       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
13698       switch (rlet)
13699 	{
13700 	case DW_RLE_end_of_list:
13701 	  break;
13702 	case DW_RLE_base_address:
13703 	  if (buffer + cu->header.addr_size > buf_end)
13704 	    {
13705 	      overflow = true;
13706 	      break;
13707 	    }
13708 	  base = cu->header.read_address (obfd, buffer, &bytes_read);
13709 	  buffer += bytes_read;
13710 	  break;
13711 	case DW_RLE_base_addressx:
13712 	  addr_index = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13713 	  buffer += bytes_read;
13714 	  base = read_addr_index (cu, addr_index);
13715 	  break;
13716 	case DW_RLE_start_length:
13717 	  if (buffer + cu->header.addr_size > buf_end)
13718 	    {
13719 	      overflow = true;
13720 	      break;
13721 	    }
13722 	  range_beginning = cu->header.read_address (obfd, buffer,
13723 						     &bytes_read);
13724 	  buffer += bytes_read;
13725 	  range_end = (range_beginning
13726 		       + read_unsigned_leb128 (obfd, buffer, &bytes_read));
13727 	  buffer += bytes_read;
13728 	  if (buffer > buf_end)
13729 	    {
13730 	      overflow = true;
13731 	      break;
13732 	    }
13733 	  break;
13734 	case DW_RLE_startx_length:
13735 	  addr_index = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13736 	  buffer += bytes_read;
13737 	  range_beginning = read_addr_index (cu, addr_index);
13738 	  if (buffer > buf_end)
13739 	    {
13740 	      overflow = true;
13741 	      break;
13742 	    }
13743 	  range_end = (range_beginning
13744 		       + read_unsigned_leb128 (obfd, buffer, &bytes_read));
13745 	  buffer += bytes_read;
13746 	  break;
13747 	case DW_RLE_offset_pair:
13748 	  range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13749 	  buffer += bytes_read;
13750 	  if (buffer > buf_end)
13751 	    {
13752 	      overflow = true;
13753 	      break;
13754 	    }
13755 	  range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13756 	  buffer += bytes_read;
13757 	  if (buffer > buf_end)
13758 	    {
13759 	      overflow = true;
13760 	      break;
13761 	    }
13762 	  break;
13763 	case DW_RLE_start_end:
13764 	  if (buffer + 2 * cu->header.addr_size > buf_end)
13765 	    {
13766 	      overflow = true;
13767 	      break;
13768 	    }
13769 	  range_beginning = cu->header.read_address (obfd, buffer,
13770 						     &bytes_read);
13771 	  buffer += bytes_read;
13772 	  range_end = cu->header.read_address (obfd, buffer, &bytes_read);
13773 	  buffer += bytes_read;
13774 	  break;
13775 	case DW_RLE_startx_endx:
13776 	  addr_index = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13777 	  buffer += bytes_read;
13778 	  range_beginning = read_addr_index (cu, addr_index);
13779 	  if (buffer > buf_end)
13780 	    {
13781 	      overflow = true;
13782 	      break;
13783 	    }
13784 	  addr_index = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13785 	  buffer += bytes_read;
13786 	  range_end = read_addr_index (cu, addr_index);
13787 	  break;
13788 	default:
13789 	  complaint (_("Invalid .debug_rnglists data (no base address)"));
13790 	  return false;
13791 	}
13792       if (rlet == DW_RLE_end_of_list || overflow)
13793 	break;
13794       if (rlet == DW_RLE_base_address)
13795 	continue;
13796 
13797       if (range_beginning > range_end)
13798 	{
13799 	  /* Inverted range entries are invalid.  */
13800 	  complaint (_("Invalid .debug_rnglists data (inverted range)"));
13801 	  return false;
13802 	}
13803 
13804       /* Empty range entries have no effect.  */
13805       if (range_beginning == range_end)
13806 	continue;
13807 
13808       /* Only DW_RLE_offset_pair needs the base address added.  */
13809       if (rlet == DW_RLE_offset_pair)
13810 	{
13811 	  if (!base.has_value ())
13812 	    {
13813 	      /* We have no valid base address for the DW_RLE_offset_pair.  */
13814 	      complaint (_("Invalid .debug_rnglists data (no base address for "
13815 			   "DW_RLE_offset_pair)"));
13816 	      return false;
13817 	    }
13818 
13819 	  range_beginning += *base;
13820 	  range_end += *base;
13821 	}
13822 
13823       /* A not-uncommon case of bad debug info.
13824 	 Don't pollute the addrmap with bad data.  */
13825       if (range_beginning == 0
13826 	  && !per_objfile->per_bfd->has_section_at_zero)
13827 	{
13828 	  complaint (_(".debug_rnglists entry has start address of zero"
13829 		       " [in module %s]"), objfile_name (objfile));
13830 	  continue;
13831 	}
13832 
13833       callback (range_beginning, range_end);
13834     }
13835 
13836   if (overflow)
13837     {
13838       complaint (_("Offset %d is not terminated "
13839 		   "for DW_AT_ranges attribute"),
13840 		 offset);
13841       return false;
13842     }
13843 
13844   return true;
13845 }
13846 
13847 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
13848    Callback's type should be:
13849     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
13850    Return 1 if the attributes are present and valid, otherwise, return 0.  */
13851 
13852 template <typename Callback>
13853 static int
13854 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu, dwarf_tag tag,
13855 		       Callback &&callback)
13856 {
13857   dwarf2_per_objfile *per_objfile = cu->per_objfile;
13858   struct objfile *objfile = per_objfile->objfile;
13859   struct comp_unit_head *cu_header = &cu->header;
13860   bfd *obfd = objfile->obfd;
13861   unsigned int addr_size = cu_header->addr_size;
13862   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
13863   /* Base address selection entry.  */
13864   gdb::optional<CORE_ADDR> base;
13865   unsigned int dummy;
13866   const gdb_byte *buffer;
13867 
13868   if (cu_header->version >= 5)
13869     return dwarf2_rnglists_process (offset, cu, tag, callback);
13870 
13871   base = cu->base_address;
13872 
13873   per_objfile->per_bfd->ranges.read (objfile);
13874   if (offset >= per_objfile->per_bfd->ranges.size)
13875     {
13876       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
13877 		 offset);
13878       return 0;
13879     }
13880   buffer = per_objfile->per_bfd->ranges.buffer + offset;
13881 
13882   while (1)
13883     {
13884       CORE_ADDR range_beginning, range_end;
13885 
13886       range_beginning = cu->header.read_address (obfd, buffer, &dummy);
13887       buffer += addr_size;
13888       range_end = cu->header.read_address (obfd, buffer, &dummy);
13889       buffer += addr_size;
13890       offset += 2 * addr_size;
13891 
13892       /* An end of list marker is a pair of zero addresses.  */
13893       if (range_beginning == 0 && range_end == 0)
13894 	/* Found the end of list entry.  */
13895 	break;
13896 
13897       /* Each base address selection entry is a pair of 2 values.
13898 	 The first is the largest possible address, the second is
13899 	 the base address.  Check for a base address here.  */
13900       if ((range_beginning & mask) == mask)
13901 	{
13902 	  /* If we found the largest possible address, then we already
13903 	     have the base address in range_end.  */
13904 	  base = range_end;
13905 	  continue;
13906 	}
13907 
13908       if (!base.has_value ())
13909 	{
13910 	  /* We have no valid base address for the ranges
13911 	     data.  */
13912 	  complaint (_("Invalid .debug_ranges data (no base address)"));
13913 	  return 0;
13914 	}
13915 
13916       if (range_beginning > range_end)
13917 	{
13918 	  /* Inverted range entries are invalid.  */
13919 	  complaint (_("Invalid .debug_ranges data (inverted range)"));
13920 	  return 0;
13921 	}
13922 
13923       /* Empty range entries have no effect.  */
13924       if (range_beginning == range_end)
13925 	continue;
13926 
13927       range_beginning += *base;
13928       range_end += *base;
13929 
13930       /* A not-uncommon case of bad debug info.
13931 	 Don't pollute the addrmap with bad data.  */
13932       if (range_beginning == 0
13933 	  && !per_objfile->per_bfd->has_section_at_zero)
13934 	{
13935 	  complaint (_(".debug_ranges entry has start address of zero"
13936 		       " [in module %s]"), objfile_name (objfile));
13937 	  continue;
13938 	}
13939 
13940       callback (range_beginning, range_end);
13941     }
13942 
13943   return 1;
13944 }
13945 
13946 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
13947    Return 1 if the attributes are present and valid, otherwise, return 0.
13948    If RANGES_PST is not NULL we should set up the `psymtabs_addrmap'.  */
13949 
13950 static int
13951 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
13952 		    CORE_ADDR *high_return, struct dwarf2_cu *cu,
13953 		    dwarf2_psymtab *ranges_pst, dwarf_tag tag)
13954 {
13955   struct objfile *objfile = cu->per_objfile->objfile;
13956   dwarf2_per_bfd *per_bfd = cu->per_objfile->per_bfd;
13957   struct gdbarch *gdbarch = objfile->arch ();
13958   const CORE_ADDR baseaddr = objfile->text_section_offset ();
13959   int low_set = 0;
13960   CORE_ADDR low = 0;
13961   CORE_ADDR high = 0;
13962   int retval;
13963 
13964   retval = dwarf2_ranges_process (offset, cu, tag,
13965     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
13966     {
13967       if (ranges_pst != NULL)
13968 	{
13969 	  CORE_ADDR lowpc;
13970 	  CORE_ADDR highpc;
13971 
13972 	  lowpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
13973 					       range_beginning + baseaddr)
13974 		   - baseaddr);
13975 	  highpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
13976 						range_end + baseaddr)
13977 		    - baseaddr);
13978 	  addrmap_set_empty (per_bfd->partial_symtabs->psymtabs_addrmap,
13979 			     lowpc, highpc - 1, ranges_pst);
13980 	}
13981 
13982       /* FIXME: This is recording everything as a low-high
13983 	 segment of consecutive addresses.  We should have a
13984 	 data structure for discontiguous block ranges
13985 	 instead.  */
13986       if (! low_set)
13987 	{
13988 	  low = range_beginning;
13989 	  high = range_end;
13990 	  low_set = 1;
13991 	}
13992       else
13993 	{
13994 	  if (range_beginning < low)
13995 	    low = range_beginning;
13996 	  if (range_end > high)
13997 	    high = range_end;
13998 	}
13999     });
14000   if (!retval)
14001     return 0;
14002 
14003   if (! low_set)
14004     /* If the first entry is an end-of-list marker, the range
14005        describes an empty scope, i.e. no instructions.  */
14006     return 0;
14007 
14008   if (low_return)
14009     *low_return = low;
14010   if (high_return)
14011     *high_return = high;
14012   return 1;
14013 }
14014 
14015 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14016    definition for the return value.  *LOWPC and *HIGHPC are set iff
14017    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14018 
14019 static enum pc_bounds_kind
14020 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14021 		      CORE_ADDR *highpc, struct dwarf2_cu *cu,
14022 		      dwarf2_psymtab *pst)
14023 {
14024   dwarf2_per_objfile *per_objfile = cu->per_objfile;
14025   struct attribute *attr;
14026   struct attribute *attr_high;
14027   CORE_ADDR low = 0;
14028   CORE_ADDR high = 0;
14029   enum pc_bounds_kind ret;
14030 
14031   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14032   if (attr_high)
14033     {
14034       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14035       if (attr != nullptr)
14036 	{
14037 	  low = attr->as_address ();
14038 	  high = attr_high->as_address ();
14039 	  if (cu->header.version >= 4 && attr_high->form_is_constant ())
14040 	    high += low;
14041 	}
14042       else
14043 	/* Found high w/o low attribute.  */
14044 	return PC_BOUNDS_INVALID;
14045 
14046       /* Found consecutive range of addresses.  */
14047       ret = PC_BOUNDS_HIGH_LOW;
14048     }
14049   else
14050     {
14051       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14052       if (attr != nullptr && attr->form_is_unsigned ())
14053 	{
14054 	  /* Offset in the .debug_ranges or .debug_rnglist section (depending
14055 	     on DWARF version).  */
14056 	  ULONGEST ranges_offset = attr->as_unsigned ();
14057 
14058 	  /* See dwarf2_cu::gnu_ranges_base's doc for why we might want to add
14059 	     this value.  */
14060 	  if (die->tag != DW_TAG_compile_unit)
14061 	    ranges_offset += cu->gnu_ranges_base;
14062 
14063 	  /* Value of the DW_AT_ranges attribute is the offset in the
14064 	     .debug_ranges section.  */
14065 	  if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst,
14066 				   die->tag))
14067 	    return PC_BOUNDS_INVALID;
14068 	  /* Found discontinuous range of addresses.  */
14069 	  ret = PC_BOUNDS_RANGES;
14070 	}
14071       else
14072 	return PC_BOUNDS_NOT_PRESENT;
14073     }
14074 
14075   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14076   if (high <= low)
14077     return PC_BOUNDS_INVALID;
14078 
14079   /* When using the GNU linker, .gnu.linkonce. sections are used to
14080      eliminate duplicate copies of functions and vtables and such.
14081      The linker will arbitrarily choose one and discard the others.
14082      The AT_*_pc values for such functions refer to local labels in
14083      these sections.  If the section from that file was discarded, the
14084      labels are not in the output, so the relocs get a value of 0.
14085      If this is a discarded function, mark the pc bounds as invalid,
14086      so that GDB will ignore it.  */
14087   if (low == 0 && !per_objfile->per_bfd->has_section_at_zero)
14088     return PC_BOUNDS_INVALID;
14089 
14090   *lowpc = low;
14091   if (highpc)
14092     *highpc = high;
14093   return ret;
14094 }
14095 
14096 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14097    its low and high PC addresses.  Do nothing if these addresses could not
14098    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14099    and HIGHPC to the high address if greater than HIGHPC.  */
14100 
14101 static void
14102 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14103 				 CORE_ADDR *lowpc, CORE_ADDR *highpc,
14104 				 struct dwarf2_cu *cu)
14105 {
14106   CORE_ADDR low, high;
14107   struct die_info *child = die->child;
14108 
14109   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14110     {
14111       *lowpc = std::min (*lowpc, low);
14112       *highpc = std::max (*highpc, high);
14113     }
14114 
14115   /* If the language does not allow nested subprograms (either inside
14116      subprograms or lexical blocks), we're done.  */
14117   if (cu->per_cu->lang != language_ada)
14118     return;
14119 
14120   /* Check all the children of the given DIE.  If it contains nested
14121      subprograms, then check their pc bounds.  Likewise, we need to
14122      check lexical blocks as well, as they may also contain subprogram
14123      definitions.  */
14124   while (child && child->tag)
14125     {
14126       if (child->tag == DW_TAG_subprogram
14127 	  || child->tag == DW_TAG_lexical_block)
14128 	dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14129       child = child->sibling;
14130     }
14131 }
14132 
14133 /* Get the low and high pc's represented by the scope DIE, and store
14134    them in *LOWPC and *HIGHPC.  If the correct values can't be
14135    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14136 
14137 static void
14138 get_scope_pc_bounds (struct die_info *die,
14139 		     CORE_ADDR *lowpc, CORE_ADDR *highpc,
14140 		     struct dwarf2_cu *cu)
14141 {
14142   CORE_ADDR best_low = (CORE_ADDR) -1;
14143   CORE_ADDR best_high = (CORE_ADDR) 0;
14144   CORE_ADDR current_low, current_high;
14145 
14146   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14147       >= PC_BOUNDS_RANGES)
14148     {
14149       best_low = current_low;
14150       best_high = current_high;
14151     }
14152   else
14153     {
14154       struct die_info *child = die->child;
14155 
14156       while (child && child->tag)
14157 	{
14158 	  switch (child->tag) {
14159 	  case DW_TAG_subprogram:
14160 	    dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14161 	    break;
14162 	  case DW_TAG_namespace:
14163 	  case DW_TAG_module:
14164 	    /* FIXME: carlton/2004-01-16: Should we do this for
14165 	       DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14166 	       that current GCC's always emit the DIEs corresponding
14167 	       to definitions of methods of classes as children of a
14168 	       DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14169 	       the DIEs giving the declarations, which could be
14170 	       anywhere).  But I don't see any reason why the
14171 	       standards says that they have to be there.  */
14172 	    get_scope_pc_bounds (child, &current_low, &current_high, cu);
14173 
14174 	    if (current_low != ((CORE_ADDR) -1))
14175 	      {
14176 		best_low = std::min (best_low, current_low);
14177 		best_high = std::max (best_high, current_high);
14178 	      }
14179 	    break;
14180 	  default:
14181 	    /* Ignore.  */
14182 	    break;
14183 	  }
14184 
14185 	  child = child->sibling;
14186 	}
14187     }
14188 
14189   *lowpc = best_low;
14190   *highpc = best_high;
14191 }
14192 
14193 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14194    in DIE.  */
14195 
14196 static void
14197 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14198 			    CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14199 {
14200   struct objfile *objfile = cu->per_objfile->objfile;
14201   struct gdbarch *gdbarch = objfile->arch ();
14202   struct attribute *attr;
14203   struct attribute *attr_high;
14204 
14205   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14206   if (attr_high)
14207     {
14208       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14209       if (attr != nullptr)
14210 	{
14211 	  CORE_ADDR low = attr->as_address ();
14212 	  CORE_ADDR high = attr_high->as_address ();
14213 
14214 	  if (cu->header.version >= 4 && attr_high->form_is_constant ())
14215 	    high += low;
14216 
14217 	  low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14218 	  high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14219 	  cu->get_builder ()->record_block_range (block, low, high - 1);
14220 	}
14221     }
14222 
14223   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14224   if (attr != nullptr && attr->form_is_unsigned ())
14225     {
14226       /* Offset in the .debug_ranges or .debug_rnglist section (depending
14227 	 on DWARF version).  */
14228       ULONGEST ranges_offset = attr->as_unsigned ();
14229 
14230       /* See dwarf2_cu::gnu_ranges_base's doc for why we might want to add
14231 	 this value.  */
14232       if (die->tag != DW_TAG_compile_unit)
14233 	ranges_offset += cu->gnu_ranges_base;
14234 
14235       std::vector<blockrange> blockvec;
14236       dwarf2_ranges_process (ranges_offset, cu, die->tag,
14237 	[&] (CORE_ADDR start, CORE_ADDR end)
14238 	{
14239 	  start += baseaddr;
14240 	  end += baseaddr;
14241 	  start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14242 	  end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14243 	  cu->get_builder ()->record_block_range (block, start, end - 1);
14244 	  blockvec.emplace_back (start, end);
14245 	});
14246 
14247       BLOCK_RANGES(block) = make_blockranges (objfile, blockvec);
14248     }
14249 }
14250 
14251 /* Check whether the producer field indicates either of GCC < 4.6, or the
14252    Intel C/C++ compiler, and cache the result in CU.  */
14253 
14254 static void
14255 check_producer (struct dwarf2_cu *cu)
14256 {
14257   int major, minor;
14258 
14259   if (cu->producer == NULL)
14260     {
14261       /* For unknown compilers expect their behavior is DWARF version
14262 	 compliant.
14263 
14264 	 GCC started to support .debug_types sections by -gdwarf-4 since
14265 	 gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14266 	 for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14267 	 combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14268 	 interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14269     }
14270   else if (producer_is_gcc (cu->producer, &major, &minor))
14271     {
14272       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14273       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14274     }
14275   else if (producer_is_icc (cu->producer, &major, &minor))
14276     {
14277       cu->producer_is_icc = true;
14278       cu->producer_is_icc_lt_14 = major < 14;
14279     }
14280   else if (startswith (cu->producer, "CodeWarrior S12/L-ISA"))
14281     cu->producer_is_codewarrior = true;
14282   else
14283     {
14284       /* For other non-GCC compilers, expect their behavior is DWARF version
14285 	 compliant.  */
14286     }
14287 
14288   cu->checked_producer = true;
14289 }
14290 
14291 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14292    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14293    during 4.6.0 experimental.  */
14294 
14295 static bool
14296 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14297 {
14298   if (!cu->checked_producer)
14299     check_producer (cu);
14300 
14301   return cu->producer_is_gxx_lt_4_6;
14302 }
14303 
14304 
14305 /* Codewarrior (at least as of version 5.0.40) generates dwarf line information
14306    with incorrect is_stmt attributes.  */
14307 
14308 static bool
14309 producer_is_codewarrior (struct dwarf2_cu *cu)
14310 {
14311   if (!cu->checked_producer)
14312     check_producer (cu);
14313 
14314   return cu->producer_is_codewarrior;
14315 }
14316 
14317 /* Return the accessibility of DIE, as given by DW_AT_accessibility.
14318    If that attribute is not available, return the appropriate
14319    default.  */
14320 
14321 static enum dwarf_access_attribute
14322 dwarf2_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14323 {
14324   attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14325   if (attr != nullptr)
14326     {
14327       LONGEST value = attr->constant_value (-1);
14328       if (value == DW_ACCESS_public
14329 	  || value == DW_ACCESS_protected
14330 	  || value == DW_ACCESS_private)
14331 	return (dwarf_access_attribute) value;
14332       complaint (_("Unhandled DW_AT_accessibility value (%s)"),
14333 		 plongest (value));
14334     }
14335 
14336   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14337     {
14338       /* The default DWARF 2 accessibility for members is public, the default
14339 	 accessibility for inheritance is private.  */
14340 
14341       if (die->tag != DW_TAG_inheritance)
14342 	return DW_ACCESS_public;
14343       else
14344 	return DW_ACCESS_private;
14345     }
14346   else
14347     {
14348       /* DWARF 3+ defines the default accessibility a different way.  The same
14349 	 rules apply now for DW_TAG_inheritance as for the members and it only
14350 	 depends on the container kind.  */
14351 
14352       if (die->parent->tag == DW_TAG_class_type)
14353 	return DW_ACCESS_private;
14354       else
14355 	return DW_ACCESS_public;
14356     }
14357 }
14358 
14359 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14360    offset.  If the attribute was not found return 0, otherwise return
14361    1.  If it was found but could not properly be handled, set *OFFSET
14362    to 0.  */
14363 
14364 static int
14365 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14366 			     LONGEST *offset)
14367 {
14368   struct attribute *attr;
14369 
14370   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14371   if (attr != NULL)
14372     {
14373       *offset = 0;
14374 
14375       /* Note that we do not check for a section offset first here.
14376 	 This is because DW_AT_data_member_location is new in DWARF 4,
14377 	 so if we see it, we can assume that a constant form is really
14378 	 a constant and not a section offset.  */
14379       if (attr->form_is_constant ())
14380 	*offset = attr->constant_value (0);
14381       else if (attr->form_is_section_offset ())
14382 	dwarf2_complex_location_expr_complaint ();
14383       else if (attr->form_is_block ())
14384 	*offset = decode_locdesc (attr->as_block (), cu);
14385       else
14386 	dwarf2_complex_location_expr_complaint ();
14387 
14388       return 1;
14389     }
14390 
14391   return 0;
14392 }
14393 
14394 /* Look for DW_AT_data_member_location and store the results in FIELD.  */
14395 
14396 static void
14397 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14398 			     struct field *field)
14399 {
14400   struct attribute *attr;
14401 
14402   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14403   if (attr != NULL)
14404     {
14405       if (attr->form_is_constant ())
14406 	{
14407 	  LONGEST offset = attr->constant_value (0);
14408 	  SET_FIELD_BITPOS (*field, offset * bits_per_byte);
14409 	}
14410       else if (attr->form_is_section_offset ())
14411 	dwarf2_complex_location_expr_complaint ();
14412       else if (attr->form_is_block ())
14413 	{
14414 	  bool handled;
14415 	  CORE_ADDR offset = decode_locdesc (attr->as_block (), cu, &handled);
14416 	  if (handled)
14417 	    SET_FIELD_BITPOS (*field, offset * bits_per_byte);
14418 	  else
14419 	    {
14420 	      dwarf2_per_objfile *per_objfile = cu->per_objfile;
14421 	      struct objfile *objfile = per_objfile->objfile;
14422 	      struct dwarf2_locexpr_baton *dlbaton
14423 		= XOBNEW (&objfile->objfile_obstack,
14424 			  struct dwarf2_locexpr_baton);
14425 	      dlbaton->data = attr->as_block ()->data;
14426 	      dlbaton->size = attr->as_block ()->size;
14427 	      /* When using this baton, we want to compute the address
14428 		 of the field, not the value.  This is why
14429 		 is_reference is set to false here.  */
14430 	      dlbaton->is_reference = false;
14431 	      dlbaton->per_objfile = per_objfile;
14432 	      dlbaton->per_cu = cu->per_cu;
14433 
14434 	      SET_FIELD_DWARF_BLOCK (*field, dlbaton);
14435 	    }
14436 	}
14437       else
14438 	dwarf2_complex_location_expr_complaint ();
14439     }
14440 }
14441 
14442 /* Add an aggregate field to the field list.  */
14443 
14444 static void
14445 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14446 		  struct dwarf2_cu *cu)
14447 {
14448   struct objfile *objfile = cu->per_objfile->objfile;
14449   struct gdbarch *gdbarch = objfile->arch ();
14450   struct nextfield *new_field;
14451   struct attribute *attr;
14452   struct field *fp;
14453   const char *fieldname = "";
14454 
14455   if (die->tag == DW_TAG_inheritance)
14456     {
14457       fip->baseclasses.emplace_back ();
14458       new_field = &fip->baseclasses.back ();
14459     }
14460   else
14461     {
14462       fip->fields.emplace_back ();
14463       new_field = &fip->fields.back ();
14464     }
14465 
14466   new_field->offset = die->sect_off;
14467 
14468   new_field->accessibility = dwarf2_access_attribute (die, cu);
14469   if (new_field->accessibility != DW_ACCESS_public)
14470     fip->non_public_fields = true;
14471 
14472   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14473   if (attr != nullptr)
14474     new_field->virtuality = attr->as_virtuality ();
14475   else
14476     new_field->virtuality = DW_VIRTUALITY_none;
14477 
14478   fp = &new_field->field;
14479 
14480   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
14481     {
14482       /* Data member other than a C++ static data member.  */
14483 
14484       /* Get type of field.  */
14485       fp->set_type (die_type (die, cu));
14486 
14487       SET_FIELD_BITPOS (*fp, 0);
14488 
14489       /* Get bit size of field (zero if none).  */
14490       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
14491       if (attr != nullptr)
14492 	{
14493 	  FIELD_BITSIZE (*fp) = attr->constant_value (0);
14494 	}
14495       else
14496 	{
14497 	  FIELD_BITSIZE (*fp) = 0;
14498 	}
14499 
14500       /* Get bit offset of field.  */
14501       handle_data_member_location (die, cu, fp);
14502       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
14503       if (attr != nullptr && attr->form_is_constant ())
14504 	{
14505 	  if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
14506 	    {
14507 	      /* For big endian bits, the DW_AT_bit_offset gives the
14508 		 additional bit offset from the MSB of the containing
14509 		 anonymous object to the MSB of the field.  We don't
14510 		 have to do anything special since we don't need to
14511 		 know the size of the anonymous object.  */
14512 	      SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
14513 				      + attr->constant_value (0)));
14514 	    }
14515 	  else
14516 	    {
14517 	      /* For little endian bits, compute the bit offset to the
14518 		 MSB of the anonymous object, subtract off the number of
14519 		 bits from the MSB of the field to the MSB of the
14520 		 object, and then subtract off the number of bits of
14521 		 the field itself.  The result is the bit offset of
14522 		 the LSB of the field.  */
14523 	      int anonymous_size;
14524 	      int bit_offset = attr->constant_value (0);
14525 
14526 	      attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14527 	      if (attr != nullptr && attr->form_is_constant ())
14528 		{
14529 		  /* The size of the anonymous object containing
14530 		     the bit field is explicit, so use the
14531 		     indicated size (in bytes).  */
14532 		  anonymous_size = attr->constant_value (0);
14533 		}
14534 	      else
14535 		{
14536 		  /* The size of the anonymous object containing
14537 		     the bit field must be inferred from the type
14538 		     attribute of the data member containing the
14539 		     bit field.  */
14540 		  anonymous_size = TYPE_LENGTH (fp->type ());
14541 		}
14542 	      SET_FIELD_BITPOS (*fp,
14543 				(FIELD_BITPOS (*fp)
14544 				 + anonymous_size * bits_per_byte
14545 				 - bit_offset - FIELD_BITSIZE (*fp)));
14546 	    }
14547 	}
14548       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
14549       if (attr != NULL)
14550 	SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
14551 				+ attr->constant_value (0)));
14552 
14553       /* Get name of field.  */
14554       fieldname = dwarf2_name (die, cu);
14555       if (fieldname == NULL)
14556 	fieldname = "";
14557 
14558       /* The name is already allocated along with this objfile, so we don't
14559 	 need to duplicate it for the type.  */
14560       fp->name = fieldname;
14561 
14562       /* Change accessibility for artificial fields (e.g. virtual table
14563 	 pointer or virtual base class pointer) to private.  */
14564       if (dwarf2_attr (die, DW_AT_artificial, cu))
14565 	{
14566 	  FIELD_ARTIFICIAL (*fp) = 1;
14567 	  new_field->accessibility = DW_ACCESS_private;
14568 	  fip->non_public_fields = true;
14569 	}
14570     }
14571   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
14572     {
14573       /* C++ static member.  */
14574 
14575       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
14576 	 is a declaration, but all versions of G++ as of this writing
14577 	 (so through at least 3.2.1) incorrectly generate
14578 	 DW_TAG_variable tags.  */
14579 
14580       const char *physname;
14581 
14582       /* Get name of field.  */
14583       fieldname = dwarf2_name (die, cu);
14584       if (fieldname == NULL)
14585 	return;
14586 
14587       attr = dwarf2_attr (die, DW_AT_const_value, cu);
14588       if (attr
14589 	  /* Only create a symbol if this is an external value.
14590 	     new_symbol checks this and puts the value in the global symbol
14591 	     table, which we want.  If it is not external, new_symbol
14592 	     will try to put the value in cu->list_in_scope which is wrong.  */
14593 	  && dwarf2_flag_true_p (die, DW_AT_external, cu))
14594 	{
14595 	  /* A static const member, not much different than an enum as far as
14596 	     we're concerned, except that we can support more types.  */
14597 	  new_symbol (die, NULL, cu);
14598 	}
14599 
14600       /* Get physical name.  */
14601       physname = dwarf2_physname (fieldname, die, cu);
14602 
14603       /* The name is already allocated along with this objfile, so we don't
14604 	 need to duplicate it for the type.  */
14605       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
14606       fp->set_type (die_type (die, cu));
14607       FIELD_NAME (*fp) = fieldname;
14608     }
14609   else if (die->tag == DW_TAG_inheritance)
14610     {
14611       /* C++ base class field.  */
14612       handle_data_member_location (die, cu, fp);
14613       FIELD_BITSIZE (*fp) = 0;
14614       fp->set_type (die_type (die, cu));
14615       FIELD_NAME (*fp) = fp->type ()->name ();
14616     }
14617   else
14618     gdb_assert_not_reached ("missing case in dwarf2_add_field");
14619 }
14620 
14621 /* Can the type given by DIE define another type?  */
14622 
14623 static bool
14624 type_can_define_types (const struct die_info *die)
14625 {
14626   switch (die->tag)
14627     {
14628     case DW_TAG_typedef:
14629     case DW_TAG_class_type:
14630     case DW_TAG_structure_type:
14631     case DW_TAG_union_type:
14632     case DW_TAG_enumeration_type:
14633       return true;
14634 
14635     default:
14636       return false;
14637     }
14638 }
14639 
14640 /* Add a type definition defined in the scope of the FIP's class.  */
14641 
14642 static void
14643 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
14644 		      struct dwarf2_cu *cu)
14645 {
14646   struct decl_field fp;
14647   memset (&fp, 0, sizeof (fp));
14648 
14649   gdb_assert (type_can_define_types (die));
14650 
14651   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
14652   fp.name = dwarf2_name (die, cu);
14653   fp.type = read_type_die (die, cu);
14654 
14655   /* Save accessibility.  */
14656   dwarf_access_attribute accessibility = dwarf2_access_attribute (die, cu);
14657   switch (accessibility)
14658     {
14659     case DW_ACCESS_public:
14660       /* The assumed value if neither private nor protected.  */
14661       break;
14662     case DW_ACCESS_private:
14663       fp.is_private = 1;
14664       break;
14665     case DW_ACCESS_protected:
14666       fp.is_protected = 1;
14667       break;
14668     }
14669 
14670   if (die->tag == DW_TAG_typedef)
14671     fip->typedef_field_list.push_back (fp);
14672   else
14673     fip->nested_types_list.push_back (fp);
14674 }
14675 
14676 /* A convenience typedef that's used when finding the discriminant
14677    field for a variant part.  */
14678 typedef std::unordered_map<sect_offset, int, gdb::hash_enum<sect_offset>>
14679   offset_map_type;
14680 
14681 /* Compute the discriminant range for a given variant.  OBSTACK is
14682    where the results will be stored.  VARIANT is the variant to
14683    process.  IS_UNSIGNED indicates whether the discriminant is signed
14684    or unsigned.  */
14685 
14686 static const gdb::array_view<discriminant_range>
14687 convert_variant_range (struct obstack *obstack, const variant_field &variant,
14688 		       bool is_unsigned)
14689 {
14690   std::vector<discriminant_range> ranges;
14691 
14692   if (variant.default_branch)
14693     return {};
14694 
14695   if (variant.discr_list_data == nullptr)
14696     {
14697       discriminant_range r
14698 	= {variant.discriminant_value, variant.discriminant_value};
14699       ranges.push_back (r);
14700     }
14701   else
14702     {
14703       gdb::array_view<const gdb_byte> data (variant.discr_list_data->data,
14704 					    variant.discr_list_data->size);
14705       while (!data.empty ())
14706 	{
14707 	  if (data[0] != DW_DSC_range && data[0] != DW_DSC_label)
14708 	    {
14709 	      complaint (_("invalid discriminant marker: %d"), data[0]);
14710 	      break;
14711 	    }
14712 	  bool is_range = data[0] == DW_DSC_range;
14713 	  data = data.slice (1);
14714 
14715 	  ULONGEST low, high;
14716 	  unsigned int bytes_read;
14717 
14718 	  if (data.empty ())
14719 	    {
14720 	      complaint (_("DW_AT_discr_list missing low value"));
14721 	      break;
14722 	    }
14723 	  if (is_unsigned)
14724 	    low = read_unsigned_leb128 (nullptr, data.data (), &bytes_read);
14725 	  else
14726 	    low = (ULONGEST) read_signed_leb128 (nullptr, data.data (),
14727 						 &bytes_read);
14728 	  data = data.slice (bytes_read);
14729 
14730 	  if (is_range)
14731 	    {
14732 	      if (data.empty ())
14733 		{
14734 		  complaint (_("DW_AT_discr_list missing high value"));
14735 		  break;
14736 		}
14737 	      if (is_unsigned)
14738 		high = read_unsigned_leb128 (nullptr, data.data (),
14739 					     &bytes_read);
14740 	      else
14741 		high = (LONGEST) read_signed_leb128 (nullptr, data.data (),
14742 						     &bytes_read);
14743 	      data = data.slice (bytes_read);
14744 	    }
14745 	  else
14746 	    high = low;
14747 
14748 	  ranges.push_back ({ low, high });
14749 	}
14750     }
14751 
14752   discriminant_range *result = XOBNEWVEC (obstack, discriminant_range,
14753 					  ranges.size ());
14754   std::copy (ranges.begin (), ranges.end (), result);
14755   return gdb::array_view<discriminant_range> (result, ranges.size ());
14756 }
14757 
14758 static const gdb::array_view<variant_part> create_variant_parts
14759   (struct obstack *obstack,
14760    const offset_map_type &offset_map,
14761    struct field_info *fi,
14762    const std::vector<variant_part_builder> &variant_parts);
14763 
14764 /* Fill in a "struct variant" for a given variant field.  RESULT is
14765    the variant to fill in.  OBSTACK is where any needed allocations
14766    will be done.  OFFSET_MAP holds the mapping from section offsets to
14767    fields for the type.  FI describes the fields of the type we're
14768    processing.  FIELD is the variant field we're converting.  */
14769 
14770 static void
14771 create_one_variant (variant &result, struct obstack *obstack,
14772 		    const offset_map_type &offset_map,
14773 		    struct field_info *fi, const variant_field &field)
14774 {
14775   result.discriminants = convert_variant_range (obstack, field, false);
14776   result.first_field = field.first_field + fi->baseclasses.size ();
14777   result.last_field = field.last_field + fi->baseclasses.size ();
14778   result.parts = create_variant_parts (obstack, offset_map, fi,
14779 				       field.variant_parts);
14780 }
14781 
14782 /* Fill in a "struct variant_part" for a given variant part.  RESULT
14783    is the variant part to fill in.  OBSTACK is where any needed
14784    allocations will be done.  OFFSET_MAP holds the mapping from
14785    section offsets to fields for the type.  FI describes the fields of
14786    the type we're processing.  BUILDER is the variant part to be
14787    converted.  */
14788 
14789 static void
14790 create_one_variant_part (variant_part &result,
14791 			 struct obstack *obstack,
14792 			 const offset_map_type &offset_map,
14793 			 struct field_info *fi,
14794 			 const variant_part_builder &builder)
14795 {
14796   auto iter = offset_map.find (builder.discriminant_offset);
14797   if (iter == offset_map.end ())
14798     {
14799       result.discriminant_index = -1;
14800       /* Doesn't matter.  */
14801       result.is_unsigned = false;
14802     }
14803   else
14804     {
14805       result.discriminant_index = iter->second;
14806       result.is_unsigned
14807 	= fi->fields[result.discriminant_index].field.type ()->is_unsigned ();
14808     }
14809 
14810   size_t n = builder.variants.size ();
14811   variant *output = new (obstack) variant[n];
14812   for (size_t i = 0; i < n; ++i)
14813     create_one_variant (output[i], obstack, offset_map, fi,
14814 			builder.variants[i]);
14815 
14816   result.variants = gdb::array_view<variant> (output, n);
14817 }
14818 
14819 /* Create a vector of variant parts that can be attached to a type.
14820    OBSTACK is where any needed allocations will be done.  OFFSET_MAP
14821    holds the mapping from section offsets to fields for the type.  FI
14822    describes the fields of the type we're processing.  VARIANT_PARTS
14823    is the vector to convert.  */
14824 
14825 static const gdb::array_view<variant_part>
14826 create_variant_parts (struct obstack *obstack,
14827 		      const offset_map_type &offset_map,
14828 		      struct field_info *fi,
14829 		      const std::vector<variant_part_builder> &variant_parts)
14830 {
14831   if (variant_parts.empty ())
14832     return {};
14833 
14834   size_t n = variant_parts.size ();
14835   variant_part *result = new (obstack) variant_part[n];
14836   for (size_t i = 0; i < n; ++i)
14837     create_one_variant_part (result[i], obstack, offset_map, fi,
14838 			     variant_parts[i]);
14839 
14840   return gdb::array_view<variant_part> (result, n);
14841 }
14842 
14843 /* Compute the variant part vector for FIP, attaching it to TYPE when
14844    done.  */
14845 
14846 static void
14847 add_variant_property (struct field_info *fip, struct type *type,
14848 		      struct dwarf2_cu *cu)
14849 {
14850   /* Map section offsets of fields to their field index.  Note the
14851      field index here does not take the number of baseclasses into
14852      account.  */
14853   offset_map_type offset_map;
14854   for (int i = 0; i < fip->fields.size (); ++i)
14855     offset_map[fip->fields[i].offset] = i;
14856 
14857   struct objfile *objfile = cu->per_objfile->objfile;
14858   gdb::array_view<variant_part> parts
14859     = create_variant_parts (&objfile->objfile_obstack, offset_map, fip,
14860 			    fip->variant_parts);
14861 
14862   struct dynamic_prop prop;
14863   prop.set_variant_parts ((gdb::array_view<variant_part> *)
14864 			  obstack_copy (&objfile->objfile_obstack, &parts,
14865 					sizeof (parts)));
14866 
14867   type->add_dyn_prop (DYN_PROP_VARIANT_PARTS, prop);
14868 }
14869 
14870 /* Create the vector of fields, and attach it to the type.  */
14871 
14872 static void
14873 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
14874 			      struct dwarf2_cu *cu)
14875 {
14876   int nfields = fip->nfields ();
14877 
14878   /* Record the field count, allocate space for the array of fields,
14879      and create blank accessibility bitfields if necessary.  */
14880   type->set_num_fields (nfields);
14881   type->set_fields
14882     ((struct field *) TYPE_ZALLOC (type, sizeof (struct field) * nfields));
14883 
14884   if (fip->non_public_fields && cu->per_cu->lang != language_ada)
14885     {
14886       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14887 
14888       TYPE_FIELD_PRIVATE_BITS (type) =
14889 	(B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14890       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
14891 
14892       TYPE_FIELD_PROTECTED_BITS (type) =
14893 	(B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14894       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
14895 
14896       TYPE_FIELD_IGNORE_BITS (type) =
14897 	(B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14898       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
14899     }
14900 
14901   /* If the type has baseclasses, allocate and clear a bit vector for
14902      TYPE_FIELD_VIRTUAL_BITS.  */
14903   if (!fip->baseclasses.empty () && cu->per_cu->lang != language_ada)
14904     {
14905       int num_bytes = B_BYTES (fip->baseclasses.size ());
14906       unsigned char *pointer;
14907 
14908       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14909       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
14910       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
14911       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
14912       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
14913     }
14914 
14915   if (!fip->variant_parts.empty ())
14916     add_variant_property (fip, type, cu);
14917 
14918   /* Copy the saved-up fields into the field vector.  */
14919   for (int i = 0; i < nfields; ++i)
14920     {
14921       struct nextfield &field
14922 	= ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
14923 	   : fip->fields[i - fip->baseclasses.size ()]);
14924 
14925       type->field (i) = field.field;
14926       switch (field.accessibility)
14927 	{
14928 	case DW_ACCESS_private:
14929 	  if (cu->per_cu->lang != language_ada)
14930 	    SET_TYPE_FIELD_PRIVATE (type, i);
14931 	  break;
14932 
14933 	case DW_ACCESS_protected:
14934 	  if (cu->per_cu->lang != language_ada)
14935 	    SET_TYPE_FIELD_PROTECTED (type, i);
14936 	  break;
14937 
14938 	case DW_ACCESS_public:
14939 	  break;
14940 
14941 	default:
14942 	  /* Unknown accessibility.  Complain and treat it as public.  */
14943 	  {
14944 	    complaint (_("unsupported accessibility %d"),
14945 		       field.accessibility);
14946 	  }
14947 	  break;
14948 	}
14949       if (i < fip->baseclasses.size ())
14950 	{
14951 	  switch (field.virtuality)
14952 	    {
14953 	    case DW_VIRTUALITY_virtual:
14954 	    case DW_VIRTUALITY_pure_virtual:
14955 	      if (cu->per_cu->lang == language_ada)
14956 		error (_("unexpected virtuality in component of Ada type"));
14957 	      SET_TYPE_FIELD_VIRTUAL (type, i);
14958 	      break;
14959 	    }
14960 	}
14961     }
14962 }
14963 
14964 /* Return true if this member function is a constructor, false
14965    otherwise.  */
14966 
14967 static int
14968 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
14969 {
14970   const char *fieldname;
14971   const char *type_name;
14972   int len;
14973 
14974   if (die->parent == NULL)
14975     return 0;
14976 
14977   if (die->parent->tag != DW_TAG_structure_type
14978       && die->parent->tag != DW_TAG_union_type
14979       && die->parent->tag != DW_TAG_class_type)
14980     return 0;
14981 
14982   fieldname = dwarf2_name (die, cu);
14983   type_name = dwarf2_name (die->parent, cu);
14984   if (fieldname == NULL || type_name == NULL)
14985     return 0;
14986 
14987   len = strlen (fieldname);
14988   return (strncmp (fieldname, type_name, len) == 0
14989 	  && (type_name[len] == '\0' || type_name[len] == '<'));
14990 }
14991 
14992 /* Add a member function to the proper fieldlist.  */
14993 
14994 static void
14995 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
14996 		      struct type *type, struct dwarf2_cu *cu)
14997 {
14998   struct objfile *objfile = cu->per_objfile->objfile;
14999   struct attribute *attr;
15000   int i;
15001   struct fnfieldlist *flp = nullptr;
15002   struct fn_field *fnp;
15003   const char *fieldname;
15004   struct type *this_type;
15005 
15006   if (cu->per_cu->lang == language_ada)
15007     error (_("unexpected member function in Ada type"));
15008 
15009   /* Get name of member function.  */
15010   fieldname = dwarf2_name (die, cu);
15011   if (fieldname == NULL)
15012     return;
15013 
15014   /* Look up member function name in fieldlist.  */
15015   for (i = 0; i < fip->fnfieldlists.size (); i++)
15016     {
15017       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15018 	{
15019 	  flp = &fip->fnfieldlists[i];
15020 	  break;
15021 	}
15022     }
15023 
15024   /* Create a new fnfieldlist if necessary.  */
15025   if (flp == nullptr)
15026     {
15027       fip->fnfieldlists.emplace_back ();
15028       flp = &fip->fnfieldlists.back ();
15029       flp->name = fieldname;
15030       i = fip->fnfieldlists.size () - 1;
15031     }
15032 
15033   /* Create a new member function field and add it to the vector of
15034      fnfieldlists.  */
15035   flp->fnfields.emplace_back ();
15036   fnp = &flp->fnfields.back ();
15037 
15038   /* Delay processing of the physname until later.  */
15039   if (cu->per_cu->lang == language_cplus)
15040     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15041 			die, cu);
15042   else
15043     {
15044       const char *physname = dwarf2_physname (fieldname, die, cu);
15045       fnp->physname = physname ? physname : "";
15046     }
15047 
15048   fnp->type = alloc_type (objfile);
15049   this_type = read_type_die (die, cu);
15050   if (this_type && this_type->code () == TYPE_CODE_FUNC)
15051     {
15052       int nparams = this_type->num_fields ();
15053 
15054       /* TYPE is the domain of this method, and THIS_TYPE is the type
15055 	   of the method itself (TYPE_CODE_METHOD).  */
15056       smash_to_method_type (fnp->type, type,
15057 			    TYPE_TARGET_TYPE (this_type),
15058 			    this_type->fields (),
15059 			    this_type->num_fields (),
15060 			    this_type->has_varargs ());
15061 
15062       /* Handle static member functions.
15063 	 Dwarf2 has no clean way to discern C++ static and non-static
15064 	 member functions.  G++ helps GDB by marking the first
15065 	 parameter for non-static member functions (which is the this
15066 	 pointer) as artificial.  We obtain this information from
15067 	 read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15068       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15069 	fnp->voffset = VOFFSET_STATIC;
15070     }
15071   else
15072     complaint (_("member function type missing for '%s'"),
15073 	       dwarf2_full_name (fieldname, die, cu));
15074 
15075   /* Get fcontext from DW_AT_containing_type if present.  */
15076   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15077     fnp->fcontext = die_containing_type (die, cu);
15078 
15079   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15080      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15081 
15082   /* Get accessibility.  */
15083   dwarf_access_attribute accessibility = dwarf2_access_attribute (die, cu);
15084   switch (accessibility)
15085     {
15086     case DW_ACCESS_private:
15087       fnp->is_private = 1;
15088       break;
15089     case DW_ACCESS_protected:
15090       fnp->is_protected = 1;
15091       break;
15092     }
15093 
15094   /* Check for artificial methods.  */
15095   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15096   if (attr && attr->as_boolean ())
15097     fnp->is_artificial = 1;
15098 
15099   /* Check for defaulted methods.  */
15100   attr = dwarf2_attr (die, DW_AT_defaulted, cu);
15101   if (attr != nullptr)
15102     fnp->defaulted = attr->defaulted ();
15103 
15104   /* Check for deleted methods.  */
15105   attr = dwarf2_attr (die, DW_AT_deleted, cu);
15106   if (attr != nullptr && attr->as_boolean ())
15107     fnp->is_deleted = 1;
15108 
15109   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15110 
15111   /* Get index in virtual function table if it is a virtual member
15112      function.  For older versions of GCC, this is an offset in the
15113      appropriate virtual table, as specified by DW_AT_containing_type.
15114      For everyone else, it is an expression to be evaluated relative
15115      to the object address.  */
15116 
15117   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15118   if (attr != nullptr)
15119     {
15120       if (attr->form_is_block () && attr->as_block ()->size > 0)
15121 	{
15122 	  struct dwarf_block *block = attr->as_block ();
15123 
15124 	  if (block->data[0] == DW_OP_constu)
15125 	    {
15126 	      /* Old-style GCC.  */
15127 	      fnp->voffset = decode_locdesc (block, cu) + 2;
15128 	    }
15129 	  else if (block->data[0] == DW_OP_deref
15130 		   || (block->size > 1
15131 		       && block->data[0] == DW_OP_deref_size
15132 		       && block->data[1] == cu->header.addr_size))
15133 	    {
15134 	      fnp->voffset = decode_locdesc (block, cu);
15135 	      if ((fnp->voffset % cu->header.addr_size) != 0)
15136 		dwarf2_complex_location_expr_complaint ();
15137 	      else
15138 		fnp->voffset /= cu->header.addr_size;
15139 	      fnp->voffset += 2;
15140 	    }
15141 	  else
15142 	    dwarf2_complex_location_expr_complaint ();
15143 
15144 	  if (!fnp->fcontext)
15145 	    {
15146 	      /* If there is no `this' field and no DW_AT_containing_type,
15147 		 we cannot actually find a base class context for the
15148 		 vtable!  */
15149 	      if (this_type->num_fields () == 0
15150 		  || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15151 		{
15152 		  complaint (_("cannot determine context for virtual member "
15153 			       "function \"%s\" (offset %s)"),
15154 			     fieldname, sect_offset_str (die->sect_off));
15155 		}
15156 	      else
15157 		{
15158 		  fnp->fcontext
15159 		    = TYPE_TARGET_TYPE (this_type->field (0).type ());
15160 		}
15161 	    }
15162 	}
15163       else if (attr->form_is_section_offset ())
15164 	{
15165 	  dwarf2_complex_location_expr_complaint ();
15166 	}
15167       else
15168 	{
15169 	  dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15170 						 fieldname);
15171 	}
15172     }
15173   else
15174     {
15175       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15176       if (attr != nullptr && attr->as_virtuality () != DW_VIRTUALITY_none)
15177 	{
15178 	  /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15179 	  complaint (_("Member function \"%s\" (offset %s) is virtual "
15180 		       "but the vtable offset is not specified"),
15181 		     fieldname, sect_offset_str (die->sect_off));
15182 	  ALLOCATE_CPLUS_STRUCT_TYPE (type);
15183 	  TYPE_CPLUS_DYNAMIC (type) = 1;
15184 	}
15185     }
15186 }
15187 
15188 /* Create the vector of member function fields, and attach it to the type.  */
15189 
15190 static void
15191 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15192 				 struct dwarf2_cu *cu)
15193 {
15194   if (cu->per_cu->lang == language_ada)
15195     error (_("unexpected member functions in Ada type"));
15196 
15197   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15198   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15199     TYPE_ALLOC (type,
15200 		sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15201 
15202   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15203     {
15204       struct fnfieldlist &nf = fip->fnfieldlists[i];
15205       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15206 
15207       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15208       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15209       fn_flp->fn_fields = (struct fn_field *)
15210 	TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15211 
15212       for (int k = 0; k < nf.fnfields.size (); ++k)
15213 	fn_flp->fn_fields[k] = nf.fnfields[k];
15214     }
15215 
15216   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15217 }
15218 
15219 /* Returns non-zero if NAME is the name of a vtable member in CU's
15220    language, zero otherwise.  */
15221 static int
15222 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15223 {
15224   static const char vptr[] = "_vptr";
15225 
15226   /* Look for the C++ form of the vtable.  */
15227   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15228     return 1;
15229 
15230   return 0;
15231 }
15232 
15233 /* GCC outputs unnamed structures that are really pointers to member
15234    functions, with the ABI-specified layout.  If TYPE describes
15235    such a structure, smash it into a member function type.
15236 
15237    GCC shouldn't do this; it should just output pointer to member DIEs.
15238    This is GCC PR debug/28767.  */
15239 
15240 static void
15241 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15242 {
15243   struct type *pfn_type, *self_type, *new_type;
15244 
15245   /* Check for a structure with no name and two children.  */
15246   if (type->code () != TYPE_CODE_STRUCT || type->num_fields () != 2)
15247     return;
15248 
15249   /* Check for __pfn and __delta members.  */
15250   if (TYPE_FIELD_NAME (type, 0) == NULL
15251       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15252       || TYPE_FIELD_NAME (type, 1) == NULL
15253       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15254     return;
15255 
15256   /* Find the type of the method.  */
15257   pfn_type = type->field (0).type ();
15258   if (pfn_type == NULL
15259       || pfn_type->code () != TYPE_CODE_PTR
15260       || TYPE_TARGET_TYPE (pfn_type)->code () != TYPE_CODE_FUNC)
15261     return;
15262 
15263   /* Look for the "this" argument.  */
15264   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15265   if (pfn_type->num_fields () == 0
15266       /* || pfn_type->field (0).type () == NULL */
15267       || pfn_type->field (0).type ()->code () != TYPE_CODE_PTR)
15268     return;
15269 
15270   self_type = TYPE_TARGET_TYPE (pfn_type->field (0).type ());
15271   new_type = alloc_type (objfile);
15272   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15273 			pfn_type->fields (), pfn_type->num_fields (),
15274 			pfn_type->has_varargs ());
15275   smash_to_methodptr_type (type, new_type);
15276 }
15277 
15278 /* Helper for quirk_ada_thick_pointer.  If TYPE is an array type that
15279    requires rewriting, then copy it and return the updated copy.
15280    Otherwise return nullptr.  */
15281 
15282 static struct type *
15283 rewrite_array_type (struct type *type)
15284 {
15285   if (type->code () != TYPE_CODE_ARRAY)
15286     return nullptr;
15287 
15288   struct type *index_type = type->index_type ();
15289   range_bounds *current_bounds = index_type->bounds ();
15290 
15291   /* Handle multi-dimensional arrays.  */
15292   struct type *new_target = rewrite_array_type (TYPE_TARGET_TYPE (type));
15293   if (new_target == nullptr)
15294     {
15295       /* Maybe we don't need to rewrite this array.  */
15296       if (current_bounds->low.kind () == PROP_CONST
15297 	  && current_bounds->high.kind () == PROP_CONST)
15298 	return nullptr;
15299     }
15300 
15301   /* Either the target type was rewritten, or the bounds have to be
15302      updated.  Either way we want to copy the type and update
15303      everything.  */
15304   struct type *copy = copy_type (type);
15305   int nfields = copy->num_fields ();
15306   field *new_fields
15307     = ((struct field *) TYPE_ZALLOC (copy,
15308 				     nfields * sizeof (struct field)));
15309   memcpy (new_fields, copy->fields (), nfields * sizeof (struct field));
15310   copy->set_fields (new_fields);
15311   if (new_target != nullptr)
15312     TYPE_TARGET_TYPE (copy) = new_target;
15313 
15314   struct type *index_copy = copy_type (index_type);
15315   range_bounds *bounds
15316     = (struct range_bounds *) TYPE_ZALLOC (index_copy,
15317 					   sizeof (range_bounds));
15318   *bounds = *current_bounds;
15319   bounds->low.set_const_val (1);
15320   bounds->high.set_const_val (0);
15321   index_copy->set_bounds (bounds);
15322   copy->set_index_type (index_copy);
15323 
15324   return copy;
15325 }
15326 
15327 /* While some versions of GCC will generate complicated DWARF for an
15328    array (see quirk_ada_thick_pointer), more recent versions were
15329    modified to emit an explicit thick pointer structure.  However, in
15330    this case, the array still has DWARF expressions for its ranges,
15331    and these must be ignored.  */
15332 
15333 static void
15334 quirk_ada_thick_pointer_struct (struct die_info *die, struct dwarf2_cu *cu,
15335 				struct type *type)
15336 {
15337   gdb_assert (cu->per_cu->lang == language_ada);
15338 
15339   /* Check for a structure with two children.  */
15340   if (type->code () != TYPE_CODE_STRUCT || type->num_fields () != 2)
15341     return;
15342 
15343   /* Check for P_ARRAY and P_BOUNDS members.  */
15344   if (TYPE_FIELD_NAME (type, 0) == NULL
15345       || strcmp (TYPE_FIELD_NAME (type, 0), "P_ARRAY") != 0
15346       || TYPE_FIELD_NAME (type, 1) == NULL
15347       || strcmp (TYPE_FIELD_NAME (type, 1), "P_BOUNDS") != 0)
15348     return;
15349 
15350   /* Make sure we're looking at a pointer to an array.  */
15351   if (type->field (0).type ()->code () != TYPE_CODE_PTR)
15352     return;
15353 
15354   /* The Ada code already knows how to handle these types, so all that
15355      we need to do is turn the bounds into static bounds.  However, we
15356      don't want to rewrite existing array or index types in-place,
15357      because those may be referenced in other contexts where this
15358      rewriting is undesirable.  */
15359   struct type *new_ary_type
15360     = rewrite_array_type (TYPE_TARGET_TYPE (type->field (0).type ()));
15361   if (new_ary_type != nullptr)
15362     type->field (0).set_type (lookup_pointer_type (new_ary_type));
15363 }
15364 
15365 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15366    appropriate error checking and issuing complaints if there is a
15367    problem.  */
15368 
15369 static ULONGEST
15370 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15371 {
15372   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15373 
15374   if (attr == nullptr)
15375     return 0;
15376 
15377   if (!attr->form_is_constant ())
15378     {
15379       complaint (_("DW_AT_alignment must have constant form"
15380 		   " - DIE at %s [in module %s]"),
15381 		 sect_offset_str (die->sect_off),
15382 		 objfile_name (cu->per_objfile->objfile));
15383       return 0;
15384     }
15385 
15386   LONGEST val = attr->constant_value (0);
15387   if (val < 0)
15388     {
15389       complaint (_("DW_AT_alignment value must not be negative"
15390 		   " - DIE at %s [in module %s]"),
15391 		 sect_offset_str (die->sect_off),
15392 		 objfile_name (cu->per_objfile->objfile));
15393       return 0;
15394     }
15395   ULONGEST align = val;
15396 
15397   if (align == 0)
15398     {
15399       complaint (_("DW_AT_alignment value must not be zero"
15400 		   " - DIE at %s [in module %s]"),
15401 		 sect_offset_str (die->sect_off),
15402 		 objfile_name (cu->per_objfile->objfile));
15403       return 0;
15404     }
15405   if ((align & (align - 1)) != 0)
15406     {
15407       complaint (_("DW_AT_alignment value must be a power of 2"
15408 		   " - DIE at %s [in module %s]"),
15409 		 sect_offset_str (die->sect_off),
15410 		 objfile_name (cu->per_objfile->objfile));
15411       return 0;
15412     }
15413 
15414   return align;
15415 }
15416 
15417 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15418    the alignment for TYPE.  */
15419 
15420 static void
15421 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15422 		     struct type *type)
15423 {
15424   if (!set_type_align (type, get_alignment (cu, die)))
15425     complaint (_("DW_AT_alignment value too large"
15426 		 " - DIE at %s [in module %s]"),
15427 	       sect_offset_str (die->sect_off),
15428 	       objfile_name (cu->per_objfile->objfile));
15429 }
15430 
15431 /* Check if the given VALUE is a valid enum dwarf_calling_convention
15432    constant for a type, according to DWARF5 spec, Table 5.5.  */
15433 
15434 static bool
15435 is_valid_DW_AT_calling_convention_for_type (ULONGEST value)
15436 {
15437   switch (value)
15438     {
15439     case DW_CC_normal:
15440     case DW_CC_pass_by_reference:
15441     case DW_CC_pass_by_value:
15442       return true;
15443 
15444     default:
15445       complaint (_("unrecognized DW_AT_calling_convention value "
15446 		   "(%s) for a type"), pulongest (value));
15447       return false;
15448     }
15449 }
15450 
15451 /* Check if the given VALUE is a valid enum dwarf_calling_convention
15452    constant for a subroutine, according to DWARF5 spec, Table 3.3, and
15453    also according to GNU-specific values (see include/dwarf2.h).  */
15454 
15455 static bool
15456 is_valid_DW_AT_calling_convention_for_subroutine (ULONGEST value)
15457 {
15458   switch (value)
15459     {
15460     case DW_CC_normal:
15461     case DW_CC_program:
15462     case DW_CC_nocall:
15463       return true;
15464 
15465     case DW_CC_GNU_renesas_sh:
15466     case DW_CC_GNU_borland_fastcall_i386:
15467     case DW_CC_GDB_IBM_OpenCL:
15468       return true;
15469 
15470     default:
15471       complaint (_("unrecognized DW_AT_calling_convention value "
15472 		   "(%s) for a subroutine"), pulongest (value));
15473       return false;
15474     }
15475 }
15476 
15477 /* Called when we find the DIE that starts a structure or union scope
15478    (definition) to create a type for the structure or union.  Fill in
15479    the type's name and general properties; the members will not be
15480    processed until process_structure_scope.  A symbol table entry for
15481    the type will also not be done until process_structure_scope (assuming
15482    the type has a name).
15483 
15484    NOTE: we need to call these functions regardless of whether or not the
15485    DIE has a DW_AT_name attribute, since it might be an anonymous
15486    structure or union.  This gets the type entered into our set of
15487    user defined types.  */
15488 
15489 static struct type *
15490 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15491 {
15492   struct objfile *objfile = cu->per_objfile->objfile;
15493   struct type *type;
15494   struct attribute *attr;
15495   const char *name;
15496 
15497   /* If the definition of this type lives in .debug_types, read that type.
15498      Don't follow DW_AT_specification though, that will take us back up
15499      the chain and we want to go down.  */
15500   attr = die->attr (DW_AT_signature);
15501   if (attr != nullptr)
15502     {
15503       type = get_DW_AT_signature_type (die, attr, cu);
15504 
15505       /* The type's CU may not be the same as CU.
15506 	 Ensure TYPE is recorded with CU in die_type_hash.  */
15507       return set_die_type (die, type, cu);
15508     }
15509 
15510   type = alloc_type (objfile);
15511   INIT_CPLUS_SPECIFIC (type);
15512 
15513   name = dwarf2_name (die, cu);
15514   if (name != NULL)
15515     {
15516       if (cu->per_cu->lang == language_cplus
15517 	  || cu->per_cu->lang == language_d
15518 	  || cu->per_cu->lang == language_rust)
15519 	{
15520 	  const char *full_name = dwarf2_full_name (name, die, cu);
15521 
15522 	  /* dwarf2_full_name might have already finished building the DIE's
15523 	     type.  If so, there is no need to continue.  */
15524 	  if (get_die_type (die, cu) != NULL)
15525 	    return get_die_type (die, cu);
15526 
15527 	  type->set_name (full_name);
15528 	}
15529       else
15530 	{
15531 	  /* The name is already allocated along with this objfile, so
15532 	     we don't need to duplicate it for the type.  */
15533 	  type->set_name (name);
15534 	}
15535     }
15536 
15537   if (die->tag == DW_TAG_structure_type)
15538     {
15539       type->set_code (TYPE_CODE_STRUCT);
15540     }
15541   else if (die->tag == DW_TAG_union_type)
15542     {
15543       type->set_code (TYPE_CODE_UNION);
15544     }
15545   else
15546     {
15547       type->set_code (TYPE_CODE_STRUCT);
15548     }
15549 
15550   if (cu->per_cu->lang == language_cplus && die->tag == DW_TAG_class_type)
15551     type->set_is_declared_class (true);
15552 
15553   /* Store the calling convention in the type if it's available in
15554      the die.  Otherwise the calling convention remains set to
15555      the default value DW_CC_normal.  */
15556   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
15557   if (attr != nullptr
15558       && is_valid_DW_AT_calling_convention_for_type (attr->constant_value (0)))
15559     {
15560       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15561       TYPE_CPLUS_CALLING_CONVENTION (type)
15562 	= (enum dwarf_calling_convention) (attr->constant_value (0));
15563     }
15564 
15565   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15566   if (attr != nullptr)
15567     {
15568       if (attr->form_is_constant ())
15569 	TYPE_LENGTH (type) = attr->constant_value (0);
15570       else
15571 	{
15572 	  struct dynamic_prop prop;
15573 	  if (attr_to_dynamic_prop (attr, die, cu, &prop, cu->addr_type ()))
15574 	    type->add_dyn_prop (DYN_PROP_BYTE_SIZE, prop);
15575 	  TYPE_LENGTH (type) = 0;
15576 	}
15577     }
15578   else
15579     {
15580       TYPE_LENGTH (type) = 0;
15581     }
15582 
15583   maybe_set_alignment (cu, die, type);
15584 
15585   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15586     {
15587       /* ICC<14 does not output the required DW_AT_declaration on
15588 	 incomplete types, but gives them a size of zero.  */
15589       type->set_is_stub (true);
15590     }
15591   else
15592     type->set_stub_is_supported (true);
15593 
15594   if (die_is_declaration (die, cu))
15595     type->set_is_stub (true);
15596   else if (attr == NULL && die->child == NULL
15597 	   && producer_is_realview (cu->producer))
15598     /* RealView does not output the required DW_AT_declaration
15599        on incomplete types.  */
15600     type->set_is_stub (true);
15601 
15602   /* We need to add the type field to the die immediately so we don't
15603      infinitely recurse when dealing with pointers to the structure
15604      type within the structure itself.  */
15605   set_die_type (die, type, cu);
15606 
15607   /* set_die_type should be already done.  */
15608   set_descriptive_type (type, die, cu);
15609 
15610   return type;
15611 }
15612 
15613 static void handle_struct_member_die
15614   (struct die_info *child_die,
15615    struct type *type,
15616    struct field_info *fi,
15617    std::vector<struct symbol *> *template_args,
15618    struct dwarf2_cu *cu);
15619 
15620 /* A helper for handle_struct_member_die that handles
15621    DW_TAG_variant_part.  */
15622 
15623 static void
15624 handle_variant_part (struct die_info *die, struct type *type,
15625 		     struct field_info *fi,
15626 		     std::vector<struct symbol *> *template_args,
15627 		     struct dwarf2_cu *cu)
15628 {
15629   variant_part_builder *new_part;
15630   if (fi->current_variant_part == nullptr)
15631     {
15632       fi->variant_parts.emplace_back ();
15633       new_part = &fi->variant_parts.back ();
15634     }
15635   else if (!fi->current_variant_part->processing_variant)
15636     {
15637       complaint (_("nested DW_TAG_variant_part seen "
15638 		   "- DIE at %s [in module %s]"),
15639 		 sect_offset_str (die->sect_off),
15640 		 objfile_name (cu->per_objfile->objfile));
15641       return;
15642     }
15643   else
15644     {
15645       variant_field &current = fi->current_variant_part->variants.back ();
15646       current.variant_parts.emplace_back ();
15647       new_part = &current.variant_parts.back ();
15648     }
15649 
15650   /* When we recurse, we want callees to add to this new variant
15651      part.  */
15652   scoped_restore save_current_variant_part
15653     = make_scoped_restore (&fi->current_variant_part, new_part);
15654 
15655   struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15656   if (discr == NULL)
15657     {
15658       /* It's a univariant form, an extension we support.  */
15659     }
15660   else if (discr->form_is_ref ())
15661     {
15662       struct dwarf2_cu *target_cu = cu;
15663       struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15664 
15665       new_part->discriminant_offset = target_die->sect_off;
15666     }
15667   else
15668     {
15669       complaint (_("DW_AT_discr does not have DIE reference form"
15670 		   " - DIE at %s [in module %s]"),
15671 		 sect_offset_str (die->sect_off),
15672 		 objfile_name (cu->per_objfile->objfile));
15673     }
15674 
15675   for (die_info *child_die = die->child;
15676        child_die != NULL;
15677        child_die = child_die->sibling)
15678     handle_struct_member_die (child_die, type, fi, template_args, cu);
15679 }
15680 
15681 /* A helper for handle_struct_member_die that handles
15682    DW_TAG_variant.  */
15683 
15684 static void
15685 handle_variant (struct die_info *die, struct type *type,
15686 		struct field_info *fi,
15687 		std::vector<struct symbol *> *template_args,
15688 		struct dwarf2_cu *cu)
15689 {
15690   if (fi->current_variant_part == nullptr)
15691     {
15692       complaint (_("saw DW_TAG_variant outside DW_TAG_variant_part "
15693 		   "- DIE at %s [in module %s]"),
15694 		 sect_offset_str (die->sect_off),
15695 		 objfile_name (cu->per_objfile->objfile));
15696       return;
15697     }
15698   if (fi->current_variant_part->processing_variant)
15699     {
15700       complaint (_("nested DW_TAG_variant seen "
15701 		   "- DIE at %s [in module %s]"),
15702 		 sect_offset_str (die->sect_off),
15703 		 objfile_name (cu->per_objfile->objfile));
15704       return;
15705     }
15706 
15707   scoped_restore save_processing_variant
15708     = make_scoped_restore (&fi->current_variant_part->processing_variant,
15709 			   true);
15710 
15711   fi->current_variant_part->variants.emplace_back ();
15712   variant_field &variant = fi->current_variant_part->variants.back ();
15713   variant.first_field = fi->fields.size ();
15714 
15715   /* In a variant we want to get the discriminant and also add a
15716      field for our sole member child.  */
15717   struct attribute *discr = dwarf2_attr (die, DW_AT_discr_value, cu);
15718   if (discr == nullptr || !discr->form_is_constant ())
15719     {
15720       discr = dwarf2_attr (die, DW_AT_discr_list, cu);
15721       if (discr == nullptr || discr->as_block ()->size == 0)
15722 	variant.default_branch = true;
15723       else
15724 	variant.discr_list_data = discr->as_block ();
15725     }
15726   else
15727     variant.discriminant_value = discr->constant_value (0);
15728 
15729   for (die_info *variant_child = die->child;
15730        variant_child != NULL;
15731        variant_child = variant_child->sibling)
15732     handle_struct_member_die (variant_child, type, fi, template_args, cu);
15733 
15734   variant.last_field = fi->fields.size ();
15735 }
15736 
15737 /* A helper for process_structure_scope that handles a single member
15738    DIE.  */
15739 
15740 static void
15741 handle_struct_member_die (struct die_info *child_die, struct type *type,
15742 			  struct field_info *fi,
15743 			  std::vector<struct symbol *> *template_args,
15744 			  struct dwarf2_cu *cu)
15745 {
15746   if (child_die->tag == DW_TAG_member
15747       || child_die->tag == DW_TAG_variable)
15748     {
15749       /* NOTE: carlton/2002-11-05: A C++ static data member
15750 	 should be a DW_TAG_member that is a declaration, but
15751 	 all versions of G++ as of this writing (so through at
15752 	 least 3.2.1) incorrectly generate DW_TAG_variable
15753 	 tags for them instead.  */
15754       dwarf2_add_field (fi, child_die, cu);
15755     }
15756   else if (child_die->tag == DW_TAG_subprogram)
15757     {
15758       /* Rust doesn't have member functions in the C++ sense.
15759 	 However, it does emit ordinary functions as children
15760 	 of a struct DIE.  */
15761       if (cu->per_cu->lang == language_rust)
15762 	read_func_scope (child_die, cu);
15763       else
15764 	{
15765 	  /* C++ member function.  */
15766 	  dwarf2_add_member_fn (fi, child_die, type, cu);
15767 	}
15768     }
15769   else if (child_die->tag == DW_TAG_inheritance)
15770     {
15771       /* C++ base class field.  */
15772       dwarf2_add_field (fi, child_die, cu);
15773     }
15774   else if (type_can_define_types (child_die))
15775     dwarf2_add_type_defn (fi, child_die, cu);
15776   else if (child_die->tag == DW_TAG_template_type_param
15777 	   || child_die->tag == DW_TAG_template_value_param)
15778     {
15779       struct symbol *arg = new_symbol (child_die, NULL, cu);
15780 
15781       if (arg != NULL)
15782 	template_args->push_back (arg);
15783     }
15784   else if (child_die->tag == DW_TAG_variant_part)
15785     handle_variant_part (child_die, type, fi, template_args, cu);
15786   else if (child_die->tag == DW_TAG_variant)
15787     handle_variant (child_die, type, fi, template_args, cu);
15788 }
15789 
15790 /* Finish creating a structure or union type, including filling in
15791    its members and creating a symbol for it.  */
15792 
15793 static void
15794 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15795 {
15796   struct objfile *objfile = cu->per_objfile->objfile;
15797   struct die_info *child_die;
15798   struct type *type;
15799 
15800   type = get_die_type (die, cu);
15801   if (type == NULL)
15802     type = read_structure_type (die, cu);
15803 
15804   bool has_template_parameters = false;
15805   if (die->child != NULL && ! die_is_declaration (die, cu))
15806     {
15807       struct field_info fi;
15808       std::vector<struct symbol *> template_args;
15809 
15810       child_die = die->child;
15811 
15812       while (child_die && child_die->tag)
15813 	{
15814 	  handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15815 	  child_die = child_die->sibling;
15816 	}
15817 
15818       /* Attach template arguments to type.  */
15819       if (!template_args.empty ())
15820 	{
15821 	  has_template_parameters = true;
15822 	  ALLOCATE_CPLUS_STRUCT_TYPE (type);
15823 	  TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15824 	  TYPE_TEMPLATE_ARGUMENTS (type)
15825 	    = XOBNEWVEC (&objfile->objfile_obstack,
15826 			 struct symbol *,
15827 			 TYPE_N_TEMPLATE_ARGUMENTS (type));
15828 	  memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15829 		  template_args.data (),
15830 		  (TYPE_N_TEMPLATE_ARGUMENTS (type)
15831 		   * sizeof (struct symbol *)));
15832 	}
15833 
15834       /* Attach fields and member functions to the type.  */
15835       if (fi.nfields () > 0)
15836 	dwarf2_attach_fields_to_type (&fi, type, cu);
15837       if (!fi.fnfieldlists.empty ())
15838 	{
15839 	  dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15840 
15841 	  /* Get the type which refers to the base class (possibly this
15842 	     class itself) which contains the vtable pointer for the current
15843 	     class from the DW_AT_containing_type attribute.  This use of
15844 	     DW_AT_containing_type is a GNU extension.  */
15845 
15846 	  if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15847 	    {
15848 	      struct type *t = die_containing_type (die, cu);
15849 
15850 	      set_type_vptr_basetype (type, t);
15851 	      if (type == t)
15852 		{
15853 		  int i;
15854 
15855 		  /* Our own class provides vtbl ptr.  */
15856 		  for (i = t->num_fields () - 1;
15857 		       i >= TYPE_N_BASECLASSES (t);
15858 		       --i)
15859 		    {
15860 		      const char *fieldname = TYPE_FIELD_NAME (t, i);
15861 
15862 		      if (is_vtable_name (fieldname, cu))
15863 			{
15864 			  set_type_vptr_fieldno (type, i);
15865 			  break;
15866 			}
15867 		    }
15868 
15869 		  /* Complain if virtual function table field not found.  */
15870 		  if (i < TYPE_N_BASECLASSES (t))
15871 		    complaint (_("virtual function table pointer "
15872 				 "not found when defining class '%s'"),
15873 			       type->name () ? type->name () : "");
15874 		}
15875 	      else
15876 		{
15877 		  set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
15878 		}
15879 	    }
15880 	  else if (cu->producer
15881 		   && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
15882 	    {
15883 	      /* The IBM XLC compiler does not provide direct indication
15884 		 of the containing type, but the vtable pointer is
15885 		 always named __vfp.  */
15886 
15887 	      int i;
15888 
15889 	      for (i = type->num_fields () - 1;
15890 		   i >= TYPE_N_BASECLASSES (type);
15891 		   --i)
15892 		{
15893 		  if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
15894 		    {
15895 		      set_type_vptr_fieldno (type, i);
15896 		      set_type_vptr_basetype (type, type);
15897 		      break;
15898 		    }
15899 		}
15900 	    }
15901 	}
15902 
15903       /* Copy fi.typedef_field_list linked list elements content into the
15904 	 allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
15905       if (!fi.typedef_field_list.empty ())
15906 	{
15907 	  int count = fi.typedef_field_list.size ();
15908 
15909 	  ALLOCATE_CPLUS_STRUCT_TYPE (type);
15910 	  TYPE_TYPEDEF_FIELD_ARRAY (type)
15911 	    = ((struct decl_field *)
15912 	       TYPE_ALLOC (type,
15913 			   sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
15914 	  TYPE_TYPEDEF_FIELD_COUNT (type) = count;
15915 
15916 	  for (int i = 0; i < fi.typedef_field_list.size (); ++i)
15917 	    TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
15918 	}
15919 
15920       /* Copy fi.nested_types_list linked list elements content into the
15921 	 allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
15922       if (!fi.nested_types_list.empty ()
15923 	  && cu->per_cu->lang != language_ada)
15924 	{
15925 	  int count = fi.nested_types_list.size ();
15926 
15927 	  ALLOCATE_CPLUS_STRUCT_TYPE (type);
15928 	  TYPE_NESTED_TYPES_ARRAY (type)
15929 	    = ((struct decl_field *)
15930 	       TYPE_ALLOC (type, sizeof (struct decl_field) * count));
15931 	  TYPE_NESTED_TYPES_COUNT (type) = count;
15932 
15933 	  for (int i = 0; i < fi.nested_types_list.size (); ++i)
15934 	    TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
15935 	}
15936     }
15937 
15938   quirk_gcc_member_function_pointer (type, objfile);
15939   if (cu->per_cu->lang == language_rust && die->tag == DW_TAG_union_type)
15940     cu->rust_unions.push_back (type);
15941   else if (cu->per_cu->lang == language_ada)
15942     quirk_ada_thick_pointer_struct (die, cu, type);
15943 
15944   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
15945      snapshots) has been known to create a die giving a declaration
15946      for a class that has, as a child, a die giving a definition for a
15947      nested class.  So we have to process our children even if the
15948      current die is a declaration.  Normally, of course, a declaration
15949      won't have any children at all.  */
15950 
15951   child_die = die->child;
15952 
15953   while (child_die != NULL && child_die->tag)
15954     {
15955       if (child_die->tag == DW_TAG_member
15956 	  || child_die->tag == DW_TAG_variable
15957 	  || child_die->tag == DW_TAG_inheritance
15958 	  || child_die->tag == DW_TAG_template_value_param
15959 	  || child_die->tag == DW_TAG_template_type_param)
15960 	{
15961 	  /* Do nothing.  */
15962 	}
15963       else
15964 	process_die (child_die, cu);
15965 
15966       child_die = child_die->sibling;
15967     }
15968 
15969   /* Do not consider external references.  According to the DWARF standard,
15970      these DIEs are identified by the fact that they have no byte_size
15971      attribute, and a declaration attribute.  */
15972   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
15973       || !die_is_declaration (die, cu)
15974       || dwarf2_attr (die, DW_AT_signature, cu) != NULL)
15975     {
15976       struct symbol *sym = new_symbol (die, type, cu);
15977 
15978       if (has_template_parameters)
15979 	{
15980 	  struct symtab *symtab;
15981 	  if (sym != nullptr)
15982 	    symtab = symbol_symtab (sym);
15983 	  else if (cu->line_header != nullptr)
15984 	    {
15985 	      /* Any related symtab will do.  */
15986 	      symtab
15987 		= cu->line_header->file_names ()[0].symtab;
15988 	    }
15989 	  else
15990 	    {
15991 	      symtab = nullptr;
15992 	      complaint (_("could not find suitable "
15993 			   "symtab for template parameter"
15994 			   " - DIE at %s [in module %s]"),
15995 			 sect_offset_str (die->sect_off),
15996 			 objfile_name (objfile));
15997 	    }
15998 
15999 	  if (symtab != nullptr)
16000 	    {
16001 	      /* Make sure that the symtab is set on the new symbols.
16002 		 Even though they don't appear in this symtab directly,
16003 		 other parts of gdb assume that symbols do, and this is
16004 		 reasonably true.  */
16005 	      for (int i = 0; i < TYPE_N_TEMPLATE_ARGUMENTS (type); ++i)
16006 		symbol_set_symtab (TYPE_TEMPLATE_ARGUMENT (type, i), symtab);
16007 	    }
16008 	}
16009     }
16010 }
16011 
16012 /* Assuming DIE is an enumeration type, and TYPE is its associated
16013    type, update TYPE using some information only available in DIE's
16014    children.  In particular, the fields are computed.  */
16015 
16016 static void
16017 update_enumeration_type_from_children (struct die_info *die,
16018 				       struct type *type,
16019 				       struct dwarf2_cu *cu)
16020 {
16021   struct die_info *child_die;
16022   int unsigned_enum = 1;
16023   int flag_enum = 1;
16024 
16025   auto_obstack obstack;
16026   std::vector<struct field> fields;
16027 
16028   for (child_die = die->child;
16029        child_die != NULL && child_die->tag;
16030        child_die = child_die->sibling)
16031     {
16032       struct attribute *attr;
16033       LONGEST value;
16034       const gdb_byte *bytes;
16035       struct dwarf2_locexpr_baton *baton;
16036       const char *name;
16037 
16038       if (child_die->tag != DW_TAG_enumerator)
16039 	continue;
16040 
16041       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16042       if (attr == NULL)
16043 	continue;
16044 
16045       name = dwarf2_name (child_die, cu);
16046       if (name == NULL)
16047 	name = "<anonymous enumerator>";
16048 
16049       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16050 			       &value, &bytes, &baton);
16051       if (value < 0)
16052 	{
16053 	  unsigned_enum = 0;
16054 	  flag_enum = 0;
16055 	}
16056       else
16057 	{
16058 	  if (count_one_bits_ll (value) >= 2)
16059 	    flag_enum = 0;
16060 	}
16061 
16062       fields.emplace_back ();
16063       struct field &field = fields.back ();
16064       FIELD_NAME (field) = dwarf2_physname (name, child_die, cu);
16065       SET_FIELD_ENUMVAL (field, value);
16066     }
16067 
16068   if (!fields.empty ())
16069     {
16070       type->set_num_fields (fields.size ());
16071       type->set_fields
16072 	((struct field *)
16073 	 TYPE_ALLOC (type, sizeof (struct field) * fields.size ()));
16074       memcpy (type->fields (), fields.data (),
16075 	      sizeof (struct field) * fields.size ());
16076     }
16077 
16078   if (unsigned_enum)
16079     type->set_is_unsigned (true);
16080 
16081   if (flag_enum)
16082     type->set_is_flag_enum (true);
16083 }
16084 
16085 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16086    complete the type's fields yet, or create any symbols.  */
16087 
16088 static struct type *
16089 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16090 {
16091   struct objfile *objfile = cu->per_objfile->objfile;
16092   struct type *type;
16093   struct attribute *attr;
16094   const char *name;
16095 
16096   /* If the definition of this type lives in .debug_types, read that type.
16097      Don't follow DW_AT_specification though, that will take us back up
16098      the chain and we want to go down.  */
16099   attr = die->attr (DW_AT_signature);
16100   if (attr != nullptr)
16101     {
16102       type = get_DW_AT_signature_type (die, attr, cu);
16103 
16104       /* The type's CU may not be the same as CU.
16105 	 Ensure TYPE is recorded with CU in die_type_hash.  */
16106       return set_die_type (die, type, cu);
16107     }
16108 
16109   type = alloc_type (objfile);
16110 
16111   type->set_code (TYPE_CODE_ENUM);
16112   name = dwarf2_full_name (NULL, die, cu);
16113   if (name != NULL)
16114     type->set_name (name);
16115 
16116   attr = dwarf2_attr (die, DW_AT_type, cu);
16117   if (attr != NULL)
16118     {
16119       struct type *underlying_type = die_type (die, cu);
16120 
16121       TYPE_TARGET_TYPE (type) = underlying_type;
16122     }
16123 
16124   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16125   if (attr != nullptr)
16126     {
16127       TYPE_LENGTH (type) = attr->constant_value (0);
16128     }
16129   else
16130     {
16131       TYPE_LENGTH (type) = 0;
16132     }
16133 
16134   maybe_set_alignment (cu, die, type);
16135 
16136   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16137      declared as private in the package spec, and then defined only
16138      inside the package body.  Such types are known as Taft Amendment
16139      Types.  When another package uses such a type, an incomplete DIE
16140      may be generated by the compiler.  */
16141   if (die_is_declaration (die, cu))
16142     type->set_is_stub (true);
16143 
16144   /* If this type has an underlying type that is not a stub, then we
16145      may use its attributes.  We always use the "unsigned" attribute
16146      in this situation, because ordinarily we guess whether the type
16147      is unsigned -- but the guess can be wrong and the underlying type
16148      can tell us the reality.  However, we defer to a local size
16149      attribute if one exists, because this lets the compiler override
16150      the underlying type if needed.  */
16151   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_TARGET_TYPE (type)->is_stub ())
16152     {
16153       struct type *underlying_type = TYPE_TARGET_TYPE (type);
16154       underlying_type = check_typedef (underlying_type);
16155 
16156       type->set_is_unsigned (underlying_type->is_unsigned ());
16157 
16158       if (TYPE_LENGTH (type) == 0)
16159 	TYPE_LENGTH (type) = TYPE_LENGTH (underlying_type);
16160 
16161       if (TYPE_RAW_ALIGN (type) == 0
16162 	  && TYPE_RAW_ALIGN (underlying_type) != 0)
16163 	set_type_align (type, TYPE_RAW_ALIGN (underlying_type));
16164     }
16165 
16166   type->set_is_declared_class (dwarf2_flag_true_p (die, DW_AT_enum_class, cu));
16167 
16168   set_die_type (die, type, cu);
16169 
16170   /* Finish the creation of this type by using the enum's children.
16171      Note that, as usual, this must come after set_die_type to avoid
16172      infinite recursion when trying to compute the names of the
16173      enumerators.  */
16174   update_enumeration_type_from_children (die, type, cu);
16175 
16176   return type;
16177 }
16178 
16179 /* Given a pointer to a die which begins an enumeration, process all
16180    the dies that define the members of the enumeration, and create the
16181    symbol for the enumeration type.
16182 
16183    NOTE: We reverse the order of the element list.  */
16184 
16185 static void
16186 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16187 {
16188   struct type *this_type;
16189 
16190   this_type = get_die_type (die, cu);
16191   if (this_type == NULL)
16192     this_type = read_enumeration_type (die, cu);
16193 
16194   if (die->child != NULL)
16195     {
16196       struct die_info *child_die;
16197       const char *name;
16198 
16199       child_die = die->child;
16200       while (child_die && child_die->tag)
16201 	{
16202 	  if (child_die->tag != DW_TAG_enumerator)
16203 	    {
16204 	      process_die (child_die, cu);
16205 	    }
16206 	  else
16207 	    {
16208 	      name = dwarf2_name (child_die, cu);
16209 	      if (name)
16210 		new_symbol (child_die, this_type, cu);
16211 	    }
16212 
16213 	  child_die = child_die->sibling;
16214 	}
16215     }
16216 
16217   /* If we are reading an enum from a .debug_types unit, and the enum
16218      is a declaration, and the enum is not the signatured type in the
16219      unit, then we do not want to add a symbol for it.  Adding a
16220      symbol would in some cases obscure the true definition of the
16221      enum, giving users an incomplete type when the definition is
16222      actually available.  Note that we do not want to do this for all
16223      enums which are just declarations, because C++0x allows forward
16224      enum declarations.  */
16225   if (cu->per_cu->is_debug_types
16226       && die_is_declaration (die, cu))
16227     {
16228       struct signatured_type *sig_type;
16229 
16230       sig_type = (struct signatured_type *) cu->per_cu;
16231       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16232       if (sig_type->type_offset_in_section != die->sect_off)
16233 	return;
16234     }
16235 
16236   new_symbol (die, this_type, cu);
16237 }
16238 
16239 /* Helper function for quirk_ada_thick_pointer that examines a bounds
16240    expression for an index type and finds the corresponding field
16241    offset in the hidden "P_BOUNDS" structure.  Returns true on success
16242    and updates *FIELD, false if it fails to recognize an
16243    expression.  */
16244 
16245 static bool
16246 recognize_bound_expression (struct die_info *die, enum dwarf_attribute name,
16247 			    int *bounds_offset, struct field *field,
16248 			    struct dwarf2_cu *cu)
16249 {
16250   struct attribute *attr = dwarf2_attr (die, name, cu);
16251   if (attr == nullptr || !attr->form_is_block ())
16252     return false;
16253 
16254   const struct dwarf_block *block = attr->as_block ();
16255   const gdb_byte *start = block->data;
16256   const gdb_byte *end = block->data + block->size;
16257 
16258   /* The expression to recognize generally looks like:
16259 
16260      (DW_OP_push_object_address; DW_OP_plus_uconst: 8; DW_OP_deref;
16261      DW_OP_plus_uconst: 4; DW_OP_deref_size: 4)
16262 
16263      However, the second "plus_uconst" may be missing:
16264 
16265      (DW_OP_push_object_address; DW_OP_plus_uconst: 8; DW_OP_deref;
16266      DW_OP_deref_size: 4)
16267 
16268      This happens when the field is at the start of the structure.
16269 
16270      Also, the final deref may not be sized:
16271 
16272      (DW_OP_push_object_address; DW_OP_plus_uconst: 4; DW_OP_deref;
16273      DW_OP_deref)
16274 
16275      This happens when the size of the index type happens to be the
16276      same as the architecture's word size.  This can occur with or
16277      without the second plus_uconst.  */
16278 
16279   if (end - start < 2)
16280     return false;
16281   if (*start++ != DW_OP_push_object_address)
16282     return false;
16283   if (*start++ != DW_OP_plus_uconst)
16284     return false;
16285 
16286   uint64_t this_bound_off;
16287   start = gdb_read_uleb128 (start, end, &this_bound_off);
16288   if (start == nullptr || (int) this_bound_off != this_bound_off)
16289     return false;
16290   /* Update *BOUNDS_OFFSET if needed, or alternatively verify that it
16291      is consistent among all bounds.  */
16292   if (*bounds_offset == -1)
16293     *bounds_offset = this_bound_off;
16294   else if (*bounds_offset != this_bound_off)
16295     return false;
16296 
16297   if (start == end || *start++ != DW_OP_deref)
16298     return false;
16299 
16300   int offset = 0;
16301   if (start ==end)
16302     return false;
16303   else if (*start == DW_OP_deref_size || *start == DW_OP_deref)
16304     {
16305       /* This means an offset of 0.  */
16306     }
16307   else if (*start++ != DW_OP_plus_uconst)
16308     return false;
16309   else
16310     {
16311       /* The size is the parameter to DW_OP_plus_uconst.  */
16312       uint64_t val;
16313       start = gdb_read_uleb128 (start, end, &val);
16314       if (start == nullptr)
16315 	return false;
16316       if ((int) val != val)
16317 	return false;
16318       offset = val;
16319     }
16320 
16321   if (start == end)
16322     return false;
16323 
16324   uint64_t size;
16325   if (*start == DW_OP_deref_size)
16326     {
16327       start = gdb_read_uleb128 (start + 1, end, &size);
16328       if (start == nullptr)
16329 	return false;
16330     }
16331   else if (*start == DW_OP_deref)
16332     {
16333       size = cu->header.addr_size;
16334       ++start;
16335     }
16336   else
16337     return false;
16338 
16339   SET_FIELD_BITPOS (*field, 8 * offset);
16340   if (size != TYPE_LENGTH (field->type ()))
16341     FIELD_BITSIZE (*field) = 8 * size;
16342 
16343   return true;
16344 }
16345 
16346 /* With -fgnat-encodings=minimal, gcc will emit some unusual DWARF for
16347    some kinds of Ada arrays:
16348 
16349    <1><11db>: Abbrev Number: 7 (DW_TAG_array_type)
16350       <11dc>   DW_AT_name        : (indirect string, offset: 0x1bb8): string
16351       <11e0>   DW_AT_data_location: 2 byte block: 97 6
16352 	  (DW_OP_push_object_address; DW_OP_deref)
16353       <11e3>   DW_AT_type        : <0x1173>
16354       <11e7>   DW_AT_sibling     : <0x1201>
16355    <2><11eb>: Abbrev Number: 8 (DW_TAG_subrange_type)
16356       <11ec>   DW_AT_type        : <0x1206>
16357       <11f0>   DW_AT_lower_bound : 6 byte block: 97 23 8 6 94 4
16358 	  (DW_OP_push_object_address; DW_OP_plus_uconst: 8; DW_OP_deref;
16359 	   DW_OP_deref_size: 4)
16360       <11f7>   DW_AT_upper_bound : 8 byte block: 97 23 8 6 23 4 94 4
16361 	  (DW_OP_push_object_address; DW_OP_plus_uconst: 8; DW_OP_deref;
16362 	   DW_OP_plus_uconst: 4; DW_OP_deref_size: 4)
16363 
16364    This actually represents a "thick pointer", which is a structure
16365    with two elements: one that is a pointer to the array data, and one
16366    that is a pointer to another structure; this second structure holds
16367    the array bounds.
16368 
16369    This returns a new type on success, or nullptr if this didn't
16370    recognize the type.  */
16371 
16372 static struct type *
16373 quirk_ada_thick_pointer (struct die_info *die, struct dwarf2_cu *cu,
16374 			 struct type *type)
16375 {
16376   struct attribute *attr = dwarf2_attr (die, DW_AT_data_location, cu);
16377   /* So far we've only seen this with block form.  */
16378   if (attr == nullptr || !attr->form_is_block ())
16379     return nullptr;
16380 
16381   /* Note that this will fail if the structure layout is changed by
16382      the compiler.  However, we have no good way to recognize some
16383      other layout, because we don't know what expression the compiler
16384      might choose to emit should this happen.  */
16385   struct dwarf_block *blk = attr->as_block ();
16386   if (blk->size != 2
16387       || blk->data[0] != DW_OP_push_object_address
16388       || blk->data[1] != DW_OP_deref)
16389     return nullptr;
16390 
16391   int bounds_offset = -1;
16392   int max_align = -1;
16393   std::vector<struct field> range_fields;
16394   for (struct die_info *child_die = die->child;
16395        child_die;
16396        child_die = child_die->sibling)
16397     {
16398       if (child_die->tag == DW_TAG_subrange_type)
16399 	{
16400 	  struct type *underlying = read_subrange_index_type (child_die, cu);
16401 
16402 	  int this_align = type_align (underlying);
16403 	  if (this_align > max_align)
16404 	    max_align = this_align;
16405 
16406 	  range_fields.emplace_back ();
16407 	  range_fields.emplace_back ();
16408 
16409 	  struct field &lower = range_fields[range_fields.size () - 2];
16410 	  struct field &upper = range_fields[range_fields.size () - 1];
16411 
16412 	  lower.set_type (underlying);
16413 	  FIELD_ARTIFICIAL (lower) = 1;
16414 
16415 	  upper.set_type (underlying);
16416 	  FIELD_ARTIFICIAL (upper) = 1;
16417 
16418 	  if (!recognize_bound_expression (child_die, DW_AT_lower_bound,
16419 					   &bounds_offset, &lower, cu)
16420 	      || !recognize_bound_expression (child_die, DW_AT_upper_bound,
16421 					      &bounds_offset, &upper, cu))
16422 	    return nullptr;
16423 	}
16424     }
16425 
16426   /* This shouldn't really happen, but double-check that we found
16427      where the bounds are stored.  */
16428   if (bounds_offset == -1)
16429     return nullptr;
16430 
16431   struct objfile *objfile = cu->per_objfile->objfile;
16432   for (int i = 0; i < range_fields.size (); i += 2)
16433     {
16434       char name[20];
16435 
16436       /* Set the name of each field in the bounds.  */
16437       xsnprintf (name, sizeof (name), "LB%d", i / 2);
16438       FIELD_NAME (range_fields[i]) = objfile->intern (name);
16439       xsnprintf (name, sizeof (name), "UB%d", i / 2);
16440       FIELD_NAME (range_fields[i + 1]) = objfile->intern (name);
16441     }
16442 
16443   struct type *bounds = alloc_type (objfile);
16444   bounds->set_code (TYPE_CODE_STRUCT);
16445 
16446   bounds->set_num_fields (range_fields.size ());
16447   bounds->set_fields
16448     ((struct field *) TYPE_ALLOC (bounds, (bounds->num_fields ()
16449 					   * sizeof (struct field))));
16450   memcpy (bounds->fields (), range_fields.data (),
16451 	  bounds->num_fields () * sizeof (struct field));
16452 
16453   int last_fieldno = range_fields.size () - 1;
16454   int bounds_size = (TYPE_FIELD_BITPOS (bounds, last_fieldno) / 8
16455 		     + TYPE_LENGTH (bounds->field (last_fieldno).type ()));
16456   TYPE_LENGTH (bounds) = align_up (bounds_size, max_align);
16457 
16458   /* Rewrite the existing array type in place.  Specifically, we
16459      remove any dynamic properties we might have read, and we replace
16460      the index types.  */
16461   struct type *iter = type;
16462   for (int i = 0; i < range_fields.size (); i += 2)
16463     {
16464       gdb_assert (iter->code () == TYPE_CODE_ARRAY);
16465       iter->main_type->dyn_prop_list = nullptr;
16466       iter->set_index_type
16467 	(create_static_range_type (NULL, bounds->field (i).type (), 1, 0));
16468       iter = TYPE_TARGET_TYPE (iter);
16469     }
16470 
16471   struct type *result = alloc_type (objfile);
16472   result->set_code (TYPE_CODE_STRUCT);
16473 
16474   result->set_num_fields (2);
16475   result->set_fields
16476     ((struct field *) TYPE_ZALLOC (result, (result->num_fields ()
16477 					    * sizeof (struct field))));
16478 
16479   /* The names are chosen to coincide with what the compiler does with
16480      -fgnat-encodings=all, which the Ada code in gdb already
16481      understands.  */
16482   TYPE_FIELD_NAME (result, 0) = "P_ARRAY";
16483   result->field (0).set_type (lookup_pointer_type (type));
16484 
16485   TYPE_FIELD_NAME (result, 1) = "P_BOUNDS";
16486   result->field (1).set_type (lookup_pointer_type (bounds));
16487   SET_FIELD_BITPOS (result->field (1), 8 * bounds_offset);
16488 
16489   result->set_name (type->name ());
16490   TYPE_LENGTH (result) = (TYPE_LENGTH (result->field (0).type ())
16491 			  + TYPE_LENGTH (result->field (1).type ()));
16492 
16493   return result;
16494 }
16495 
16496 /* Extract all information from a DW_TAG_array_type DIE and put it in
16497    the DIE's type field.  For now, this only handles one dimensional
16498    arrays.  */
16499 
16500 static struct type *
16501 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16502 {
16503   struct objfile *objfile = cu->per_objfile->objfile;
16504   struct die_info *child_die;
16505   struct type *type;
16506   struct type *element_type, *range_type, *index_type;
16507   struct attribute *attr;
16508   const char *name;
16509   struct dynamic_prop *byte_stride_prop = NULL;
16510   unsigned int bit_stride = 0;
16511 
16512   element_type = die_type (die, cu);
16513 
16514   /* The die_type call above may have already set the type for this DIE.  */
16515   type = get_die_type (die, cu);
16516   if (type)
16517     return type;
16518 
16519   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16520   if (attr != NULL)
16521     {
16522       int stride_ok;
16523       struct type *prop_type = cu->addr_sized_int_type (false);
16524 
16525       byte_stride_prop
16526 	= (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16527       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop,
16528 					prop_type);
16529       if (!stride_ok)
16530 	{
16531 	  complaint (_("unable to read array DW_AT_byte_stride "
16532 		       " - DIE at %s [in module %s]"),
16533 		     sect_offset_str (die->sect_off),
16534 		     objfile_name (cu->per_objfile->objfile));
16535 	  /* Ignore this attribute.  We will likely not be able to print
16536 	     arrays of this type correctly, but there is little we can do
16537 	     to help if we cannot read the attribute's value.  */
16538 	  byte_stride_prop = NULL;
16539 	}
16540     }
16541 
16542   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16543   if (attr != NULL)
16544     bit_stride = attr->constant_value (0);
16545 
16546   /* Irix 6.2 native cc creates array types without children for
16547      arrays with unspecified length.  */
16548   if (die->child == NULL)
16549     {
16550       index_type = objfile_type (objfile)->builtin_int;
16551       range_type = create_static_range_type (NULL, index_type, 0, -1);
16552       type = create_array_type_with_stride (NULL, element_type, range_type,
16553 					    byte_stride_prop, bit_stride);
16554       return set_die_type (die, type, cu);
16555     }
16556 
16557   std::vector<struct type *> range_types;
16558   child_die = die->child;
16559   while (child_die && child_die->tag)
16560     {
16561       if (child_die->tag == DW_TAG_subrange_type)
16562 	{
16563 	  struct type *child_type = read_type_die (child_die, cu);
16564 
16565 	  if (child_type != NULL)
16566 	    {
16567 	      /* The range type was succesfully read.  Save it for the
16568 		 array type creation.  */
16569 	      range_types.push_back (child_type);
16570 	    }
16571 	}
16572       child_die = child_die->sibling;
16573     }
16574 
16575   if (range_types.empty ())
16576     {
16577       complaint (_("unable to find array range - DIE at %s [in module %s]"),
16578 		 sect_offset_str (die->sect_off),
16579 		 objfile_name (cu->per_objfile->objfile));
16580       return NULL;
16581     }
16582 
16583   /* Dwarf2 dimensions are output from left to right, create the
16584      necessary array types in backwards order.  */
16585 
16586   type = element_type;
16587 
16588   if (read_array_order (die, cu) == DW_ORD_col_major)
16589     {
16590       int i = 0;
16591 
16592       while (i < range_types.size ())
16593 	{
16594 	  type = create_array_type_with_stride (NULL, type, range_types[i++],
16595 						byte_stride_prop, bit_stride);
16596 	  bit_stride = 0;
16597 	  byte_stride_prop = nullptr;
16598 	}
16599     }
16600   else
16601     {
16602       size_t ndim = range_types.size ();
16603       while (ndim-- > 0)
16604 	{
16605 	  type = create_array_type_with_stride (NULL, type, range_types[ndim],
16606 						byte_stride_prop, bit_stride);
16607 	  bit_stride = 0;
16608 	  byte_stride_prop = nullptr;
16609 	}
16610     }
16611 
16612   gdb_assert (type != element_type);
16613 
16614   /* Understand Dwarf2 support for vector types (like they occur on
16615      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16616      array type.  This is not part of the Dwarf2/3 standard yet, but a
16617      custom vendor extension.  The main difference between a regular
16618      array and the vector variant is that vectors are passed by value
16619      to functions.  */
16620   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16621   if (attr != nullptr)
16622     make_vector_type (type);
16623 
16624   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16625      implementation may choose to implement triple vectors using this
16626      attribute.  */
16627   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16628   if (attr != nullptr && attr->form_is_unsigned ())
16629     {
16630       if (attr->as_unsigned () >= TYPE_LENGTH (type))
16631 	TYPE_LENGTH (type) = attr->as_unsigned ();
16632       else
16633 	complaint (_("DW_AT_byte_size for array type smaller "
16634 		     "than the total size of elements"));
16635     }
16636 
16637   name = dwarf2_name (die, cu);
16638   if (name)
16639     type->set_name (name);
16640 
16641   maybe_set_alignment (cu, die, type);
16642 
16643   struct type *replacement_type = nullptr;
16644   if (cu->per_cu->lang == language_ada)
16645     {
16646       replacement_type = quirk_ada_thick_pointer (die, cu, type);
16647       if (replacement_type != nullptr)
16648 	type = replacement_type;
16649     }
16650 
16651   /* Install the type in the die.  */
16652   set_die_type (die, type, cu, replacement_type != nullptr);
16653 
16654   /* set_die_type should be already done.  */
16655   set_descriptive_type (type, die, cu);
16656 
16657   return type;
16658 }
16659 
16660 static enum dwarf_array_dim_ordering
16661 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16662 {
16663   struct attribute *attr;
16664 
16665   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16666 
16667   if (attr != nullptr)
16668     {
16669       LONGEST val = attr->constant_value (-1);
16670       if (val == DW_ORD_row_major || val == DW_ORD_col_major)
16671 	return (enum dwarf_array_dim_ordering) val;
16672     }
16673 
16674   /* GNU F77 is a special case, as at 08/2004 array type info is the
16675      opposite order to the dwarf2 specification, but data is still
16676      laid out as per normal fortran.
16677 
16678      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16679      version checking.  */
16680 
16681   if (cu->per_cu->lang == language_fortran
16682       && cu->producer && strstr (cu->producer, "GNU F77"))
16683     {
16684       return DW_ORD_row_major;
16685     }
16686 
16687   switch (cu->language_defn->array_ordering ())
16688     {
16689     case array_column_major:
16690       return DW_ORD_col_major;
16691     case array_row_major:
16692     default:
16693       return DW_ORD_row_major;
16694     };
16695 }
16696 
16697 /* Extract all information from a DW_TAG_set_type DIE and put it in
16698    the DIE's type field.  */
16699 
16700 static struct type *
16701 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16702 {
16703   struct type *domain_type, *set_type;
16704   struct attribute *attr;
16705 
16706   domain_type = die_type (die, cu);
16707 
16708   /* The die_type call above may have already set the type for this DIE.  */
16709   set_type = get_die_type (die, cu);
16710   if (set_type)
16711     return set_type;
16712 
16713   set_type = create_set_type (NULL, domain_type);
16714 
16715   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16716   if (attr != nullptr && attr->form_is_unsigned ())
16717     TYPE_LENGTH (set_type) = attr->as_unsigned ();
16718 
16719   maybe_set_alignment (cu, die, set_type);
16720 
16721   return set_die_type (die, set_type, cu);
16722 }
16723 
16724 /* A helper for read_common_block that creates a locexpr baton.
16725    SYM is the symbol which we are marking as computed.
16726    COMMON_DIE is the DIE for the common block.
16727    COMMON_LOC is the location expression attribute for the common
16728    block itself.
16729    MEMBER_LOC is the location expression attribute for the particular
16730    member of the common block that we are processing.
16731    CU is the CU from which the above come.  */
16732 
16733 static void
16734 mark_common_block_symbol_computed (struct symbol *sym,
16735 				   struct die_info *common_die,
16736 				   struct attribute *common_loc,
16737 				   struct attribute *member_loc,
16738 				   struct dwarf2_cu *cu)
16739 {
16740   dwarf2_per_objfile *per_objfile = cu->per_objfile;
16741   struct objfile *objfile = per_objfile->objfile;
16742   struct dwarf2_locexpr_baton *baton;
16743   gdb_byte *ptr;
16744   unsigned int cu_off;
16745   enum bfd_endian byte_order = gdbarch_byte_order (objfile->arch ());
16746   LONGEST offset = 0;
16747 
16748   gdb_assert (common_loc && member_loc);
16749   gdb_assert (common_loc->form_is_block ());
16750   gdb_assert (member_loc->form_is_block ()
16751 	      || member_loc->form_is_constant ());
16752 
16753   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16754   baton->per_objfile = per_objfile;
16755   baton->per_cu = cu->per_cu;
16756   gdb_assert (baton->per_cu);
16757 
16758   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16759 
16760   if (member_loc->form_is_constant ())
16761     {
16762       offset = member_loc->constant_value (0);
16763       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16764     }
16765   else
16766     baton->size += member_loc->as_block ()->size;
16767 
16768   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16769   baton->data = ptr;
16770 
16771   *ptr++ = DW_OP_call4;
16772   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16773   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16774   ptr += 4;
16775 
16776   if (member_loc->form_is_constant ())
16777     {
16778       *ptr++ = DW_OP_addr;
16779       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16780       ptr += cu->header.addr_size;
16781     }
16782   else
16783     {
16784       /* We have to copy the data here, because DW_OP_call4 will only
16785 	 use a DW_AT_location attribute.  */
16786       struct dwarf_block *block = member_loc->as_block ();
16787       memcpy (ptr, block->data, block->size);
16788       ptr += block->size;
16789     }
16790 
16791   *ptr++ = DW_OP_plus;
16792   gdb_assert (ptr - baton->data == baton->size);
16793 
16794   SYMBOL_LOCATION_BATON (sym) = baton;
16795   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16796 }
16797 
16798 /* Create appropriate locally-scoped variables for all the
16799    DW_TAG_common_block entries.  Also create a struct common_block
16800    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16801    is used to separate the common blocks name namespace from regular
16802    variable names.  */
16803 
16804 static void
16805 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16806 {
16807   struct attribute *attr;
16808 
16809   attr = dwarf2_attr (die, DW_AT_location, cu);
16810   if (attr != nullptr)
16811     {
16812       /* Support the .debug_loc offsets.  */
16813       if (attr->form_is_block ())
16814 	{
16815 	  /* Ok.  */
16816 	}
16817       else if (attr->form_is_section_offset ())
16818 	{
16819 	  dwarf2_complex_location_expr_complaint ();
16820 	  attr = NULL;
16821 	}
16822       else
16823 	{
16824 	  dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16825 						 "common block member");
16826 	  attr = NULL;
16827 	}
16828     }
16829 
16830   if (die->child != NULL)
16831     {
16832       struct objfile *objfile = cu->per_objfile->objfile;
16833       struct die_info *child_die;
16834       size_t n_entries = 0, size;
16835       struct common_block *common_block;
16836       struct symbol *sym;
16837 
16838       for (child_die = die->child;
16839 	   child_die && child_die->tag;
16840 	   child_die = child_die->sibling)
16841 	++n_entries;
16842 
16843       size = (sizeof (struct common_block)
16844 	      + (n_entries - 1) * sizeof (struct symbol *));
16845       common_block
16846 	= (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16847 						 size);
16848       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16849       common_block->n_entries = 0;
16850 
16851       for (child_die = die->child;
16852 	   child_die && child_die->tag;
16853 	   child_die = child_die->sibling)
16854 	{
16855 	  /* Create the symbol in the DW_TAG_common_block block in the current
16856 	     symbol scope.  */
16857 	  sym = new_symbol (child_die, NULL, cu);
16858 	  if (sym != NULL)
16859 	    {
16860 	      struct attribute *member_loc;
16861 
16862 	      common_block->contents[common_block->n_entries++] = sym;
16863 
16864 	      member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16865 					cu);
16866 	      if (member_loc)
16867 		{
16868 		  /* GDB has handled this for a long time, but it is
16869 		     not specified by DWARF.  It seems to have been
16870 		     emitted by gfortran at least as recently as:
16871 		     http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16872 		  complaint (_("Variable in common block has "
16873 			       "DW_AT_data_member_location "
16874 			       "- DIE at %s [in module %s]"),
16875 			       sect_offset_str (child_die->sect_off),
16876 			     objfile_name (objfile));
16877 
16878 		  if (member_loc->form_is_section_offset ())
16879 		    dwarf2_complex_location_expr_complaint ();
16880 		  else if (member_loc->form_is_constant ()
16881 			   || member_loc->form_is_block ())
16882 		    {
16883 		      if (attr != nullptr)
16884 			mark_common_block_symbol_computed (sym, die, attr,
16885 							   member_loc, cu);
16886 		    }
16887 		  else
16888 		    dwarf2_complex_location_expr_complaint ();
16889 		}
16890 	    }
16891 	}
16892 
16893       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16894       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16895     }
16896 }
16897 
16898 /* Create a type for a C++ namespace.  */
16899 
16900 static struct type *
16901 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16902 {
16903   struct objfile *objfile = cu->per_objfile->objfile;
16904   const char *previous_prefix, *name;
16905   int is_anonymous;
16906   struct type *type;
16907 
16908   /* For extensions, reuse the type of the original namespace.  */
16909   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16910     {
16911       struct die_info *ext_die;
16912       struct dwarf2_cu *ext_cu = cu;
16913 
16914       ext_die = dwarf2_extension (die, &ext_cu);
16915       type = read_type_die (ext_die, ext_cu);
16916 
16917       /* EXT_CU may not be the same as CU.
16918 	 Ensure TYPE is recorded with CU in die_type_hash.  */
16919       return set_die_type (die, type, cu);
16920     }
16921 
16922   name = namespace_name (die, &is_anonymous, cu);
16923 
16924   /* Now build the name of the current namespace.  */
16925 
16926   previous_prefix = determine_prefix (die, cu);
16927   if (previous_prefix[0] != '\0')
16928     name = typename_concat (&objfile->objfile_obstack,
16929 			    previous_prefix, name, 0, cu);
16930 
16931   /* Create the type.  */
16932   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16933 
16934   return set_die_type (die, type, cu);
16935 }
16936 
16937 /* Read a namespace scope.  */
16938 
16939 static void
16940 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16941 {
16942   struct objfile *objfile = cu->per_objfile->objfile;
16943   int is_anonymous;
16944 
16945   /* Add a symbol associated to this if we haven't seen the namespace
16946      before.  Also, add a using directive if it's an anonymous
16947      namespace.  */
16948 
16949   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16950     {
16951       struct type *type;
16952 
16953       type = read_type_die (die, cu);
16954       new_symbol (die, type, cu);
16955 
16956       namespace_name (die, &is_anonymous, cu);
16957       if (is_anonymous)
16958 	{
16959 	  const char *previous_prefix = determine_prefix (die, cu);
16960 
16961 	  std::vector<const char *> excludes;
16962 	  add_using_directive (using_directives (cu),
16963 			       previous_prefix, type->name (), NULL,
16964 			       NULL, excludes, 0, &objfile->objfile_obstack);
16965 	}
16966     }
16967 
16968   if (die->child != NULL)
16969     {
16970       struct die_info *child_die = die->child;
16971 
16972       while (child_die && child_die->tag)
16973 	{
16974 	  process_die (child_die, cu);
16975 	  child_die = child_die->sibling;
16976 	}
16977     }
16978 }
16979 
16980 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16981    imported module.  Still we need that type as local Fortran "use ... only"
16982    declaration imports depend on the created type in determine_prefix.  */
16983 
16984 static struct type *
16985 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16986 {
16987   struct objfile *objfile = cu->per_objfile->objfile;
16988   const char *module_name;
16989   struct type *type;
16990 
16991   module_name = dwarf2_name (die, cu);
16992   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16993 
16994   return set_die_type (die, type, cu);
16995 }
16996 
16997 /* Read a Fortran module.  */
16998 
16999 static void
17000 read_module (struct die_info *die, struct dwarf2_cu *cu)
17001 {
17002   struct die_info *child_die = die->child;
17003   struct type *type;
17004 
17005   type = read_type_die (die, cu);
17006   new_symbol (die, type, cu);
17007 
17008   while (child_die && child_die->tag)
17009     {
17010       process_die (child_die, cu);
17011       child_die = child_die->sibling;
17012     }
17013 }
17014 
17015 /* Return the name of the namespace represented by DIE.  Set
17016    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
17017    namespace.  */
17018 
17019 static const char *
17020 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
17021 {
17022   struct die_info *current_die;
17023   const char *name = NULL;
17024 
17025   /* Loop through the extensions until we find a name.  */
17026 
17027   for (current_die = die;
17028        current_die != NULL;
17029        current_die = dwarf2_extension (die, &cu))
17030     {
17031       /* We don't use dwarf2_name here so that we can detect the absence
17032 	 of a name -> anonymous namespace.  */
17033       name = dwarf2_string_attr (die, DW_AT_name, cu);
17034 
17035       if (name != NULL)
17036 	break;
17037     }
17038 
17039   /* Is it an anonymous namespace?  */
17040 
17041   *is_anonymous = (name == NULL);
17042   if (*is_anonymous)
17043     name = CP_ANONYMOUS_NAMESPACE_STR;
17044 
17045   return name;
17046 }
17047 
17048 /* Extract all information from a DW_TAG_pointer_type DIE and add to
17049    the user defined type vector.  */
17050 
17051 static struct type *
17052 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
17053 {
17054   struct gdbarch *gdbarch = cu->per_objfile->objfile->arch ();
17055   struct comp_unit_head *cu_header = &cu->header;
17056   struct type *type;
17057   struct attribute *attr_byte_size;
17058   struct attribute *attr_address_class;
17059   int byte_size, addr_class;
17060   struct type *target_type;
17061 
17062   target_type = die_type (die, cu);
17063 
17064   /* The die_type call above may have already set the type for this DIE.  */
17065   type = get_die_type (die, cu);
17066   if (type)
17067     return type;
17068 
17069   type = lookup_pointer_type (target_type);
17070 
17071   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
17072   if (attr_byte_size)
17073     byte_size = attr_byte_size->constant_value (cu_header->addr_size);
17074   else
17075     byte_size = cu_header->addr_size;
17076 
17077   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
17078   if (attr_address_class)
17079     addr_class = attr_address_class->constant_value (DW_ADDR_none);
17080   else
17081     addr_class = DW_ADDR_none;
17082 
17083   ULONGEST alignment = get_alignment (cu, die);
17084 
17085   /* If the pointer size, alignment, or address class is different
17086      than the default, create a type variant marked as such and set
17087      the length accordingly.  */
17088   if (TYPE_LENGTH (type) != byte_size
17089       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
17090 	  && alignment != TYPE_RAW_ALIGN (type))
17091       || addr_class != DW_ADDR_none)
17092     {
17093       if (gdbarch_address_class_type_flags_p (gdbarch))
17094 	{
17095 	  type_instance_flags type_flags
17096 	    = gdbarch_address_class_type_flags (gdbarch, byte_size,
17097 						addr_class);
17098 	  gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
17099 		      == 0);
17100 	  type = make_type_with_address_space (type, type_flags);
17101 	}
17102       else if (TYPE_LENGTH (type) != byte_size)
17103 	{
17104 	  complaint (_("invalid pointer size %d"), byte_size);
17105 	}
17106       else if (TYPE_RAW_ALIGN (type) != alignment)
17107 	{
17108 	  complaint (_("Invalid DW_AT_alignment"
17109 		       " - DIE at %s [in module %s]"),
17110 		     sect_offset_str (die->sect_off),
17111 		     objfile_name (cu->per_objfile->objfile));
17112 	}
17113       else
17114 	{
17115 	  /* Should we also complain about unhandled address classes?  */
17116 	}
17117     }
17118 
17119   TYPE_LENGTH (type) = byte_size;
17120   set_type_align (type, alignment);
17121   return set_die_type (die, type, cu);
17122 }
17123 
17124 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17125    the user defined type vector.  */
17126 
17127 static struct type *
17128 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17129 {
17130   struct type *type;
17131   struct type *to_type;
17132   struct type *domain;
17133 
17134   to_type = die_type (die, cu);
17135   domain = die_containing_type (die, cu);
17136 
17137   /* The calls above may have already set the type for this DIE.  */
17138   type = get_die_type (die, cu);
17139   if (type)
17140     return type;
17141 
17142   if (check_typedef (to_type)->code () == TYPE_CODE_METHOD)
17143     type = lookup_methodptr_type (to_type);
17144   else if (check_typedef (to_type)->code () == TYPE_CODE_FUNC)
17145     {
17146       struct type *new_type = alloc_type (cu->per_objfile->objfile);
17147 
17148       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17149 			    to_type->fields (), to_type->num_fields (),
17150 			    to_type->has_varargs ());
17151       type = lookup_methodptr_type (new_type);
17152     }
17153   else
17154     type = lookup_memberptr_type (to_type, domain);
17155 
17156   return set_die_type (die, type, cu);
17157 }
17158 
17159 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17160    the user defined type vector.  */
17161 
17162 static struct type *
17163 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17164 			  enum type_code refcode)
17165 {
17166   struct comp_unit_head *cu_header = &cu->header;
17167   struct type *type, *target_type;
17168   struct attribute *attr;
17169 
17170   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17171 
17172   target_type = die_type (die, cu);
17173 
17174   /* The die_type call above may have already set the type for this DIE.  */
17175   type = get_die_type (die, cu);
17176   if (type)
17177     return type;
17178 
17179   type = lookup_reference_type (target_type, refcode);
17180   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17181   if (attr != nullptr)
17182     {
17183       TYPE_LENGTH (type) = attr->constant_value (cu_header->addr_size);
17184     }
17185   else
17186     {
17187       TYPE_LENGTH (type) = cu_header->addr_size;
17188     }
17189   maybe_set_alignment (cu, die, type);
17190   return set_die_type (die, type, cu);
17191 }
17192 
17193 /* Add the given cv-qualifiers to the element type of the array.  GCC
17194    outputs DWARF type qualifiers that apply to an array, not the
17195    element type.  But GDB relies on the array element type to carry
17196    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17197    specification.  */
17198 
17199 static struct type *
17200 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17201 		   struct type *base_type, int cnst, int voltl)
17202 {
17203   struct type *el_type, *inner_array;
17204 
17205   base_type = copy_type (base_type);
17206   inner_array = base_type;
17207 
17208   while (TYPE_TARGET_TYPE (inner_array)->code () == TYPE_CODE_ARRAY)
17209     {
17210       TYPE_TARGET_TYPE (inner_array) =
17211 	copy_type (TYPE_TARGET_TYPE (inner_array));
17212       inner_array = TYPE_TARGET_TYPE (inner_array);
17213     }
17214 
17215   el_type = TYPE_TARGET_TYPE (inner_array);
17216   cnst |= TYPE_CONST (el_type);
17217   voltl |= TYPE_VOLATILE (el_type);
17218   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17219 
17220   return set_die_type (die, base_type, cu);
17221 }
17222 
17223 static struct type *
17224 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17225 {
17226   struct type *base_type, *cv_type;
17227 
17228   base_type = die_type (die, cu);
17229 
17230   /* The die_type call above may have already set the type for this DIE.  */
17231   cv_type = get_die_type (die, cu);
17232   if (cv_type)
17233     return cv_type;
17234 
17235   /* In case the const qualifier is applied to an array type, the element type
17236      is so qualified, not the array type (section 6.7.3 of C99).  */
17237   if (base_type->code () == TYPE_CODE_ARRAY)
17238     return add_array_cv_type (die, cu, base_type, 1, 0);
17239 
17240   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17241   return set_die_type (die, cv_type, cu);
17242 }
17243 
17244 static struct type *
17245 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17246 {
17247   struct type *base_type, *cv_type;
17248 
17249   base_type = die_type (die, cu);
17250 
17251   /* The die_type call above may have already set the type for this DIE.  */
17252   cv_type = get_die_type (die, cu);
17253   if (cv_type)
17254     return cv_type;
17255 
17256   /* In case the volatile qualifier is applied to an array type, the
17257      element type is so qualified, not the array type (section 6.7.3
17258      of C99).  */
17259   if (base_type->code () == TYPE_CODE_ARRAY)
17260     return add_array_cv_type (die, cu, base_type, 0, 1);
17261 
17262   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17263   return set_die_type (die, cv_type, cu);
17264 }
17265 
17266 /* Handle DW_TAG_restrict_type.  */
17267 
17268 static struct type *
17269 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17270 {
17271   struct type *base_type, *cv_type;
17272 
17273   base_type = die_type (die, cu);
17274 
17275   /* The die_type call above may have already set the type for this DIE.  */
17276   cv_type = get_die_type (die, cu);
17277   if (cv_type)
17278     return cv_type;
17279 
17280   cv_type = make_restrict_type (base_type);
17281   return set_die_type (die, cv_type, cu);
17282 }
17283 
17284 /* Handle DW_TAG_atomic_type.  */
17285 
17286 static struct type *
17287 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17288 {
17289   struct type *base_type, *cv_type;
17290 
17291   base_type = die_type (die, cu);
17292 
17293   /* The die_type call above may have already set the type for this DIE.  */
17294   cv_type = get_die_type (die, cu);
17295   if (cv_type)
17296     return cv_type;
17297 
17298   cv_type = make_atomic_type (base_type);
17299   return set_die_type (die, cv_type, cu);
17300 }
17301 
17302 /* Extract all information from a DW_TAG_string_type DIE and add to
17303    the user defined type vector.  It isn't really a user defined type,
17304    but it behaves like one, with other DIE's using an AT_user_def_type
17305    attribute to reference it.  */
17306 
17307 static struct type *
17308 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17309 {
17310   struct objfile *objfile = cu->per_objfile->objfile;
17311   struct gdbarch *gdbarch = objfile->arch ();
17312   struct type *type, *range_type, *index_type, *char_type;
17313   struct attribute *attr;
17314   struct dynamic_prop prop;
17315   bool length_is_constant = true;
17316   LONGEST length;
17317 
17318   /* There are a couple of places where bit sizes might be made use of
17319      when parsing a DW_TAG_string_type, however, no producer that we know
17320      of make use of these.  Handling bit sizes that are a multiple of the
17321      byte size is easy enough, but what about other bit sizes?  Lets deal
17322      with that problem when we have to.  Warn about these attributes being
17323      unsupported, then parse the type and ignore them like we always
17324      have.  */
17325   if (dwarf2_attr (die, DW_AT_bit_size, cu) != nullptr
17326       || dwarf2_attr (die, DW_AT_string_length_bit_size, cu) != nullptr)
17327     {
17328       static bool warning_printed = false;
17329       if (!warning_printed)
17330 	{
17331 	  warning (_("DW_AT_bit_size and DW_AT_string_length_bit_size not "
17332 		     "currently supported on DW_TAG_string_type."));
17333 	  warning_printed = true;
17334 	}
17335     }
17336 
17337   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17338   if (attr != nullptr && !attr->form_is_constant ())
17339     {
17340       /* The string length describes the location at which the length of
17341 	 the string can be found.  The size of the length field can be
17342 	 specified with one of the attributes below.  */
17343       struct type *prop_type;
17344       struct attribute *len
17345 	= dwarf2_attr (die, DW_AT_string_length_byte_size, cu);
17346       if (len == nullptr)
17347 	len = dwarf2_attr (die, DW_AT_byte_size, cu);
17348       if (len != nullptr && len->form_is_constant ())
17349 	{
17350 	  /* Pass 0 as the default as we know this attribute is constant
17351 	     and the default value will not be returned.  */
17352 	  LONGEST sz = len->constant_value (0);
17353 	  prop_type = cu->per_objfile->int_type (sz, true);
17354 	}
17355       else
17356 	{
17357 	  /* If the size is not specified then we assume it is the size of
17358 	     an address on this target.  */
17359 	  prop_type = cu->addr_sized_int_type (true);
17360 	}
17361 
17362       /* Convert the attribute into a dynamic property.  */
17363       if (!attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
17364 	length = 1;
17365       else
17366 	length_is_constant = false;
17367     }
17368   else if (attr != nullptr)
17369     {
17370       /* This DW_AT_string_length just contains the length with no
17371 	 indirection.  There's no need to create a dynamic property in this
17372 	 case.  Pass 0 for the default value as we know it will not be
17373 	 returned in this case.  */
17374       length = attr->constant_value (0);
17375     }
17376   else if ((attr = dwarf2_attr (die, DW_AT_byte_size, cu)) != nullptr)
17377     {
17378       /* We don't currently support non-constant byte sizes for strings.  */
17379       length = attr->constant_value (1);
17380     }
17381   else
17382     {
17383       /* Use 1 as a fallback length if we have nothing else.  */
17384       length = 1;
17385     }
17386 
17387   index_type = objfile_type (objfile)->builtin_int;
17388   if (length_is_constant)
17389     range_type = create_static_range_type (NULL, index_type, 1, length);
17390   else
17391     {
17392       struct dynamic_prop low_bound;
17393 
17394       low_bound.set_const_val (1);
17395       range_type = create_range_type (NULL, index_type, &low_bound, &prop, 0);
17396     }
17397   char_type = language_string_char_type (cu->language_defn, gdbarch);
17398   type = create_string_type (NULL, char_type, range_type);
17399 
17400   return set_die_type (die, type, cu);
17401 }
17402 
17403 /* Assuming that DIE corresponds to a function, returns nonzero
17404    if the function is prototyped.  */
17405 
17406 static int
17407 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17408 {
17409   struct attribute *attr;
17410 
17411   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17412   if (attr && attr->as_boolean ())
17413     return 1;
17414 
17415   /* The DWARF standard implies that the DW_AT_prototyped attribute
17416      is only meaningful for C, but the concept also extends to other
17417      languages that allow unprototyped functions (Eg: Objective C).
17418      For all other languages, assume that functions are always
17419      prototyped.  */
17420   if (cu->per_cu->lang != language_c
17421       && cu->per_cu->lang != language_objc
17422       && cu->per_cu->lang != language_opencl)
17423     return 1;
17424 
17425   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17426      prototyped and unprototyped functions; default to prototyped,
17427      since that is more common in modern code (and RealView warns
17428      about unprototyped functions).  */
17429   if (producer_is_realview (cu->producer))
17430     return 1;
17431 
17432   return 0;
17433 }
17434 
17435 /* Handle DIES due to C code like:
17436 
17437    struct foo
17438    {
17439    int (*funcp)(int a, long l);
17440    int b;
17441    };
17442 
17443    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17444 
17445 static struct type *
17446 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17447 {
17448   struct objfile *objfile = cu->per_objfile->objfile;
17449   struct type *type;		/* Type that this function returns.  */
17450   struct type *ftype;		/* Function that returns above type.  */
17451   struct attribute *attr;
17452 
17453   type = die_type (die, cu);
17454 
17455   /* The die_type call above may have already set the type for this DIE.  */
17456   ftype = get_die_type (die, cu);
17457   if (ftype)
17458     return ftype;
17459 
17460   ftype = lookup_function_type (type);
17461 
17462   if (prototyped_function_p (die, cu))
17463     ftype->set_is_prototyped (true);
17464 
17465   /* Store the calling convention in the type if it's available in
17466      the subroutine die.  Otherwise set the calling convention to
17467      the default value DW_CC_normal.  */
17468   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17469   if (attr != nullptr
17470       && is_valid_DW_AT_calling_convention_for_subroutine (attr->constant_value (0)))
17471     TYPE_CALLING_CONVENTION (ftype)
17472       = (enum dwarf_calling_convention) attr->constant_value (0);
17473   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17474     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17475   else
17476     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17477 
17478   /* Record whether the function returns normally to its caller or not
17479      if the DWARF producer set that information.  */
17480   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17481   if (attr && attr->as_boolean ())
17482     TYPE_NO_RETURN (ftype) = 1;
17483 
17484   /* We need to add the subroutine type to the die immediately so
17485      we don't infinitely recurse when dealing with parameters
17486      declared as the same subroutine type.  */
17487   set_die_type (die, ftype, cu);
17488 
17489   if (die->child != NULL)
17490     {
17491       struct type *void_type = objfile_type (objfile)->builtin_void;
17492       struct die_info *child_die;
17493       int nparams, iparams;
17494 
17495       /* Count the number of parameters.
17496 	 FIXME: GDB currently ignores vararg functions, but knows about
17497 	 vararg member functions.  */
17498       nparams = 0;
17499       child_die = die->child;
17500       while (child_die && child_die->tag)
17501 	{
17502 	  if (child_die->tag == DW_TAG_formal_parameter)
17503 	    nparams++;
17504 	  else if (child_die->tag == DW_TAG_unspecified_parameters)
17505 	    ftype->set_has_varargs (true);
17506 
17507 	  child_die = child_die->sibling;
17508 	}
17509 
17510       /* Allocate storage for parameters and fill them in.  */
17511       ftype->set_num_fields (nparams);
17512       ftype->set_fields
17513 	((struct field *) TYPE_ZALLOC (ftype, nparams * sizeof (struct field)));
17514 
17515       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17516 	 even if we error out during the parameters reading below.  */
17517       for (iparams = 0; iparams < nparams; iparams++)
17518 	ftype->field (iparams).set_type (void_type);
17519 
17520       iparams = 0;
17521       child_die = die->child;
17522       while (child_die && child_die->tag)
17523 	{
17524 	  if (child_die->tag == DW_TAG_formal_parameter)
17525 	    {
17526 	      struct type *arg_type;
17527 
17528 	      /* DWARF version 2 has no clean way to discern C++
17529 		 static and non-static member functions.  G++ helps
17530 		 GDB by marking the first parameter for non-static
17531 		 member functions (which is the this pointer) as
17532 		 artificial.  We pass this information to
17533 		 dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17534 
17535 		 DWARF version 3 added DW_AT_object_pointer, which GCC
17536 		 4.5 does not yet generate.  */
17537 	      attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17538 	      if (attr != nullptr)
17539 		TYPE_FIELD_ARTIFICIAL (ftype, iparams) = attr->as_boolean ();
17540 	      else
17541 		TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17542 	      arg_type = die_type (child_die, cu);
17543 
17544 	      /* RealView does not mark THIS as const, which the testsuite
17545 		 expects.  GCC marks THIS as const in method definitions,
17546 		 but not in the class specifications (GCC PR 43053).  */
17547 	      if (cu->per_cu->lang == language_cplus
17548 		  && !TYPE_CONST (arg_type)
17549 		  && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17550 		{
17551 		  int is_this = 0;
17552 		  struct dwarf2_cu *arg_cu = cu;
17553 		  const char *name = dwarf2_name (child_die, cu);
17554 
17555 		  attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17556 		  if (attr != nullptr)
17557 		    {
17558 		      /* If the compiler emits this, use it.  */
17559 		      if (follow_die_ref (die, attr, &arg_cu) == child_die)
17560 			is_this = 1;
17561 		    }
17562 		  else if (name && strcmp (name, "this") == 0)
17563 		    /* Function definitions will have the argument names.  */
17564 		    is_this = 1;
17565 		  else if (name == NULL && iparams == 0)
17566 		    /* Declarations may not have the names, so like
17567 		       elsewhere in GDB, assume an artificial first
17568 		       argument is "this".  */
17569 		    is_this = 1;
17570 
17571 		  if (is_this)
17572 		    arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17573 					     arg_type, 0);
17574 		}
17575 
17576 	      ftype->field (iparams).set_type (arg_type);
17577 	      iparams++;
17578 	    }
17579 	  child_die = child_die->sibling;
17580 	}
17581     }
17582 
17583   return ftype;
17584 }
17585 
17586 static struct type *
17587 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17588 {
17589   struct objfile *objfile = cu->per_objfile->objfile;
17590   const char *name = NULL;
17591   struct type *this_type, *target_type;
17592 
17593   name = dwarf2_full_name (NULL, die, cu);
17594   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17595   this_type->set_target_is_stub (true);
17596   set_die_type (die, this_type, cu);
17597   target_type = die_type (die, cu);
17598   if (target_type != this_type)
17599     TYPE_TARGET_TYPE (this_type) = target_type;
17600   else
17601     {
17602       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17603 	 spec and cause infinite loops in GDB.  */
17604       complaint (_("Self-referential DW_TAG_typedef "
17605 		   "- DIE at %s [in module %s]"),
17606 		 sect_offset_str (die->sect_off), objfile_name (objfile));
17607       TYPE_TARGET_TYPE (this_type) = NULL;
17608     }
17609   if (name == NULL)
17610     {
17611       /* Gcc-7 and before supports -feliminate-dwarf2-dups, which generates
17612 	 anonymous typedefs, which is, strictly speaking, invalid DWARF.
17613 	 Handle these by just returning the target type, rather than
17614 	 constructing an anonymous typedef type and trying to handle this
17615 	 elsewhere.  */
17616       set_die_type (die, target_type, cu);
17617       return target_type;
17618     }
17619   return this_type;
17620 }
17621 
17622 /* Helper for get_dwarf2_rational_constant that computes the value of
17623    a given gmp_mpz given an attribute.  */
17624 
17625 static void
17626 get_mpz (struct dwarf2_cu *cu, gdb_mpz *value, struct attribute *attr)
17627 {
17628   /* GCC will sometimes emit a 16-byte constant value as a DWARF
17629      location expression that pushes an implicit value.  */
17630   if (attr->form == DW_FORM_exprloc)
17631     {
17632       dwarf_block *blk = attr->as_block ();
17633       if (blk->size > 0 && blk->data[0] == DW_OP_implicit_value)
17634 	{
17635 	  uint64_t len;
17636 	  const gdb_byte *ptr = safe_read_uleb128 (blk->data + 1,
17637 						   blk->data + blk->size,
17638 						   &len);
17639 	  if (ptr - blk->data + len <= blk->size)
17640 	    {
17641 	      mpz_import (value->val, len,
17642 			  bfd_big_endian (cu->per_objfile->objfile->obfd) ? 1 : -1,
17643 			  1, 0, 0, ptr);
17644 	      return;
17645 	    }
17646 	}
17647 
17648       /* On failure set it to 1.  */
17649       *value = gdb_mpz (1);
17650     }
17651   else if (attr->form_is_block ())
17652     {
17653       dwarf_block *blk = attr->as_block ();
17654       mpz_import (value->val, blk->size,
17655 		  bfd_big_endian (cu->per_objfile->objfile->obfd) ? 1 : -1,
17656 		  1, 0, 0, blk->data);
17657     }
17658   else
17659     *value = gdb_mpz (attr->constant_value (1));
17660 }
17661 
17662 /* Assuming DIE is a rational DW_TAG_constant, read the DIE's
17663    numerator and denominator into NUMERATOR and DENOMINATOR (resp).
17664 
17665    If the numerator and/or numerator attribute is missing,
17666    a complaint is filed, and NUMERATOR and DENOMINATOR are left
17667    untouched.  */
17668 
17669 static void
17670 get_dwarf2_rational_constant (struct die_info *die, struct dwarf2_cu *cu,
17671 			      gdb_mpz *numerator, gdb_mpz *denominator)
17672 {
17673   struct attribute *num_attr, *denom_attr;
17674 
17675   num_attr = dwarf2_attr (die, DW_AT_GNU_numerator, cu);
17676   if (num_attr == nullptr)
17677     complaint (_("DW_AT_GNU_numerator missing in %s DIE at %s"),
17678 	       dwarf_tag_name (die->tag), sect_offset_str (die->sect_off));
17679 
17680   denom_attr = dwarf2_attr (die, DW_AT_GNU_denominator, cu);
17681   if (denom_attr == nullptr)
17682     complaint (_("DW_AT_GNU_denominator missing in %s DIE at %s"),
17683 	       dwarf_tag_name (die->tag), sect_offset_str (die->sect_off));
17684 
17685   if (num_attr == nullptr || denom_attr == nullptr)
17686     return;
17687 
17688   get_mpz (cu, numerator, num_attr);
17689   get_mpz (cu, denominator, denom_attr);
17690 }
17691 
17692 /* Same as get_dwarf2_rational_constant, but extracting an unsigned
17693    rational constant, rather than a signed one.
17694 
17695    If the rational constant has a negative value, a complaint
17696    is filed, and NUMERATOR and DENOMINATOR are left untouched.  */
17697 
17698 static void
17699 get_dwarf2_unsigned_rational_constant (struct die_info *die,
17700 				       struct dwarf2_cu *cu,
17701 				       gdb_mpz *numerator,
17702 				       gdb_mpz *denominator)
17703 {
17704   gdb_mpz num (1);
17705   gdb_mpz denom (1);
17706 
17707   get_dwarf2_rational_constant (die, cu, &num, &denom);
17708   if (mpz_sgn (num.val) == -1 && mpz_sgn (denom.val) == -1)
17709     {
17710       mpz_neg (num.val, num.val);
17711       mpz_neg (denom.val, denom.val);
17712     }
17713   else if (mpz_sgn (num.val) == -1)
17714     {
17715       complaint (_("unexpected negative value for DW_AT_GNU_numerator"
17716 		   " in DIE at %s"),
17717 		 sect_offset_str (die->sect_off));
17718       return;
17719     }
17720   else if (mpz_sgn (denom.val) == -1)
17721     {
17722       complaint (_("unexpected negative value for DW_AT_GNU_denominator"
17723 		   " in DIE at %s"),
17724 		 sect_offset_str (die->sect_off));
17725       return;
17726     }
17727 
17728   *numerator = std::move (num);
17729   *denominator = std::move (denom);
17730 }
17731 
17732 /* Assuming that ENCODING is a string whose contents starting at the
17733    K'th character is "_nn" where "nn" is a decimal number, scan that
17734    number and set RESULT to the value. K is updated to point to the
17735    character immediately following the number.
17736 
17737    If the string does not conform to the format described above, false
17738    is returned, and K may or may not be changed.  */
17739 
17740 static bool
17741 ada_get_gnat_encoded_number (const char *encoding, int &k, gdb_mpz *result)
17742 {
17743   /* The next character should be an underscore ('_') followed
17744      by a digit.  */
17745   if (encoding[k] != '_' || !isdigit (encoding[k + 1]))
17746     return false;
17747 
17748   /* Skip the underscore.  */
17749   k++;
17750   int start = k;
17751 
17752   /* Determine the number of digits for our number.  */
17753   while (isdigit (encoding[k]))
17754     k++;
17755   if (k == start)
17756     return false;
17757 
17758   std::string copy (&encoding[start], k - start);
17759   if (mpz_set_str (result->val, copy.c_str (), 10) == -1)
17760     return false;
17761 
17762   return true;
17763 }
17764 
17765 /* Scan two numbers from ENCODING at OFFSET, assuming the string is of
17766    the form _NN_DD, where NN and DD are decimal numbers.  Set NUM and
17767    DENOM, update OFFSET, and return true on success.  Return false on
17768    failure.  */
17769 
17770 static bool
17771 ada_get_gnat_encoded_ratio (const char *encoding, int &offset,
17772 			    gdb_mpz *num, gdb_mpz *denom)
17773 {
17774   if (!ada_get_gnat_encoded_number (encoding, offset, num))
17775     return false;
17776   return ada_get_gnat_encoded_number (encoding, offset, denom);
17777 }
17778 
17779 /* Assuming DIE corresponds to a fixed point type, finish the creation
17780    of the corresponding TYPE by setting its type-specific data.  CU is
17781    the DIE's CU.  SUFFIX is the "XF" type name suffix coming from GNAT
17782    encodings.  It is nullptr if the GNAT encoding should be
17783    ignored.  */
17784 
17785 static void
17786 finish_fixed_point_type (struct type *type, const char *suffix,
17787 			 struct die_info *die, struct dwarf2_cu *cu)
17788 {
17789   gdb_assert (type->code () == TYPE_CODE_FIXED_POINT
17790 	      && TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_FIXED_POINT);
17791 
17792   /* If GNAT encodings are preferred, don't examine the
17793      attributes.  */
17794   struct attribute *attr = nullptr;
17795   if (suffix == nullptr)
17796     {
17797       attr = dwarf2_attr (die, DW_AT_binary_scale, cu);
17798       if (attr == nullptr)
17799 	attr = dwarf2_attr (die, DW_AT_decimal_scale, cu);
17800       if (attr == nullptr)
17801 	attr = dwarf2_attr (die, DW_AT_small, cu);
17802     }
17803 
17804   /* Numerator and denominator of our fixed-point type's scaling factor.
17805      The default is a scaling factor of 1, which we use as a fallback
17806      when we are not able to decode it (problem with the debugging info,
17807      unsupported forms, bug in GDB, etc...).  Using that as the default
17808      allows us to at least print the unscaled value, which might still
17809      be useful to a user.  */
17810   gdb_mpz scale_num (1);
17811   gdb_mpz scale_denom (1);
17812 
17813   if (attr == nullptr)
17814     {
17815       int offset = 0;
17816       if (suffix != nullptr
17817 	  && ada_get_gnat_encoded_ratio (suffix, offset, &scale_num,
17818 					 &scale_denom)
17819 	  /* The number might be encoded as _nn_dd_nn_dd, where the
17820 	     second ratio is the 'small value.  In this situation, we
17821 	     want the second value.  */
17822 	  && (suffix[offset] != '_'
17823 	      || ada_get_gnat_encoded_ratio (suffix, offset, &scale_num,
17824 					     &scale_denom)))
17825 	{
17826 	  /* Found it.  */
17827 	}
17828       else
17829 	{
17830 	  /* Scaling factor not found.  Assume a scaling factor of 1,
17831 	     and hope for the best.  At least the user will be able to
17832 	     see the encoded value.  */
17833 	  scale_num = 1;
17834 	  scale_denom = 1;
17835 	  complaint (_("no scale found for fixed-point type (DIE at %s)"),
17836 		     sect_offset_str (die->sect_off));
17837 	}
17838     }
17839   else if (attr->name == DW_AT_binary_scale)
17840     {
17841       LONGEST scale_exp = attr->constant_value (0);
17842       gdb_mpz *num_or_denom = scale_exp > 0 ? &scale_num : &scale_denom;
17843 
17844       mpz_mul_2exp (num_or_denom->val, num_or_denom->val, std::abs (scale_exp));
17845     }
17846   else if (attr->name == DW_AT_decimal_scale)
17847     {
17848       LONGEST scale_exp = attr->constant_value (0);
17849       gdb_mpz *num_or_denom = scale_exp > 0 ? &scale_num : &scale_denom;
17850 
17851       mpz_ui_pow_ui (num_or_denom->val, 10, std::abs (scale_exp));
17852     }
17853   else if (attr->name == DW_AT_small)
17854     {
17855       struct die_info *scale_die;
17856       struct dwarf2_cu *scale_cu = cu;
17857 
17858       scale_die = follow_die_ref (die, attr, &scale_cu);
17859       if (scale_die->tag == DW_TAG_constant)
17860 	get_dwarf2_unsigned_rational_constant (scale_die, scale_cu,
17861 					       &scale_num, &scale_denom);
17862       else
17863 	complaint (_("%s DIE not supported as target of DW_AT_small attribute"
17864 		     " (DIE at %s)"),
17865 		   dwarf_tag_name (die->tag), sect_offset_str (die->sect_off));
17866     }
17867   else
17868     {
17869       complaint (_("unsupported scale attribute %s for fixed-point type"
17870 		   " (DIE at %s)"),
17871 		 dwarf_attr_name (attr->name),
17872 		 sect_offset_str (die->sect_off));
17873     }
17874 
17875   gdb_mpq &scaling_factor = type->fixed_point_info ().scaling_factor;
17876   mpz_set (mpq_numref (scaling_factor.val), scale_num.val);
17877   mpz_set (mpq_denref (scaling_factor.val), scale_denom.val);
17878   mpq_canonicalize (scaling_factor.val);
17879 }
17880 
17881 /* The gnat-encoding suffix for fixed point.  */
17882 
17883 #define GNAT_FIXED_POINT_SUFFIX "___XF_"
17884 
17885 /* If NAME encodes an Ada fixed-point type, return a pointer to the
17886    "XF" suffix of the name.  The text after this is what encodes the
17887    'small and 'delta information.  Otherwise, return nullptr.  */
17888 
17889 static const char *
17890 gnat_encoded_fixed_point_type_info (const char *name)
17891 {
17892   return strstr (name, GNAT_FIXED_POINT_SUFFIX);
17893 }
17894 
17895 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17896    (which may be different from NAME) to the architecture back-end to allow
17897    it to guess the correct format if necessary.  */
17898 
17899 static struct type *
17900 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17901 			const char *name_hint, enum bfd_endian byte_order)
17902 {
17903   struct gdbarch *gdbarch = objfile->arch ();
17904   const struct floatformat **format;
17905   struct type *type;
17906 
17907   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17908   if (format)
17909     type = init_float_type (objfile, bits, name, format, byte_order);
17910   else
17911     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17912 
17913   return type;
17914 }
17915 
17916 /* Allocate an integer type of size BITS and name NAME.  */
17917 
17918 static struct type *
17919 dwarf2_init_integer_type (struct dwarf2_cu *cu, struct objfile *objfile,
17920 			  int bits, int unsigned_p, const char *name)
17921 {
17922   struct type *type;
17923 
17924   /* Versions of Intel's C Compiler generate an integer type called "void"
17925      instead of using DW_TAG_unspecified_type.  This has been seen on
17926      at least versions 14, 17, and 18.  */
17927   if (bits == 0 && producer_is_icc (cu) && name != nullptr
17928       && strcmp (name, "void") == 0)
17929     type = objfile_type (objfile)->builtin_void;
17930   else
17931     type = init_integer_type (objfile, bits, unsigned_p, name);
17932 
17933   return type;
17934 }
17935 
17936 /* Return true if DIE has a DW_AT_small attribute whose value is
17937    a constant rational, where both the numerator and denominator
17938    are equal to zero.
17939 
17940    CU is the DIE's Compilation Unit.  */
17941 
17942 static bool
17943 has_zero_over_zero_small_attribute (struct die_info *die,
17944 				    struct dwarf2_cu *cu)
17945 {
17946   struct attribute *attr = dwarf2_attr (die, DW_AT_small, cu);
17947   if (attr == nullptr)
17948     return false;
17949 
17950   struct dwarf2_cu *scale_cu = cu;
17951   struct die_info *scale_die
17952     = follow_die_ref (die, attr, &scale_cu);
17953 
17954   if (scale_die->tag != DW_TAG_constant)
17955     return false;
17956 
17957   gdb_mpz num (1), denom (1);
17958   get_dwarf2_rational_constant (scale_die, cu, &num, &denom);
17959   return mpz_sgn (num.val) == 0 && mpz_sgn (denom.val) == 0;
17960 }
17961 
17962 /* Initialise and return a floating point type of size BITS suitable for
17963    use as a component of a complex number.  The NAME_HINT is passed through
17964    when initialising the floating point type and is the name of the complex
17965    type.
17966 
17967    As DWARF doesn't currently provide an explicit name for the components
17968    of a complex number, but it can be helpful to have these components
17969    named, we try to select a suitable name based on the size of the
17970    component.  */
17971 static struct type *
17972 dwarf2_init_complex_target_type (struct dwarf2_cu *cu,
17973 				 struct objfile *objfile,
17974 				 int bits, const char *name_hint,
17975 				 enum bfd_endian byte_order)
17976 {
17977   gdbarch *gdbarch = objfile->arch ();
17978   struct type *tt = nullptr;
17979 
17980   /* Try to find a suitable floating point builtin type of size BITS.
17981      We're going to use the name of this type as the name for the complex
17982      target type that we are about to create.  */
17983   switch (cu->per_cu->lang)
17984     {
17985     case language_fortran:
17986       switch (bits)
17987 	{
17988 	case 32:
17989 	  tt = builtin_f_type (gdbarch)->builtin_real;
17990 	  break;
17991 	case 64:
17992 	  tt = builtin_f_type (gdbarch)->builtin_real_s8;
17993 	  break;
17994 	case 96:	/* The x86-32 ABI specifies 96-bit long double.  */
17995 	case 128:
17996 	  tt = builtin_f_type (gdbarch)->builtin_real_s16;
17997 	  break;
17998 	}
17999       break;
18000     default:
18001       switch (bits)
18002 	{
18003 	case 32:
18004 	  tt = builtin_type (gdbarch)->builtin_float;
18005 	  break;
18006 	case 64:
18007 	  tt = builtin_type (gdbarch)->builtin_double;
18008 	  break;
18009 	case 96:	/* The x86-32 ABI specifies 96-bit long double.  */
18010 	case 128:
18011 	  tt = builtin_type (gdbarch)->builtin_long_double;
18012 	  break;
18013 	}
18014       break;
18015     }
18016 
18017   /* If the type we found doesn't match the size we were looking for, then
18018      pretend we didn't find a type at all, the complex target type we
18019      create will then be nameless.  */
18020   if (tt != nullptr && TYPE_LENGTH (tt) * TARGET_CHAR_BIT != bits)
18021     tt = nullptr;
18022 
18023   const char *name = (tt == nullptr) ? nullptr : tt->name ();
18024   return dwarf2_init_float_type (objfile, bits, name, name_hint, byte_order);
18025 }
18026 
18027 /* Find a representation of a given base type and install
18028    it in the TYPE field of the die.  */
18029 
18030 static struct type *
18031 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
18032 {
18033   struct objfile *objfile = cu->per_objfile->objfile;
18034   struct type *type;
18035   struct attribute *attr;
18036   int encoding = 0, bits = 0;
18037   const char *name;
18038   gdbarch *arch;
18039 
18040   attr = dwarf2_attr (die, DW_AT_encoding, cu);
18041   if (attr != nullptr && attr->form_is_constant ())
18042     encoding = attr->constant_value (0);
18043   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
18044   if (attr != nullptr)
18045     bits = attr->constant_value (0) * TARGET_CHAR_BIT;
18046   name = dwarf2_name (die, cu);
18047   if (!name)
18048     complaint (_("DW_AT_name missing from DW_TAG_base_type"));
18049 
18050   arch = objfile->arch ();
18051   enum bfd_endian byte_order = gdbarch_byte_order (arch);
18052 
18053   attr = dwarf2_attr (die, DW_AT_endianity, cu);
18054   if (attr != nullptr && attr->form_is_constant ())
18055     {
18056       int endianity = attr->constant_value (0);
18057 
18058       switch (endianity)
18059 	{
18060 	case DW_END_big:
18061 	  byte_order = BFD_ENDIAN_BIG;
18062 	  break;
18063 	case DW_END_little:
18064 	  byte_order = BFD_ENDIAN_LITTLE;
18065 	  break;
18066 	default:
18067 	  complaint (_("DW_AT_endianity has unrecognized value %d"), endianity);
18068 	  break;
18069 	}
18070     }
18071 
18072   if ((encoding == DW_ATE_signed_fixed || encoding == DW_ATE_unsigned_fixed)
18073       && cu->per_cu->lang == language_ada
18074       && has_zero_over_zero_small_attribute (die, cu))
18075     {
18076       /* brobecker/2018-02-24: This is a fixed point type for which
18077 	 the scaling factor is represented as fraction whose value
18078 	 does not make sense (zero divided by zero), so we should
18079 	 normally never see these.  However, there is a small category
18080 	 of fixed point types for which GNAT is unable to provide
18081 	 the scaling factor via the standard DWARF mechanisms, and
18082 	 for which the info is provided via the GNAT encodings instead.
18083 	 This is likely what this DIE is about.  */
18084       encoding = (encoding == DW_ATE_signed_fixed
18085 		  ? DW_ATE_signed
18086 		  : DW_ATE_unsigned);
18087     }
18088 
18089   /* With GNAT encodings, fixed-point information will be encoded in
18090      the type name.  Note that this can also occur with the above
18091      zero-over-zero case, which is why this is a separate "if" rather
18092      than an "else if".  */
18093   const char *gnat_encoding_suffix = nullptr;
18094   if ((encoding == DW_ATE_signed || encoding == DW_ATE_unsigned)
18095       && cu->per_cu->lang == language_ada
18096       && name != nullptr)
18097     {
18098       gnat_encoding_suffix = gnat_encoded_fixed_point_type_info (name);
18099       if (gnat_encoding_suffix != nullptr)
18100 	{
18101 	  gdb_assert (startswith (gnat_encoding_suffix,
18102 				  GNAT_FIXED_POINT_SUFFIX));
18103 	  name = obstack_strndup (&cu->per_objfile->objfile->objfile_obstack,
18104 				  name, gnat_encoding_suffix - name);
18105 	  /* Use -1 here so that SUFFIX points at the "_" after the
18106 	     "XF".  */
18107 	  gnat_encoding_suffix += strlen (GNAT_FIXED_POINT_SUFFIX) - 1;
18108 
18109 	  encoding = (encoding == DW_ATE_signed
18110 		      ? DW_ATE_signed_fixed
18111 		      : DW_ATE_unsigned_fixed);
18112 	}
18113     }
18114 
18115   switch (encoding)
18116     {
18117       case DW_ATE_address:
18118 	/* Turn DW_ATE_address into a void * pointer.  */
18119 	type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
18120 	type = init_pointer_type (objfile, bits, name, type);
18121 	break;
18122       case DW_ATE_boolean:
18123 	type = init_boolean_type (objfile, bits, 1, name);
18124 	break;
18125       case DW_ATE_complex_float:
18126 	type = dwarf2_init_complex_target_type (cu, objfile, bits / 2, name,
18127 						byte_order);
18128 	if (type->code () == TYPE_CODE_ERROR)
18129 	  {
18130 	    if (name == nullptr)
18131 	      {
18132 		struct obstack *obstack
18133 		  = &cu->per_objfile->objfile->objfile_obstack;
18134 		name = obconcat (obstack, "_Complex ", type->name (),
18135 				 nullptr);
18136 	      }
18137 	    type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
18138 	  }
18139 	else
18140 	  type = init_complex_type (name, type);
18141 	break;
18142       case DW_ATE_decimal_float:
18143 	type = init_decfloat_type (objfile, bits, name);
18144 	break;
18145       case DW_ATE_float:
18146 	type = dwarf2_init_float_type (objfile, bits, name, name, byte_order);
18147 	break;
18148       case DW_ATE_signed:
18149 	type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
18150 	break;
18151       case DW_ATE_unsigned:
18152 	if (cu->per_cu->lang == language_fortran
18153 	    && name
18154 	    && startswith (name, "character("))
18155 	  type = init_character_type (objfile, bits, 1, name);
18156 	else
18157 	  type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
18158 	break;
18159       case DW_ATE_signed_char:
18160 	if (cu->per_cu->lang == language_ada
18161 	    || cu->per_cu->lang == language_m2
18162 	    || cu->per_cu->lang == language_pascal
18163 	    || cu->per_cu->lang == language_fortran)
18164 	  type = init_character_type (objfile, bits, 0, name);
18165 	else
18166 	  type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
18167 	break;
18168       case DW_ATE_unsigned_char:
18169 	if (cu->per_cu->lang == language_ada
18170 	    || cu->per_cu->lang == language_m2
18171 	    || cu->per_cu->lang == language_pascal
18172 	    || cu->per_cu->lang == language_fortran
18173 	    || cu->per_cu->lang == language_rust)
18174 	  type = init_character_type (objfile, bits, 1, name);
18175 	else
18176 	  type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
18177 	break;
18178       case DW_ATE_UTF:
18179 	{
18180 	  if (bits == 16)
18181 	    type = builtin_type (arch)->builtin_char16;
18182 	  else if (bits == 32)
18183 	    type = builtin_type (arch)->builtin_char32;
18184 	  else
18185 	    {
18186 	      complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
18187 			 bits);
18188 	      type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
18189 	    }
18190 	  return set_die_type (die, type, cu);
18191 	}
18192 	break;
18193       case DW_ATE_signed_fixed:
18194 	type = init_fixed_point_type (objfile, bits, 0, name);
18195 	finish_fixed_point_type (type, gnat_encoding_suffix, die, cu);
18196 	break;
18197       case DW_ATE_unsigned_fixed:
18198 	type = init_fixed_point_type (objfile, bits, 1, name);
18199 	finish_fixed_point_type (type, gnat_encoding_suffix, die, cu);
18200 	break;
18201 
18202       default:
18203 	complaint (_("unsupported DW_AT_encoding: '%s'"),
18204 		   dwarf_type_encoding_name (encoding));
18205 	type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
18206 	break;
18207     }
18208 
18209   if (name && strcmp (name, "char") == 0)
18210     type->set_has_no_signedness (true);
18211 
18212   maybe_set_alignment (cu, die, type);
18213 
18214   type->set_endianity_is_not_default (gdbarch_byte_order (arch) != byte_order);
18215 
18216   if (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_INT)
18217     {
18218       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
18219       if (attr != nullptr && attr->as_unsigned () <= 8 * TYPE_LENGTH (type))
18220 	{
18221 	  unsigned real_bit_size = attr->as_unsigned ();
18222 	  attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
18223 	  /* Only use the attributes if they make sense together.  */
18224 	  if (attr == nullptr
18225 	      || (attr->as_unsigned () + real_bit_size
18226 		  <= 8 * TYPE_LENGTH (type)))
18227 	    {
18228 	      TYPE_MAIN_TYPE (type)->type_specific.int_stuff.bit_size
18229 		= real_bit_size;
18230 	      if (attr != nullptr)
18231 		TYPE_MAIN_TYPE (type)->type_specific.int_stuff.bit_offset
18232 		  = attr->as_unsigned ();
18233 	    }
18234 	}
18235     }
18236 
18237   return set_die_type (die, type, cu);
18238 }
18239 
18240 /* A helper function that returns the name of DIE, if it refers to a
18241    variable declaration.  */
18242 
18243 static const char *
18244 var_decl_name (struct die_info *die, struct dwarf2_cu *cu)
18245 {
18246   if (die->tag != DW_TAG_variable)
18247     return nullptr;
18248 
18249   attribute *attr = dwarf2_attr (die, DW_AT_declaration, cu);
18250   if (attr == nullptr || !attr->as_boolean ())
18251     return nullptr;
18252 
18253   attr = dwarf2_attr (die, DW_AT_name, cu);
18254   if (attr == nullptr)
18255     return nullptr;
18256   return attr->as_string ();
18257 }
18258 
18259 /* Parse dwarf attribute if it's a block, reference or constant and put the
18260    resulting value of the attribute into struct bound_prop.
18261    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
18262 
18263 static int
18264 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
18265 		      struct dwarf2_cu *cu, struct dynamic_prop *prop,
18266 		      struct type *default_type)
18267 {
18268   struct dwarf2_property_baton *baton;
18269   dwarf2_per_objfile *per_objfile = cu->per_objfile;
18270   struct objfile *objfile = per_objfile->objfile;
18271   struct obstack *obstack = &objfile->objfile_obstack;
18272 
18273   gdb_assert (default_type != NULL);
18274 
18275   if (attr == NULL || prop == NULL)
18276     return 0;
18277 
18278   if (attr->form_is_block ())
18279     {
18280       baton = XOBNEW (obstack, struct dwarf2_property_baton);
18281       baton->property_type = default_type;
18282       baton->locexpr.per_cu = cu->per_cu;
18283       baton->locexpr.per_objfile = per_objfile;
18284 
18285       struct dwarf_block *block;
18286       if (attr->form == DW_FORM_data16)
18287 	{
18288 	  size_t data_size = 16;
18289 	  block = XOBNEW (obstack, struct dwarf_block);
18290 	  block->size = (data_size
18291 			 + 2 /* Extra bytes for DW_OP and arg.  */);
18292 	  gdb_byte *data = XOBNEWVEC (obstack, gdb_byte, block->size);
18293 	  data[0] = DW_OP_implicit_value;
18294 	  data[1] = data_size;
18295 	  memcpy (&data[2], attr->as_block ()->data, data_size);
18296 	  block->data = data;
18297 	}
18298       else
18299 	block = attr->as_block ();
18300 
18301       baton->locexpr.size = block->size;
18302       baton->locexpr.data = block->data;
18303       switch (attr->name)
18304 	{
18305 	case DW_AT_string_length:
18306 	  baton->locexpr.is_reference = true;
18307 	  break;
18308 	default:
18309 	  baton->locexpr.is_reference = false;
18310 	  break;
18311 	}
18312 
18313       prop->set_locexpr (baton);
18314       gdb_assert (prop->baton () != NULL);
18315     }
18316   else if (attr->form_is_ref ())
18317     {
18318       struct dwarf2_cu *target_cu = cu;
18319       struct die_info *target_die;
18320       struct attribute *target_attr;
18321 
18322       target_die = follow_die_ref (die, attr, &target_cu);
18323       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
18324       if (target_attr == NULL)
18325 	target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
18326 				   target_cu);
18327       if (target_attr == NULL)
18328 	{
18329 	  const char *name = var_decl_name (target_die, target_cu);
18330 	  if (name != nullptr)
18331 	    {
18332 	      prop->set_variable_name (name);
18333 	      return 1;
18334 	    }
18335 	  return 0;
18336 	}
18337 
18338       switch (target_attr->name)
18339 	{
18340 	  case DW_AT_location:
18341 	    if (target_attr->form_is_section_offset ())
18342 	      {
18343 		baton = XOBNEW (obstack, struct dwarf2_property_baton);
18344 		baton->property_type = die_type (target_die, target_cu);
18345 		fill_in_loclist_baton (cu, &baton->loclist, target_attr);
18346 		prop->set_loclist (baton);
18347 		gdb_assert (prop->baton () != NULL);
18348 	      }
18349 	    else if (target_attr->form_is_block ())
18350 	      {
18351 		baton = XOBNEW (obstack, struct dwarf2_property_baton);
18352 		baton->property_type = die_type (target_die, target_cu);
18353 		baton->locexpr.per_cu = cu->per_cu;
18354 		baton->locexpr.per_objfile = per_objfile;
18355 		struct dwarf_block *block = target_attr->as_block ();
18356 		baton->locexpr.size = block->size;
18357 		baton->locexpr.data = block->data;
18358 		baton->locexpr.is_reference = true;
18359 		prop->set_locexpr (baton);
18360 		gdb_assert (prop->baton () != NULL);
18361 	      }
18362 	    else
18363 	      {
18364 		dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18365 						       "dynamic property");
18366 		return 0;
18367 	      }
18368 	    break;
18369 	  case DW_AT_data_member_location:
18370 	    {
18371 	      LONGEST offset;
18372 
18373 	      if (!handle_data_member_location (target_die, target_cu,
18374 						&offset))
18375 		return 0;
18376 
18377 	      baton = XOBNEW (obstack, struct dwarf2_property_baton);
18378 	      baton->property_type = read_type_die (target_die->parent,
18379 						      target_cu);
18380 	      baton->offset_info.offset = offset;
18381 	      baton->offset_info.type = die_type (target_die, target_cu);
18382 	      prop->set_addr_offset (baton);
18383 	      break;
18384 	    }
18385 	}
18386     }
18387   else if (attr->form_is_constant ())
18388     prop->set_const_val (attr->constant_value (0));
18389   else
18390     {
18391       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
18392 					     dwarf2_name (die, cu));
18393       return 0;
18394     }
18395 
18396   return 1;
18397 }
18398 
18399 /* See read.h.  */
18400 
18401 struct type *
18402 dwarf2_per_objfile::int_type (int size_in_bytes, bool unsigned_p) const
18403 {
18404   struct type *int_type;
18405 
18406   /* Helper macro to examine the various builtin types.  */
18407 #define TRY_TYPE(F)							\
18408   int_type = (unsigned_p						\
18409 	      ? objfile_type (objfile)->builtin_unsigned_ ## F		\
18410 	      : objfile_type (objfile)->builtin_ ## F);			\
18411   if (int_type != NULL && TYPE_LENGTH (int_type) == size_in_bytes)	\
18412     return int_type
18413 
18414   TRY_TYPE (char);
18415   TRY_TYPE (short);
18416   TRY_TYPE (int);
18417   TRY_TYPE (long);
18418   TRY_TYPE (long_long);
18419 
18420 #undef TRY_TYPE
18421 
18422   gdb_assert_not_reached ("unable to find suitable integer type");
18423 }
18424 
18425 /* Read the DW_AT_type attribute for a sub-range.  If this attribute is not
18426    present (which is valid) then compute the default type based on the
18427    compilation units address size.  */
18428 
18429 static struct type *
18430 read_subrange_index_type (struct die_info *die, struct dwarf2_cu *cu)
18431 {
18432   struct type *index_type = die_type (die, cu);
18433 
18434   /* Dwarf-2 specifications explicitly allows to create subrange types
18435      without specifying a base type.
18436      In that case, the base type must be set to the type of
18437      the lower bound, upper bound or count, in that order, if any of these
18438      three attributes references an object that has a type.
18439      If no base type is found, the Dwarf-2 specifications say that
18440      a signed integer type of size equal to the size of an address should
18441      be used.
18442      For the following C code: `extern char gdb_int [];'
18443      GCC produces an empty range DIE.
18444      FIXME: muller/2010-05-28: Possible references to object for low bound,
18445      high bound or count are not yet handled by this code.  */
18446   if (index_type->code () == TYPE_CODE_VOID)
18447     index_type = cu->addr_sized_int_type (false);
18448 
18449   return index_type;
18450 }
18451 
18452 /* Read the given DW_AT_subrange DIE.  */
18453 
18454 static struct type *
18455 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
18456 {
18457   struct type *base_type, *orig_base_type;
18458   struct type *range_type;
18459   struct attribute *attr;
18460   struct dynamic_prop low, high;
18461   int low_default_is_valid;
18462   int high_bound_is_count = 0;
18463   const char *name;
18464   ULONGEST negative_mask;
18465 
18466   orig_base_type = read_subrange_index_type (die, cu);
18467 
18468   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
18469      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
18470      creating the range type, but we use the result of check_typedef
18471      when examining properties of the type.  */
18472   base_type = check_typedef (orig_base_type);
18473 
18474   /* The die_type call above may have already set the type for this DIE.  */
18475   range_type = get_die_type (die, cu);
18476   if (range_type)
18477     return range_type;
18478 
18479   high.set_const_val (0);
18480 
18481   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
18482      omitting DW_AT_lower_bound.  */
18483   switch (cu->per_cu->lang)
18484     {
18485     case language_c:
18486     case language_cplus:
18487       low.set_const_val (0);
18488       low_default_is_valid = 1;
18489       break;
18490     case language_fortran:
18491       low.set_const_val (1);
18492       low_default_is_valid = 1;
18493       break;
18494     case language_d:
18495     case language_objc:
18496     case language_rust:
18497       low.set_const_val (0);
18498       low_default_is_valid = (cu->header.version >= 4);
18499       break;
18500     case language_ada:
18501     case language_m2:
18502     case language_pascal:
18503       low.set_const_val (1);
18504       low_default_is_valid = (cu->header.version >= 4);
18505       break;
18506     default:
18507       low.set_const_val (0);
18508       low_default_is_valid = 0;
18509       break;
18510     }
18511 
18512   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
18513   if (attr != nullptr)
18514     attr_to_dynamic_prop (attr, die, cu, &low, base_type);
18515   else if (!low_default_is_valid)
18516     complaint (_("Missing DW_AT_lower_bound "
18517 				      "- DIE at %s [in module %s]"),
18518 	       sect_offset_str (die->sect_off),
18519 	       objfile_name (cu->per_objfile->objfile));
18520 
18521   struct attribute *attr_ub, *attr_count;
18522   attr = attr_ub = dwarf2_attr (die, DW_AT_upper_bound, cu);
18523   if (!attr_to_dynamic_prop (attr, die, cu, &high, base_type))
18524     {
18525       attr = attr_count = dwarf2_attr (die, DW_AT_count, cu);
18526       if (attr_to_dynamic_prop (attr, die, cu, &high, base_type))
18527 	{
18528 	  /* If bounds are constant do the final calculation here.  */
18529 	  if (low.kind () == PROP_CONST && high.kind () == PROP_CONST)
18530 	    high.set_const_val (low.const_val () + high.const_val () - 1);
18531 	  else
18532 	    high_bound_is_count = 1;
18533 	}
18534       else
18535 	{
18536 	  if (attr_ub != NULL)
18537 	    complaint (_("Unresolved DW_AT_upper_bound "
18538 			 "- DIE at %s [in module %s]"),
18539 		       sect_offset_str (die->sect_off),
18540 		       objfile_name (cu->per_objfile->objfile));
18541 	  if (attr_count != NULL)
18542 	    complaint (_("Unresolved DW_AT_count "
18543 			 "- DIE at %s [in module %s]"),
18544 		       sect_offset_str (die->sect_off),
18545 		       objfile_name (cu->per_objfile->objfile));
18546 	}
18547     }
18548 
18549   LONGEST bias = 0;
18550   struct attribute *bias_attr = dwarf2_attr (die, DW_AT_GNU_bias, cu);
18551   if (bias_attr != nullptr && bias_attr->form_is_constant ())
18552     bias = bias_attr->constant_value (0);
18553 
18554   /* Normally, the DWARF producers are expected to use a signed
18555      constant form (Eg. DW_FORM_sdata) to express negative bounds.
18556      But this is unfortunately not always the case, as witnessed
18557      with GCC, for instance, where the ambiguous DW_FORM_dataN form
18558      is used instead.  To work around that ambiguity, we treat
18559      the bounds as signed, and thus sign-extend their values, when
18560      the base type is signed.  */
18561   negative_mask =
18562     -((ULONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
18563   if (low.kind () == PROP_CONST
18564       && !base_type->is_unsigned () && (low.const_val () & negative_mask))
18565     low.set_const_val (low.const_val () | negative_mask);
18566   if (high.kind () == PROP_CONST
18567       && !base_type->is_unsigned () && (high.const_val () & negative_mask))
18568     high.set_const_val (high.const_val () | negative_mask);
18569 
18570   /* Check for bit and byte strides.  */
18571   struct dynamic_prop byte_stride_prop;
18572   attribute *attr_byte_stride = dwarf2_attr (die, DW_AT_byte_stride, cu);
18573   if (attr_byte_stride != nullptr)
18574     {
18575       struct type *prop_type = cu->addr_sized_int_type (false);
18576       attr_to_dynamic_prop (attr_byte_stride, die, cu, &byte_stride_prop,
18577 			    prop_type);
18578     }
18579 
18580   struct dynamic_prop bit_stride_prop;
18581   attribute *attr_bit_stride = dwarf2_attr (die, DW_AT_bit_stride, cu);
18582   if (attr_bit_stride != nullptr)
18583     {
18584       /* It only makes sense to have either a bit or byte stride.  */
18585       if (attr_byte_stride != nullptr)
18586 	{
18587 	  complaint (_("Found DW_AT_bit_stride and DW_AT_byte_stride "
18588 		       "- DIE at %s [in module %s]"),
18589 		     sect_offset_str (die->sect_off),
18590 		     objfile_name (cu->per_objfile->objfile));
18591 	  attr_bit_stride = nullptr;
18592 	}
18593       else
18594 	{
18595 	  struct type *prop_type = cu->addr_sized_int_type (false);
18596 	  attr_to_dynamic_prop (attr_bit_stride, die, cu, &bit_stride_prop,
18597 				prop_type);
18598 	}
18599     }
18600 
18601   if (attr_byte_stride != nullptr
18602       || attr_bit_stride != nullptr)
18603     {
18604       bool byte_stride_p = (attr_byte_stride != nullptr);
18605       struct dynamic_prop *stride
18606 	= byte_stride_p ? &byte_stride_prop : &bit_stride_prop;
18607 
18608       range_type
18609 	= create_range_type_with_stride (NULL, orig_base_type, &low,
18610 					 &high, bias, stride, byte_stride_p);
18611     }
18612   else
18613     range_type = create_range_type (NULL, orig_base_type, &low, &high, bias);
18614 
18615   if (high_bound_is_count)
18616     range_type->bounds ()->flag_upper_bound_is_count = 1;
18617 
18618   /* Ada expects an empty array on no boundary attributes.  */
18619   if (attr == NULL && cu->per_cu->lang != language_ada)
18620     range_type->bounds ()->high.set_undefined ();
18621 
18622   name = dwarf2_name (die, cu);
18623   if (name)
18624     range_type->set_name (name);
18625 
18626   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
18627   if (attr != nullptr)
18628     TYPE_LENGTH (range_type) = attr->constant_value (0);
18629 
18630   maybe_set_alignment (cu, die, range_type);
18631 
18632   set_die_type (die, range_type, cu);
18633 
18634   /* set_die_type should be already done.  */
18635   set_descriptive_type (range_type, die, cu);
18636 
18637   return range_type;
18638 }
18639 
18640 static struct type *
18641 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
18642 {
18643   struct type *type;
18644 
18645   type = init_type (cu->per_objfile->objfile, TYPE_CODE_VOID, 0, NULL);
18646   type->set_name (dwarf2_name (die, cu));
18647 
18648   /* In Ada, an unspecified type is typically used when the description
18649      of the type is deferred to a different unit.  When encountering
18650      such a type, we treat it as a stub, and try to resolve it later on,
18651      when needed.  */
18652   if (cu->per_cu->lang == language_ada)
18653     type->set_is_stub (true);
18654 
18655   return set_die_type (die, type, cu);
18656 }
18657 
18658 /* Read a single die and all its descendents.  Set the die's sibling
18659    field to NULL; set other fields in the die correctly, and set all
18660    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
18661    location of the info_ptr after reading all of those dies.  PARENT
18662    is the parent of the die in question.  */
18663 
18664 static struct die_info *
18665 read_die_and_children (const struct die_reader_specs *reader,
18666 		       const gdb_byte *info_ptr,
18667 		       const gdb_byte **new_info_ptr,
18668 		       struct die_info *parent)
18669 {
18670   struct die_info *die;
18671   const gdb_byte *cur_ptr;
18672 
18673   cur_ptr = read_full_die_1 (reader, &die, info_ptr, 0);
18674   if (die == NULL)
18675     {
18676       *new_info_ptr = cur_ptr;
18677       return NULL;
18678     }
18679   store_in_ref_table (die, reader->cu);
18680 
18681   if (die->has_children)
18682     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
18683   else
18684     {
18685       die->child = NULL;
18686       *new_info_ptr = cur_ptr;
18687     }
18688 
18689   die->sibling = NULL;
18690   die->parent = parent;
18691   return die;
18692 }
18693 
18694 /* Read a die, all of its descendents, and all of its siblings; set
18695    all of the fields of all of the dies correctly.  Arguments are as
18696    in read_die_and_children.  */
18697 
18698 static struct die_info *
18699 read_die_and_siblings_1 (const struct die_reader_specs *reader,
18700 			 const gdb_byte *info_ptr,
18701 			 const gdb_byte **new_info_ptr,
18702 			 struct die_info *parent)
18703 {
18704   struct die_info *first_die, *last_sibling;
18705   const gdb_byte *cur_ptr;
18706 
18707   cur_ptr = info_ptr;
18708   first_die = last_sibling = NULL;
18709 
18710   while (1)
18711     {
18712       struct die_info *die
18713 	= read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
18714 
18715       if (die == NULL)
18716 	{
18717 	  *new_info_ptr = cur_ptr;
18718 	  return first_die;
18719 	}
18720 
18721       if (!first_die)
18722 	first_die = die;
18723       else
18724 	last_sibling->sibling = die;
18725 
18726       last_sibling = die;
18727     }
18728 }
18729 
18730 /* Read a die, all of its descendents, and all of its siblings; set
18731    all of the fields of all of the dies correctly.  Arguments are as
18732    in read_die_and_children.
18733    This the main entry point for reading a DIE and all its children.  */
18734 
18735 static struct die_info *
18736 read_die_and_siblings (const struct die_reader_specs *reader,
18737 		       const gdb_byte *info_ptr,
18738 		       const gdb_byte **new_info_ptr,
18739 		       struct die_info *parent)
18740 {
18741   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
18742 						  new_info_ptr, parent);
18743 
18744   if (dwarf_die_debug)
18745     {
18746       fprintf_unfiltered (gdb_stdlog,
18747 			  "Read die from %s@0x%x of %s:\n",
18748 			  reader->die_section->get_name (),
18749 			  (unsigned) (info_ptr - reader->die_section->buffer),
18750 			  bfd_get_filename (reader->abfd));
18751       dump_die (die, dwarf_die_debug);
18752     }
18753 
18754   return die;
18755 }
18756 
18757 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
18758    attributes.
18759    The caller is responsible for filling in the extra attributes
18760    and updating (*DIEP)->num_attrs.
18761    Set DIEP to point to a newly allocated die with its information,
18762    except for its child, sibling, and parent fields.  */
18763 
18764 static const gdb_byte *
18765 read_full_die_1 (const struct die_reader_specs *reader,
18766 		 struct die_info **diep, const gdb_byte *info_ptr,
18767 		 int num_extra_attrs)
18768 {
18769   unsigned int abbrev_number, bytes_read, i;
18770   const struct abbrev_info *abbrev;
18771   struct die_info *die;
18772   struct dwarf2_cu *cu = reader->cu;
18773   bfd *abfd = reader->abfd;
18774 
18775   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
18776   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18777   info_ptr += bytes_read;
18778   if (!abbrev_number)
18779     {
18780       *diep = NULL;
18781       return info_ptr;
18782     }
18783 
18784   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
18785   if (!abbrev)
18786     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
18787 	   abbrev_number,
18788 	   bfd_get_filename (abfd));
18789 
18790   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
18791   die->sect_off = sect_off;
18792   die->tag = abbrev->tag;
18793   die->abbrev = abbrev_number;
18794   die->has_children = abbrev->has_children;
18795 
18796   /* Make the result usable.
18797      The caller needs to update num_attrs after adding the extra
18798      attributes.  */
18799   die->num_attrs = abbrev->num_attrs;
18800 
18801   bool any_need_reprocess = false;
18802   for (i = 0; i < abbrev->num_attrs; ++i)
18803     {
18804       info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
18805 				 info_ptr);
18806       if (die->attrs[i].requires_reprocessing_p ())
18807 	any_need_reprocess = true;
18808     }
18809 
18810   struct attribute *attr = die->attr (DW_AT_str_offsets_base);
18811   if (attr != nullptr && attr->form_is_unsigned ())
18812     cu->str_offsets_base = attr->as_unsigned ();
18813 
18814   attr = die->attr (DW_AT_loclists_base);
18815   if (attr != nullptr)
18816     cu->loclist_base = attr->as_unsigned ();
18817 
18818   auto maybe_addr_base = die->addr_base ();
18819   if (maybe_addr_base.has_value ())
18820     cu->addr_base = *maybe_addr_base;
18821 
18822   attr = die->attr (DW_AT_rnglists_base);
18823   if (attr != nullptr)
18824     cu->rnglists_base = attr->as_unsigned ();
18825 
18826   if (any_need_reprocess)
18827     {
18828       for (i = 0; i < abbrev->num_attrs; ++i)
18829 	{
18830 	  if (die->attrs[i].requires_reprocessing_p ())
18831 	    read_attribute_reprocess (reader, &die->attrs[i], die->tag);
18832 	}
18833     }
18834   *diep = die;
18835   return info_ptr;
18836 }
18837 
18838 /* Read a die and all its attributes.
18839    Set DIEP to point to a newly allocated die with its information,
18840    except for its child, sibling, and parent fields.  */
18841 
18842 static const gdb_byte *
18843 read_full_die (const struct die_reader_specs *reader,
18844 	       struct die_info **diep, const gdb_byte *info_ptr)
18845 {
18846   const gdb_byte *result;
18847 
18848   result = read_full_die_1 (reader, diep, info_ptr, 0);
18849 
18850   if (dwarf_die_debug)
18851     {
18852       fprintf_unfiltered (gdb_stdlog,
18853 			  "Read die from %s@0x%x of %s:\n",
18854 			  reader->die_section->get_name (),
18855 			  (unsigned) (info_ptr - reader->die_section->buffer),
18856 			  bfd_get_filename (reader->abfd));
18857       dump_die (*diep, dwarf_die_debug);
18858     }
18859 
18860   return result;
18861 }
18862 
18863 
18864 /* Returns nonzero if TAG represents a type that we might generate a partial
18865    symbol for.  */
18866 
18867 static int
18868 is_type_tag_for_partial (int tag, enum language lang)
18869 {
18870   switch (tag)
18871     {
18872 #if 0
18873     /* Some types that would be reasonable to generate partial symbols for,
18874        that we don't at present.  Note that normally this does not
18875        matter, mainly because C compilers don't give names to these
18876        types, but instead emit DW_TAG_typedef.  */
18877     case DW_TAG_file_type:
18878     case DW_TAG_ptr_to_member_type:
18879     case DW_TAG_set_type:
18880     case DW_TAG_string_type:
18881     case DW_TAG_subroutine_type:
18882 #endif
18883 
18884       /* GNAT may emit an array with a name, but no typedef, so we
18885 	 need to make a symbol in this case.  */
18886     case DW_TAG_array_type:
18887       return lang == language_ada;
18888 
18889     case DW_TAG_base_type:
18890     case DW_TAG_class_type:
18891     case DW_TAG_interface_type:
18892     case DW_TAG_enumeration_type:
18893     case DW_TAG_structure_type:
18894     case DW_TAG_subrange_type:
18895     case DW_TAG_typedef:
18896     case DW_TAG_union_type:
18897       return 1;
18898     default:
18899       return 0;
18900     }
18901 }
18902 
18903 /* Load all DIEs that are interesting for partial symbols into memory.  */
18904 
18905 static struct partial_die_info *
18906 load_partial_dies (const struct die_reader_specs *reader,
18907 		   const gdb_byte *info_ptr, int building_psymtab)
18908 {
18909   struct dwarf2_cu *cu = reader->cu;
18910   struct objfile *objfile = cu->per_objfile->objfile;
18911   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18912   unsigned int bytes_read;
18913   unsigned int load_all = 0;
18914   int nesting_level = 1;
18915 
18916   parent_die = NULL;
18917   last_die = NULL;
18918 
18919   gdb_assert (cu->per_cu != NULL);
18920   if (cu->load_all_dies)
18921     load_all = 1;
18922 
18923   cu->partial_dies
18924     = htab_create_alloc_ex (cu->header.length / 12,
18925 			    partial_die_hash,
18926 			    partial_die_eq,
18927 			    NULL,
18928 			    &cu->comp_unit_obstack,
18929 			    hashtab_obstack_allocate,
18930 			    dummy_obstack_deallocate);
18931 
18932   while (1)
18933     {
18934       const abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr,
18935 						   &bytes_read);
18936 
18937       /* A NULL abbrev means the end of a series of children.  */
18938       if (abbrev == NULL)
18939 	{
18940 	  if (--nesting_level == 0)
18941 	    return first_die;
18942 
18943 	  info_ptr += bytes_read;
18944 	  last_die = parent_die;
18945 	  parent_die = parent_die->die_parent;
18946 	  continue;
18947 	}
18948 
18949       /* Check for template arguments.  We never save these; if
18950 	 they're seen, we just mark the parent, and go on our way.  */
18951       if (parent_die != NULL
18952 	  && cu->per_cu->lang == language_cplus
18953 	  && (abbrev->tag == DW_TAG_template_type_param
18954 	      || abbrev->tag == DW_TAG_template_value_param))
18955 	{
18956 	  parent_die->has_template_arguments = 1;
18957 
18958 	  if (!load_all)
18959 	    {
18960 	      /* We don't need a partial DIE for the template argument.  */
18961 	      info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18962 	      continue;
18963 	    }
18964 	}
18965 
18966       /* We only recurse into c++ subprograms looking for template arguments.
18967 	 Skip their other children.  */
18968       if (!load_all
18969 	  && cu->per_cu->lang == language_cplus
18970 	  && parent_die != NULL
18971 	  && parent_die->tag == DW_TAG_subprogram
18972 	  && abbrev->tag != DW_TAG_inlined_subroutine)
18973 	{
18974 	  info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18975 	  continue;
18976 	}
18977 
18978       /* Check whether this DIE is interesting enough to save.  Normally
18979 	 we would not be interested in members here, but there may be
18980 	 later variables referencing them via DW_AT_specification (for
18981 	 static members).  */
18982       if (!load_all
18983 	  && !is_type_tag_for_partial (abbrev->tag, cu->per_cu->lang)
18984 	  && abbrev->tag != DW_TAG_constant
18985 	  && abbrev->tag != DW_TAG_enumerator
18986 	  && abbrev->tag != DW_TAG_subprogram
18987 	  && abbrev->tag != DW_TAG_inlined_subroutine
18988 	  && abbrev->tag != DW_TAG_lexical_block
18989 	  && abbrev->tag != DW_TAG_variable
18990 	  && abbrev->tag != DW_TAG_namespace
18991 	  && abbrev->tag != DW_TAG_module
18992 	  && abbrev->tag != DW_TAG_member
18993 	  && abbrev->tag != DW_TAG_imported_unit
18994 	  && abbrev->tag != DW_TAG_imported_declaration)
18995 	{
18996 	  /* Otherwise we skip to the next sibling, if any.  */
18997 	  info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18998 	  continue;
18999 	}
19000 
19001       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
19002 				   abbrev);
19003 
19004       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
19005 
19006       /* This two-pass algorithm for processing partial symbols has a
19007 	 high cost in cache pressure.  Thus, handle some simple cases
19008 	 here which cover the majority of C partial symbols.  DIEs
19009 	 which neither have specification tags in them, nor could have
19010 	 specification tags elsewhere pointing at them, can simply be
19011 	 processed and discarded.
19012 
19013 	 This segment is also optional; scan_partial_symbols and
19014 	 add_partial_symbol will handle these DIEs if we chain
19015 	 them in normally.  When compilers which do not emit large
19016 	 quantities of duplicate debug information are more common,
19017 	 this code can probably be removed.  */
19018 
19019       /* Any complete simple types at the top level (pretty much all
19020 	 of them, for a language without namespaces), can be processed
19021 	 directly.  */
19022       if (parent_die == NULL
19023 	  && pdi.has_specification == 0
19024 	  && pdi.is_declaration == 0
19025 	  && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
19026 	      || pdi.tag == DW_TAG_base_type
19027 	      || pdi.tag == DW_TAG_array_type
19028 	      || pdi.tag == DW_TAG_subrange_type))
19029 	{
19030 	  if (building_psymtab && pdi.raw_name != NULL)
19031 	    add_partial_symbol (&pdi, cu);
19032 
19033 	  info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
19034 	  continue;
19035 	}
19036 
19037       /* The exception for DW_TAG_typedef with has_children above is
19038 	 a workaround of GCC PR debug/47510.  In the case of this complaint
19039 	 type_name_or_error will error on such types later.
19040 
19041 	 GDB skipped children of DW_TAG_typedef by the shortcut above and then
19042 	 it could not find the child DIEs referenced later, this is checked
19043 	 above.  In correct DWARF DW_TAG_typedef should have no children.  */
19044 
19045       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
19046 	complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
19047 		     "- DIE at %s [in module %s]"),
19048 		   sect_offset_str (pdi.sect_off), objfile_name (objfile));
19049 
19050       /* If we're at the second level, and we're an enumerator, and
19051 	 our parent has no specification (meaning possibly lives in a
19052 	 namespace elsewhere), then we can add the partial symbol now
19053 	 instead of queueing it.  */
19054       if (pdi.tag == DW_TAG_enumerator
19055 	  && parent_die != NULL
19056 	  && parent_die->die_parent == NULL
19057 	  && parent_die->tag == DW_TAG_enumeration_type
19058 	  && parent_die->has_specification == 0)
19059 	{
19060 	  if (pdi.raw_name == NULL)
19061 	    complaint (_("malformed enumerator DIE ignored"));
19062 	  else if (building_psymtab)
19063 	    add_partial_symbol (&pdi, cu);
19064 
19065 	  info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
19066 	  continue;
19067 	}
19068 
19069       struct partial_die_info *part_die
19070 	= new (&cu->comp_unit_obstack) partial_die_info (pdi);
19071 
19072       /* We'll save this DIE so link it in.  */
19073       part_die->die_parent = parent_die;
19074       part_die->die_sibling = NULL;
19075       part_die->die_child = NULL;
19076 
19077       if (last_die && last_die == parent_die)
19078 	last_die->die_child = part_die;
19079       else if (last_die)
19080 	last_die->die_sibling = part_die;
19081 
19082       last_die = part_die;
19083 
19084       if (first_die == NULL)
19085 	first_die = part_die;
19086 
19087       /* Maybe add the DIE to the hash table.  Not all DIEs that we
19088 	 find interesting need to be in the hash table, because we
19089 	 also have the parent/sibling/child chains; only those that we
19090 	 might refer to by offset later during partial symbol reading.
19091 
19092 	 For now this means things that might have be the target of a
19093 	 DW_AT_specification, DW_AT_abstract_origin, or
19094 	 DW_AT_extension.  DW_AT_extension will refer only to
19095 	 namespaces; DW_AT_abstract_origin refers to functions (and
19096 	 many things under the function DIE, but we do not recurse
19097 	 into function DIEs during partial symbol reading) and
19098 	 possibly variables as well; DW_AT_specification refers to
19099 	 declarations.  Declarations ought to have the DW_AT_declaration
19100 	 flag.  It happens that GCC forgets to put it in sometimes, but
19101 	 only for functions, not for types.
19102 
19103 	 Adding more things than necessary to the hash table is harmless
19104 	 except for the performance cost.  Adding too few will result in
19105 	 wasted time in find_partial_die, when we reread the compilation
19106 	 unit with load_all_dies set.  */
19107 
19108       if (load_all
19109 	  || abbrev->tag == DW_TAG_constant
19110 	  || abbrev->tag == DW_TAG_subprogram
19111 	  || abbrev->tag == DW_TAG_variable
19112 	  || abbrev->tag == DW_TAG_namespace
19113 	  || part_die->is_declaration)
19114 	{
19115 	  void **slot;
19116 
19117 	  slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
19118 					   to_underlying (part_die->sect_off),
19119 					   INSERT);
19120 	  *slot = part_die;
19121 	}
19122 
19123       /* For some DIEs we want to follow their children (if any).  For C
19124 	 we have no reason to follow the children of structures; for other
19125 	 languages we have to, so that we can get at method physnames
19126 	 to infer fully qualified class names, for DW_AT_specification,
19127 	 and for C++ template arguments.  For C++, we also look one level
19128 	 inside functions to find template arguments (if the name of the
19129 	 function does not already contain the template arguments).
19130 
19131 	 For Ada and Fortran, we need to scan the children of subprograms
19132 	 and lexical blocks as well because these languages allow the
19133 	 definition of nested entities that could be interesting for the
19134 	 debugger, such as nested subprograms for instance.  */
19135       if (last_die->has_children
19136 	  && (load_all
19137 	      || last_die->tag == DW_TAG_namespace
19138 	      || last_die->tag == DW_TAG_module
19139 	      || last_die->tag == DW_TAG_enumeration_type
19140 	      || (cu->per_cu->lang == language_cplus
19141 		  && last_die->tag == DW_TAG_subprogram
19142 		  && (last_die->raw_name == NULL
19143 		      || strchr (last_die->raw_name, '<') == NULL))
19144 	      || (cu->per_cu->lang != language_c
19145 		  && (last_die->tag == DW_TAG_class_type
19146 		      || last_die->tag == DW_TAG_interface_type
19147 		      || last_die->tag == DW_TAG_structure_type
19148 		      || last_die->tag == DW_TAG_union_type))
19149 	      || ((cu->per_cu->lang == language_ada
19150 		   || cu->per_cu->lang == language_fortran)
19151 		  && (last_die->tag == DW_TAG_subprogram
19152 		      || last_die->tag == DW_TAG_lexical_block))))
19153 	{
19154 	  nesting_level++;
19155 	  parent_die = last_die;
19156 	  continue;
19157 	}
19158 
19159       /* Otherwise we skip to the next sibling, if any.  */
19160       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
19161 
19162       /* Back to the top, do it again.  */
19163     }
19164 }
19165 
19166 partial_die_info::partial_die_info (sect_offset sect_off_,
19167 				    const struct abbrev_info *abbrev)
19168   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
19169 {
19170 }
19171 
19172 /* See class definition.  */
19173 
19174 const char *
19175 partial_die_info::name (dwarf2_cu *cu)
19176 {
19177   if (!canonical_name && raw_name != nullptr)
19178     {
19179       struct objfile *objfile = cu->per_objfile->objfile;
19180       raw_name = dwarf2_canonicalize_name (raw_name, cu, objfile);
19181       canonical_name = 1;
19182     }
19183 
19184   return raw_name;
19185 }
19186 
19187 /* Read a minimal amount of information into the minimal die structure.
19188    INFO_PTR should point just after the initial uleb128 of a DIE.  */
19189 
19190 const gdb_byte *
19191 partial_die_info::read (const struct die_reader_specs *reader,
19192 			const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
19193 {
19194   struct dwarf2_cu *cu = reader->cu;
19195   dwarf2_per_objfile *per_objfile = cu->per_objfile;
19196   unsigned int i;
19197   int has_low_pc_attr = 0;
19198   int has_high_pc_attr = 0;
19199   int high_pc_relative = 0;
19200 
19201   for (i = 0; i < abbrev.num_attrs; ++i)
19202     {
19203       attribute attr;
19204       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
19205       /* String and address offsets that need to do the reprocessing have
19206 	 already been read at this point, so there is no need to wait until
19207 	 the loop terminates to do the reprocessing.  */
19208       if (attr.requires_reprocessing_p ())
19209 	read_attribute_reprocess (reader, &attr, tag);
19210       /* Store the data if it is of an attribute we want to keep in a
19211 	 partial symbol table.  */
19212       switch (attr.name)
19213 	{
19214 	case DW_AT_name:
19215 	  switch (tag)
19216 	    {
19217 	    case DW_TAG_compile_unit:
19218 	    case DW_TAG_partial_unit:
19219 	    case DW_TAG_type_unit:
19220 	      /* Compilation units have a DW_AT_name that is a filename, not
19221 		 a source language identifier.  */
19222 	    case DW_TAG_enumeration_type:
19223 	    case DW_TAG_enumerator:
19224 	      /* These tags always have simple identifiers already; no need
19225 		 to canonicalize them.  */
19226 	      canonical_name = 1;
19227 	      raw_name = attr.as_string ();
19228 	      break;
19229 	    default:
19230 	      canonical_name = 0;
19231 	      raw_name = attr.as_string ();
19232 	      break;
19233 	    }
19234 	  break;
19235 	case DW_AT_linkage_name:
19236 	case DW_AT_MIPS_linkage_name:
19237 	  /* Note that both forms of linkage name might appear.  We
19238 	     assume they will be the same, and we only store the last
19239 	     one we see.  */
19240 	  linkage_name = attr.as_string ();
19241 	  break;
19242 	case DW_AT_low_pc:
19243 	  has_low_pc_attr = 1;
19244 	  lowpc = attr.as_address ();
19245 	  break;
19246 	case DW_AT_high_pc:
19247 	  has_high_pc_attr = 1;
19248 	  highpc = attr.as_address ();
19249 	  if (cu->header.version >= 4 && attr.form_is_constant ())
19250 		high_pc_relative = 1;
19251 	  break;
19252 	case DW_AT_location:
19253 	  /* Support the .debug_loc offsets.  */
19254 	  if (attr.form_is_block ())
19255 	    {
19256 	      d.locdesc = attr.as_block ();
19257 	    }
19258 	  else if (attr.form_is_section_offset ())
19259 	    {
19260 	      dwarf2_complex_location_expr_complaint ();
19261 	    }
19262 	  else
19263 	    {
19264 	      dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
19265 						     "partial symbol information");
19266 	    }
19267 	  break;
19268 	case DW_AT_external:
19269 	  is_external = attr.as_boolean ();
19270 	  break;
19271 	case DW_AT_declaration:
19272 	  is_declaration = attr.as_boolean ();
19273 	  break;
19274 	case DW_AT_type:
19275 	  has_type = 1;
19276 	  break;
19277 	case DW_AT_abstract_origin:
19278 	case DW_AT_specification:
19279 	case DW_AT_extension:
19280 	  has_specification = 1;
19281 	  spec_offset = attr.get_ref_die_offset ();
19282 	  spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
19283 				   || cu->per_cu->is_dwz);
19284 	  break;
19285 	case DW_AT_sibling:
19286 	  /* Ignore absolute siblings, they might point outside of
19287 	     the current compile unit.  */
19288 	  if (attr.form == DW_FORM_ref_addr)
19289 	    complaint (_("ignoring absolute DW_AT_sibling"));
19290 	  else
19291 	    {
19292 	      const gdb_byte *buffer = reader->buffer;
19293 	      sect_offset off = attr.get_ref_die_offset ();
19294 	      const gdb_byte *sibling_ptr = buffer + to_underlying (off);
19295 
19296 	      if (sibling_ptr < info_ptr)
19297 		complaint (_("DW_AT_sibling points backwards"));
19298 	      else if (sibling_ptr > reader->buffer_end)
19299 		reader->die_section->overflow_complaint ();
19300 	      else
19301 		sibling = sibling_ptr;
19302 	    }
19303 	  break;
19304 	case DW_AT_byte_size:
19305 	  has_byte_size = 1;
19306 	  break;
19307 	case DW_AT_const_value:
19308 	  has_const_value = 1;
19309 	  break;
19310 	case DW_AT_calling_convention:
19311 	  /* DWARF doesn't provide a way to identify a program's source-level
19312 	     entry point.  DW_AT_calling_convention attributes are only meant
19313 	     to describe functions' calling conventions.
19314 
19315 	     However, because it's a necessary piece of information in
19316 	     Fortran, and before DWARF 4 DW_CC_program was the only
19317 	     piece of debugging information whose definition refers to
19318 	     a 'main program' at all, several compilers marked Fortran
19319 	     main programs with DW_CC_program --- even when those
19320 	     functions use the standard calling conventions.
19321 
19322 	     Although DWARF now specifies a way to provide this
19323 	     information, we support this practice for backward
19324 	     compatibility.  */
19325 	  if (attr.constant_value (0) == DW_CC_program
19326 	      && cu->per_cu->lang == language_fortran)
19327 	    main_subprogram = 1;
19328 	  break;
19329 	case DW_AT_inline:
19330 	  {
19331 	    LONGEST value = attr.constant_value (-1);
19332 	    if (value == DW_INL_inlined
19333 		|| value == DW_INL_declared_inlined)
19334 	      may_be_inlined = 1;
19335 	  }
19336 	  break;
19337 
19338 	case DW_AT_import:
19339 	  if (tag == DW_TAG_imported_unit)
19340 	    {
19341 	      d.sect_off = attr.get_ref_die_offset ();
19342 	      is_dwz = (attr.form == DW_FORM_GNU_ref_alt
19343 				  || cu->per_cu->is_dwz);
19344 	    }
19345 	  break;
19346 
19347 	case DW_AT_main_subprogram:
19348 	  main_subprogram = attr.as_boolean ();
19349 	  break;
19350 
19351 	case DW_AT_ranges:
19352 	  {
19353 	    /* Offset in the .debug_ranges or .debug_rnglist section (depending
19354 	       on DWARF version).  */
19355 	    ULONGEST ranges_offset = attr.as_unsigned ();
19356 
19357 	    /* See dwarf2_cu::gnu_ranges_base's doc for why we might want to add
19358 	       this value.  */
19359 	    if (tag != DW_TAG_compile_unit)
19360 	      ranges_offset += cu->gnu_ranges_base;
19361 
19362 	    if (dwarf2_ranges_read (ranges_offset, &lowpc, &highpc, cu,
19363 				    nullptr, tag))
19364 	      has_pc_info = 1;
19365 	  }
19366 	  break;
19367 
19368 	default:
19369 	  break;
19370 	}
19371     }
19372 
19373   /* For Ada, if both the name and the linkage name appear, we prefer
19374      the latter.  This lets "catch exception" work better, regardless
19375      of the order in which the name and linkage name were emitted.
19376      Really, though, this is just a workaround for the fact that gdb
19377      doesn't store both the name and the linkage name.  */
19378   if (cu->per_cu->lang == language_ada && linkage_name != nullptr)
19379     raw_name = linkage_name;
19380 
19381   if (high_pc_relative)
19382     highpc += lowpc;
19383 
19384   if (has_low_pc_attr && has_high_pc_attr)
19385     {
19386       /* When using the GNU linker, .gnu.linkonce. sections are used to
19387 	 eliminate duplicate copies of functions and vtables and such.
19388 	 The linker will arbitrarily choose one and discard the others.
19389 	 The AT_*_pc values for such functions refer to local labels in
19390 	 these sections.  If the section from that file was discarded, the
19391 	 labels are not in the output, so the relocs get a value of 0.
19392 	 If this is a discarded function, mark the pc bounds as invalid,
19393 	 so that GDB will ignore it.  */
19394       if (lowpc == 0 && !per_objfile->per_bfd->has_section_at_zero)
19395 	{
19396 	  struct objfile *objfile = per_objfile->objfile;
19397 	  struct gdbarch *gdbarch = objfile->arch ();
19398 
19399 	  complaint (_("DW_AT_low_pc %s is zero "
19400 		       "for DIE at %s [in module %s]"),
19401 		     paddress (gdbarch, lowpc),
19402 		     sect_offset_str (sect_off),
19403 		     objfile_name (objfile));
19404 	}
19405       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
19406       else if (lowpc >= highpc)
19407 	{
19408 	  struct objfile *objfile = per_objfile->objfile;
19409 	  struct gdbarch *gdbarch = objfile->arch ();
19410 
19411 	  complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
19412 		       "for DIE at %s [in module %s]"),
19413 		     paddress (gdbarch, lowpc),
19414 		     paddress (gdbarch, highpc),
19415 		     sect_offset_str (sect_off),
19416 		     objfile_name (objfile));
19417 	}
19418       else
19419 	has_pc_info = 1;
19420     }
19421 
19422   return info_ptr;
19423 }
19424 
19425 /* Find a cached partial DIE at OFFSET in CU.  */
19426 
19427 struct partial_die_info *
19428 dwarf2_cu::find_partial_die (sect_offset sect_off)
19429 {
19430   struct partial_die_info *lookup_die = NULL;
19431   struct partial_die_info part_die (sect_off);
19432 
19433   lookup_die = ((struct partial_die_info *)
19434 		htab_find_with_hash (partial_dies, &part_die,
19435 				     to_underlying (sect_off)));
19436 
19437   return lookup_die;
19438 }
19439 
19440 /* Find a partial DIE at OFFSET, which may or may not be in CU,
19441    except in the case of .debug_types DIEs which do not reference
19442    outside their CU (they do however referencing other types via
19443    DW_FORM_ref_sig8).  */
19444 
19445 static const struct cu_partial_die_info
19446 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
19447 {
19448   dwarf2_per_objfile *per_objfile = cu->per_objfile;
19449   struct objfile *objfile = per_objfile->objfile;
19450   struct partial_die_info *pd = NULL;
19451 
19452   if (offset_in_dwz == cu->per_cu->is_dwz
19453       && cu->header.offset_in_cu_p (sect_off))
19454     {
19455       pd = cu->find_partial_die (sect_off);
19456       if (pd != NULL)
19457 	return { cu, pd };
19458       /* We missed recording what we needed.
19459 	 Load all dies and try again.  */
19460     }
19461   else
19462     {
19463       /* TUs don't reference other CUs/TUs (except via type signatures).  */
19464       if (cu->per_cu->is_debug_types)
19465 	{
19466 	  error (_("Dwarf Error: Type Unit at offset %s contains"
19467 		   " external reference to offset %s [in module %s].\n"),
19468 		 sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
19469 		 bfd_get_filename (objfile->obfd));
19470 	}
19471       dwarf2_per_cu_data *per_cu
19472 	= dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
19473 					    per_objfile);
19474 
19475       cu = per_objfile->get_cu (per_cu);
19476       if (cu == NULL || cu->partial_dies == NULL)
19477 	load_partial_comp_unit (per_cu, per_objfile, nullptr);
19478 
19479       cu = per_objfile->get_cu (per_cu);
19480 
19481       cu->last_used = 0;
19482       pd = cu->find_partial_die (sect_off);
19483     }
19484 
19485   /* If we didn't find it, and not all dies have been loaded,
19486      load them all and try again.  */
19487 
19488   if (pd == NULL && cu->load_all_dies == 0)
19489     {
19490       cu->load_all_dies = 1;
19491 
19492       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
19493 	 THIS_CU->cu may already be in use.  So we can't just free it and
19494 	 replace its DIEs with the ones we read in.  Instead, we leave those
19495 	 DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
19496 	 and clobber THIS_CU->cu->partial_dies with the hash table for the new
19497 	 set.  */
19498       load_partial_comp_unit (cu->per_cu, per_objfile, cu);
19499 
19500       pd = cu->find_partial_die (sect_off);
19501     }
19502 
19503   if (pd == NULL)
19504     error (_("Dwarf Error: Cannot find DIE at %s [from module %s]\n"),
19505 		    sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
19506   return { cu, pd };
19507 }
19508 
19509 /* See if we can figure out if the class lives in a namespace.  We do
19510    this by looking for a member function; its demangled name will
19511    contain namespace info, if there is any.  */
19512 
19513 static void
19514 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
19515 				  struct dwarf2_cu *cu)
19516 {
19517   /* NOTE: carlton/2003-10-07: Getting the info this way changes
19518      what template types look like, because the demangler
19519      frequently doesn't give the same name as the debug info.  We
19520      could fix this by only using the demangled name to get the
19521      prefix (but see comment in read_structure_type).  */
19522 
19523   struct partial_die_info *real_pdi;
19524   struct partial_die_info *child_pdi;
19525 
19526   /* If this DIE (this DIE's specification, if any) has a parent, then
19527      we should not do this.  We'll prepend the parent's fully qualified
19528      name when we create the partial symbol.  */
19529 
19530   real_pdi = struct_pdi;
19531   while (real_pdi->has_specification)
19532     {
19533       auto res = find_partial_die (real_pdi->spec_offset,
19534 				   real_pdi->spec_is_dwz, cu);
19535       real_pdi = res.pdi;
19536       cu = res.cu;
19537     }
19538 
19539   if (real_pdi->die_parent != NULL)
19540     return;
19541 
19542   for (child_pdi = struct_pdi->die_child;
19543        child_pdi != NULL;
19544        child_pdi = child_pdi->die_sibling)
19545     {
19546       if (child_pdi->tag == DW_TAG_subprogram
19547 	  && child_pdi->linkage_name != NULL)
19548 	{
19549 	  gdb::unique_xmalloc_ptr<char> actual_class_name
19550 	    (cu->language_defn->class_name_from_physname
19551 	     (child_pdi->linkage_name));
19552 	  if (actual_class_name != NULL)
19553 	    {
19554 	      struct objfile *objfile = cu->per_objfile->objfile;
19555 	      struct_pdi->raw_name = objfile->intern (actual_class_name.get ());
19556 	      struct_pdi->canonical_name = 1;
19557 	    }
19558 	  break;
19559 	}
19560     }
19561 }
19562 
19563 /* Return true if a DIE with TAG may have the DW_AT_const_value
19564    attribute.  */
19565 
19566 static bool
19567 can_have_DW_AT_const_value_p (enum dwarf_tag tag)
19568 {
19569   switch (tag)
19570     {
19571     case DW_TAG_constant:
19572     case DW_TAG_enumerator:
19573     case DW_TAG_formal_parameter:
19574     case DW_TAG_template_value_param:
19575     case DW_TAG_variable:
19576       return true;
19577     }
19578 
19579   return false;
19580 }
19581 
19582 void
19583 partial_die_info::fixup (struct dwarf2_cu *cu)
19584 {
19585   /* Once we've fixed up a die, there's no point in doing so again.
19586      This also avoids a memory leak if we were to call
19587      guess_partial_die_structure_name multiple times.  */
19588   if (fixup_called)
19589     return;
19590 
19591   /* If we found a reference attribute and the DIE has no name, try
19592      to find a name in the referred to DIE.  */
19593 
19594   if (raw_name == NULL && has_specification)
19595     {
19596       struct partial_die_info *spec_die;
19597 
19598       auto res = find_partial_die (spec_offset, spec_is_dwz, cu);
19599       spec_die = res.pdi;
19600       cu = res.cu;
19601 
19602       spec_die->fixup (cu);
19603 
19604       if (spec_die->raw_name)
19605 	{
19606 	  raw_name = spec_die->raw_name;
19607 	  canonical_name = spec_die->canonical_name;
19608 
19609 	  /* Copy DW_AT_external attribute if it is set.  */
19610 	  if (spec_die->is_external)
19611 	    is_external = spec_die->is_external;
19612 	}
19613     }
19614 
19615   if (!has_const_value && has_specification
19616       && can_have_DW_AT_const_value_p (tag))
19617     {
19618       struct partial_die_info *spec_die;
19619 
19620       auto res = find_partial_die (spec_offset, spec_is_dwz, cu);
19621       spec_die = res.pdi;
19622       cu = res.cu;
19623 
19624       spec_die->fixup (cu);
19625 
19626       if (spec_die->has_const_value)
19627 	{
19628 	  /* Copy DW_AT_const_value attribute if it is set.  */
19629 	  has_const_value = spec_die->has_const_value;
19630 	}
19631     }
19632 
19633   /* Set default names for some unnamed DIEs.  */
19634 
19635   if (raw_name == NULL && tag == DW_TAG_namespace)
19636     {
19637       raw_name = CP_ANONYMOUS_NAMESPACE_STR;
19638       canonical_name = 1;
19639     }
19640 
19641   /* If there is no parent die to provide a namespace, and there are
19642      children, see if we can determine the namespace from their linkage
19643      name.  */
19644   if (cu->per_cu->lang == language_cplus
19645       && !cu->per_objfile->per_bfd->types.empty ()
19646       && die_parent == NULL
19647       && has_children
19648       && (tag == DW_TAG_class_type
19649 	  || tag == DW_TAG_structure_type
19650 	  || tag == DW_TAG_union_type))
19651     guess_partial_die_structure_name (this, cu);
19652 
19653   /* GCC might emit a nameless struct or union that has a linkage
19654      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19655   if (raw_name == NULL
19656       && (tag == DW_TAG_class_type
19657 	  || tag == DW_TAG_interface_type
19658 	  || tag == DW_TAG_structure_type
19659 	  || tag == DW_TAG_union_type)
19660       && linkage_name != NULL)
19661     {
19662       gdb::unique_xmalloc_ptr<char> demangled
19663 	(gdb_demangle (linkage_name, DMGL_TYPES));
19664       if (demangled != nullptr)
19665 	{
19666 	  const char *base;
19667 
19668 	  /* Strip any leading namespaces/classes, keep only the base name.
19669 	     DW_AT_name for named DIEs does not contain the prefixes.  */
19670 	  base = strrchr (demangled.get (), ':');
19671 	  if (base && base > demangled.get () && base[-1] == ':')
19672 	    base++;
19673 	  else
19674 	    base = demangled.get ();
19675 
19676 	  struct objfile *objfile = cu->per_objfile->objfile;
19677 	  raw_name = objfile->intern (base);
19678 	  canonical_name = 1;
19679 	}
19680     }
19681 
19682   fixup_called = 1;
19683 }
19684 
19685 /* Read the .debug_loclists or .debug_rnglists header (they are the same format)
19686    contents from the given SECTION in the HEADER.
19687 
19688    HEADER_OFFSET is the offset of the header in the section.  */
19689 static void
19690 read_loclists_rnglists_header (struct loclists_rnglists_header *header,
19691 			       struct dwarf2_section_info *section,
19692 			       sect_offset header_offset)
19693 {
19694   unsigned int bytes_read;
19695   bfd *abfd = section->get_bfd_owner ();
19696   const gdb_byte *info_ptr = section->buffer + to_underlying (header_offset);
19697 
19698   header->length = read_initial_length (abfd, info_ptr, &bytes_read);
19699   info_ptr += bytes_read;
19700 
19701   header->version = read_2_bytes (abfd, info_ptr);
19702   info_ptr += 2;
19703 
19704   header->addr_size = read_1_byte (abfd, info_ptr);
19705   info_ptr += 1;
19706 
19707   header->segment_collector_size = read_1_byte (abfd, info_ptr);
19708   info_ptr += 1;
19709 
19710   header->offset_entry_count = read_4_bytes (abfd, info_ptr);
19711 }
19712 
19713 /* Return the DW_AT_loclists_base value for the CU.  */
19714 static ULONGEST
19715 lookup_loclist_base (struct dwarf2_cu *cu)
19716 {
19717   /* For the .dwo unit, the loclist_base points to the first offset following
19718      the header. The header consists of the following entities-
19719      1. Unit Length (4 bytes for 32 bit DWARF format, and 12 bytes for the 64
19720 	 bit format)
19721      2. version (2 bytes)
19722      3. address size (1 byte)
19723      4. segment selector size (1 byte)
19724      5. offset entry count (4 bytes)
19725      These sizes are derived as per the DWARFv5 standard.  */
19726   if (cu->dwo_unit != nullptr)
19727     {
19728       if (cu->header.initial_length_size == 4)
19729 	 return LOCLIST_HEADER_SIZE32;
19730       return LOCLIST_HEADER_SIZE64;
19731     }
19732   return cu->loclist_base;
19733 }
19734 
19735 /* Given a DW_FORM_loclistx value LOCLIST_INDEX, fetch the offset from the
19736    array of offsets in the .debug_loclists section.  */
19737 
19738 static sect_offset
19739 read_loclist_index (struct dwarf2_cu *cu, ULONGEST loclist_index)
19740 {
19741   dwarf2_per_objfile *per_objfile = cu->per_objfile;
19742   struct objfile *objfile = per_objfile->objfile;
19743   bfd *abfd = objfile->obfd;
19744   ULONGEST loclist_header_size =
19745     (cu->header.initial_length_size == 4 ? LOCLIST_HEADER_SIZE32
19746      : LOCLIST_HEADER_SIZE64);
19747   ULONGEST loclist_base = lookup_loclist_base (cu);
19748 
19749   /* Offset in .debug_loclists of the offset for LOCLIST_INDEX.  */
19750   ULONGEST start_offset =
19751     loclist_base + loclist_index * cu->header.offset_size;
19752 
19753   /* Get loclists section.  */
19754   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19755 
19756   /* Read the loclists section content.  */
19757   section->read (objfile);
19758   if (section->buffer == NULL)
19759     error (_("DW_FORM_loclistx used without .debug_loclists "
19760 	     "section [in module %s]"), objfile_name (objfile));
19761 
19762   /* DW_AT_loclists_base points after the .debug_loclists contribution header,
19763      so if loclist_base is smaller than the header size, we have a problem.  */
19764   if (loclist_base < loclist_header_size)
19765     error (_("DW_AT_loclists_base is smaller than header size [in module %s]"),
19766 	   objfile_name (objfile));
19767 
19768   /* Read the header of the loclists contribution.  */
19769   struct loclists_rnglists_header header;
19770   read_loclists_rnglists_header (&header, section,
19771 				 (sect_offset) (loclist_base - loclist_header_size));
19772 
19773   /* Verify the loclist index is valid.  */
19774   if (loclist_index >= header.offset_entry_count)
19775     error (_("DW_FORM_loclistx pointing outside of "
19776 	     ".debug_loclists offset array [in module %s]"),
19777 	   objfile_name (objfile));
19778 
19779   /* Validate that reading won't go beyond the end of the section.  */
19780   if (start_offset + cu->header.offset_size > section->size)
19781     error (_("Reading DW_FORM_loclistx index beyond end of"
19782 	     ".debug_loclists section [in module %s]"),
19783 	   objfile_name (objfile));
19784 
19785   const gdb_byte *info_ptr = section->buffer + start_offset;
19786 
19787   if (cu->header.offset_size == 4)
19788     return (sect_offset) (bfd_get_32 (abfd, info_ptr) + loclist_base);
19789   else
19790     return (sect_offset) (bfd_get_64 (abfd, info_ptr) + loclist_base);
19791 }
19792 
19793 /* Given a DW_FORM_rnglistx value RNGLIST_INDEX, fetch the offset from the
19794    array of offsets in the .debug_rnglists section.  */
19795 
19796 static sect_offset
19797 read_rnglist_index (struct dwarf2_cu *cu, ULONGEST rnglist_index,
19798 		    dwarf_tag tag)
19799 {
19800   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->per_objfile;
19801   struct objfile *objfile = dwarf2_per_objfile->objfile;
19802   bfd *abfd = objfile->obfd;
19803   ULONGEST rnglist_header_size =
19804     (cu->header.initial_length_size == 4 ? RNGLIST_HEADER_SIZE32
19805      : RNGLIST_HEADER_SIZE64);
19806 
19807   /* When reading a DW_FORM_rnglistx from a DWO, we read from the DWO's
19808      .debug_rnglists.dwo section.  The rnglists base given in the skeleton
19809      doesn't apply.  */
19810   ULONGEST rnglist_base =
19811       (cu->dwo_unit != nullptr) ? rnglist_header_size : cu->rnglists_base;
19812 
19813   /* Offset in .debug_rnglists of the offset for RNGLIST_INDEX.  */
19814   ULONGEST start_offset =
19815     rnglist_base + rnglist_index * cu->header.offset_size;
19816 
19817   /* Get rnglists section.  */
19818   struct dwarf2_section_info *section = cu_debug_rnglists_section (cu, tag);
19819 
19820   /* Read the rnglists section content.  */
19821   section->read (objfile);
19822   if (section->buffer == nullptr)
19823     error (_("DW_FORM_rnglistx used without .debug_rnglists section "
19824 	     "[in module %s]"),
19825 	   objfile_name (objfile));
19826 
19827   /* DW_AT_rnglists_base points after the .debug_rnglists contribution header,
19828      so if rnglist_base is smaller than the header size, we have a problem.  */
19829   if (rnglist_base < rnglist_header_size)
19830     error (_("DW_AT_rnglists_base is smaller than header size [in module %s]"),
19831 	   objfile_name (objfile));
19832 
19833   /* Read the header of the rnglists contribution.  */
19834   struct loclists_rnglists_header header;
19835   read_loclists_rnglists_header (&header, section,
19836 				 (sect_offset) (rnglist_base - rnglist_header_size));
19837 
19838   /* Verify the rnglist index is valid.  */
19839   if (rnglist_index >= header.offset_entry_count)
19840     error (_("DW_FORM_rnglistx index pointing outside of "
19841 	     ".debug_rnglists offset array [in module %s]"),
19842 	   objfile_name (objfile));
19843 
19844   /* Validate that reading won't go beyond the end of the section.  */
19845   if (start_offset + cu->header.offset_size > section->size)
19846     error (_("Reading DW_FORM_rnglistx index beyond end of"
19847 	     ".debug_rnglists section [in module %s]"),
19848 	   objfile_name (objfile));
19849 
19850   const gdb_byte *info_ptr = section->buffer + start_offset;
19851 
19852   if (cu->header.offset_size == 4)
19853     return (sect_offset) (read_4_bytes (abfd, info_ptr) + rnglist_base);
19854   else
19855     return (sect_offset) (read_8_bytes (abfd, info_ptr) + rnglist_base);
19856 }
19857 
19858 /* Process the attributes that had to be skipped in the first round. These
19859    attributes are the ones that need str_offsets_base or addr_base attributes.
19860    They could not have been processed in the first round, because at the time
19861    the values of str_offsets_base or addr_base may not have been known.  */
19862 static void
19863 read_attribute_reprocess (const struct die_reader_specs *reader,
19864 			  struct attribute *attr, dwarf_tag tag)
19865 {
19866   struct dwarf2_cu *cu = reader->cu;
19867   switch (attr->form)
19868     {
19869       case DW_FORM_addrx:
19870       case DW_FORM_GNU_addr_index:
19871 	attr->set_address (read_addr_index (cu,
19872 					    attr->as_unsigned_reprocess ()));
19873 	break;
19874       case DW_FORM_loclistx:
19875 	{
19876 	  sect_offset loclists_sect_off
19877 	    = read_loclist_index (cu, attr->as_unsigned_reprocess ());
19878 
19879 	  attr->set_unsigned (to_underlying (loclists_sect_off));
19880 	}
19881 	break;
19882       case DW_FORM_rnglistx:
19883 	{
19884 	  sect_offset rnglists_sect_off
19885 	    = read_rnglist_index (cu, attr->as_unsigned_reprocess (), tag);
19886 
19887 	  attr->set_unsigned (to_underlying (rnglists_sect_off));
19888 	}
19889 	break;
19890       case DW_FORM_strx:
19891       case DW_FORM_strx1:
19892       case DW_FORM_strx2:
19893       case DW_FORM_strx3:
19894       case DW_FORM_strx4:
19895       case DW_FORM_GNU_str_index:
19896 	{
19897 	  unsigned int str_index = attr->as_unsigned_reprocess ();
19898 	  gdb_assert (!attr->canonical_string_p ());
19899 	  if (reader->dwo_file != NULL)
19900 	    attr->set_string_noncanonical (read_dwo_str_index (reader,
19901 							       str_index));
19902 	  else
19903 	    attr->set_string_noncanonical (read_stub_str_index (cu,
19904 								str_index));
19905 	  break;
19906 	}
19907       default:
19908 	gdb_assert_not_reached (_("Unexpected DWARF form."));
19909     }
19910 }
19911 
19912 /* Read an attribute value described by an attribute form.  */
19913 
19914 static const gdb_byte *
19915 read_attribute_value (const struct die_reader_specs *reader,
19916 		      struct attribute *attr, unsigned form,
19917 		      LONGEST implicit_const, const gdb_byte *info_ptr)
19918 {
19919   struct dwarf2_cu *cu = reader->cu;
19920   dwarf2_per_objfile *per_objfile = cu->per_objfile;
19921   struct objfile *objfile = per_objfile->objfile;
19922   bfd *abfd = reader->abfd;
19923   struct comp_unit_head *cu_header = &cu->header;
19924   unsigned int bytes_read;
19925   struct dwarf_block *blk;
19926 
19927   attr->form = (enum dwarf_form) form;
19928   switch (form)
19929     {
19930     case DW_FORM_ref_addr:
19931       if (cu_header->version == 2)
19932 	attr->set_unsigned (cu_header->read_address (abfd, info_ptr,
19933 						     &bytes_read));
19934       else
19935 	attr->set_unsigned (cu_header->read_offset (abfd, info_ptr,
19936 						    &bytes_read));
19937       info_ptr += bytes_read;
19938       break;
19939     case DW_FORM_GNU_ref_alt:
19940       attr->set_unsigned (cu_header->read_offset (abfd, info_ptr,
19941 						  &bytes_read));
19942       info_ptr += bytes_read;
19943       break;
19944     case DW_FORM_addr:
19945       {
19946 	struct gdbarch *gdbarch = objfile->arch ();
19947 	CORE_ADDR addr = cu_header->read_address (abfd, info_ptr, &bytes_read);
19948 	addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr);
19949 	attr->set_address (addr);
19950 	info_ptr += bytes_read;
19951       }
19952       break;
19953     case DW_FORM_block2:
19954       blk = dwarf_alloc_block (cu);
19955       blk->size = read_2_bytes (abfd, info_ptr);
19956       info_ptr += 2;
19957       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19958       info_ptr += blk->size;
19959       attr->set_block (blk);
19960       break;
19961     case DW_FORM_block4:
19962       blk = dwarf_alloc_block (cu);
19963       blk->size = read_4_bytes (abfd, info_ptr);
19964       info_ptr += 4;
19965       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19966       info_ptr += blk->size;
19967       attr->set_block (blk);
19968       break;
19969     case DW_FORM_data2:
19970       attr->set_unsigned (read_2_bytes (abfd, info_ptr));
19971       info_ptr += 2;
19972       break;
19973     case DW_FORM_data4:
19974       attr->set_unsigned (read_4_bytes (abfd, info_ptr));
19975       info_ptr += 4;
19976       break;
19977     case DW_FORM_data8:
19978       attr->set_unsigned (read_8_bytes (abfd, info_ptr));
19979       info_ptr += 8;
19980       break;
19981     case DW_FORM_data16:
19982       blk = dwarf_alloc_block (cu);
19983       blk->size = 16;
19984       blk->data = read_n_bytes (abfd, info_ptr, 16);
19985       info_ptr += 16;
19986       attr->set_block (blk);
19987       break;
19988     case DW_FORM_sec_offset:
19989       attr->set_unsigned (cu_header->read_offset (abfd, info_ptr,
19990 						  &bytes_read));
19991       info_ptr += bytes_read;
19992       break;
19993     case DW_FORM_loclistx:
19994       {
19995 	attr->set_unsigned_reprocess (read_unsigned_leb128 (abfd, info_ptr,
19996 							    &bytes_read));
19997 	info_ptr += bytes_read;
19998       }
19999       break;
20000     case DW_FORM_string:
20001       attr->set_string_noncanonical (read_direct_string (abfd, info_ptr,
20002 							 &bytes_read));
20003       info_ptr += bytes_read;
20004       break;
20005     case DW_FORM_strp:
20006       if (!cu->per_cu->is_dwz)
20007 	{
20008 	  attr->set_string_noncanonical
20009 	    (read_indirect_string (per_objfile,
20010 				   abfd, info_ptr, cu_header,
20011 				   &bytes_read));
20012 	  info_ptr += bytes_read;
20013 	  break;
20014 	}
20015       /* FALLTHROUGH */
20016     case DW_FORM_line_strp:
20017       if (!cu->per_cu->is_dwz)
20018 	{
20019 	  attr->set_string_noncanonical
20020 	    (per_objfile->read_line_string (info_ptr, cu_header,
20021 					    &bytes_read));
20022 	  info_ptr += bytes_read;
20023 	  break;
20024 	}
20025       /* FALLTHROUGH */
20026     case DW_FORM_GNU_strp_alt:
20027       {
20028 	dwz_file *dwz = dwarf2_get_dwz_file (per_objfile->per_bfd, true);
20029 	LONGEST str_offset = cu_header->read_offset (abfd, info_ptr,
20030 						     &bytes_read);
20031 
20032 	attr->set_string_noncanonical
20033 	  (dwz->read_string (objfile, str_offset));
20034 	info_ptr += bytes_read;
20035       }
20036       break;
20037     case DW_FORM_exprloc:
20038     case DW_FORM_block:
20039       blk = dwarf_alloc_block (cu);
20040       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
20041       info_ptr += bytes_read;
20042       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
20043       info_ptr += blk->size;
20044       attr->set_block (blk);
20045       break;
20046     case DW_FORM_block1:
20047       blk = dwarf_alloc_block (cu);
20048       blk->size = read_1_byte (abfd, info_ptr);
20049       info_ptr += 1;
20050       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
20051       info_ptr += blk->size;
20052       attr->set_block (blk);
20053       break;
20054     case DW_FORM_data1:
20055     case DW_FORM_flag:
20056       attr->set_unsigned (read_1_byte (abfd, info_ptr));
20057       info_ptr += 1;
20058       break;
20059     case DW_FORM_flag_present:
20060       attr->set_unsigned (1);
20061       break;
20062     case DW_FORM_sdata:
20063       attr->set_signed (read_signed_leb128 (abfd, info_ptr, &bytes_read));
20064       info_ptr += bytes_read;
20065       break;
20066     case DW_FORM_rnglistx:
20067       {
20068 	attr->set_unsigned_reprocess (read_unsigned_leb128 (abfd, info_ptr,
20069 							    &bytes_read));
20070 	info_ptr += bytes_read;
20071       }
20072       break;
20073     case DW_FORM_udata:
20074       attr->set_unsigned (read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
20075       info_ptr += bytes_read;
20076       break;
20077     case DW_FORM_ref1:
20078       attr->set_unsigned ((to_underlying (cu_header->sect_off)
20079 			   + read_1_byte (abfd, info_ptr)));
20080       info_ptr += 1;
20081       break;
20082     case DW_FORM_ref2:
20083       attr->set_unsigned ((to_underlying (cu_header->sect_off)
20084 			   + read_2_bytes (abfd, info_ptr)));
20085       info_ptr += 2;
20086       break;
20087     case DW_FORM_ref4:
20088       attr->set_unsigned ((to_underlying (cu_header->sect_off)
20089 			   + read_4_bytes (abfd, info_ptr)));
20090       info_ptr += 4;
20091       break;
20092     case DW_FORM_ref8:
20093       attr->set_unsigned ((to_underlying (cu_header->sect_off)
20094 			   + read_8_bytes (abfd, info_ptr)));
20095       info_ptr += 8;
20096       break;
20097     case DW_FORM_ref_sig8:
20098       attr->set_signature (read_8_bytes (abfd, info_ptr));
20099       info_ptr += 8;
20100       break;
20101     case DW_FORM_ref_udata:
20102       attr->set_unsigned ((to_underlying (cu_header->sect_off)
20103 			   + read_unsigned_leb128 (abfd, info_ptr,
20104 						   &bytes_read)));
20105       info_ptr += bytes_read;
20106       break;
20107     case DW_FORM_indirect:
20108       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
20109       info_ptr += bytes_read;
20110       if (form == DW_FORM_implicit_const)
20111 	{
20112 	  implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
20113 	  info_ptr += bytes_read;
20114 	}
20115       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
20116 				       info_ptr);
20117       break;
20118     case DW_FORM_implicit_const:
20119       attr->set_signed (implicit_const);
20120       break;
20121     case DW_FORM_addrx:
20122     case DW_FORM_GNU_addr_index:
20123       attr->set_unsigned_reprocess (read_unsigned_leb128 (abfd, info_ptr,
20124 							  &bytes_read));
20125       info_ptr += bytes_read;
20126       break;
20127     case DW_FORM_strx:
20128     case DW_FORM_strx1:
20129     case DW_FORM_strx2:
20130     case DW_FORM_strx3:
20131     case DW_FORM_strx4:
20132     case DW_FORM_GNU_str_index:
20133       {
20134 	ULONGEST str_index;
20135 	if (form == DW_FORM_strx1)
20136 	  {
20137 	    str_index = read_1_byte (abfd, info_ptr);
20138 	    info_ptr += 1;
20139 	  }
20140 	else if (form == DW_FORM_strx2)
20141 	  {
20142 	    str_index = read_2_bytes (abfd, info_ptr);
20143 	    info_ptr += 2;
20144 	  }
20145 	else if (form == DW_FORM_strx3)
20146 	  {
20147 	    str_index = read_3_bytes (abfd, info_ptr);
20148 	    info_ptr += 3;
20149 	  }
20150 	else if (form == DW_FORM_strx4)
20151 	  {
20152 	    str_index = read_4_bytes (abfd, info_ptr);
20153 	    info_ptr += 4;
20154 	  }
20155 	else
20156 	  {
20157 	    str_index = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
20158 	    info_ptr += bytes_read;
20159 	  }
20160 	attr->set_unsigned_reprocess (str_index);
20161       }
20162       break;
20163     default:
20164       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
20165 	     dwarf_form_name (form),
20166 	     bfd_get_filename (abfd));
20167     }
20168 
20169   /* Super hack.  */
20170   if (cu->per_cu->is_dwz && attr->form_is_ref ())
20171     attr->form = DW_FORM_GNU_ref_alt;
20172 
20173   /* We have seen instances where the compiler tried to emit a byte
20174      size attribute of -1 which ended up being encoded as an unsigned
20175      0xffffffff.  Although 0xffffffff is technically a valid size value,
20176      an object of this size seems pretty unlikely so we can relatively
20177      safely treat these cases as if the size attribute was invalid and
20178      treat them as zero by default.  */
20179   if (attr->name == DW_AT_byte_size
20180       && form == DW_FORM_data4
20181       && attr->as_unsigned () >= 0xffffffff)
20182     {
20183       complaint
20184 	(_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
20185 	 hex_string (attr->as_unsigned ()));
20186       attr->set_unsigned (0);
20187     }
20188 
20189   return info_ptr;
20190 }
20191 
20192 /* Read an attribute described by an abbreviated attribute.  */
20193 
20194 static const gdb_byte *
20195 read_attribute (const struct die_reader_specs *reader,
20196 		struct attribute *attr, const struct attr_abbrev *abbrev,
20197 		const gdb_byte *info_ptr)
20198 {
20199   attr->name = abbrev->name;
20200   attr->string_is_canonical = 0;
20201   attr->requires_reprocessing = 0;
20202   return read_attribute_value (reader, attr, abbrev->form,
20203 			       abbrev->implicit_const, info_ptr);
20204 }
20205 
20206 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
20207 
20208 static const char *
20209 read_indirect_string_at_offset (dwarf2_per_objfile *per_objfile,
20210 				LONGEST str_offset)
20211 {
20212   return per_objfile->per_bfd->str.read_string (per_objfile->objfile,
20213 						str_offset, "DW_FORM_strp");
20214 }
20215 
20216 /* Return pointer to string at .debug_str offset as read from BUF.
20217    BUF is assumed to be in a compilation unit described by CU_HEADER.
20218    Return *BYTES_READ_PTR count of bytes read from BUF.  */
20219 
20220 static const char *
20221 read_indirect_string (dwarf2_per_objfile *per_objfile, bfd *abfd,
20222 		      const gdb_byte *buf,
20223 		      const struct comp_unit_head *cu_header,
20224 		      unsigned int *bytes_read_ptr)
20225 {
20226   LONGEST str_offset = cu_header->read_offset (abfd, buf, bytes_read_ptr);
20227 
20228   return read_indirect_string_at_offset (per_objfile, str_offset);
20229 }
20230 
20231 /* See read.h.  */
20232 
20233 const char *
20234 dwarf2_per_objfile::read_line_string (const gdb_byte *buf,
20235 				      const struct comp_unit_head *cu_header,
20236 				      unsigned int *bytes_read_ptr)
20237 {
20238   bfd *abfd = objfile->obfd;
20239   LONGEST str_offset = cu_header->read_offset (abfd, buf, bytes_read_ptr);
20240 
20241   return per_bfd->line_str.read_string (objfile, str_offset, "DW_FORM_line_strp");
20242 }
20243 
20244 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
20245    ADDR_BASE is the DW_AT_addr_base (DW_AT_GNU_addr_base) attribute or zero.
20246    ADDR_SIZE is the size of addresses from the CU header.  */
20247 
20248 static CORE_ADDR
20249 read_addr_index_1 (dwarf2_per_objfile *per_objfile, unsigned int addr_index,
20250 		   gdb::optional<ULONGEST> addr_base, int addr_size)
20251 {
20252   struct objfile *objfile = per_objfile->objfile;
20253   bfd *abfd = objfile->obfd;
20254   const gdb_byte *info_ptr;
20255   ULONGEST addr_base_or_zero = addr_base.has_value () ? *addr_base : 0;
20256 
20257   per_objfile->per_bfd->addr.read (objfile);
20258   if (per_objfile->per_bfd->addr.buffer == NULL)
20259     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
20260 	   objfile_name (objfile));
20261   if (addr_base_or_zero + addr_index * addr_size
20262       >= per_objfile->per_bfd->addr.size)
20263     error (_("DW_FORM_addr_index pointing outside of "
20264 	     ".debug_addr section [in module %s]"),
20265 	   objfile_name (objfile));
20266   info_ptr = (per_objfile->per_bfd->addr.buffer + addr_base_or_zero
20267 	      + addr_index * addr_size);
20268   if (addr_size == 4)
20269     return bfd_get_32 (abfd, info_ptr);
20270   else
20271     return bfd_get_64 (abfd, info_ptr);
20272 }
20273 
20274 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
20275 
20276 static CORE_ADDR
20277 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
20278 {
20279   return read_addr_index_1 (cu->per_objfile, addr_index,
20280 			    cu->addr_base, cu->header.addr_size);
20281 }
20282 
20283 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
20284 
20285 static CORE_ADDR
20286 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
20287 			     unsigned int *bytes_read)
20288 {
20289   bfd *abfd = cu->per_objfile->objfile->obfd;
20290   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
20291 
20292   return read_addr_index (cu, addr_index);
20293 }
20294 
20295 /* See read.h.  */
20296 
20297 CORE_ADDR
20298 dwarf2_read_addr_index (dwarf2_per_cu_data *per_cu,
20299 			dwarf2_per_objfile *per_objfile,
20300 			unsigned int addr_index)
20301 {
20302   struct dwarf2_cu *cu = per_objfile->get_cu (per_cu);
20303   gdb::optional<ULONGEST> addr_base;
20304   int addr_size;
20305 
20306   /* We need addr_base and addr_size.
20307      If we don't have PER_CU->cu, we have to get it.
20308      Nasty, but the alternative is storing the needed info in PER_CU,
20309      which at this point doesn't seem justified: it's not clear how frequently
20310      it would get used and it would increase the size of every PER_CU.
20311      Entry points like dwarf2_per_cu_addr_size do a similar thing
20312      so we're not in uncharted territory here.
20313      Alas we need to be a bit more complicated as addr_base is contained
20314      in the DIE.
20315 
20316      We don't need to read the entire CU(/TU).
20317      We just need the header and top level die.
20318 
20319      IWBN to use the aging mechanism to let us lazily later discard the CU.
20320      For now we skip this optimization.  */
20321 
20322   if (cu != NULL)
20323     {
20324       addr_base = cu->addr_base;
20325       addr_size = cu->header.addr_size;
20326     }
20327   else
20328     {
20329       cutu_reader reader (per_cu, per_objfile, nullptr, nullptr, false);
20330       addr_base = reader.cu->addr_base;
20331       addr_size = reader.cu->header.addr_size;
20332     }
20333 
20334   return read_addr_index_1 (per_objfile, addr_index, addr_base, addr_size);
20335 }
20336 
20337 /* Given a DW_FORM_GNU_str_index value STR_INDEX, fetch the string.
20338    STR_SECTION, STR_OFFSETS_SECTION can be from a Fission stub or a
20339    DWO file.  */
20340 
20341 static const char *
20342 read_str_index (struct dwarf2_cu *cu,
20343 		struct dwarf2_section_info *str_section,
20344 		struct dwarf2_section_info *str_offsets_section,
20345 		ULONGEST str_offsets_base, ULONGEST str_index)
20346 {
20347   dwarf2_per_objfile *per_objfile = cu->per_objfile;
20348   struct objfile *objfile = per_objfile->objfile;
20349   const char *objf_name = objfile_name (objfile);
20350   bfd *abfd = objfile->obfd;
20351   const gdb_byte *info_ptr;
20352   ULONGEST str_offset;
20353   static const char form_name[] = "DW_FORM_GNU_str_index or DW_FORM_strx";
20354 
20355   str_section->read (objfile);
20356   str_offsets_section->read (objfile);
20357   if (str_section->buffer == NULL)
20358     error (_("%s used without %s section"
20359 	     " in CU at offset %s [in module %s]"),
20360 	   form_name, str_section->get_name (),
20361 	   sect_offset_str (cu->header.sect_off), objf_name);
20362   if (str_offsets_section->buffer == NULL)
20363     error (_("%s used without %s section"
20364 	     " in CU at offset %s [in module %s]"),
20365 	   form_name, str_section->get_name (),
20366 	   sect_offset_str (cu->header.sect_off), objf_name);
20367   info_ptr = (str_offsets_section->buffer
20368 	      + str_offsets_base
20369 	      + str_index * cu->header.offset_size);
20370   if (cu->header.offset_size == 4)
20371     str_offset = bfd_get_32 (abfd, info_ptr);
20372   else
20373     str_offset = bfd_get_64 (abfd, info_ptr);
20374   if (str_offset >= str_section->size)
20375     error (_("Offset from %s pointing outside of"
20376 	     " .debug_str.dwo section in CU at offset %s [in module %s]"),
20377 	   form_name, sect_offset_str (cu->header.sect_off), objf_name);
20378   return (const char *) (str_section->buffer + str_offset);
20379 }
20380 
20381 /* Given a DW_FORM_GNU_str_index from a DWO file, fetch the string.  */
20382 
20383 static const char *
20384 read_dwo_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
20385 {
20386   ULONGEST str_offsets_base = reader->cu->header.version >= 5
20387 			      ? reader->cu->header.addr_size : 0;
20388   return read_str_index (reader->cu,
20389 			 &reader->dwo_file->sections.str,
20390 			 &reader->dwo_file->sections.str_offsets,
20391 			 str_offsets_base, str_index);
20392 }
20393 
20394 /* Given a DW_FORM_GNU_str_index from a Fission stub, fetch the string.  */
20395 
20396 static const char *
20397 read_stub_str_index (struct dwarf2_cu *cu, ULONGEST str_index)
20398 {
20399   struct objfile *objfile = cu->per_objfile->objfile;
20400   const char *objf_name = objfile_name (objfile);
20401   static const char form_name[] = "DW_FORM_GNU_str_index";
20402   static const char str_offsets_attr_name[] = "DW_AT_str_offsets";
20403 
20404   if (!cu->str_offsets_base.has_value ())
20405     error (_("%s used in Fission stub without %s"
20406 	     " in CU at offset 0x%lx [in module %s]"),
20407 	   form_name, str_offsets_attr_name,
20408 	   (long) cu->header.offset_size, objf_name);
20409 
20410   return read_str_index (cu,
20411 			 &cu->per_objfile->per_bfd->str,
20412 			 &cu->per_objfile->per_bfd->str_offsets,
20413 			 *cu->str_offsets_base, str_index);
20414 }
20415 
20416 /* Return the length of an LEB128 number in BUF.  */
20417 
20418 static int
20419 leb128_size (const gdb_byte *buf)
20420 {
20421   const gdb_byte *begin = buf;
20422   gdb_byte byte;
20423 
20424   while (1)
20425     {
20426       byte = *buf++;
20427       if ((byte & 128) == 0)
20428 	return buf - begin;
20429     }
20430 }
20431 
20432 static enum language
20433 dwarf_lang_to_enum_language (unsigned int lang)
20434 {
20435   enum language language;
20436 
20437   switch (lang)
20438     {
20439     case DW_LANG_C89:
20440     case DW_LANG_C99:
20441     case DW_LANG_C11:
20442     case DW_LANG_C:
20443     case DW_LANG_UPC:
20444       language = language_c;
20445       break;
20446     case DW_LANG_Java:
20447     case DW_LANG_C_plus_plus:
20448     case DW_LANG_C_plus_plus_11:
20449     case DW_LANG_C_plus_plus_14:
20450       language = language_cplus;
20451       break;
20452     case DW_LANG_D:
20453       language = language_d;
20454       break;
20455     case DW_LANG_Fortran77:
20456     case DW_LANG_Fortran90:
20457     case DW_LANG_Fortran95:
20458     case DW_LANG_Fortran03:
20459     case DW_LANG_Fortran08:
20460       language = language_fortran;
20461       break;
20462     case DW_LANG_Go:
20463       language = language_go;
20464       break;
20465     case DW_LANG_Mips_Assembler:
20466       language = language_asm;
20467       break;
20468     case DW_LANG_Ada83:
20469     case DW_LANG_Ada95:
20470       language = language_ada;
20471       break;
20472     case DW_LANG_Modula2:
20473       language = language_m2;
20474       break;
20475     case DW_LANG_Pascal83:
20476       language = language_pascal;
20477       break;
20478     case DW_LANG_ObjC:
20479       language = language_objc;
20480       break;
20481     case DW_LANG_Rust:
20482     case DW_LANG_Rust_old:
20483       language = language_rust;
20484       break;
20485     case DW_LANG_OpenCL:
20486       language = language_opencl;
20487       break;
20488     case DW_LANG_Cobol74:
20489     case DW_LANG_Cobol85:
20490     default:
20491       language = language_minimal;
20492       break;
20493     }
20494 
20495   return language;
20496 }
20497 
20498 /* Return the named attribute or NULL if not there.  */
20499 
20500 static struct attribute *
20501 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20502 {
20503   for (;;)
20504     {
20505       unsigned int i;
20506       struct attribute *spec = NULL;
20507 
20508       for (i = 0; i < die->num_attrs; ++i)
20509 	{
20510 	  if (die->attrs[i].name == name)
20511 	    return &die->attrs[i];
20512 	  if (die->attrs[i].name == DW_AT_specification
20513 	      || die->attrs[i].name == DW_AT_abstract_origin)
20514 	    spec = &die->attrs[i];
20515 	}
20516 
20517       if (!spec)
20518 	break;
20519 
20520       die = follow_die_ref (die, spec, &cu);
20521     }
20522 
20523   return NULL;
20524 }
20525 
20526 /* Return the string associated with a string-typed attribute, or NULL if it
20527    is either not found or is of an incorrect type.  */
20528 
20529 static const char *
20530 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20531 {
20532   struct attribute *attr;
20533   const char *str = NULL;
20534 
20535   attr = dwarf2_attr (die, name, cu);
20536 
20537   if (attr != NULL)
20538     {
20539       str = attr->as_string ();
20540       if (str == nullptr)
20541 	complaint (_("string type expected for attribute %s for "
20542 		     "DIE at %s in module %s"),
20543 		   dwarf_attr_name (name), sect_offset_str (die->sect_off),
20544 		   objfile_name (cu->per_objfile->objfile));
20545     }
20546 
20547   return str;
20548 }
20549 
20550 /* Return the dwo name or NULL if not present. If present, it is in either
20551    DW_AT_GNU_dwo_name or DW_AT_dwo_name attribute.  */
20552 static const char *
20553 dwarf2_dwo_name (struct die_info *die, struct dwarf2_cu *cu)
20554 {
20555   const char *dwo_name = dwarf2_string_attr (die, DW_AT_GNU_dwo_name, cu);
20556   if (dwo_name == nullptr)
20557     dwo_name = dwarf2_string_attr (die, DW_AT_dwo_name, cu);
20558   return dwo_name;
20559 }
20560 
20561 /* Return non-zero iff the attribute NAME is defined for the given DIE,
20562    and holds a non-zero value.  This function should only be used for
20563    DW_FORM_flag or DW_FORM_flag_present attributes.  */
20564 
20565 static int
20566 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
20567 {
20568   struct attribute *attr = dwarf2_attr (die, name, cu);
20569 
20570   return attr != nullptr && attr->as_boolean ();
20571 }
20572 
20573 static int
20574 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
20575 {
20576   /* A DIE is a declaration if it has a DW_AT_declaration attribute
20577      which value is non-zero.  However, we have to be careful with
20578      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
20579      (via dwarf2_flag_true_p) follows this attribute.  So we may
20580      end up accidently finding a declaration attribute that belongs
20581      to a different DIE referenced by the specification attribute,
20582      even though the given DIE does not have a declaration attribute.  */
20583   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
20584 	  && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
20585 }
20586 
20587 /* Return the die giving the specification for DIE, if there is
20588    one.  *SPEC_CU is the CU containing DIE on input, and the CU
20589    containing the return value on output.  If there is no
20590    specification, but there is an abstract origin, that is
20591    returned.  */
20592 
20593 static struct die_info *
20594 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
20595 {
20596   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
20597 					     *spec_cu);
20598 
20599   if (spec_attr == NULL)
20600     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
20601 
20602   if (spec_attr == NULL)
20603     return NULL;
20604   else
20605     return follow_die_ref (die, spec_attr, spec_cu);
20606 }
20607 
20608 /* A convenience function to find the proper .debug_line section for a CU.  */
20609 
20610 static struct dwarf2_section_info *
20611 get_debug_line_section (struct dwarf2_cu *cu)
20612 {
20613   struct dwarf2_section_info *section;
20614   dwarf2_per_objfile *per_objfile = cu->per_objfile;
20615 
20616   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20617      DWO file.  */
20618   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20619     section = &cu->dwo_unit->dwo_file->sections.line;
20620   else if (cu->per_cu->is_dwz)
20621     {
20622       dwz_file *dwz = dwarf2_get_dwz_file (per_objfile->per_bfd, true);
20623 
20624       section = &dwz->line;
20625     }
20626   else
20627     section = &per_objfile->per_bfd->line;
20628 
20629   return section;
20630 }
20631 
20632 /* Read the statement program header starting at OFFSET in
20633    .debug_line, or .debug_line.dwo.  Return a pointer
20634    to a struct line_header, allocated using xmalloc.
20635    Returns NULL if there is a problem reading the header, e.g., if it
20636    has a version we don't understand.
20637 
20638    NOTE: the strings in the include directory and file name tables of
20639    the returned object point into the dwarf line section buffer,
20640    and must not be freed.  */
20641 
20642 static line_header_up
20643 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20644 {
20645   struct dwarf2_section_info *section;
20646   dwarf2_per_objfile *per_objfile = cu->per_objfile;
20647 
20648   section = get_debug_line_section (cu);
20649   section->read (per_objfile->objfile);
20650   if (section->buffer == NULL)
20651     {
20652       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20653 	complaint (_("missing .debug_line.dwo section"));
20654       else
20655 	complaint (_("missing .debug_line section"));
20656       return 0;
20657     }
20658 
20659   return dwarf_decode_line_header (sect_off, cu->per_cu->is_dwz,
20660 				   per_objfile, section, &cu->header);
20661 }
20662 
20663 /* Subroutine of dwarf_decode_lines to simplify it.
20664    Return the file name of the psymtab for the given file_entry.
20665    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20666    If space for the result is malloc'd, *NAME_HOLDER will be set.
20667    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20668 
20669 static const char *
20670 psymtab_include_file_name (const struct line_header *lh, const file_entry &fe,
20671 			   const dwarf2_psymtab *pst,
20672 			   const char *comp_dir,
20673 			   gdb::unique_xmalloc_ptr<char> *name_holder)
20674 {
20675   const char *include_name = fe.name;
20676   const char *include_name_to_compare = include_name;
20677   const char *pst_filename;
20678   int file_is_pst;
20679 
20680   const char *dir_name = fe.include_dir (lh);
20681 
20682   gdb::unique_xmalloc_ptr<char> hold_compare;
20683   if (!IS_ABSOLUTE_PATH (include_name)
20684       && (dir_name != NULL || comp_dir != NULL))
20685     {
20686       /* Avoid creating a duplicate psymtab for PST.
20687 	 We do this by comparing INCLUDE_NAME and PST_FILENAME.
20688 	 Before we do the comparison, however, we need to account
20689 	 for DIR_NAME and COMP_DIR.
20690 	 First prepend dir_name (if non-NULL).  If we still don't
20691 	 have an absolute path prepend comp_dir (if non-NULL).
20692 	 However, the directory we record in the include-file's
20693 	 psymtab does not contain COMP_DIR (to match the
20694 	 corresponding symtab(s)).
20695 
20696 	 Example:
20697 
20698 	 bash$ cd /tmp
20699 	 bash$ gcc -g ./hello.c
20700 	 include_name = "hello.c"
20701 	 dir_name = "."
20702 	 DW_AT_comp_dir = comp_dir = "/tmp"
20703 	 DW_AT_name = "./hello.c"
20704 
20705       */
20706 
20707       if (dir_name != NULL)
20708 	{
20709 	  name_holder->reset (concat (dir_name, SLASH_STRING,
20710 				      include_name, (char *) NULL));
20711 	  include_name = name_holder->get ();
20712 	  include_name_to_compare = include_name;
20713 	}
20714       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20715 	{
20716 	  hold_compare.reset (concat (comp_dir, SLASH_STRING,
20717 				      include_name, (char *) NULL));
20718 	  include_name_to_compare = hold_compare.get ();
20719 	}
20720     }
20721 
20722   pst_filename = pst->filename;
20723   gdb::unique_xmalloc_ptr<char> copied_name;
20724   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20725     {
20726       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20727 				 pst_filename, (char *) NULL));
20728       pst_filename = copied_name.get ();
20729     }
20730 
20731   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20732 
20733   if (file_is_pst)
20734     return NULL;
20735   return include_name;
20736 }
20737 
20738 /* State machine to track the state of the line number program.  */
20739 
20740 class lnp_state_machine
20741 {
20742 public:
20743   /* Initialize a machine state for the start of a line number
20744      program.  */
20745   lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch, line_header *lh,
20746 		     bool record_lines_p);
20747 
20748   file_entry *current_file ()
20749   {
20750     /* lh->file_names is 0-based, but the file name numbers in the
20751        statement program are 1-based.  */
20752     return m_line_header->file_name_at (m_file);
20753   }
20754 
20755   /* Record the line in the state machine.  END_SEQUENCE is true if
20756      we're processing the end of a sequence.  */
20757   void record_line (bool end_sequence);
20758 
20759   /* Check ADDRESS is -1, or zero and less than UNRELOCATED_LOWPC, and if true
20760      nop-out rest of the lines in this sequence.  */
20761   void check_line_address (struct dwarf2_cu *cu,
20762 			   const gdb_byte *line_ptr,
20763 			   CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20764 
20765   void handle_set_discriminator (unsigned int discriminator)
20766   {
20767     m_discriminator = discriminator;
20768     m_line_has_non_zero_discriminator |= discriminator != 0;
20769   }
20770 
20771   /* Handle DW_LNE_set_address.  */
20772   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20773   {
20774     m_op_index = 0;
20775     address += baseaddr;
20776     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20777   }
20778 
20779   /* Handle DW_LNS_advance_pc.  */
20780   void handle_advance_pc (CORE_ADDR adjust);
20781 
20782   /* Handle a special opcode.  */
20783   void handle_special_opcode (unsigned char op_code);
20784 
20785   /* Handle DW_LNS_advance_line.  */
20786   void handle_advance_line (int line_delta)
20787   {
20788     advance_line (line_delta);
20789   }
20790 
20791   /* Handle DW_LNS_set_file.  */
20792   void handle_set_file (file_name_index file);
20793 
20794   /* Handle DW_LNS_negate_stmt.  */
20795   void handle_negate_stmt ()
20796   {
20797     m_is_stmt = !m_is_stmt;
20798   }
20799 
20800   /* Handle DW_LNS_const_add_pc.  */
20801   void handle_const_add_pc ();
20802 
20803   /* Handle DW_LNS_fixed_advance_pc.  */
20804   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20805   {
20806     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20807     m_op_index = 0;
20808   }
20809 
20810   /* Handle DW_LNS_copy.  */
20811   void handle_copy ()
20812   {
20813     record_line (false);
20814     m_discriminator = 0;
20815   }
20816 
20817   /* Handle DW_LNE_end_sequence.  */
20818   void handle_end_sequence ()
20819   {
20820     m_currently_recording_lines = true;
20821   }
20822 
20823 private:
20824   /* Advance the line by LINE_DELTA.  */
20825   void advance_line (int line_delta)
20826   {
20827     m_line += line_delta;
20828 
20829     if (line_delta != 0)
20830       m_line_has_non_zero_discriminator = m_discriminator != 0;
20831   }
20832 
20833   struct dwarf2_cu *m_cu;
20834 
20835   gdbarch *m_gdbarch;
20836 
20837   /* True if we're recording lines.
20838      Otherwise we're building partial symtabs and are just interested in
20839      finding include files mentioned by the line number program.  */
20840   bool m_record_lines_p;
20841 
20842   /* The line number header.  */
20843   line_header *m_line_header;
20844 
20845   /* These are part of the standard DWARF line number state machine,
20846      and initialized according to the DWARF spec.  */
20847 
20848   unsigned char m_op_index = 0;
20849   /* The line table index of the current file.  */
20850   file_name_index m_file = 1;
20851   unsigned int m_line = 1;
20852 
20853   /* These are initialized in the constructor.  */
20854 
20855   CORE_ADDR m_address;
20856   bool m_is_stmt;
20857   unsigned int m_discriminator;
20858 
20859   /* Additional bits of state we need to track.  */
20860 
20861   /* The last file that we called dwarf2_start_subfile for.
20862      This is only used for TLLs.  */
20863   unsigned int m_last_file = 0;
20864   /* The last file a line number was recorded for.  */
20865   struct subfile *m_last_subfile = NULL;
20866 
20867   /* The address of the last line entry.  */
20868   CORE_ADDR m_last_address;
20869 
20870   /* Set to true when a previous line at the same address (using
20871      m_last_address) had m_is_stmt true.  This is reset to false when a
20872      line entry at a new address (m_address different to m_last_address) is
20873      processed.  */
20874   bool m_stmt_at_address = false;
20875 
20876   /* When true, record the lines we decode.  */
20877   bool m_currently_recording_lines = false;
20878 
20879   /* The last line number that was recorded, used to coalesce
20880      consecutive entries for the same line.  This can happen, for
20881      example, when discriminators are present.  PR 17276.  */
20882   unsigned int m_last_line = 0;
20883   bool m_line_has_non_zero_discriminator = false;
20884 };
20885 
20886 void
20887 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20888 {
20889   CORE_ADDR addr_adj = (((m_op_index + adjust)
20890 			 / m_line_header->maximum_ops_per_instruction)
20891 			* m_line_header->minimum_instruction_length);
20892   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20893   m_op_index = ((m_op_index + adjust)
20894 		% m_line_header->maximum_ops_per_instruction);
20895 }
20896 
20897 void
20898 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20899 {
20900   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20901   unsigned char adj_opcode_d = adj_opcode / m_line_header->line_range;
20902   unsigned char adj_opcode_r = adj_opcode % m_line_header->line_range;
20903   CORE_ADDR addr_adj = (((m_op_index + adj_opcode_d)
20904 			 / m_line_header->maximum_ops_per_instruction)
20905 			* m_line_header->minimum_instruction_length);
20906   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20907   m_op_index = ((m_op_index + adj_opcode_d)
20908 		% m_line_header->maximum_ops_per_instruction);
20909 
20910   int line_delta = m_line_header->line_base + adj_opcode_r;
20911   advance_line (line_delta);
20912   record_line (false);
20913   m_discriminator = 0;
20914 }
20915 
20916 void
20917 lnp_state_machine::handle_set_file (file_name_index file)
20918 {
20919   m_file = file;
20920 
20921   const file_entry *fe = current_file ();
20922   if (fe == NULL)
20923     dwarf2_debug_line_missing_file_complaint ();
20924   else if (m_record_lines_p)
20925     {
20926       const char *dir = fe->include_dir (m_line_header);
20927 
20928       m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
20929       m_line_has_non_zero_discriminator = m_discriminator != 0;
20930       dwarf2_start_subfile (m_cu, fe->name, dir);
20931     }
20932 }
20933 
20934 void
20935 lnp_state_machine::handle_const_add_pc ()
20936 {
20937   CORE_ADDR adjust
20938     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20939 
20940   CORE_ADDR addr_adj
20941     = (((m_op_index + adjust)
20942 	/ m_line_header->maximum_ops_per_instruction)
20943        * m_line_header->minimum_instruction_length);
20944 
20945   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20946   m_op_index = ((m_op_index + adjust)
20947 		% m_line_header->maximum_ops_per_instruction);
20948 }
20949 
20950 /* Return non-zero if we should add LINE to the line number table.
20951    LINE is the line to add, LAST_LINE is the last line that was added,
20952    LAST_SUBFILE is the subfile for LAST_LINE.
20953    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20954    had a non-zero discriminator.
20955 
20956    We have to be careful in the presence of discriminators.
20957    E.g., for this line:
20958 
20959      for (i = 0; i < 100000; i++);
20960 
20961    clang can emit four line number entries for that one line,
20962    each with a different discriminator.
20963    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20964 
20965    However, we want gdb to coalesce all four entries into one.
20966    Otherwise the user could stepi into the middle of the line and
20967    gdb would get confused about whether the pc really was in the
20968    middle of the line.
20969 
20970    Things are further complicated by the fact that two consecutive
20971    line number entries for the same line is a heuristic used by gcc
20972    to denote the end of the prologue.  So we can't just discard duplicate
20973    entries, we have to be selective about it.  The heuristic we use is
20974    that we only collapse consecutive entries for the same line if at least
20975    one of those entries has a non-zero discriminator.  PR 17276.
20976 
20977    Note: Addresses in the line number state machine can never go backwards
20978    within one sequence, thus this coalescing is ok.  */
20979 
20980 static int
20981 dwarf_record_line_p (struct dwarf2_cu *cu,
20982 		     unsigned int line, unsigned int last_line,
20983 		     int line_has_non_zero_discriminator,
20984 		     struct subfile *last_subfile)
20985 {
20986   if (cu->get_builder ()->get_current_subfile () != last_subfile)
20987     return 1;
20988   if (line != last_line)
20989     return 1;
20990   /* Same line for the same file that we've seen already.
20991      As a last check, for pr 17276, only record the line if the line
20992      has never had a non-zero discriminator.  */
20993   if (!line_has_non_zero_discriminator)
20994     return 1;
20995   return 0;
20996 }
20997 
20998 /* Use the CU's builder to record line number LINE beginning at
20999    address ADDRESS in the line table of subfile SUBFILE.  */
21000 
21001 static void
21002 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
21003 		     unsigned int line, CORE_ADDR address, bool is_stmt,
21004 		     struct dwarf2_cu *cu)
21005 {
21006   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
21007 
21008   if (dwarf_line_debug)
21009     {
21010       fprintf_unfiltered (gdb_stdlog,
21011 			  "Recording line %u, file %s, address %s\n",
21012 			  line, lbasename (subfile->name),
21013 			  paddress (gdbarch, address));
21014     }
21015 
21016   if (cu != nullptr)
21017     cu->get_builder ()->record_line (subfile, line, addr, is_stmt);
21018 }
21019 
21020 /* Subroutine of dwarf_decode_lines_1 to simplify it.
21021    Mark the end of a set of line number records.
21022    The arguments are the same as for dwarf_record_line_1.
21023    If SUBFILE is NULL the request is ignored.  */
21024 
21025 static void
21026 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
21027 		   CORE_ADDR address, struct dwarf2_cu *cu)
21028 {
21029   if (subfile == NULL)
21030     return;
21031 
21032   if (dwarf_line_debug)
21033     {
21034       fprintf_unfiltered (gdb_stdlog,
21035 			  "Finishing current line, file %s, address %s\n",
21036 			  lbasename (subfile->name),
21037 			  paddress (gdbarch, address));
21038     }
21039 
21040   dwarf_record_line_1 (gdbarch, subfile, 0, address, true, cu);
21041 }
21042 
21043 void
21044 lnp_state_machine::record_line (bool end_sequence)
21045 {
21046   if (dwarf_line_debug)
21047     {
21048       fprintf_unfiltered (gdb_stdlog,
21049 			  "Processing actual line %u: file %u,"
21050 			  " address %s, is_stmt %u, discrim %u%s\n",
21051 			  m_line, m_file,
21052 			  paddress (m_gdbarch, m_address),
21053 			  m_is_stmt, m_discriminator,
21054 			  (end_sequence ? "\t(end sequence)" : ""));
21055     }
21056 
21057   file_entry *fe = current_file ();
21058 
21059   if (fe == NULL)
21060     dwarf2_debug_line_missing_file_complaint ();
21061   /* For now we ignore lines not starting on an instruction boundary.
21062      But not when processing end_sequence for compatibility with the
21063      previous version of the code.  */
21064   else if (m_op_index == 0 || end_sequence)
21065     {
21066       fe->included_p = 1;
21067       if (m_record_lines_p)
21068 	{
21069 	  /* When we switch files we insert an end maker in the first file,
21070 	     switch to the second file and add a new line entry.  The
21071 	     problem is that the end marker inserted in the first file will
21072 	     discard any previous line entries at the same address.  If the
21073 	     line entries in the first file are marked as is-stmt, while
21074 	     the new line in the second file is non-stmt, then this means
21075 	     the end marker will discard is-stmt lines so we can have a
21076 	     non-stmt line.  This means that there are less addresses at
21077 	     which the user can insert a breakpoint.
21078 
21079 	     To improve this we track the last address in m_last_address,
21080 	     and whether we have seen an is-stmt at this address.  Then
21081 	     when switching files, if we have seen a stmt at the current
21082 	     address, and we are switching to create a non-stmt line, then
21083 	     discard the new line.  */
21084 	  bool file_changed
21085 	    = m_last_subfile != m_cu->get_builder ()->get_current_subfile ();
21086 	  bool ignore_this_line
21087 	   = ((file_changed && !end_sequence && m_last_address == m_address
21088 	       && !m_is_stmt && m_stmt_at_address)
21089 	      || (!end_sequence && m_line == 0));
21090 
21091 	  if ((file_changed && !ignore_this_line) || end_sequence)
21092 	    {
21093 	      dwarf_finish_line (m_gdbarch, m_last_subfile, m_address,
21094 				 m_currently_recording_lines ? m_cu : nullptr);
21095 	    }
21096 
21097 	  if (!end_sequence && !ignore_this_line)
21098 	    {
21099 	      bool is_stmt = producer_is_codewarrior (m_cu) || m_is_stmt;
21100 
21101 	      if (dwarf_record_line_p (m_cu, m_line, m_last_line,
21102 				       m_line_has_non_zero_discriminator,
21103 				       m_last_subfile))
21104 		{
21105 		  buildsym_compunit *builder = m_cu->get_builder ();
21106 		  dwarf_record_line_1 (m_gdbarch,
21107 				       builder->get_current_subfile (),
21108 				       m_line, m_address, is_stmt,
21109 				       m_currently_recording_lines ? m_cu : nullptr);
21110 		}
21111 	      m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
21112 	      m_last_line = m_line;
21113 	    }
21114 	}
21115     }
21116 
21117   /* Track whether we have seen any m_is_stmt true at m_address in case we
21118      have multiple line table entries all at m_address.  */
21119   if (m_last_address != m_address)
21120     {
21121       m_stmt_at_address = false;
21122       m_last_address = m_address;
21123     }
21124   m_stmt_at_address |= m_is_stmt;
21125 }
21126 
21127 lnp_state_machine::lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch,
21128 				      line_header *lh, bool record_lines_p)
21129 {
21130   m_cu = cu;
21131   m_gdbarch = arch;
21132   m_record_lines_p = record_lines_p;
21133   m_line_header = lh;
21134 
21135   m_currently_recording_lines = true;
21136 
21137   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
21138      was a line entry for it so that the backend has a chance to adjust it
21139      and also record it in case it needs it.  This is currently used by MIPS
21140      code, cf. `mips_adjust_dwarf2_line'.  */
21141   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
21142   m_is_stmt = lh->default_is_stmt;
21143   m_discriminator = 0;
21144 
21145   m_last_address = m_address;
21146   m_stmt_at_address = false;
21147 }
21148 
21149 void
21150 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
21151 				       const gdb_byte *line_ptr,
21152 				       CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
21153 {
21154   /* Linkers resolve a symbolic relocation referencing a GC'd function to 0 or
21155      -1.  If ADDRESS is 0, ignoring the opcode will err if the text section is
21156      located at 0x0.  In this case, additionally check that if
21157      ADDRESS < UNRELOCATED_LOWPC.  */
21158 
21159   if ((address == 0 && address < unrelocated_lowpc)
21160       || address == (CORE_ADDR) -1)
21161     {
21162       /* This line table is for a function which has been
21163 	 GCd by the linker.  Ignore it.  PR gdb/12528 */
21164 
21165       struct objfile *objfile = cu->per_objfile->objfile;
21166       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
21167 
21168       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
21169 		 line_offset, objfile_name (objfile));
21170       m_currently_recording_lines = false;
21171       /* Note: m_currently_recording_lines is left as false until we see
21172 	 DW_LNE_end_sequence.  */
21173     }
21174 }
21175 
21176 /* Subroutine of dwarf_decode_lines to simplify it.
21177    Process the line number information in LH.
21178    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
21179    program in order to set included_p for every referenced header.  */
21180 
21181 static void
21182 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
21183 		      const int decode_for_pst_p, CORE_ADDR lowpc)
21184 {
21185   const gdb_byte *line_ptr, *extended_end;
21186   const gdb_byte *line_end;
21187   unsigned int bytes_read, extended_len;
21188   unsigned char op_code, extended_op;
21189   CORE_ADDR baseaddr;
21190   struct objfile *objfile = cu->per_objfile->objfile;
21191   bfd *abfd = objfile->obfd;
21192   struct gdbarch *gdbarch = objfile->arch ();
21193   /* True if we're recording line info (as opposed to building partial
21194      symtabs and just interested in finding include files mentioned by
21195      the line number program).  */
21196   bool record_lines_p = !decode_for_pst_p;
21197 
21198   baseaddr = objfile->text_section_offset ();
21199 
21200   line_ptr = lh->statement_program_start;
21201   line_end = lh->statement_program_end;
21202 
21203   /* Read the statement sequences until there's nothing left.  */
21204   while (line_ptr < line_end)
21205     {
21206       /* The DWARF line number program state machine.  Reset the state
21207 	 machine at the start of each sequence.  */
21208       lnp_state_machine state_machine (cu, gdbarch, lh, record_lines_p);
21209       bool end_sequence = false;
21210 
21211       if (record_lines_p)
21212 	{
21213 	  /* Start a subfile for the current file of the state
21214 	     machine.  */
21215 	  const file_entry *fe = state_machine.current_file ();
21216 
21217 	  if (fe != NULL)
21218 	    dwarf2_start_subfile (cu, fe->name, fe->include_dir (lh));
21219 	}
21220 
21221       /* Decode the table.  */
21222       while (line_ptr < line_end && !end_sequence)
21223 	{
21224 	  op_code = read_1_byte (abfd, line_ptr);
21225 	  line_ptr += 1;
21226 
21227 	  if (op_code >= lh->opcode_base)
21228 	    {
21229 	      /* Special opcode.  */
21230 	      state_machine.handle_special_opcode (op_code);
21231 	    }
21232 	  else switch (op_code)
21233 	    {
21234 	    case DW_LNS_extended_op:
21235 	      extended_len = read_unsigned_leb128 (abfd, line_ptr,
21236 						   &bytes_read);
21237 	      line_ptr += bytes_read;
21238 	      extended_end = line_ptr + extended_len;
21239 	      extended_op = read_1_byte (abfd, line_ptr);
21240 	      line_ptr += 1;
21241 	      if (DW_LNE_lo_user <= extended_op
21242 		  && extended_op <= DW_LNE_hi_user)
21243 		{
21244 		  /* Vendor extension, ignore.  */
21245 		  line_ptr = extended_end;
21246 		  break;
21247 		}
21248 	      switch (extended_op)
21249 		{
21250 		case DW_LNE_end_sequence:
21251 		  state_machine.handle_end_sequence ();
21252 		  end_sequence = true;
21253 		  break;
21254 		case DW_LNE_set_address:
21255 		  {
21256 		    CORE_ADDR address
21257 		      = cu->header.read_address (abfd, line_ptr, &bytes_read);
21258 		    line_ptr += bytes_read;
21259 
21260 		    state_machine.check_line_address (cu, line_ptr,
21261 						      lowpc - baseaddr, address);
21262 		    state_machine.handle_set_address (baseaddr, address);
21263 		  }
21264 		  break;
21265 		case DW_LNE_define_file:
21266 		  {
21267 		    const char *cur_file;
21268 		    unsigned int mod_time, length;
21269 		    dir_index dindex;
21270 
21271 		    cur_file = read_direct_string (abfd, line_ptr,
21272 						   &bytes_read);
21273 		    line_ptr += bytes_read;
21274 		    dindex = (dir_index)
21275 		      read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21276 		    line_ptr += bytes_read;
21277 		    mod_time =
21278 		      read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21279 		    line_ptr += bytes_read;
21280 		    length =
21281 		      read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21282 		    line_ptr += bytes_read;
21283 		    lh->add_file_name (cur_file, dindex, mod_time, length);
21284 		  }
21285 		  break;
21286 		case DW_LNE_set_discriminator:
21287 		  {
21288 		    /* The discriminator is not interesting to the
21289 		       debugger; just ignore it.  We still need to
21290 		       check its value though:
21291 		       if there are consecutive entries for the same
21292 		       (non-prologue) line we want to coalesce them.
21293 		       PR 17276.  */
21294 		    unsigned int discr
21295 		      = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21296 		    line_ptr += bytes_read;
21297 
21298 		    state_machine.handle_set_discriminator (discr);
21299 		  }
21300 		  break;
21301 		default:
21302 		  complaint (_("mangled .debug_line section"));
21303 		  return;
21304 		}
21305 	      /* Make sure that we parsed the extended op correctly.  If e.g.
21306 		 we expected a different address size than the producer used,
21307 		 we may have read the wrong number of bytes.  */
21308 	      if (line_ptr != extended_end)
21309 		{
21310 		  complaint (_("mangled .debug_line section"));
21311 		  return;
21312 		}
21313 	      break;
21314 	    case DW_LNS_copy:
21315 	      state_machine.handle_copy ();
21316 	      break;
21317 	    case DW_LNS_advance_pc:
21318 	      {
21319 		CORE_ADDR adjust
21320 		  = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21321 		line_ptr += bytes_read;
21322 
21323 		state_machine.handle_advance_pc (adjust);
21324 	      }
21325 	      break;
21326 	    case DW_LNS_advance_line:
21327 	      {
21328 		int line_delta
21329 		  = read_signed_leb128 (abfd, line_ptr, &bytes_read);
21330 		line_ptr += bytes_read;
21331 
21332 		state_machine.handle_advance_line (line_delta);
21333 	      }
21334 	      break;
21335 	    case DW_LNS_set_file:
21336 	      {
21337 		file_name_index file
21338 		  = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
21339 							    &bytes_read);
21340 		line_ptr += bytes_read;
21341 
21342 		state_machine.handle_set_file (file);
21343 	      }
21344 	      break;
21345 	    case DW_LNS_set_column:
21346 	      (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21347 	      line_ptr += bytes_read;
21348 	      break;
21349 	    case DW_LNS_negate_stmt:
21350 	      state_machine.handle_negate_stmt ();
21351 	      break;
21352 	    case DW_LNS_set_basic_block:
21353 	      break;
21354 	    /* Add to the address register of the state machine the
21355 	       address increment value corresponding to special opcode
21356 	       255.  I.e., this value is scaled by the minimum
21357 	       instruction length since special opcode 255 would have
21358 	       scaled the increment.  */
21359 	    case DW_LNS_const_add_pc:
21360 	      state_machine.handle_const_add_pc ();
21361 	      break;
21362 	    case DW_LNS_fixed_advance_pc:
21363 	      {
21364 		CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21365 		line_ptr += 2;
21366 
21367 		state_machine.handle_fixed_advance_pc (addr_adj);
21368 	      }
21369 	      break;
21370 	    default:
21371 	      {
21372 		/* Unknown standard opcode, ignore it.  */
21373 		int i;
21374 
21375 		for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21376 		  {
21377 		    (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21378 		    line_ptr += bytes_read;
21379 		  }
21380 	      }
21381 	    }
21382 	}
21383 
21384       if (!end_sequence)
21385 	dwarf2_debug_line_missing_end_sequence_complaint ();
21386 
21387       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21388 	 in which case we still finish recording the last line).  */
21389       state_machine.record_line (true);
21390     }
21391 }
21392 
21393 /* Decode the Line Number Program (LNP) for the given line_header
21394    structure and CU.  The actual information extracted and the type
21395    of structures created from the LNP depends on the value of PST.
21396 
21397    1. If PST is NULL, then this procedure uses the data from the program
21398       to create all necessary symbol tables, and their linetables.
21399 
21400    2. If PST is not NULL, this procedure reads the program to determine
21401       the list of files included by the unit represented by PST, and
21402       builds all the associated partial symbol tables.
21403 
21404    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21405    It is used for relative paths in the line table.
21406    NOTE: When processing partial symtabs (pst != NULL),
21407    comp_dir == pst->dirname.
21408 
21409    NOTE: It is important that psymtabs have the same file name (via strcmp)
21410    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21411    symtab we don't use it in the name of the psymtabs we create.
21412    E.g. expand_line_sal requires this when finding psymtabs to expand.
21413    A good testcase for this is mb-inline.exp.
21414 
21415    LOWPC is the lowest address in CU (or 0 if not known).
21416 
21417    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21418    for its PC<->lines mapping information.  Otherwise only the filename
21419    table is read in.  */
21420 
21421 static void
21422 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21423 		    struct dwarf2_cu *cu, dwarf2_psymtab *pst,
21424 		    CORE_ADDR lowpc, int decode_mapping)
21425 {
21426   struct objfile *objfile = cu->per_objfile->objfile;
21427   const int decode_for_pst_p = (pst != NULL);
21428 
21429   if (decode_mapping)
21430     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21431 
21432   if (decode_for_pst_p)
21433     {
21434       /* Now that we're done scanning the Line Header Program, we can
21435 	 create the psymtab of each included file.  */
21436       for (auto &file_entry : lh->file_names ())
21437 	if (file_entry.included_p == 1)
21438 	  {
21439 	    gdb::unique_xmalloc_ptr<char> name_holder;
21440 	    const char *include_name =
21441 	      psymtab_include_file_name (lh, file_entry, pst,
21442 					 comp_dir, &name_holder);
21443 	    if (include_name != NULL)
21444 	      dwarf2_create_include_psymtab
21445 		(cu->per_objfile->per_bfd, include_name, pst,
21446 		 cu->per_objfile->per_bfd->partial_symtabs.get (),
21447 		 objfile->per_bfd);
21448 	  }
21449     }
21450   else
21451     {
21452       /* Make sure a symtab is created for every file, even files
21453 	 which contain only variables (i.e. no code with associated
21454 	 line numbers).  */
21455       buildsym_compunit *builder = cu->get_builder ();
21456       struct compunit_symtab *cust = builder->get_compunit_symtab ();
21457 
21458       for (auto &fe : lh->file_names ())
21459 	{
21460 	  dwarf2_start_subfile (cu, fe.name, fe.include_dir (lh));
21461 	  if (builder->get_current_subfile ()->symtab == NULL)
21462 	    {
21463 	      builder->get_current_subfile ()->symtab
21464 		= allocate_symtab (cust,
21465 				   builder->get_current_subfile ()->name);
21466 	    }
21467 	  fe.symtab = builder->get_current_subfile ()->symtab;
21468 	}
21469     }
21470 }
21471 
21472 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21473    DIRNAME the name of the source directory which contains FILENAME
21474    or NULL if not known.
21475    This routine tries to keep line numbers from identical absolute and
21476    relative file names in a common subfile.
21477 
21478    Using the `list' example from the GDB testsuite, which resides in
21479    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21480    of /srcdir/list0.c yields the following debugging information for list0.c:
21481 
21482    DW_AT_name:          /srcdir/list0.c
21483    DW_AT_comp_dir:      /compdir
21484    files.files[0].name: list0.h
21485    files.files[0].dir:  /srcdir
21486    files.files[1].name: list0.c
21487    files.files[1].dir:  /srcdir
21488 
21489    The line number information for list0.c has to end up in a single
21490    subfile, so that `break /srcdir/list0.c:1' works as expected.
21491    start_subfile will ensure that this happens provided that we pass the
21492    concatenation of files.files[1].dir and files.files[1].name as the
21493    subfile's name.  */
21494 
21495 static void
21496 dwarf2_start_subfile (struct dwarf2_cu *cu, const char *filename,
21497 		      const char *dirname)
21498 {
21499   gdb::unique_xmalloc_ptr<char> copy;
21500 
21501   /* In order not to lose the line information directory,
21502      we concatenate it to the filename when it makes sense.
21503      Note that the Dwarf3 standard says (speaking of filenames in line
21504      information): ``The directory index is ignored for file names
21505      that represent full path names''.  Thus ignoring dirname in the
21506      `else' branch below isn't an issue.  */
21507 
21508   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21509     {
21510       copy.reset (concat (dirname, SLASH_STRING, filename, (char *) NULL));
21511       filename = copy.get ();
21512     }
21513 
21514   cu->get_builder ()->start_subfile (filename);
21515 }
21516 
21517 static void
21518 var_decode_location (struct attribute *attr, struct symbol *sym,
21519 		     struct dwarf2_cu *cu)
21520 {
21521   struct objfile *objfile = cu->per_objfile->objfile;
21522   struct comp_unit_head *cu_header = &cu->header;
21523 
21524   /* NOTE drow/2003-01-30: There used to be a comment and some special
21525      code here to turn a symbol with DW_AT_external and a
21526      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21527      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21528      with some versions of binutils) where shared libraries could have
21529      relocations against symbols in their debug information - the
21530      minimal symbol would have the right address, but the debug info
21531      would not.  It's no longer necessary, because we will explicitly
21532      apply relocations when we read in the debug information now.  */
21533 
21534   /* A DW_AT_location attribute with no contents indicates that a
21535      variable has been optimized away.  */
21536   if (attr->form_is_block () && attr->as_block ()->size == 0)
21537     {
21538       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21539       return;
21540     }
21541 
21542   /* Handle one degenerate form of location expression specially, to
21543      preserve GDB's previous behavior when section offsets are
21544      specified.  If this is just a DW_OP_addr, DW_OP_addrx, or
21545      DW_OP_GNU_addr_index then mark this symbol as LOC_STATIC.  */
21546 
21547   if (attr->form_is_block ())
21548     {
21549       struct dwarf_block *block = attr->as_block ();
21550 
21551       if ((block->data[0] == DW_OP_addr
21552 	   && block->size == 1 + cu_header->addr_size)
21553 	  || ((block->data[0] == DW_OP_GNU_addr_index
21554 	       || block->data[0] == DW_OP_addrx)
21555 	      && (block->size
21556 		  == 1 + leb128_size (&block->data[1]))))
21557 	{
21558 	  unsigned int dummy;
21559 
21560 	  if (block->data[0] == DW_OP_addr)
21561 	    SET_SYMBOL_VALUE_ADDRESS
21562 	      (sym, cu->header.read_address (objfile->obfd,
21563 					     block->data + 1,
21564 					     &dummy));
21565 	  else
21566 	    SET_SYMBOL_VALUE_ADDRESS
21567 	      (sym, read_addr_index_from_leb128 (cu, block->data + 1,
21568 						 &dummy));
21569 	  SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21570 	  fixup_symbol_section (sym, objfile);
21571 	  SET_SYMBOL_VALUE_ADDRESS
21572 	    (sym,
21573 	     SYMBOL_VALUE_ADDRESS (sym)
21574 	     + objfile->section_offsets[sym->section_index ()]);
21575 	  return;
21576 	}
21577     }
21578 
21579   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21580      expression evaluator, and use LOC_COMPUTED only when necessary
21581      (i.e. when the value of a register or memory location is
21582      referenced, or a thread-local block, etc.).  Then again, it might
21583      not be worthwhile.  I'm assuming that it isn't unless performance
21584      or memory numbers show me otherwise.  */
21585 
21586   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21587 
21588   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21589     cu->has_loclist = true;
21590 }
21591 
21592 /* Given a pointer to a DWARF information entry, figure out if we need
21593    to make a symbol table entry for it, and if so, create a new entry
21594    and return a pointer to it.
21595    If TYPE is NULL, determine symbol type from the die, otherwise
21596    used the passed type.
21597    If SPACE is not NULL, use it to hold the new symbol.  If it is
21598    NULL, allocate a new symbol on the objfile's obstack.  */
21599 
21600 static struct symbol *
21601 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21602 	    struct symbol *space)
21603 {
21604   dwarf2_per_objfile *per_objfile = cu->per_objfile;
21605   struct objfile *objfile = per_objfile->objfile;
21606   struct gdbarch *gdbarch = objfile->arch ();
21607   struct symbol *sym = NULL;
21608   const char *name;
21609   struct attribute *attr = NULL;
21610   struct attribute *attr2 = NULL;
21611   CORE_ADDR baseaddr;
21612   struct pending **list_to_add = NULL;
21613 
21614   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21615 
21616   baseaddr = objfile->text_section_offset ();
21617 
21618   name = dwarf2_name (die, cu);
21619   if (name)
21620     {
21621       int suppress_add = 0;
21622 
21623       if (space)
21624 	sym = space;
21625       else
21626 	sym = new (&objfile->objfile_obstack) symbol;
21627       OBJSTAT (objfile, n_syms++);
21628 
21629       /* Cache this symbol's name and the name's demangled form (if any).  */
21630       sym->set_language (cu->per_cu->lang, &objfile->objfile_obstack);
21631       /* Fortran does not have mangling standard and the mangling does differ
21632 	 between gfortran, iFort etc.  */
21633       const char *physname
21634 	= (cu->per_cu->lang == language_fortran
21635 	   ? dwarf2_full_name (name, die, cu)
21636 	   : dwarf2_physname (name, die, cu));
21637       const char *linkagename = dw2_linkage_name (die, cu);
21638 
21639       if (linkagename == nullptr || cu->per_cu->lang == language_ada)
21640 	sym->set_linkage_name (physname);
21641       else
21642 	{
21643 	  sym->set_demangled_name (physname, &objfile->objfile_obstack);
21644 	  sym->set_linkage_name (linkagename);
21645 	}
21646 
21647       /* Default assumptions.
21648 	 Use the passed type or decode it from the die.  */
21649       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21650       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21651       if (type != NULL)
21652 	SYMBOL_TYPE (sym) = type;
21653       else
21654 	SYMBOL_TYPE (sym) = die_type (die, cu);
21655       attr = dwarf2_attr (die,
21656 			  inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21657 			  cu);
21658       if (attr != nullptr)
21659 	SYMBOL_LINE (sym) = attr->constant_value (0);
21660 
21661       attr = dwarf2_attr (die,
21662 			  inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21663 			  cu);
21664       if (attr != nullptr && attr->is_nonnegative ())
21665 	{
21666 	  file_name_index file_index
21667 	    = (file_name_index) attr->as_nonnegative ();
21668 	  struct file_entry *fe;
21669 
21670 	  if (cu->line_header != NULL)
21671 	    fe = cu->line_header->file_name_at (file_index);
21672 	  else
21673 	    fe = NULL;
21674 
21675 	  if (fe == NULL)
21676 	    complaint (_("file index out of range"));
21677 	  else
21678 	    symbol_set_symtab (sym, fe->symtab);
21679 	}
21680 
21681       switch (die->tag)
21682 	{
21683 	case DW_TAG_label:
21684 	  attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21685 	  if (attr != nullptr)
21686 	    {
21687 	      CORE_ADDR addr;
21688 
21689 	      addr = attr->as_address ();
21690 	      addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21691 	      SET_SYMBOL_VALUE_ADDRESS (sym, addr);
21692 	      SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21693 	    }
21694 	  else
21695 	    SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21696 	  SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21697 	  SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21698 	  add_symbol_to_list (sym, cu->list_in_scope);
21699 	  break;
21700 	case DW_TAG_subprogram:
21701 	  /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21702 	     finish_block.  */
21703 	  SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21704 	  attr2 = dwarf2_attr (die, DW_AT_external, cu);
21705 	  if ((attr2 != nullptr && attr2->as_boolean ())
21706 	      || cu->per_cu->lang == language_ada
21707 	      || cu->per_cu->lang == language_fortran)
21708 	    {
21709 	      /* Subprograms marked external are stored as a global symbol.
21710 		 Ada and Fortran subprograms, whether marked external or
21711 		 not, are always stored as a global symbol, because we want
21712 		 to be able to access them globally.  For instance, we want
21713 		 to be able to break on a nested subprogram without having
21714 		 to specify the context.  */
21715 	      list_to_add = cu->get_builder ()->get_global_symbols ();
21716 	    }
21717 	  else
21718 	    {
21719 	      list_to_add = cu->list_in_scope;
21720 	    }
21721 	  break;
21722 	case DW_TAG_inlined_subroutine:
21723 	  /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21724 	     finish_block.  */
21725 	  SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21726 	  SYMBOL_INLINED (sym) = 1;
21727 	  list_to_add = cu->list_in_scope;
21728 	  break;
21729 	case DW_TAG_template_value_param:
21730 	  suppress_add = 1;
21731 	  /* Fall through.  */
21732 	case DW_TAG_constant:
21733 	case DW_TAG_variable:
21734 	case DW_TAG_member:
21735 	  /* Compilation with minimal debug info may result in
21736 	     variables with missing type entries.  Change the
21737 	     misleading `void' type to something sensible.  */
21738 	  if (SYMBOL_TYPE (sym)->code () == TYPE_CODE_VOID)
21739 	    SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21740 
21741 	  attr = dwarf2_attr (die, DW_AT_const_value, cu);
21742 	  /* In the case of DW_TAG_member, we should only be called for
21743 	     static const members.  */
21744 	  if (die->tag == DW_TAG_member)
21745 	    {
21746 	      /* dwarf2_add_field uses die_is_declaration,
21747 		 so we do the same.  */
21748 	      gdb_assert (die_is_declaration (die, cu));
21749 	      gdb_assert (attr);
21750 	    }
21751 	  if (attr != nullptr)
21752 	    {
21753 	      dwarf2_const_value (attr, sym, cu);
21754 	      attr2 = dwarf2_attr (die, DW_AT_external, cu);
21755 	      if (!suppress_add)
21756 		{
21757 		  if (attr2 != nullptr && attr2->as_boolean ())
21758 		    list_to_add = cu->get_builder ()->get_global_symbols ();
21759 		  else
21760 		    list_to_add = cu->list_in_scope;
21761 		}
21762 	      break;
21763 	    }
21764 	  attr = dwarf2_attr (die, DW_AT_location, cu);
21765 	  if (attr != nullptr)
21766 	    {
21767 	      var_decode_location (attr, sym, cu);
21768 	      attr2 = dwarf2_attr (die, DW_AT_external, cu);
21769 
21770 	      /* Fortran explicitly imports any global symbols to the local
21771 		 scope by DW_TAG_common_block.  */
21772 	      if (cu->per_cu->lang == language_fortran && die->parent
21773 		  && die->parent->tag == DW_TAG_common_block)
21774 		attr2 = NULL;
21775 
21776 	      if (SYMBOL_CLASS (sym) == LOC_STATIC
21777 		  && SYMBOL_VALUE_ADDRESS (sym) == 0
21778 		  && !per_objfile->per_bfd->has_section_at_zero)
21779 		{
21780 		  /* When a static variable is eliminated by the linker,
21781 		     the corresponding debug information is not stripped
21782 		     out, but the variable address is set to null;
21783 		     do not add such variables into symbol table.  */
21784 		}
21785 	      else if (attr2 != nullptr && attr2->as_boolean ())
21786 		{
21787 		  if (SYMBOL_CLASS (sym) == LOC_STATIC
21788 		      && (objfile->flags & OBJF_MAINLINE) == 0
21789 		      && per_objfile->per_bfd->can_copy)
21790 		    {
21791 		      /* A global static variable might be subject to
21792 			 copy relocation.  We first check for a local
21793 			 minsym, though, because maybe the symbol was
21794 			 marked hidden, in which case this would not
21795 			 apply.  */
21796 		      bound_minimal_symbol found
21797 			= (lookup_minimal_symbol_linkage
21798 			   (sym->linkage_name (), objfile));
21799 		      if (found.minsym != nullptr)
21800 			sym->maybe_copied = 1;
21801 		    }
21802 
21803 		  /* A variable with DW_AT_external is never static,
21804 		     but it may be block-scoped.  */
21805 		  list_to_add
21806 		    = ((cu->list_in_scope
21807 			== cu->get_builder ()->get_file_symbols ())
21808 		       ? cu->get_builder ()->get_global_symbols ()
21809 		       : cu->list_in_scope);
21810 		}
21811 	      else
21812 		list_to_add = cu->list_in_scope;
21813 	    }
21814 	  else
21815 	    {
21816 	      /* We do not know the address of this symbol.
21817 		 If it is an external symbol and we have type information
21818 		 for it, enter the symbol as a LOC_UNRESOLVED symbol.
21819 		 The address of the variable will then be determined from
21820 		 the minimal symbol table whenever the variable is
21821 		 referenced.  */
21822 	      attr2 = dwarf2_attr (die, DW_AT_external, cu);
21823 
21824 	      /* Fortran explicitly imports any global symbols to the local
21825 		 scope by DW_TAG_common_block.  */
21826 	      if (cu->per_cu->lang == language_fortran && die->parent
21827 		  && die->parent->tag == DW_TAG_common_block)
21828 		{
21829 		  /* SYMBOL_CLASS doesn't matter here because
21830 		     read_common_block is going to reset it.  */
21831 		  if (!suppress_add)
21832 		    list_to_add = cu->list_in_scope;
21833 		}
21834 	      else if (attr2 != nullptr && attr2->as_boolean ()
21835 		       && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21836 		{
21837 		  /* A variable with DW_AT_external is never static, but it
21838 		     may be block-scoped.  */
21839 		  list_to_add
21840 		    = ((cu->list_in_scope
21841 			== cu->get_builder ()->get_file_symbols ())
21842 		       ? cu->get_builder ()->get_global_symbols ()
21843 		       : cu->list_in_scope);
21844 
21845 		  SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21846 		}
21847 	      else if (!die_is_declaration (die, cu))
21848 		{
21849 		  /* Use the default LOC_OPTIMIZED_OUT class.  */
21850 		  gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21851 		  if (!suppress_add)
21852 		    list_to_add = cu->list_in_scope;
21853 		}
21854 	    }
21855 	  break;
21856 	case DW_TAG_formal_parameter:
21857 	  {
21858 	    /* If we are inside a function, mark this as an argument.  If
21859 	       not, we might be looking at an argument to an inlined function
21860 	       when we do not have enough information to show inlined frames;
21861 	       pretend it's a local variable in that case so that the user can
21862 	       still see it.  */
21863 	    struct context_stack *curr
21864 	      = cu->get_builder ()->get_current_context_stack ();
21865 	    if (curr != nullptr && curr->name != nullptr)
21866 	      SYMBOL_IS_ARGUMENT (sym) = 1;
21867 	    attr = dwarf2_attr (die, DW_AT_location, cu);
21868 	    if (attr != nullptr)
21869 	      {
21870 		var_decode_location (attr, sym, cu);
21871 	      }
21872 	    attr = dwarf2_attr (die, DW_AT_const_value, cu);
21873 	    if (attr != nullptr)
21874 	      {
21875 		dwarf2_const_value (attr, sym, cu);
21876 	      }
21877 
21878 	    list_to_add = cu->list_in_scope;
21879 	  }
21880 	  break;
21881 	case DW_TAG_unspecified_parameters:
21882 	  /* From varargs functions; gdb doesn't seem to have any
21883 	     interest in this information, so just ignore it for now.
21884 	     (FIXME?) */
21885 	  break;
21886 	case DW_TAG_template_type_param:
21887 	  suppress_add = 1;
21888 	  /* Fall through.  */
21889 	case DW_TAG_class_type:
21890 	case DW_TAG_interface_type:
21891 	case DW_TAG_structure_type:
21892 	case DW_TAG_union_type:
21893 	case DW_TAG_set_type:
21894 	case DW_TAG_enumeration_type:
21895 	  SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21896 	  SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21897 
21898 	  {
21899 	    /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21900 	       really ever be static objects: otherwise, if you try
21901 	       to, say, break of a class's method and you're in a file
21902 	       which doesn't mention that class, it won't work unless
21903 	       the check for all static symbols in lookup_symbol_aux
21904 	       saves you.  See the OtherFileClass tests in
21905 	       gdb.c++/namespace.exp.  */
21906 
21907 	    if (!suppress_add)
21908 	      {
21909 		buildsym_compunit *builder = cu->get_builder ();
21910 		list_to_add
21911 		  = (cu->list_in_scope == builder->get_file_symbols ()
21912 		     && cu->per_cu->lang == language_cplus
21913 		     ? builder->get_global_symbols ()
21914 		     : cu->list_in_scope);
21915 
21916 		/* The semantics of C++ state that "struct foo {
21917 		   ... }" also defines a typedef for "foo".  */
21918 		if (cu->per_cu->lang == language_cplus
21919 		    || cu->per_cu->lang == language_ada
21920 		    || cu->per_cu->lang == language_d
21921 		    || cu->per_cu->lang == language_rust)
21922 		  {
21923 		    /* The symbol's name is already allocated along
21924 		       with this objfile, so we don't need to
21925 		       duplicate it for the type.  */
21926 		    if (SYMBOL_TYPE (sym)->name () == 0)
21927 		      SYMBOL_TYPE (sym)->set_name (sym->search_name ());
21928 		  }
21929 	      }
21930 	  }
21931 	  break;
21932 	case DW_TAG_typedef:
21933 	  SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21934 	  SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21935 	  list_to_add = cu->list_in_scope;
21936 	  break;
21937 	case DW_TAG_array_type:
21938 	case DW_TAG_base_type:
21939 	case DW_TAG_subrange_type:
21940 	  SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21941 	  SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21942 	  list_to_add = cu->list_in_scope;
21943 	  break;
21944 	case DW_TAG_enumerator:
21945 	  attr = dwarf2_attr (die, DW_AT_const_value, cu);
21946 	  if (attr != nullptr)
21947 	    {
21948 	      dwarf2_const_value (attr, sym, cu);
21949 	    }
21950 	  {
21951 	    /* NOTE: carlton/2003-11-10: See comment above in the
21952 	       DW_TAG_class_type, etc. block.  */
21953 
21954 	    list_to_add
21955 	      = (cu->list_in_scope == cu->get_builder ()->get_file_symbols ()
21956 		 && cu->per_cu->lang == language_cplus
21957 		 ? cu->get_builder ()->get_global_symbols ()
21958 		 : cu->list_in_scope);
21959 	  }
21960 	  break;
21961 	case DW_TAG_imported_declaration:
21962 	case DW_TAG_namespace:
21963 	  SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21964 	  list_to_add = cu->get_builder ()->get_global_symbols ();
21965 	  break;
21966 	case DW_TAG_module:
21967 	  SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21968 	  SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21969 	  list_to_add = cu->get_builder ()->get_global_symbols ();
21970 	  break;
21971 	case DW_TAG_common_block:
21972 	  SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21973 	  SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21974 	  add_symbol_to_list (sym, cu->list_in_scope);
21975 	  break;
21976 	default:
21977 	  /* Not a tag we recognize.  Hopefully we aren't processing
21978 	     trash data, but since we must specifically ignore things
21979 	     we don't recognize, there is nothing else we should do at
21980 	     this point.  */
21981 	  complaint (_("unsupported tag: '%s'"),
21982 		     dwarf_tag_name (die->tag));
21983 	  break;
21984 	}
21985 
21986       if (suppress_add)
21987 	{
21988 	  sym->hash_next = objfile->template_symbols;
21989 	  objfile->template_symbols = sym;
21990 	  list_to_add = NULL;
21991 	}
21992 
21993       if (list_to_add != NULL)
21994 	add_symbol_to_list (sym, list_to_add);
21995 
21996       /* For the benefit of old versions of GCC, check for anonymous
21997 	 namespaces based on the demangled name.  */
21998       if (!cu->processing_has_namespace_info
21999 	  && cu->per_cu->lang == language_cplus)
22000 	cp_scan_for_anonymous_namespaces (cu->get_builder (), sym, objfile);
22001     }
22002   return (sym);
22003 }
22004 
22005 /* Given an attr with a DW_FORM_dataN value in host byte order,
22006    zero-extend it as appropriate for the symbol's type.  The DWARF
22007    standard (v4) is not entirely clear about the meaning of using
22008    DW_FORM_dataN for a constant with a signed type, where the type is
22009    wider than the data.  The conclusion of a discussion on the DWARF
22010    list was that this is unspecified.  We choose to always zero-extend
22011    because that is the interpretation long in use by GCC.  */
22012 
22013 static gdb_byte *
22014 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
22015 			 struct dwarf2_cu *cu, LONGEST *value, int bits)
22016 {
22017   struct objfile *objfile = cu->per_objfile->objfile;
22018   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
22019 				BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
22020   LONGEST l = attr->constant_value (0);
22021 
22022   if (bits < sizeof (*value) * 8)
22023     {
22024       l &= ((LONGEST) 1 << bits) - 1;
22025       *value = l;
22026     }
22027   else if (bits == sizeof (*value) * 8)
22028     *value = l;
22029   else
22030     {
22031       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
22032       store_unsigned_integer (bytes, bits / 8, byte_order, l);
22033       return bytes;
22034     }
22035 
22036   return NULL;
22037 }
22038 
22039 /* Read a constant value from an attribute.  Either set *VALUE, or if
22040    the value does not fit in *VALUE, set *BYTES - either already
22041    allocated on the objfile obstack, or newly allocated on OBSTACK,
22042    or, set *BATON, if we translated the constant to a location
22043    expression.  */
22044 
22045 static void
22046 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
22047 			 const char *name, struct obstack *obstack,
22048 			 struct dwarf2_cu *cu,
22049 			 LONGEST *value, const gdb_byte **bytes,
22050 			 struct dwarf2_locexpr_baton **baton)
22051 {
22052   dwarf2_per_objfile *per_objfile = cu->per_objfile;
22053   struct objfile *objfile = per_objfile->objfile;
22054   struct comp_unit_head *cu_header = &cu->header;
22055   struct dwarf_block *blk;
22056   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
22057 				BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
22058 
22059   *value = 0;
22060   *bytes = NULL;
22061   *baton = NULL;
22062 
22063   switch (attr->form)
22064     {
22065     case DW_FORM_addr:
22066     case DW_FORM_addrx:
22067     case DW_FORM_GNU_addr_index:
22068       {
22069 	gdb_byte *data;
22070 
22071 	if (TYPE_LENGTH (type) != cu_header->addr_size)
22072 	  dwarf2_const_value_length_mismatch_complaint (name,
22073 							cu_header->addr_size,
22074 							TYPE_LENGTH (type));
22075 	/* Symbols of this form are reasonably rare, so we just
22076 	   piggyback on the existing location code rather than writing
22077 	   a new implementation of symbol_computed_ops.  */
22078 	*baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
22079 	(*baton)->per_objfile = per_objfile;
22080 	(*baton)->per_cu = cu->per_cu;
22081 	gdb_assert ((*baton)->per_cu);
22082 
22083 	(*baton)->size = 2 + cu_header->addr_size;
22084 	data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
22085 	(*baton)->data = data;
22086 
22087 	data[0] = DW_OP_addr;
22088 	store_unsigned_integer (&data[1], cu_header->addr_size,
22089 				byte_order, attr->as_address ());
22090 	data[cu_header->addr_size + 1] = DW_OP_stack_value;
22091       }
22092       break;
22093     case DW_FORM_string:
22094     case DW_FORM_strp:
22095     case DW_FORM_strx:
22096     case DW_FORM_GNU_str_index:
22097     case DW_FORM_GNU_strp_alt:
22098       /* The string is already allocated on the objfile obstack, point
22099 	 directly to it.  */
22100       *bytes = (const gdb_byte *) attr->as_string ();
22101       break;
22102     case DW_FORM_block1:
22103     case DW_FORM_block2:
22104     case DW_FORM_block4:
22105     case DW_FORM_block:
22106     case DW_FORM_exprloc:
22107     case DW_FORM_data16:
22108       blk = attr->as_block ();
22109       if (TYPE_LENGTH (type) != blk->size)
22110 	dwarf2_const_value_length_mismatch_complaint (name, blk->size,
22111 						      TYPE_LENGTH (type));
22112       *bytes = blk->data;
22113       break;
22114 
22115       /* The DW_AT_const_value attributes are supposed to carry the
22116 	 symbol's value "represented as it would be on the target
22117 	 architecture."  By the time we get here, it's already been
22118 	 converted to host endianness, so we just need to sign- or
22119 	 zero-extend it as appropriate.  */
22120     case DW_FORM_data1:
22121       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
22122       break;
22123     case DW_FORM_data2:
22124       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
22125       break;
22126     case DW_FORM_data4:
22127       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
22128       break;
22129     case DW_FORM_data8:
22130       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
22131       break;
22132 
22133     case DW_FORM_sdata:
22134     case DW_FORM_implicit_const:
22135       *value = attr->as_signed ();
22136       break;
22137 
22138     case DW_FORM_udata:
22139       *value = attr->as_unsigned ();
22140       break;
22141 
22142     default:
22143       complaint (_("unsupported const value attribute form: '%s'"),
22144 		 dwarf_form_name (attr->form));
22145       *value = 0;
22146       break;
22147     }
22148 }
22149 
22150 
22151 /* Copy constant value from an attribute to a symbol.  */
22152 
22153 static void
22154 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
22155 		    struct dwarf2_cu *cu)
22156 {
22157   struct objfile *objfile = cu->per_objfile->objfile;
22158   LONGEST value;
22159   const gdb_byte *bytes;
22160   struct dwarf2_locexpr_baton *baton;
22161 
22162   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
22163 			   sym->print_name (),
22164 			   &objfile->objfile_obstack, cu,
22165 			   &value, &bytes, &baton);
22166 
22167   if (baton != NULL)
22168     {
22169       SYMBOL_LOCATION_BATON (sym) = baton;
22170       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
22171     }
22172   else if (bytes != NULL)
22173      {
22174       SYMBOL_VALUE_BYTES (sym) = bytes;
22175       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
22176     }
22177   else
22178     {
22179       SYMBOL_VALUE (sym) = value;
22180       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
22181     }
22182 }
22183 
22184 /* Return the type of the die in question using its DW_AT_type attribute.  */
22185 
22186 static struct type *
22187 die_type (struct die_info *die, struct dwarf2_cu *cu)
22188 {
22189   struct attribute *type_attr;
22190 
22191   type_attr = dwarf2_attr (die, DW_AT_type, cu);
22192   if (!type_attr)
22193     {
22194       struct objfile *objfile = cu->per_objfile->objfile;
22195       /* A missing DW_AT_type represents a void type.  */
22196       return objfile_type (objfile)->builtin_void;
22197     }
22198 
22199   return lookup_die_type (die, type_attr, cu);
22200 }
22201 
22202 /* True iff CU's producer generates GNAT Ada auxiliary information
22203    that allows to find parallel types through that information instead
22204    of having to do expensive parallel lookups by type name.  */
22205 
22206 static int
22207 need_gnat_info (struct dwarf2_cu *cu)
22208 {
22209   /* Assume that the Ada compiler was GNAT, which always produces
22210      the auxiliary information.  */
22211   return (cu->per_cu->lang == language_ada);
22212 }
22213 
22214 /* Return the auxiliary type of the die in question using its
22215    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
22216    attribute is not present.  */
22217 
22218 static struct type *
22219 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
22220 {
22221   struct attribute *type_attr;
22222 
22223   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
22224   if (!type_attr)
22225     return NULL;
22226 
22227   return lookup_die_type (die, type_attr, cu);
22228 }
22229 
22230 /* If DIE has a descriptive_type attribute, then set the TYPE's
22231    descriptive type accordingly.  */
22232 
22233 static void
22234 set_descriptive_type (struct type *type, struct die_info *die,
22235 		      struct dwarf2_cu *cu)
22236 {
22237   struct type *descriptive_type = die_descriptive_type (die, cu);
22238 
22239   if (descriptive_type)
22240     {
22241       ALLOCATE_GNAT_AUX_TYPE (type);
22242       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
22243     }
22244 }
22245 
22246 /* Return the containing type of the die in question using its
22247    DW_AT_containing_type attribute.  */
22248 
22249 static struct type *
22250 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
22251 {
22252   struct attribute *type_attr;
22253   struct objfile *objfile = cu->per_objfile->objfile;
22254 
22255   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
22256   if (!type_attr)
22257     error (_("Dwarf Error: Problem turning containing type into gdb type "
22258 	     "[in module %s]"), objfile_name (objfile));
22259 
22260   return lookup_die_type (die, type_attr, cu);
22261 }
22262 
22263 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
22264 
22265 static struct type *
22266 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
22267 {
22268   dwarf2_per_objfile *per_objfile = cu->per_objfile;
22269   struct objfile *objfile = per_objfile->objfile;
22270   char *saved;
22271 
22272   std::string message
22273     = string_printf (_("<unknown type in %s, CU %s, DIE %s>"),
22274 		     objfile_name (objfile),
22275 		     sect_offset_str (cu->header.sect_off),
22276 		     sect_offset_str (die->sect_off));
22277   saved = obstack_strdup (&objfile->objfile_obstack, message);
22278 
22279   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
22280 }
22281 
22282 /* Look up the type of DIE in CU using its type attribute ATTR.
22283    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
22284    DW_AT_containing_type.
22285    If there is no type substitute an error marker.  */
22286 
22287 static struct type *
22288 lookup_die_type (struct die_info *die, const struct attribute *attr,
22289 		 struct dwarf2_cu *cu)
22290 {
22291   dwarf2_per_objfile *per_objfile = cu->per_objfile;
22292   struct objfile *objfile = per_objfile->objfile;
22293   struct type *this_type;
22294 
22295   gdb_assert (attr->name == DW_AT_type
22296 	      || attr->name == DW_AT_GNAT_descriptive_type
22297 	      || attr->name == DW_AT_containing_type);
22298 
22299   /* First see if we have it cached.  */
22300 
22301   if (attr->form == DW_FORM_GNU_ref_alt)
22302     {
22303       struct dwarf2_per_cu_data *per_cu;
22304       sect_offset sect_off = attr->get_ref_die_offset ();
22305 
22306       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, per_objfile);
22307       this_type = get_die_type_at_offset (sect_off, per_cu, per_objfile);
22308     }
22309   else if (attr->form_is_ref ())
22310     {
22311       sect_offset sect_off = attr->get_ref_die_offset ();
22312 
22313       this_type = get_die_type_at_offset (sect_off, cu->per_cu, per_objfile);
22314     }
22315   else if (attr->form == DW_FORM_ref_sig8)
22316     {
22317       ULONGEST signature = attr->as_signature ();
22318 
22319       return get_signatured_type (die, signature, cu);
22320     }
22321   else
22322     {
22323       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
22324 		   " at %s [in module %s]"),
22325 		 dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
22326 		 objfile_name (objfile));
22327       return build_error_marker_type (cu, die);
22328     }
22329 
22330   /* If not cached we need to read it in.  */
22331 
22332   if (this_type == NULL)
22333     {
22334       struct die_info *type_die = NULL;
22335       struct dwarf2_cu *type_cu = cu;
22336 
22337       if (attr->form_is_ref ())
22338 	type_die = follow_die_ref (die, attr, &type_cu);
22339       if (type_die == NULL)
22340 	return build_error_marker_type (cu, die);
22341       /* If we find the type now, it's probably because the type came
22342 	 from an inter-CU reference and the type's CU got expanded before
22343 	 ours.  */
22344       this_type = read_type_die (type_die, type_cu);
22345     }
22346 
22347   /* If we still don't have a type use an error marker.  */
22348 
22349   if (this_type == NULL)
22350     return build_error_marker_type (cu, die);
22351 
22352   return this_type;
22353 }
22354 
22355 /* Return the type in DIE, CU.
22356    Returns NULL for invalid types.
22357 
22358    This first does a lookup in die_type_hash,
22359    and only reads the die in if necessary.
22360 
22361    NOTE: This can be called when reading in partial or full symbols.  */
22362 
22363 static struct type *
22364 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22365 {
22366   struct type *this_type;
22367 
22368   this_type = get_die_type (die, cu);
22369   if (this_type)
22370     return this_type;
22371 
22372   return read_type_die_1 (die, cu);
22373 }
22374 
22375 /* Read the type in DIE, CU.
22376    Returns NULL for invalid types.  */
22377 
22378 static struct type *
22379 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22380 {
22381   struct type *this_type = NULL;
22382 
22383   switch (die->tag)
22384     {
22385     case DW_TAG_class_type:
22386     case DW_TAG_interface_type:
22387     case DW_TAG_structure_type:
22388     case DW_TAG_union_type:
22389       this_type = read_structure_type (die, cu);
22390       break;
22391     case DW_TAG_enumeration_type:
22392       this_type = read_enumeration_type (die, cu);
22393       break;
22394     case DW_TAG_subprogram:
22395     case DW_TAG_subroutine_type:
22396     case DW_TAG_inlined_subroutine:
22397       this_type = read_subroutine_type (die, cu);
22398       break;
22399     case DW_TAG_array_type:
22400       this_type = read_array_type (die, cu);
22401       break;
22402     case DW_TAG_set_type:
22403       this_type = read_set_type (die, cu);
22404       break;
22405     case DW_TAG_pointer_type:
22406       this_type = read_tag_pointer_type (die, cu);
22407       break;
22408     case DW_TAG_ptr_to_member_type:
22409       this_type = read_tag_ptr_to_member_type (die, cu);
22410       break;
22411     case DW_TAG_reference_type:
22412       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22413       break;
22414     case DW_TAG_rvalue_reference_type:
22415       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22416       break;
22417     case DW_TAG_const_type:
22418       this_type = read_tag_const_type (die, cu);
22419       break;
22420     case DW_TAG_volatile_type:
22421       this_type = read_tag_volatile_type (die, cu);
22422       break;
22423     case DW_TAG_restrict_type:
22424       this_type = read_tag_restrict_type (die, cu);
22425       break;
22426     case DW_TAG_string_type:
22427       this_type = read_tag_string_type (die, cu);
22428       break;
22429     case DW_TAG_typedef:
22430       this_type = read_typedef (die, cu);
22431       break;
22432     case DW_TAG_subrange_type:
22433       this_type = read_subrange_type (die, cu);
22434       break;
22435     case DW_TAG_base_type:
22436       this_type = read_base_type (die, cu);
22437       break;
22438     case DW_TAG_unspecified_type:
22439       this_type = read_unspecified_type (die, cu);
22440       break;
22441     case DW_TAG_namespace:
22442       this_type = read_namespace_type (die, cu);
22443       break;
22444     case DW_TAG_module:
22445       this_type = read_module_type (die, cu);
22446       break;
22447     case DW_TAG_atomic_type:
22448       this_type = read_tag_atomic_type (die, cu);
22449       break;
22450     default:
22451       complaint (_("unexpected tag in read_type_die: '%s'"),
22452 		 dwarf_tag_name (die->tag));
22453       break;
22454     }
22455 
22456   return this_type;
22457 }
22458 
22459 /* See if we can figure out if the class lives in a namespace.  We do
22460    this by looking for a member function; its demangled name will
22461    contain namespace info, if there is any.
22462    Return the computed name or NULL.
22463    Space for the result is allocated on the objfile's obstack.
22464    This is the full-die version of guess_partial_die_structure_name.
22465    In this case we know DIE has no useful parent.  */
22466 
22467 static const char *
22468 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22469 {
22470   struct die_info *spec_die;
22471   struct dwarf2_cu *spec_cu;
22472   struct die_info *child;
22473   struct objfile *objfile = cu->per_objfile->objfile;
22474 
22475   spec_cu = cu;
22476   spec_die = die_specification (die, &spec_cu);
22477   if (spec_die != NULL)
22478     {
22479       die = spec_die;
22480       cu = spec_cu;
22481     }
22482 
22483   for (child = die->child;
22484        child != NULL;
22485        child = child->sibling)
22486     {
22487       if (child->tag == DW_TAG_subprogram)
22488 	{
22489 	  const char *linkage_name = dw2_linkage_name (child, cu);
22490 
22491 	  if (linkage_name != NULL)
22492 	    {
22493 	      gdb::unique_xmalloc_ptr<char> actual_name
22494 		(cu->language_defn->class_name_from_physname (linkage_name));
22495 	      const char *name = NULL;
22496 
22497 	      if (actual_name != NULL)
22498 		{
22499 		  const char *die_name = dwarf2_name (die, cu);
22500 
22501 		  if (die_name != NULL
22502 		      && strcmp (die_name, actual_name.get ()) != 0)
22503 		    {
22504 		      /* Strip off the class name from the full name.
22505 			 We want the prefix.  */
22506 		      int die_name_len = strlen (die_name);
22507 		      int actual_name_len = strlen (actual_name.get ());
22508 		      const char *ptr = actual_name.get ();
22509 
22510 		      /* Test for '::' as a sanity check.  */
22511 		      if (actual_name_len > die_name_len + 2
22512 			  && ptr[actual_name_len - die_name_len - 1] == ':')
22513 			name = obstack_strndup (
22514 			  &objfile->per_bfd->storage_obstack,
22515 			  ptr, actual_name_len - die_name_len - 2);
22516 		    }
22517 		}
22518 	      return name;
22519 	    }
22520 	}
22521     }
22522 
22523   return NULL;
22524 }
22525 
22526 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22527    prefix part in such case.  See
22528    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22529 
22530 static const char *
22531 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22532 {
22533   struct attribute *attr;
22534   const char *base;
22535 
22536   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22537       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22538     return NULL;
22539 
22540   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22541     return NULL;
22542 
22543   attr = dw2_linkage_name_attr (die, cu);
22544   const char *attr_name = attr->as_string ();
22545   if (attr == NULL || attr_name == NULL)
22546     return NULL;
22547 
22548   /* dwarf2_name had to be already called.  */
22549   gdb_assert (attr->canonical_string_p ());
22550 
22551   /* Strip the base name, keep any leading namespaces/classes.  */
22552   base = strrchr (attr_name, ':');
22553   if (base == NULL || base == attr_name || base[-1] != ':')
22554     return "";
22555 
22556   struct objfile *objfile = cu->per_objfile->objfile;
22557   return obstack_strndup (&objfile->per_bfd->storage_obstack,
22558 			  attr_name,
22559 			  &base[-1] - attr_name);
22560 }
22561 
22562 /* Return the name of the namespace/class that DIE is defined within,
22563    or "" if we can't tell.  The caller should not xfree the result.
22564 
22565    For example, if we're within the method foo() in the following
22566    code:
22567 
22568    namespace N {
22569      class C {
22570        void foo () {
22571        }
22572      };
22573    }
22574 
22575    then determine_prefix on foo's die will return "N::C".  */
22576 
22577 static const char *
22578 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22579 {
22580   dwarf2_per_objfile *per_objfile = cu->per_objfile;
22581   struct die_info *parent, *spec_die;
22582   struct dwarf2_cu *spec_cu;
22583   struct type *parent_type;
22584   const char *retval;
22585 
22586   if (cu->per_cu->lang != language_cplus
22587       && cu->per_cu->lang != language_fortran
22588       && cu->per_cu->lang != language_d
22589       && cu->per_cu->lang != language_rust)
22590     return "";
22591 
22592   retval = anonymous_struct_prefix (die, cu);
22593   if (retval)
22594     return retval;
22595 
22596   /* We have to be careful in the presence of DW_AT_specification.
22597      For example, with GCC 3.4, given the code
22598 
22599      namespace N {
22600        void foo() {
22601 	 // Definition of N::foo.
22602        }
22603      }
22604 
22605      then we'll have a tree of DIEs like this:
22606 
22607      1: DW_TAG_compile_unit
22608        2: DW_TAG_namespace        // N
22609 	 3: DW_TAG_subprogram     // declaration of N::foo
22610        4: DW_TAG_subprogram       // definition of N::foo
22611 	    DW_AT_specification   // refers to die #3
22612 
22613      Thus, when processing die #4, we have to pretend that we're in
22614      the context of its DW_AT_specification, namely the contex of die
22615      #3.  */
22616   spec_cu = cu;
22617   spec_die = die_specification (die, &spec_cu);
22618   if (spec_die == NULL)
22619     parent = die->parent;
22620   else
22621     {
22622       parent = spec_die->parent;
22623       cu = spec_cu;
22624     }
22625 
22626   if (parent == NULL)
22627     return "";
22628   else if (parent->building_fullname)
22629     {
22630       const char *name;
22631       const char *parent_name;
22632 
22633       /* It has been seen on RealView 2.2 built binaries,
22634 	 DW_TAG_template_type_param types actually _defined_ as
22635 	 children of the parent class:
22636 
22637 	 enum E {};
22638 	 template class <class Enum> Class{};
22639 	 Class<enum E> class_e;
22640 
22641 	 1: DW_TAG_class_type (Class)
22642 	   2: DW_TAG_enumeration_type (E)
22643 	     3: DW_TAG_enumerator (enum1:0)
22644 	     3: DW_TAG_enumerator (enum2:1)
22645 	     ...
22646 	   2: DW_TAG_template_type_param
22647 	      DW_AT_type  DW_FORM_ref_udata (E)
22648 
22649 	 Besides being broken debug info, it can put GDB into an
22650 	 infinite loop.  Consider:
22651 
22652 	 When we're building the full name for Class<E>, we'll start
22653 	 at Class, and go look over its template type parameters,
22654 	 finding E.  We'll then try to build the full name of E, and
22655 	 reach here.  We're now trying to build the full name of E,
22656 	 and look over the parent DIE for containing scope.  In the
22657 	 broken case, if we followed the parent DIE of E, we'd again
22658 	 find Class, and once again go look at its template type
22659 	 arguments, etc., etc.  Simply don't consider such parent die
22660 	 as source-level parent of this die (it can't be, the language
22661 	 doesn't allow it), and break the loop here.  */
22662       name = dwarf2_name (die, cu);
22663       parent_name = dwarf2_name (parent, cu);
22664       complaint (_("template param type '%s' defined within parent '%s'"),
22665 		 name ? name : "<unknown>",
22666 		 parent_name ? parent_name : "<unknown>");
22667       return "";
22668     }
22669   else
22670     switch (parent->tag)
22671       {
22672       case DW_TAG_namespace:
22673 	parent_type = read_type_die (parent, cu);
22674 	/* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22675 	   DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22676 	   Work around this problem here.  */
22677 	if (cu->per_cu->lang == language_cplus
22678 	    && strcmp (parent_type->name (), "::") == 0)
22679 	  return "";
22680 	/* We give a name to even anonymous namespaces.  */
22681 	return parent_type->name ();
22682       case DW_TAG_class_type:
22683       case DW_TAG_interface_type:
22684       case DW_TAG_structure_type:
22685       case DW_TAG_union_type:
22686       case DW_TAG_module:
22687 	parent_type = read_type_die (parent, cu);
22688 	if (parent_type->name () != NULL)
22689 	  return parent_type->name ();
22690 	else
22691 	  /* An anonymous structure is only allowed non-static data
22692 	     members; no typedefs, no member functions, et cetera.
22693 	     So it does not need a prefix.  */
22694 	  return "";
22695       case DW_TAG_compile_unit:
22696       case DW_TAG_partial_unit:
22697 	/* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22698 	if (cu->per_cu->lang == language_cplus
22699 	    && !per_objfile->per_bfd->types.empty ()
22700 	    && die->child != NULL
22701 	    && (die->tag == DW_TAG_class_type
22702 		|| die->tag == DW_TAG_structure_type
22703 		|| die->tag == DW_TAG_union_type))
22704 	  {
22705 	    const char *name = guess_full_die_structure_name (die, cu);
22706 	    if (name != NULL)
22707 	      return name;
22708 	  }
22709 	return "";
22710       case DW_TAG_subprogram:
22711 	/* Nested subroutines in Fortran get a prefix with the name
22712 	   of the parent's subroutine.  */
22713 	if (cu->per_cu->lang == language_fortran)
22714 	  {
22715 	    if ((die->tag ==  DW_TAG_subprogram)
22716 		&& (dwarf2_name (parent, cu) != NULL))
22717 	      return dwarf2_name (parent, cu);
22718 	  }
22719 	return determine_prefix (parent, cu);
22720       case DW_TAG_enumeration_type:
22721 	parent_type = read_type_die (parent, cu);
22722 	if (parent_type->is_declared_class ())
22723 	  {
22724 	    if (parent_type->name () != NULL)
22725 	      return parent_type->name ();
22726 	    return "";
22727 	  }
22728 	/* Fall through.  */
22729       default:
22730 	return determine_prefix (parent, cu);
22731       }
22732 }
22733 
22734 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22735    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22736    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22737    an obconcat, otherwise allocate storage for the result.  The CU argument is
22738    used to determine the language and hence, the appropriate separator.  */
22739 
22740 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22741 
22742 static char *
22743 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22744 		 int physname, struct dwarf2_cu *cu)
22745 {
22746   const char *lead = "";
22747   const char *sep;
22748 
22749   if (suffix == NULL || suffix[0] == '\0'
22750       || prefix == NULL || prefix[0] == '\0')
22751     sep = "";
22752   else if (cu->per_cu->lang == language_d)
22753     {
22754       /* For D, the 'main' function could be defined in any module, but it
22755 	 should never be prefixed.  */
22756       if (strcmp (suffix, "D main") == 0)
22757 	{
22758 	  prefix = "";
22759 	  sep = "";
22760 	}
22761       else
22762 	sep = ".";
22763     }
22764   else if (cu->per_cu->lang == language_fortran && physname)
22765     {
22766       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22767 	 DW_AT_MIPS_linkage_name is preferred and used instead.  */
22768 
22769       lead = "__";
22770       sep = "_MOD_";
22771     }
22772   else
22773     sep = "::";
22774 
22775   if (prefix == NULL)
22776     prefix = "";
22777   if (suffix == NULL)
22778     suffix = "";
22779 
22780   if (obs == NULL)
22781     {
22782       char *retval
22783 	= ((char *)
22784 	   xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22785 
22786       strcpy (retval, lead);
22787       strcat (retval, prefix);
22788       strcat (retval, sep);
22789       strcat (retval, suffix);
22790       return retval;
22791     }
22792   else
22793     {
22794       /* We have an obstack.  */
22795       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22796     }
22797 }
22798 
22799 /* Get name of a die, return NULL if not found.  */
22800 
22801 static const char *
22802 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22803 			  struct objfile *objfile)
22804 {
22805   if (name && cu->per_cu->lang == language_cplus)
22806     {
22807       gdb::unique_xmalloc_ptr<char> canon_name
22808 	= cp_canonicalize_string (name);
22809 
22810       if (canon_name != nullptr)
22811 	name = objfile->intern (canon_name.get ());
22812     }
22813 
22814   return name;
22815 }
22816 
22817 /* Get name of a die, return NULL if not found.
22818    Anonymous namespaces are converted to their magic string.  */
22819 
22820 static const char *
22821 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22822 {
22823   struct attribute *attr;
22824   struct objfile *objfile = cu->per_objfile->objfile;
22825 
22826   attr = dwarf2_attr (die, DW_AT_name, cu);
22827   const char *attr_name = attr == nullptr ? nullptr : attr->as_string ();
22828   if (attr_name == nullptr
22829       && die->tag != DW_TAG_namespace
22830       && die->tag != DW_TAG_class_type
22831       && die->tag != DW_TAG_interface_type
22832       && die->tag != DW_TAG_structure_type
22833       && die->tag != DW_TAG_union_type)
22834     return NULL;
22835 
22836   switch (die->tag)
22837     {
22838     case DW_TAG_compile_unit:
22839     case DW_TAG_partial_unit:
22840       /* Compilation units have a DW_AT_name that is a filename, not
22841 	 a source language identifier.  */
22842     case DW_TAG_enumeration_type:
22843     case DW_TAG_enumerator:
22844       /* These tags always have simple identifiers already; no need
22845 	 to canonicalize them.  */
22846       return attr_name;
22847 
22848     case DW_TAG_namespace:
22849       if (attr_name != nullptr)
22850 	return attr_name;
22851       return CP_ANONYMOUS_NAMESPACE_STR;
22852 
22853     case DW_TAG_class_type:
22854     case DW_TAG_interface_type:
22855     case DW_TAG_structure_type:
22856     case DW_TAG_union_type:
22857       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22858 	 structures or unions.  These were of the form "._%d" in GCC 4.1,
22859 	 or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22860 	 and GCC 4.4.  We work around this problem by ignoring these.  */
22861       if (attr_name != nullptr
22862 	  && (startswith (attr_name, "._")
22863 	      || startswith (attr_name, "<anonymous")))
22864 	return NULL;
22865 
22866       /* GCC might emit a nameless typedef that has a linkage name.  See
22867 	 http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22868       if (!attr || attr_name == NULL)
22869 	{
22870 	  attr = dw2_linkage_name_attr (die, cu);
22871 	  attr_name = attr == nullptr ? nullptr : attr->as_string ();
22872 	  if (attr == NULL || attr_name == NULL)
22873 	    return NULL;
22874 
22875 	  /* Avoid demangling attr_name the second time on a second
22876 	     call for the same DIE.  */
22877 	  if (!attr->canonical_string_p ())
22878 	    {
22879 	      gdb::unique_xmalloc_ptr<char> demangled
22880 		(gdb_demangle (attr_name, DMGL_TYPES));
22881 	      if (demangled == nullptr)
22882 		return nullptr;
22883 
22884 	      attr->set_string_canonical (objfile->intern (demangled.get ()));
22885 	      attr_name = attr->as_string ();
22886 	    }
22887 
22888 	  /* Strip any leading namespaces/classes, keep only the
22889 	     base name.  DW_AT_name for named DIEs does not
22890 	     contain the prefixes.  */
22891 	  const char *base = strrchr (attr_name, ':');
22892 	  if (base && base > attr_name && base[-1] == ':')
22893 	    return &base[1];
22894 	  else
22895 	    return attr_name;
22896 	}
22897       break;
22898 
22899     default:
22900       break;
22901     }
22902 
22903   if (!attr->canonical_string_p ())
22904     attr->set_string_canonical (dwarf2_canonicalize_name (attr_name, cu,
22905 							  objfile));
22906   return attr->as_string ();
22907 }
22908 
22909 /* Return the die that this die in an extension of, or NULL if there
22910    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22911    containing the return value on output.  */
22912 
22913 static struct die_info *
22914 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22915 {
22916   struct attribute *attr;
22917 
22918   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22919   if (attr == NULL)
22920     return NULL;
22921 
22922   return follow_die_ref (die, attr, ext_cu);
22923 }
22924 
22925 static void
22926 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22927 {
22928   unsigned int i;
22929 
22930   print_spaces (indent, f);
22931   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22932 		      dwarf_tag_name (die->tag), die->abbrev,
22933 		      sect_offset_str (die->sect_off));
22934 
22935   if (die->parent != NULL)
22936     {
22937       print_spaces (indent, f);
22938       fprintf_unfiltered (f, "  parent at offset: %s\n",
22939 			  sect_offset_str (die->parent->sect_off));
22940     }
22941 
22942   print_spaces (indent, f);
22943   fprintf_unfiltered (f, "  has children: %s\n",
22944 	   dwarf_bool_name (die->child != NULL));
22945 
22946   print_spaces (indent, f);
22947   fprintf_unfiltered (f, "  attributes:\n");
22948 
22949   for (i = 0; i < die->num_attrs; ++i)
22950     {
22951       print_spaces (indent, f);
22952       fprintf_unfiltered (f, "    %s (%s) ",
22953 	       dwarf_attr_name (die->attrs[i].name),
22954 	       dwarf_form_name (die->attrs[i].form));
22955 
22956       switch (die->attrs[i].form)
22957 	{
22958 	case DW_FORM_addr:
22959 	case DW_FORM_addrx:
22960 	case DW_FORM_GNU_addr_index:
22961 	  fprintf_unfiltered (f, "address: ");
22962 	  fputs_filtered (hex_string (die->attrs[i].as_address ()), f);
22963 	  break;
22964 	case DW_FORM_block2:
22965 	case DW_FORM_block4:
22966 	case DW_FORM_block:
22967 	case DW_FORM_block1:
22968 	  fprintf_unfiltered (f, "block: size %s",
22969 			      pulongest (die->attrs[i].as_block ()->size));
22970 	  break;
22971 	case DW_FORM_exprloc:
22972 	  fprintf_unfiltered (f, "expression: size %s",
22973 			      pulongest (die->attrs[i].as_block ()->size));
22974 	  break;
22975 	case DW_FORM_data16:
22976 	  fprintf_unfiltered (f, "constant of 16 bytes");
22977 	  break;
22978 	case DW_FORM_ref_addr:
22979 	  fprintf_unfiltered (f, "ref address: ");
22980 	  fputs_filtered (hex_string (die->attrs[i].as_unsigned ()), f);
22981 	  break;
22982 	case DW_FORM_GNU_ref_alt:
22983 	  fprintf_unfiltered (f, "alt ref address: ");
22984 	  fputs_filtered (hex_string (die->attrs[i].as_unsigned ()), f);
22985 	  break;
22986 	case DW_FORM_ref1:
22987 	case DW_FORM_ref2:
22988 	case DW_FORM_ref4:
22989 	case DW_FORM_ref8:
22990 	case DW_FORM_ref_udata:
22991 	  fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22992 			      (long) (die->attrs[i].as_unsigned ()));
22993 	  break;
22994 	case DW_FORM_data1:
22995 	case DW_FORM_data2:
22996 	case DW_FORM_data4:
22997 	case DW_FORM_data8:
22998 	case DW_FORM_udata:
22999 	  fprintf_unfiltered (f, "constant: %s",
23000 			      pulongest (die->attrs[i].as_unsigned ()));
23001 	  break;
23002 	case DW_FORM_sec_offset:
23003 	  fprintf_unfiltered (f, "section offset: %s",
23004 			      pulongest (die->attrs[i].as_unsigned ()));
23005 	  break;
23006 	case DW_FORM_ref_sig8:
23007 	  fprintf_unfiltered (f, "signature: %s",
23008 			      hex_string (die->attrs[i].as_signature ()));
23009 	  break;
23010 	case DW_FORM_string:
23011 	case DW_FORM_strp:
23012 	case DW_FORM_line_strp:
23013 	case DW_FORM_strx:
23014 	case DW_FORM_GNU_str_index:
23015 	case DW_FORM_GNU_strp_alt:
23016 	  fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
23017 			      die->attrs[i].as_string ()
23018 			      ? die->attrs[i].as_string () : "",
23019 			      die->attrs[i].canonical_string_p () ? "is" : "not");
23020 	  break;
23021 	case DW_FORM_flag:
23022 	  if (die->attrs[i].as_boolean ())
23023 	    fprintf_unfiltered (f, "flag: TRUE");
23024 	  else
23025 	    fprintf_unfiltered (f, "flag: FALSE");
23026 	  break;
23027 	case DW_FORM_flag_present:
23028 	  fprintf_unfiltered (f, "flag: TRUE");
23029 	  break;
23030 	case DW_FORM_indirect:
23031 	  /* The reader will have reduced the indirect form to
23032 	     the "base form" so this form should not occur.  */
23033 	  fprintf_unfiltered (f,
23034 			      "unexpected attribute form: DW_FORM_indirect");
23035 	  break;
23036 	case DW_FORM_sdata:
23037 	case DW_FORM_implicit_const:
23038 	  fprintf_unfiltered (f, "constant: %s",
23039 			      plongest (die->attrs[i].as_signed ()));
23040 	  break;
23041 	default:
23042 	  fprintf_unfiltered (f, "unsupported attribute form: %d.",
23043 		   die->attrs[i].form);
23044 	  break;
23045 	}
23046       fprintf_unfiltered (f, "\n");
23047     }
23048 }
23049 
23050 static void
23051 dump_die_for_error (struct die_info *die)
23052 {
23053   dump_die_shallow (gdb_stderr, 0, die);
23054 }
23055 
23056 static void
23057 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
23058 {
23059   int indent = level * 4;
23060 
23061   gdb_assert (die != NULL);
23062 
23063   if (level >= max_level)
23064     return;
23065 
23066   dump_die_shallow (f, indent, die);
23067 
23068   if (die->child != NULL)
23069     {
23070       print_spaces (indent, f);
23071       fprintf_unfiltered (f, "  Children:");
23072       if (level + 1 < max_level)
23073 	{
23074 	  fprintf_unfiltered (f, "\n");
23075 	  dump_die_1 (f, level + 1, max_level, die->child);
23076 	}
23077       else
23078 	{
23079 	  fprintf_unfiltered (f,
23080 			      " [not printed, max nesting level reached]\n");
23081 	}
23082     }
23083 
23084   if (die->sibling != NULL && level > 0)
23085     {
23086       dump_die_1 (f, level, max_level, die->sibling);
23087     }
23088 }
23089 
23090 /* This is called from the pdie macro in gdbinit.in.
23091    It's not static so gcc will keep a copy callable from gdb.  */
23092 
23093 void
23094 dump_die (struct die_info *die, int max_level)
23095 {
23096   dump_die_1 (gdb_stdlog, 0, max_level, die);
23097 }
23098 
23099 static void
23100 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
23101 {
23102   void **slot;
23103 
23104   slot = htab_find_slot_with_hash (cu->die_hash, die,
23105 				   to_underlying (die->sect_off),
23106 				   INSERT);
23107 
23108   *slot = die;
23109 }
23110 
23111 /* Follow reference or signature attribute ATTR of SRC_DIE.
23112    On entry *REF_CU is the CU of SRC_DIE.
23113    On exit *REF_CU is the CU of the result.  */
23114 
23115 static struct die_info *
23116 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
23117 		       struct dwarf2_cu **ref_cu)
23118 {
23119   struct die_info *die;
23120 
23121   if (attr->form_is_ref ())
23122     die = follow_die_ref (src_die, attr, ref_cu);
23123   else if (attr->form == DW_FORM_ref_sig8)
23124     die = follow_die_sig (src_die, attr, ref_cu);
23125   else
23126     {
23127       dump_die_for_error (src_die);
23128       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
23129 	     objfile_name ((*ref_cu)->per_objfile->objfile));
23130     }
23131 
23132   return die;
23133 }
23134 
23135 /* Follow reference OFFSET.
23136    On entry *REF_CU is the CU of the source die referencing OFFSET.
23137    On exit *REF_CU is the CU of the result.
23138    Returns NULL if OFFSET is invalid.  */
23139 
23140 static struct die_info *
23141 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
23142 		   struct dwarf2_cu **ref_cu)
23143 {
23144   struct die_info temp_die;
23145   struct dwarf2_cu *target_cu, *cu = *ref_cu;
23146   dwarf2_per_objfile *per_objfile = cu->per_objfile;
23147 
23148   gdb_assert (cu->per_cu != NULL);
23149 
23150   target_cu = cu;
23151 
23152   dwarf_read_debug_printf_v ("source CU offset: %s, target offset: %s, "
23153 			     "source CU contains target offset: %d",
23154 			     sect_offset_str (cu->per_cu->sect_off),
23155 			     sect_offset_str (sect_off),
23156 			     cu->header.offset_in_cu_p (sect_off));
23157 
23158   if (cu->per_cu->is_debug_types)
23159     {
23160       /* .debug_types CUs cannot reference anything outside their CU.
23161 	 If they need to, they have to reference a signatured type via
23162 	 DW_FORM_ref_sig8.  */
23163       if (!cu->header.offset_in_cu_p (sect_off))
23164 	return NULL;
23165     }
23166   else if (offset_in_dwz != cu->per_cu->is_dwz
23167 	   || !cu->header.offset_in_cu_p (sect_off))
23168     {
23169       struct dwarf2_per_cu_data *per_cu;
23170 
23171       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
23172 						 per_objfile);
23173 
23174       dwarf_read_debug_printf_v ("target CU offset: %s, "
23175 				 "target CU DIEs loaded: %d",
23176 				 sect_offset_str (per_cu->sect_off),
23177 				 per_objfile->get_cu (per_cu) != nullptr);
23178 
23179       /* If necessary, add it to the queue and load its DIEs.
23180 
23181 	 Even if maybe_queue_comp_unit doesn't require us to load the CU's DIEs,
23182 	 it doesn't mean they are currently loaded.  Since we require them
23183 	 to be loaded, we must check for ourselves.  */
23184       if (maybe_queue_comp_unit (cu, per_cu, per_objfile, cu->per_cu->lang)
23185 	  || per_objfile->get_cu (per_cu) == nullptr)
23186 	load_full_comp_unit (per_cu, per_objfile, per_objfile->get_cu (per_cu),
23187 			     false, cu->per_cu->lang);
23188 
23189       target_cu = per_objfile->get_cu (per_cu);
23190       gdb_assert (target_cu != nullptr);
23191     }
23192   else if (cu->dies == NULL)
23193     {
23194       /* We're loading full DIEs during partial symbol reading.  */
23195       gdb_assert (per_objfile->per_bfd->reading_partial_symbols);
23196       load_full_comp_unit (cu->per_cu, per_objfile, cu, false,
23197 			   language_minimal);
23198     }
23199 
23200   *ref_cu = target_cu;
23201   temp_die.sect_off = sect_off;
23202 
23203   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
23204 						  &temp_die,
23205 						  to_underlying (sect_off));
23206 }
23207 
23208 /* Follow reference attribute ATTR of SRC_DIE.
23209    On entry *REF_CU is the CU of SRC_DIE.
23210    On exit *REF_CU is the CU of the result.  */
23211 
23212 static struct die_info *
23213 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
23214 		struct dwarf2_cu **ref_cu)
23215 {
23216   sect_offset sect_off = attr->get_ref_die_offset ();
23217   struct dwarf2_cu *cu = *ref_cu;
23218   struct die_info *die;
23219 
23220   die = follow_die_offset (sect_off,
23221 			   (attr->form == DW_FORM_GNU_ref_alt
23222 			    || cu->per_cu->is_dwz),
23223 			   ref_cu);
23224   if (!die)
23225     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
23226 	   "at %s [in module %s]"),
23227 	   sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
23228 	   objfile_name (cu->per_objfile->objfile));
23229 
23230   return die;
23231 }
23232 
23233 /* See read.h.  */
23234 
23235 struct dwarf2_locexpr_baton
23236 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
23237 			       dwarf2_per_cu_data *per_cu,
23238 			       dwarf2_per_objfile *per_objfile,
23239 			       gdb::function_view<CORE_ADDR ()> get_frame_pc,
23240 			       bool resolve_abstract_p)
23241 {
23242   struct die_info *die;
23243   struct attribute *attr;
23244   struct dwarf2_locexpr_baton retval;
23245   struct objfile *objfile = per_objfile->objfile;
23246 
23247   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
23248   if (cu == nullptr)
23249     cu = load_cu (per_cu, per_objfile, false);
23250 
23251   if (cu == nullptr)
23252     {
23253       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23254 	 Instead just throw an error, not much else we can do.  */
23255       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23256 	     sect_offset_str (sect_off), objfile_name (objfile));
23257     }
23258 
23259   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23260   if (!die)
23261     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23262 	   sect_offset_str (sect_off), objfile_name (objfile));
23263 
23264   attr = dwarf2_attr (die, DW_AT_location, cu);
23265   if (!attr && resolve_abstract_p
23266       && (per_objfile->per_bfd->abstract_to_concrete.find (die->sect_off)
23267 	  != per_objfile->per_bfd->abstract_to_concrete.end ()))
23268     {
23269       CORE_ADDR pc = get_frame_pc ();
23270       CORE_ADDR baseaddr = objfile->text_section_offset ();
23271       struct gdbarch *gdbarch = objfile->arch ();
23272 
23273       for (const auto &cand_off
23274 	     : per_objfile->per_bfd->abstract_to_concrete[die->sect_off])
23275 	{
23276 	  struct dwarf2_cu *cand_cu = cu;
23277 	  struct die_info *cand
23278 	    = follow_die_offset (cand_off, per_cu->is_dwz, &cand_cu);
23279 	  if (!cand
23280 	      || !cand->parent
23281 	      || cand->parent->tag != DW_TAG_subprogram)
23282 	    continue;
23283 
23284 	  CORE_ADDR pc_low, pc_high;
23285 	  get_scope_pc_bounds (cand->parent, &pc_low, &pc_high, cu);
23286 	  if (pc_low == ((CORE_ADDR) -1))
23287 	    continue;
23288 	  pc_low = gdbarch_adjust_dwarf2_addr (gdbarch, pc_low + baseaddr);
23289 	  pc_high = gdbarch_adjust_dwarf2_addr (gdbarch, pc_high + baseaddr);
23290 	  if (!(pc_low <= pc && pc < pc_high))
23291 	    continue;
23292 
23293 	  die = cand;
23294 	  attr = dwarf2_attr (die, DW_AT_location, cu);
23295 	  break;
23296 	}
23297     }
23298 
23299   if (!attr)
23300     {
23301       /* DWARF: "If there is no such attribute, then there is no effect.".
23302 	 DATA is ignored if SIZE is 0.  */
23303 
23304       retval.data = NULL;
23305       retval.size = 0;
23306     }
23307   else if (attr->form_is_section_offset ())
23308     {
23309       struct dwarf2_loclist_baton loclist_baton;
23310       CORE_ADDR pc = get_frame_pc ();
23311       size_t size;
23312 
23313       fill_in_loclist_baton (cu, &loclist_baton, attr);
23314 
23315       retval.data = dwarf2_find_location_expression (&loclist_baton,
23316 						     &size, pc);
23317       retval.size = size;
23318     }
23319   else
23320     {
23321       if (!attr->form_is_block ())
23322 	error (_("Dwarf Error: DIE at %s referenced in module %s "
23323 		 "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23324 	       sect_offset_str (sect_off), objfile_name (objfile));
23325 
23326       struct dwarf_block *block = attr->as_block ();
23327       retval.data = block->data;
23328       retval.size = block->size;
23329     }
23330   retval.per_objfile = per_objfile;
23331   retval.per_cu = cu->per_cu;
23332 
23333   per_objfile->age_comp_units ();
23334 
23335   return retval;
23336 }
23337 
23338 /* See read.h.  */
23339 
23340 struct dwarf2_locexpr_baton
23341 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23342 			     dwarf2_per_cu_data *per_cu,
23343 			     dwarf2_per_objfile *per_objfile,
23344 			     gdb::function_view<CORE_ADDR ()> get_frame_pc)
23345 {
23346   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23347 
23348   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, per_objfile,
23349 					get_frame_pc);
23350 }
23351 
23352 /* Write a constant of a given type as target-ordered bytes into
23353    OBSTACK.  */
23354 
23355 static const gdb_byte *
23356 write_constant_as_bytes (struct obstack *obstack,
23357 			 enum bfd_endian byte_order,
23358 			 struct type *type,
23359 			 ULONGEST value,
23360 			 LONGEST *len)
23361 {
23362   gdb_byte *result;
23363 
23364   *len = TYPE_LENGTH (type);
23365   result = (gdb_byte *) obstack_alloc (obstack, *len);
23366   store_unsigned_integer (result, *len, byte_order, value);
23367 
23368   return result;
23369 }
23370 
23371 /* See read.h.  */
23372 
23373 const gdb_byte *
23374 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23375 			     dwarf2_per_cu_data *per_cu,
23376 			     dwarf2_per_objfile *per_objfile,
23377 			     obstack *obstack,
23378 			     LONGEST *len)
23379 {
23380   struct die_info *die;
23381   struct attribute *attr;
23382   const gdb_byte *result = NULL;
23383   struct type *type;
23384   LONGEST value;
23385   enum bfd_endian byte_order;
23386   struct objfile *objfile = per_objfile->objfile;
23387 
23388   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
23389   if (cu == nullptr)
23390     cu = load_cu (per_cu, per_objfile, false);
23391 
23392   if (cu == nullptr)
23393     {
23394       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23395 	 Instead just throw an error, not much else we can do.  */
23396       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23397 	     sect_offset_str (sect_off), objfile_name (objfile));
23398     }
23399 
23400   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23401   if (!die)
23402     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23403 	   sect_offset_str (sect_off), objfile_name (objfile));
23404 
23405   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23406   if (attr == NULL)
23407     return NULL;
23408 
23409   byte_order = (bfd_big_endian (objfile->obfd)
23410 		? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23411 
23412   switch (attr->form)
23413     {
23414     case DW_FORM_addr:
23415     case DW_FORM_addrx:
23416     case DW_FORM_GNU_addr_index:
23417       {
23418 	gdb_byte *tem;
23419 
23420 	*len = cu->header.addr_size;
23421 	tem = (gdb_byte *) obstack_alloc (obstack, *len);
23422 	store_unsigned_integer (tem, *len, byte_order, attr->as_address ());
23423 	result = tem;
23424       }
23425       break;
23426     case DW_FORM_string:
23427     case DW_FORM_strp:
23428     case DW_FORM_strx:
23429     case DW_FORM_GNU_str_index:
23430     case DW_FORM_GNU_strp_alt:
23431       /* The string is already allocated on the objfile obstack, point
23432 	 directly to it.  */
23433       {
23434 	const char *attr_name = attr->as_string ();
23435 	result = (const gdb_byte *) attr_name;
23436 	*len = strlen (attr_name);
23437       }
23438       break;
23439     case DW_FORM_block1:
23440     case DW_FORM_block2:
23441     case DW_FORM_block4:
23442     case DW_FORM_block:
23443     case DW_FORM_exprloc:
23444     case DW_FORM_data16:
23445       {
23446 	struct dwarf_block *block = attr->as_block ();
23447 	result = block->data;
23448 	*len = block->size;
23449       }
23450       break;
23451 
23452       /* The DW_AT_const_value attributes are supposed to carry the
23453 	 symbol's value "represented as it would be on the target
23454 	 architecture."  By the time we get here, it's already been
23455 	 converted to host endianness, so we just need to sign- or
23456 	 zero-extend it as appropriate.  */
23457     case DW_FORM_data1:
23458       type = die_type (die, cu);
23459       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23460       if (result == NULL)
23461 	result = write_constant_as_bytes (obstack, byte_order,
23462 					  type, value, len);
23463       break;
23464     case DW_FORM_data2:
23465       type = die_type (die, cu);
23466       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23467       if (result == NULL)
23468 	result = write_constant_as_bytes (obstack, byte_order,
23469 					  type, value, len);
23470       break;
23471     case DW_FORM_data4:
23472       type = die_type (die, cu);
23473       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23474       if (result == NULL)
23475 	result = write_constant_as_bytes (obstack, byte_order,
23476 					  type, value, len);
23477       break;
23478     case DW_FORM_data8:
23479       type = die_type (die, cu);
23480       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23481       if (result == NULL)
23482 	result = write_constant_as_bytes (obstack, byte_order,
23483 					  type, value, len);
23484       break;
23485 
23486     case DW_FORM_sdata:
23487     case DW_FORM_implicit_const:
23488       type = die_type (die, cu);
23489       result = write_constant_as_bytes (obstack, byte_order,
23490 					type, attr->as_signed (), len);
23491       break;
23492 
23493     case DW_FORM_udata:
23494       type = die_type (die, cu);
23495       result = write_constant_as_bytes (obstack, byte_order,
23496 					type, attr->as_unsigned (), len);
23497       break;
23498 
23499     default:
23500       complaint (_("unsupported const value attribute form: '%s'"),
23501 		 dwarf_form_name (attr->form));
23502       break;
23503     }
23504 
23505   return result;
23506 }
23507 
23508 /* See read.h.  */
23509 
23510 struct type *
23511 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23512 				dwarf2_per_cu_data *per_cu,
23513 				dwarf2_per_objfile *per_objfile,
23514 				const char **var_name)
23515 {
23516   struct die_info *die;
23517 
23518   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
23519   if (cu == nullptr)
23520     cu = load_cu (per_cu, per_objfile, false);
23521 
23522   if (cu == nullptr)
23523     return nullptr;
23524 
23525   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23526   if (!die)
23527     return NULL;
23528 
23529   if (var_name != nullptr)
23530     *var_name = var_decl_name (die, cu);
23531   return die_type (die, cu);
23532 }
23533 
23534 /* See read.h.  */
23535 
23536 struct type *
23537 dwarf2_get_die_type (cu_offset die_offset,
23538 		     dwarf2_per_cu_data *per_cu,
23539 		     dwarf2_per_objfile *per_objfile)
23540 {
23541   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23542   return get_die_type_at_offset (die_offset_sect, per_cu, per_objfile);
23543 }
23544 
23545 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23546    On entry *REF_CU is the CU of SRC_DIE.
23547    On exit *REF_CU is the CU of the result.
23548    Returns NULL if the referenced DIE isn't found.  */
23549 
23550 static struct die_info *
23551 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23552 		  struct dwarf2_cu **ref_cu)
23553 {
23554   struct die_info temp_die;
23555   struct dwarf2_cu *sig_cu;
23556   struct die_info *die;
23557   dwarf2_per_objfile *per_objfile = (*ref_cu)->per_objfile;
23558 
23559 
23560   /* While it might be nice to assert sig_type->type == NULL here,
23561      we can get here for DW_AT_imported_declaration where we need
23562      the DIE not the type.  */
23563 
23564   /* If necessary, add it to the queue and load its DIEs.
23565 
23566      Even if maybe_queue_comp_unit doesn't require us to load the CU's DIEs,
23567      it doesn't mean they are currently loaded.  Since we require them
23568      to be loaded, we must check for ourselves.  */
23569   if (maybe_queue_comp_unit (*ref_cu, sig_type, per_objfile,
23570 			     language_minimal)
23571       || per_objfile->get_cu (sig_type) == nullptr)
23572     read_signatured_type (sig_type, per_objfile);
23573 
23574   sig_cu = per_objfile->get_cu (sig_type);
23575   gdb_assert (sig_cu != NULL);
23576   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23577   temp_die.sect_off = sig_type->type_offset_in_section;
23578   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23579 						 to_underlying (temp_die.sect_off));
23580   if (die)
23581     {
23582       /* For .gdb_index version 7 keep track of included TUs.
23583 	 http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23584       if (per_objfile->per_bfd->index_table != NULL
23585 	  && per_objfile->per_bfd->index_table->version <= 7)
23586 	{
23587 	  (*ref_cu)->per_cu->imported_symtabs_push (sig_cu->per_cu);
23588 	}
23589 
23590       *ref_cu = sig_cu;
23591       return die;
23592     }
23593 
23594   return NULL;
23595 }
23596 
23597 /* Follow signatured type referenced by ATTR in SRC_DIE.
23598    On entry *REF_CU is the CU of SRC_DIE.
23599    On exit *REF_CU is the CU of the result.
23600    The result is the DIE of the type.
23601    If the referenced type cannot be found an error is thrown.  */
23602 
23603 static struct die_info *
23604 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23605 		struct dwarf2_cu **ref_cu)
23606 {
23607   ULONGEST signature = attr->as_signature ();
23608   struct signatured_type *sig_type;
23609   struct die_info *die;
23610 
23611   gdb_assert (attr->form == DW_FORM_ref_sig8);
23612 
23613   sig_type = lookup_signatured_type (*ref_cu, signature);
23614   /* sig_type will be NULL if the signatured type is missing from
23615      the debug info.  */
23616   if (sig_type == NULL)
23617     {
23618       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23619 	       " from DIE at %s [in module %s]"),
23620 	     hex_string (signature), sect_offset_str (src_die->sect_off),
23621 	     objfile_name ((*ref_cu)->per_objfile->objfile));
23622     }
23623 
23624   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23625   if (die == NULL)
23626     {
23627       dump_die_for_error (src_die);
23628       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23629 	       " from DIE at %s [in module %s]"),
23630 	     hex_string (signature), sect_offset_str (src_die->sect_off),
23631 	     objfile_name ((*ref_cu)->per_objfile->objfile));
23632     }
23633 
23634   return die;
23635 }
23636 
23637 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23638    reading in and processing the type unit if necessary.  */
23639 
23640 static struct type *
23641 get_signatured_type (struct die_info *die, ULONGEST signature,
23642 		     struct dwarf2_cu *cu)
23643 {
23644   dwarf2_per_objfile *per_objfile = cu->per_objfile;
23645   struct signatured_type *sig_type;
23646   struct dwarf2_cu *type_cu;
23647   struct die_info *type_die;
23648   struct type *type;
23649 
23650   sig_type = lookup_signatured_type (cu, signature);
23651   /* sig_type will be NULL if the signatured type is missing from
23652      the debug info.  */
23653   if (sig_type == NULL)
23654     {
23655       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23656 		   " from DIE at %s [in module %s]"),
23657 		 hex_string (signature), sect_offset_str (die->sect_off),
23658 		 objfile_name (per_objfile->objfile));
23659       return build_error_marker_type (cu, die);
23660     }
23661 
23662   /* If we already know the type we're done.  */
23663   type = per_objfile->get_type_for_signatured_type (sig_type);
23664   if (type != nullptr)
23665     return type;
23666 
23667   type_cu = cu;
23668   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23669   if (type_die != NULL)
23670     {
23671       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23672 	 is created.  This is important, for example, because for c++ classes
23673 	 we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23674       type = read_type_die (type_die, type_cu);
23675       if (type == NULL)
23676 	{
23677 	  complaint (_("Dwarf Error: Cannot build signatured type %s"
23678 		       " referenced from DIE at %s [in module %s]"),
23679 		     hex_string (signature), sect_offset_str (die->sect_off),
23680 		     objfile_name (per_objfile->objfile));
23681 	  type = build_error_marker_type (cu, die);
23682 	}
23683     }
23684   else
23685     {
23686       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23687 		   " from DIE at %s [in module %s]"),
23688 		 hex_string (signature), sect_offset_str (die->sect_off),
23689 		 objfile_name (per_objfile->objfile));
23690       type = build_error_marker_type (cu, die);
23691     }
23692 
23693   per_objfile->set_type_for_signatured_type (sig_type, type);
23694 
23695   return type;
23696 }
23697 
23698 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23699    reading in and processing the type unit if necessary.  */
23700 
23701 static struct type *
23702 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23703 			  struct dwarf2_cu *cu) /* ARI: editCase function */
23704 {
23705   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23706   if (attr->form_is_ref ())
23707     {
23708       struct dwarf2_cu *type_cu = cu;
23709       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23710 
23711       return read_type_die (type_die, type_cu);
23712     }
23713   else if (attr->form == DW_FORM_ref_sig8)
23714     {
23715       return get_signatured_type (die, attr->as_signature (), cu);
23716     }
23717   else
23718     {
23719       dwarf2_per_objfile *per_objfile = cu->per_objfile;
23720 
23721       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23722 		   " at %s [in module %s]"),
23723 		 dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23724 		 objfile_name (per_objfile->objfile));
23725       return build_error_marker_type (cu, die);
23726     }
23727 }
23728 
23729 /* Load the DIEs associated with type unit PER_CU into memory.  */
23730 
23731 static void
23732 load_full_type_unit (dwarf2_per_cu_data *per_cu,
23733 		     dwarf2_per_objfile *per_objfile)
23734 {
23735   struct signatured_type *sig_type;
23736 
23737   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23738   gdb_assert (! per_cu->type_unit_group_p ());
23739 
23740   /* We have the per_cu, but we need the signatured_type.
23741      Fortunately this is an easy translation.  */
23742   gdb_assert (per_cu->is_debug_types);
23743   sig_type = (struct signatured_type *) per_cu;
23744 
23745   gdb_assert (per_objfile->get_cu (per_cu) == nullptr);
23746 
23747   read_signatured_type (sig_type, per_objfile);
23748 
23749   gdb_assert (per_objfile->get_cu (per_cu) != nullptr);
23750 }
23751 
23752 /* Read in a signatured type and build its CU and DIEs.
23753    If the type is a stub for the real type in a DWO file,
23754    read in the real type from the DWO file as well.  */
23755 
23756 static void
23757 read_signatured_type (signatured_type *sig_type,
23758 		      dwarf2_per_objfile *per_objfile)
23759 {
23760   gdb_assert (sig_type->is_debug_types);
23761   gdb_assert (per_objfile->get_cu (sig_type) == nullptr);
23762 
23763   cutu_reader reader (sig_type, per_objfile, nullptr, nullptr, false);
23764 
23765   if (!reader.dummy_p)
23766     {
23767       struct dwarf2_cu *cu = reader.cu;
23768       const gdb_byte *info_ptr = reader.info_ptr;
23769 
23770       gdb_assert (cu->die_hash == NULL);
23771       cu->die_hash =
23772 	htab_create_alloc_ex (cu->header.length / 12,
23773 			      die_hash,
23774 			      die_eq,
23775 			      NULL,
23776 			      &cu->comp_unit_obstack,
23777 			      hashtab_obstack_allocate,
23778 			      dummy_obstack_deallocate);
23779 
23780       if (reader.comp_unit_die->has_children)
23781 	reader.comp_unit_die->child
23782 	  = read_die_and_siblings (&reader, info_ptr, &info_ptr,
23783 				   reader.comp_unit_die);
23784       cu->dies = reader.comp_unit_die;
23785       /* comp_unit_die is not stored in die_hash, no need.  */
23786 
23787       /* We try not to read any attributes in this function, because
23788 	 not all CUs needed for references have been loaded yet, and
23789 	 symbol table processing isn't initialized.  But we have to
23790 	 set the CU language, or we won't be able to build types
23791 	 correctly.  Similarly, if we do not read the producer, we can
23792 	 not apply producer-specific interpretation.  */
23793       prepare_one_comp_unit (cu, cu->dies, language_minimal);
23794 
23795       reader.keep ();
23796     }
23797 
23798   sig_type->tu_read = 1;
23799 }
23800 
23801 /* Decode simple location descriptions.
23802    Given a pointer to a dwarf block that defines a location, compute
23803    the location and return the value.  If COMPUTED is non-null, it is
23804    set to true to indicate that decoding was successful, and false
23805    otherwise.  If COMPUTED is null, then this function may emit a
23806    complaint.  */
23807 
23808 static CORE_ADDR
23809 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu, bool *computed)
23810 {
23811   struct objfile *objfile = cu->per_objfile->objfile;
23812   size_t i;
23813   size_t size = blk->size;
23814   const gdb_byte *data = blk->data;
23815   CORE_ADDR stack[64];
23816   int stacki;
23817   unsigned int bytes_read, unsnd;
23818   gdb_byte op;
23819 
23820   if (computed != nullptr)
23821     *computed = false;
23822 
23823   i = 0;
23824   stacki = 0;
23825   stack[stacki] = 0;
23826   stack[++stacki] = 0;
23827 
23828   while (i < size)
23829     {
23830       op = data[i++];
23831       switch (op)
23832 	{
23833 	case DW_OP_lit0:
23834 	case DW_OP_lit1:
23835 	case DW_OP_lit2:
23836 	case DW_OP_lit3:
23837 	case DW_OP_lit4:
23838 	case DW_OP_lit5:
23839 	case DW_OP_lit6:
23840 	case DW_OP_lit7:
23841 	case DW_OP_lit8:
23842 	case DW_OP_lit9:
23843 	case DW_OP_lit10:
23844 	case DW_OP_lit11:
23845 	case DW_OP_lit12:
23846 	case DW_OP_lit13:
23847 	case DW_OP_lit14:
23848 	case DW_OP_lit15:
23849 	case DW_OP_lit16:
23850 	case DW_OP_lit17:
23851 	case DW_OP_lit18:
23852 	case DW_OP_lit19:
23853 	case DW_OP_lit20:
23854 	case DW_OP_lit21:
23855 	case DW_OP_lit22:
23856 	case DW_OP_lit23:
23857 	case DW_OP_lit24:
23858 	case DW_OP_lit25:
23859 	case DW_OP_lit26:
23860 	case DW_OP_lit27:
23861 	case DW_OP_lit28:
23862 	case DW_OP_lit29:
23863 	case DW_OP_lit30:
23864 	case DW_OP_lit31:
23865 	  stack[++stacki] = op - DW_OP_lit0;
23866 	  break;
23867 
23868 	case DW_OP_reg0:
23869 	case DW_OP_reg1:
23870 	case DW_OP_reg2:
23871 	case DW_OP_reg3:
23872 	case DW_OP_reg4:
23873 	case DW_OP_reg5:
23874 	case DW_OP_reg6:
23875 	case DW_OP_reg7:
23876 	case DW_OP_reg8:
23877 	case DW_OP_reg9:
23878 	case DW_OP_reg10:
23879 	case DW_OP_reg11:
23880 	case DW_OP_reg12:
23881 	case DW_OP_reg13:
23882 	case DW_OP_reg14:
23883 	case DW_OP_reg15:
23884 	case DW_OP_reg16:
23885 	case DW_OP_reg17:
23886 	case DW_OP_reg18:
23887 	case DW_OP_reg19:
23888 	case DW_OP_reg20:
23889 	case DW_OP_reg21:
23890 	case DW_OP_reg22:
23891 	case DW_OP_reg23:
23892 	case DW_OP_reg24:
23893 	case DW_OP_reg25:
23894 	case DW_OP_reg26:
23895 	case DW_OP_reg27:
23896 	case DW_OP_reg28:
23897 	case DW_OP_reg29:
23898 	case DW_OP_reg30:
23899 	case DW_OP_reg31:
23900 	  stack[++stacki] = op - DW_OP_reg0;
23901 	  if (i < size)
23902 	    {
23903 	      if (computed == nullptr)
23904 		dwarf2_complex_location_expr_complaint ();
23905 	      else
23906 		return 0;
23907 	    }
23908 	  break;
23909 
23910 	case DW_OP_regx:
23911 	  unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23912 	  i += bytes_read;
23913 	  stack[++stacki] = unsnd;
23914 	  if (i < size)
23915 	    {
23916 	      if (computed == nullptr)
23917 		dwarf2_complex_location_expr_complaint ();
23918 	      else
23919 		return 0;
23920 	    }
23921 	  break;
23922 
23923 	case DW_OP_addr:
23924 	  stack[++stacki] = cu->header.read_address (objfile->obfd, &data[i],
23925 						     &bytes_read);
23926 	  i += bytes_read;
23927 	  break;
23928 
23929 	case DW_OP_const1u:
23930 	  stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23931 	  i += 1;
23932 	  break;
23933 
23934 	case DW_OP_const1s:
23935 	  stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23936 	  i += 1;
23937 	  break;
23938 
23939 	case DW_OP_const2u:
23940 	  stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23941 	  i += 2;
23942 	  break;
23943 
23944 	case DW_OP_const2s:
23945 	  stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23946 	  i += 2;
23947 	  break;
23948 
23949 	case DW_OP_const4u:
23950 	  stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23951 	  i += 4;
23952 	  break;
23953 
23954 	case DW_OP_const4s:
23955 	  stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23956 	  i += 4;
23957 	  break;
23958 
23959 	case DW_OP_const8u:
23960 	  stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23961 	  i += 8;
23962 	  break;
23963 
23964 	case DW_OP_constu:
23965 	  stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23966 						  &bytes_read);
23967 	  i += bytes_read;
23968 	  break;
23969 
23970 	case DW_OP_consts:
23971 	  stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23972 	  i += bytes_read;
23973 	  break;
23974 
23975 	case DW_OP_dup:
23976 	  stack[stacki + 1] = stack[stacki];
23977 	  stacki++;
23978 	  break;
23979 
23980 	case DW_OP_plus:
23981 	  stack[stacki - 1] += stack[stacki];
23982 	  stacki--;
23983 	  break;
23984 
23985 	case DW_OP_plus_uconst:
23986 	  stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23987 						 &bytes_read);
23988 	  i += bytes_read;
23989 	  break;
23990 
23991 	case DW_OP_minus:
23992 	  stack[stacki - 1] -= stack[stacki];
23993 	  stacki--;
23994 	  break;
23995 
23996 	case DW_OP_deref:
23997 	  /* If we're not the last op, then we definitely can't encode
23998 	     this using GDB's address_class enum.  This is valid for partial
23999 	     global symbols, although the variable's address will be bogus
24000 	     in the psymtab.  */
24001 	  if (i < size)
24002 	    {
24003 	      if (computed == nullptr)
24004 		dwarf2_complex_location_expr_complaint ();
24005 	      else
24006 		return 0;
24007 	    }
24008 	  break;
24009 
24010 	case DW_OP_GNU_push_tls_address:
24011 	case DW_OP_form_tls_address:
24012 	  /* The top of the stack has the offset from the beginning
24013 	     of the thread control block at which the variable is located.  */
24014 	  /* Nothing should follow this operator, so the top of stack would
24015 	     be returned.  */
24016 	  /* This is valid for partial global symbols, but the variable's
24017 	     address will be bogus in the psymtab.  Make it always at least
24018 	     non-zero to not look as a variable garbage collected by linker
24019 	     which have DW_OP_addr 0.  */
24020 	  if (i < size)
24021 	    {
24022 	      if (computed == nullptr)
24023 		dwarf2_complex_location_expr_complaint ();
24024 	      else
24025 		return 0;
24026 	    }
24027 	  stack[stacki]++;
24028 	  break;
24029 
24030 	case DW_OP_GNU_uninit:
24031 	  if (computed != nullptr)
24032 	    return 0;
24033 	  break;
24034 
24035 	case DW_OP_addrx:
24036 	case DW_OP_GNU_addr_index:
24037 	case DW_OP_GNU_const_index:
24038 	  stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
24039 							 &bytes_read);
24040 	  i += bytes_read;
24041 	  break;
24042 
24043 	default:
24044 	  if (computed == nullptr)
24045 	    {
24046 	      const char *name = get_DW_OP_name (op);
24047 
24048 	      if (name)
24049 		complaint (_("unsupported stack op: '%s'"),
24050 			   name);
24051 	      else
24052 		complaint (_("unsupported stack op: '%02x'"),
24053 			   op);
24054 	    }
24055 
24056 	  return (stack[stacki]);
24057 	}
24058 
24059       /* Enforce maximum stack depth of SIZE-1 to avoid writing
24060 	 outside of the allocated space.  Also enforce minimum>0.  */
24061       if (stacki >= ARRAY_SIZE (stack) - 1)
24062 	{
24063 	  if (computed == nullptr)
24064 	    complaint (_("location description stack overflow"));
24065 	  return 0;
24066 	}
24067 
24068       if (stacki <= 0)
24069 	{
24070 	  if (computed == nullptr)
24071 	    complaint (_("location description stack underflow"));
24072 	  return 0;
24073 	}
24074     }
24075 
24076   if (computed != nullptr)
24077     *computed = true;
24078   return (stack[stacki]);
24079 }
24080 
24081 /* memory allocation interface */
24082 
24083 static struct dwarf_block *
24084 dwarf_alloc_block (struct dwarf2_cu *cu)
24085 {
24086   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
24087 }
24088 
24089 static struct die_info *
24090 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
24091 {
24092   struct die_info *die;
24093   size_t size = sizeof (struct die_info);
24094 
24095   if (num_attrs > 1)
24096     size += (num_attrs - 1) * sizeof (struct attribute);
24097 
24098   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
24099   memset (die, 0, sizeof (struct die_info));
24100   return (die);
24101 }
24102 
24103 
24104 
24105 /* Macro support.  */
24106 
24107 /* An overload of dwarf_decode_macros that finds the correct section
24108    and ensures it is read in before calling the other overload.  */
24109 
24110 static void
24111 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24112 		     int section_is_gnu)
24113 {
24114   dwarf2_per_objfile *per_objfile = cu->per_objfile;
24115   struct objfile *objfile = per_objfile->objfile;
24116   const struct line_header *lh = cu->line_header;
24117   unsigned int offset_size = cu->header.offset_size;
24118   struct dwarf2_section_info *section;
24119   const char *section_name;
24120 
24121   if (cu->dwo_unit != nullptr)
24122     {
24123       if (section_is_gnu)
24124 	{
24125 	  section = &cu->dwo_unit->dwo_file->sections.macro;
24126 	  section_name = ".debug_macro.dwo";
24127 	}
24128       else
24129 	{
24130 	  section = &cu->dwo_unit->dwo_file->sections.macinfo;
24131 	  section_name = ".debug_macinfo.dwo";
24132 	}
24133     }
24134   else
24135     {
24136       if (section_is_gnu)
24137 	{
24138 	  section = &per_objfile->per_bfd->macro;
24139 	  section_name = ".debug_macro";
24140 	}
24141       else
24142 	{
24143 	  section = &per_objfile->per_bfd->macinfo;
24144 	  section_name = ".debug_macinfo";
24145 	}
24146     }
24147 
24148   section->read (objfile);
24149   if (section->buffer == nullptr)
24150     {
24151       complaint (_("missing %s section"), section_name);
24152       return;
24153     }
24154 
24155   buildsym_compunit *builder = cu->get_builder ();
24156 
24157   struct dwarf2_section_info *str_offsets_section;
24158   struct dwarf2_section_info *str_section;
24159   ULONGEST str_offsets_base;
24160 
24161   if (cu->dwo_unit != nullptr)
24162     {
24163       str_offsets_section = &cu->dwo_unit->dwo_file
24164 			       ->sections.str_offsets;
24165       str_section = &cu->dwo_unit->dwo_file->sections.str;
24166       str_offsets_base = cu->header.addr_size;
24167     }
24168   else
24169     {
24170       str_offsets_section = &per_objfile->per_bfd->str_offsets;
24171       str_section = &per_objfile->per_bfd->str;
24172       str_offsets_base = *cu->str_offsets_base;
24173     }
24174 
24175   dwarf_decode_macros (per_objfile, builder, section, lh,
24176 		       offset_size, offset, str_section, str_offsets_section,
24177 		       str_offsets_base, section_is_gnu);
24178 }
24179 
24180 /* Return the .debug_loc section to use for CU.
24181    For DWO files use .debug_loc.dwo.  */
24182 
24183 static struct dwarf2_section_info *
24184 cu_debug_loc_section (struct dwarf2_cu *cu)
24185 {
24186   dwarf2_per_objfile *per_objfile = cu->per_objfile;
24187 
24188   if (cu->dwo_unit)
24189     {
24190       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24191 
24192       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24193     }
24194   return (cu->header.version >= 5 ? &per_objfile->per_bfd->loclists
24195 				  : &per_objfile->per_bfd->loc);
24196 }
24197 
24198 /* Return the .debug_rnglists section to use for CU.  */
24199 static struct dwarf2_section_info *
24200 cu_debug_rnglists_section (struct dwarf2_cu *cu, dwarf_tag tag)
24201 {
24202   if (cu->header.version < 5)
24203     error (_(".debug_rnglists section cannot be used in DWARF %d"),
24204 	   cu->header.version);
24205   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->per_objfile;
24206 
24207   /* Make sure we read the .debug_rnglists section from the file that
24208      contains the DW_AT_ranges attribute we are reading.  Normally that
24209      would be the .dwo file, if there is one.  However for DW_TAG_compile_unit
24210      or DW_TAG_skeleton unit, we always want to read from objfile/linked
24211      program.  */
24212   if (cu->dwo_unit != nullptr
24213       && tag != DW_TAG_compile_unit
24214       && tag != DW_TAG_skeleton_unit)
24215     {
24216       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24217 
24218       if (sections->rnglists.size > 0)
24219 	return &sections->rnglists;
24220       else
24221 	error (_(".debug_rnglists section is missing from .dwo file."));
24222     }
24223   return &dwarf2_per_objfile->per_bfd->rnglists;
24224 }
24225 
24226 /* A helper function that fills in a dwarf2_loclist_baton.  */
24227 
24228 static void
24229 fill_in_loclist_baton (struct dwarf2_cu *cu,
24230 		       struct dwarf2_loclist_baton *baton,
24231 		       const struct attribute *attr)
24232 {
24233   dwarf2_per_objfile *per_objfile = cu->per_objfile;
24234   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24235 
24236   section->read (per_objfile->objfile);
24237 
24238   baton->per_objfile = per_objfile;
24239   baton->per_cu = cu->per_cu;
24240   gdb_assert (baton->per_cu);
24241   /* We don't know how long the location list is, but make sure we
24242      don't run off the edge of the section.  */
24243   baton->size = section->size - attr->as_unsigned ();
24244   baton->data = section->buffer + attr->as_unsigned ();
24245   if (cu->base_address.has_value ())
24246     baton->base_address = *cu->base_address;
24247   else
24248     baton->base_address = 0;
24249   baton->from_dwo = cu->dwo_unit != NULL;
24250 }
24251 
24252 static void
24253 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24254 			     struct dwarf2_cu *cu, int is_block)
24255 {
24256   dwarf2_per_objfile *per_objfile = cu->per_objfile;
24257   struct objfile *objfile = per_objfile->objfile;
24258   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24259 
24260   if (attr->form_is_section_offset ()
24261       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24262 	 the section.  If so, fall through to the complaint in the
24263 	 other branch.  */
24264       && attr->as_unsigned () < section->get_size (objfile))
24265     {
24266       struct dwarf2_loclist_baton *baton;
24267 
24268       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24269 
24270       fill_in_loclist_baton (cu, baton, attr);
24271 
24272       if (!cu->base_address.has_value ())
24273 	complaint (_("Location list used without "
24274 		     "specifying the CU base address."));
24275 
24276       SYMBOL_ACLASS_INDEX (sym) = (is_block
24277 				   ? dwarf2_loclist_block_index
24278 				   : dwarf2_loclist_index);
24279       SYMBOL_LOCATION_BATON (sym) = baton;
24280     }
24281   else
24282     {
24283       struct dwarf2_locexpr_baton *baton;
24284 
24285       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24286       baton->per_objfile = per_objfile;
24287       baton->per_cu = cu->per_cu;
24288       gdb_assert (baton->per_cu);
24289 
24290       if (attr->form_is_block ())
24291 	{
24292 	  /* Note that we're just copying the block's data pointer
24293 	     here, not the actual data.  We're still pointing into the
24294 	     info_buffer for SYM's objfile; right now we never release
24295 	     that buffer, but when we do clean up properly this may
24296 	     need to change.  */
24297 	  struct dwarf_block *block = attr->as_block ();
24298 	  baton->size = block->size;
24299 	  baton->data = block->data;
24300 	}
24301       else
24302 	{
24303 	  dwarf2_invalid_attrib_class_complaint ("location description",
24304 						 sym->natural_name ());
24305 	  baton->size = 0;
24306 	}
24307 
24308       SYMBOL_ACLASS_INDEX (sym) = (is_block
24309 				   ? dwarf2_locexpr_block_index
24310 				   : dwarf2_locexpr_index);
24311       SYMBOL_LOCATION_BATON (sym) = baton;
24312     }
24313 }
24314 
24315 /* See read.h.  */
24316 
24317 const comp_unit_head *
24318 dwarf2_per_cu_data::get_header () const
24319 {
24320   if (!m_header_read_in)
24321     {
24322       const gdb_byte *info_ptr
24323 	= this->section->buffer + to_underlying (this->sect_off);
24324 
24325       memset (&m_header, 0, sizeof (m_header));
24326 
24327       read_comp_unit_head (&m_header, info_ptr, this->section,
24328 			   rcuh_kind::COMPILE);
24329 
24330       m_header_read_in = true;
24331     }
24332 
24333   return &m_header;
24334 }
24335 
24336 /* See read.h.  */
24337 
24338 int
24339 dwarf2_per_cu_data::addr_size () const
24340 {
24341   return this->get_header ()->addr_size;
24342 }
24343 
24344 /* See read.h.  */
24345 
24346 int
24347 dwarf2_per_cu_data::offset_size () const
24348 {
24349   return this->get_header ()->offset_size;
24350 }
24351 
24352 /* See read.h.  */
24353 
24354 int
24355 dwarf2_per_cu_data::ref_addr_size () const
24356 {
24357   const comp_unit_head *header = this->get_header ();
24358 
24359   if (header->version == 2)
24360     return header->addr_size;
24361   else
24362     return header->offset_size;
24363 }
24364 
24365 /* A helper function for dwarf2_find_containing_comp_unit that returns
24366    the index of the result, and that searches a vector.  It will
24367    return a result even if the offset in question does not actually
24368    occur in any CU.  This is separate so that it can be unit
24369    tested.  */
24370 
24371 static int
24372 dwarf2_find_containing_comp_unit
24373   (sect_offset sect_off,
24374    unsigned int offset_in_dwz,
24375    const std::vector<dwarf2_per_cu_data_up> &all_comp_units)
24376 {
24377   int low, high;
24378 
24379   low = 0;
24380   high = all_comp_units.size () - 1;
24381   while (high > low)
24382     {
24383       struct dwarf2_per_cu_data *mid_cu;
24384       int mid = low + (high - low) / 2;
24385 
24386       mid_cu = all_comp_units[mid].get ();
24387       if (mid_cu->is_dwz > offset_in_dwz
24388 	  || (mid_cu->is_dwz == offset_in_dwz
24389 	      && mid_cu->sect_off + mid_cu->length > sect_off))
24390 	high = mid;
24391       else
24392 	low = mid + 1;
24393     }
24394   gdb_assert (low == high);
24395   return low;
24396 }
24397 
24398 /* Locate the .debug_info compilation unit from CU's objfile which contains
24399    the DIE at OFFSET.  Raises an error on failure.  */
24400 
24401 static struct dwarf2_per_cu_data *
24402 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24403 				  unsigned int offset_in_dwz,
24404 				  dwarf2_per_objfile *per_objfile)
24405 {
24406   int low = dwarf2_find_containing_comp_unit
24407     (sect_off, offset_in_dwz, per_objfile->per_bfd->all_comp_units);
24408   dwarf2_per_cu_data *this_cu
24409     = per_objfile->per_bfd->all_comp_units[low].get ();
24410 
24411   if (this_cu->is_dwz != offset_in_dwz || this_cu->sect_off > sect_off)
24412     {
24413       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24414 	error (_("Dwarf Error: could not find partial DIE containing "
24415 	       "offset %s [in module %s]"),
24416 	       sect_offset_str (sect_off),
24417 	       bfd_get_filename (per_objfile->objfile->obfd));
24418 
24419       gdb_assert (per_objfile->per_bfd->all_comp_units[low-1]->sect_off
24420 		  <= sect_off);
24421       return per_objfile->per_bfd->all_comp_units[low - 1].get ();
24422     }
24423   else
24424     {
24425       if (low == per_objfile->per_bfd->all_comp_units.size () - 1
24426 	  && sect_off >= this_cu->sect_off + this_cu->length)
24427 	error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
24428       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
24429       return this_cu;
24430     }
24431 }
24432 
24433 #if GDB_SELF_TEST
24434 
24435 namespace selftests {
24436 namespace find_containing_comp_unit {
24437 
24438 static void
24439 run_test ()
24440 {
24441   dwarf2_per_cu_data_up one (new dwarf2_per_cu_data);
24442   dwarf2_per_cu_data *one_ptr = one.get ();
24443   dwarf2_per_cu_data_up two (new dwarf2_per_cu_data);
24444   dwarf2_per_cu_data *two_ptr = two.get ();
24445   dwarf2_per_cu_data_up three (new dwarf2_per_cu_data);
24446   dwarf2_per_cu_data *three_ptr = three.get ();
24447   dwarf2_per_cu_data_up four (new dwarf2_per_cu_data);
24448   dwarf2_per_cu_data *four_ptr = four.get ();
24449 
24450   one->length = 5;
24451   two->sect_off = sect_offset (one->length);
24452   two->length = 7;
24453 
24454   three->length = 5;
24455   three->is_dwz = 1;
24456   four->sect_off = sect_offset (three->length);
24457   four->length = 7;
24458   four->is_dwz = 1;
24459 
24460   std::vector<dwarf2_per_cu_data_up> units;
24461   units.push_back (std::move (one));
24462   units.push_back (std::move (two));
24463   units.push_back (std::move (three));
24464   units.push_back (std::move (four));
24465 
24466   int result;
24467 
24468   result = dwarf2_find_containing_comp_unit (sect_offset (0), 0, units);
24469   SELF_CHECK (units[result].get () == one_ptr);
24470   result = dwarf2_find_containing_comp_unit (sect_offset (3), 0, units);
24471   SELF_CHECK (units[result].get () == one_ptr);
24472   result = dwarf2_find_containing_comp_unit (sect_offset (5), 0, units);
24473   SELF_CHECK (units[result].get () == two_ptr);
24474 
24475   result = dwarf2_find_containing_comp_unit (sect_offset (0), 1, units);
24476   SELF_CHECK (units[result].get () == three_ptr);
24477   result = dwarf2_find_containing_comp_unit (sect_offset (3), 1, units);
24478   SELF_CHECK (units[result].get () == three_ptr);
24479   result = dwarf2_find_containing_comp_unit (sect_offset (5), 1, units);
24480   SELF_CHECK (units[result].get () == four_ptr);
24481 }
24482 
24483 }
24484 }
24485 
24486 #endif /* GDB_SELF_TEST */
24487 
24488 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
24489 
24490 static void
24491 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
24492 		       enum language pretend_language)
24493 {
24494   struct attribute *attr;
24495 
24496   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
24497 
24498   /* Set the language we're debugging.  */
24499   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
24500   if (cu->producer != nullptr
24501       && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
24502     {
24503       /* The XLCL doesn't generate DW_LANG_OpenCL because this
24504 	 attribute is not standardised yet.  As a workaround for the
24505 	 language detection we fall back to the DW_AT_producer
24506 	 string.  */
24507       cu->per_cu->lang = language_opencl;
24508     }
24509   else if (cu->producer != nullptr
24510 	   && strstr (cu->producer, "GNU Go ") != NULL)
24511     {
24512       /* Similar hack for Go.  */
24513       cu->per_cu->lang = language_go;
24514     }
24515   else if (attr != nullptr)
24516     cu->per_cu->lang = dwarf_lang_to_enum_language (attr->constant_value (0));
24517   else
24518     cu->per_cu->lang = pretend_language;
24519   cu->language_defn = language_def (cu->per_cu->lang);
24520 }
24521 
24522 /* See read.h.  */
24523 
24524 dwarf2_cu *
24525 dwarf2_per_objfile::get_cu (dwarf2_per_cu_data *per_cu)
24526 {
24527   auto it = m_dwarf2_cus.find (per_cu);
24528   if (it == m_dwarf2_cus.end ())
24529     return nullptr;
24530 
24531   return it->second;
24532 }
24533 
24534 /* See read.h.  */
24535 
24536 void
24537 dwarf2_per_objfile::set_cu (dwarf2_per_cu_data *per_cu, dwarf2_cu *cu)
24538 {
24539   gdb_assert (this->get_cu (per_cu) == nullptr);
24540 
24541   m_dwarf2_cus[per_cu] = cu;
24542 }
24543 
24544 /* See read.h.  */
24545 
24546 void
24547 dwarf2_per_objfile::age_comp_units ()
24548 {
24549   dwarf_read_debug_printf_v ("running");
24550 
24551   /* This is not expected to be called in the middle of CU expansion.  There is
24552      an invariant that if a CU is in the CUs-to-expand queue, its DIEs are
24553      loaded in memory.  Calling age_comp_units while the queue is in use could
24554      make us free the DIEs for a CU that is in the queue and therefore break
24555      that invariant.  */
24556   gdb_assert (!this->per_bfd->queue.has_value ());
24557 
24558   /* Start by clearing all marks.  */
24559   for (auto pair : m_dwarf2_cus)
24560     pair.second->clear_mark ();
24561 
24562   /* Traverse all CUs, mark them and their dependencies if used recently
24563      enough.  */
24564   for (auto pair : m_dwarf2_cus)
24565     {
24566       dwarf2_cu *cu = pair.second;
24567 
24568       cu->last_used++;
24569       if (cu->last_used <= dwarf_max_cache_age)
24570 	cu->mark ();
24571     }
24572 
24573   /* Delete all CUs still not marked.  */
24574   for (auto it = m_dwarf2_cus.begin (); it != m_dwarf2_cus.end ();)
24575     {
24576       dwarf2_cu *cu = it->second;
24577 
24578       if (!cu->is_marked ())
24579 	{
24580 	  dwarf_read_debug_printf_v ("deleting old CU %s",
24581 				     sect_offset_str (cu->per_cu->sect_off));
24582 	  delete cu;
24583 	  it = m_dwarf2_cus.erase (it);
24584 	}
24585       else
24586 	it++;
24587     }
24588 }
24589 
24590 /* See read.h.  */
24591 
24592 void
24593 dwarf2_per_objfile::remove_cu (dwarf2_per_cu_data *per_cu)
24594 {
24595   auto it = m_dwarf2_cus.find (per_cu);
24596   if (it == m_dwarf2_cus.end ())
24597     return;
24598 
24599   delete it->second;
24600 
24601   m_dwarf2_cus.erase (it);
24602 }
24603 
24604 dwarf2_per_objfile::~dwarf2_per_objfile ()
24605 {
24606   remove_all_cus ();
24607 }
24608 
24609 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
24610    We store these in a hash table separate from the DIEs, and preserve them
24611    when the DIEs are flushed out of cache.
24612 
24613    The CU "per_cu" pointer is needed because offset alone is not enough to
24614    uniquely identify the type.  A file may have multiple .debug_types sections,
24615    or the type may come from a DWO file.  Furthermore, while it's more logical
24616    to use per_cu->section+offset, with Fission the section with the data is in
24617    the DWO file but we don't know that section at the point we need it.
24618    We have to use something in dwarf2_per_cu_data (or the pointer to it)
24619    because we can enter the lookup routine, get_die_type_at_offset, from
24620    outside this file, and thus won't necessarily have PER_CU->cu.
24621    Fortunately, PER_CU is stable for the life of the objfile.  */
24622 
24623 struct dwarf2_per_cu_offset_and_type
24624 {
24625   const struct dwarf2_per_cu_data *per_cu;
24626   sect_offset sect_off;
24627   struct type *type;
24628 };
24629 
24630 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
24631 
24632 static hashval_t
24633 per_cu_offset_and_type_hash (const void *item)
24634 {
24635   const struct dwarf2_per_cu_offset_and_type *ofs
24636     = (const struct dwarf2_per_cu_offset_and_type *) item;
24637 
24638   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
24639 }
24640 
24641 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
24642 
24643 static int
24644 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
24645 {
24646   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
24647     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
24648   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
24649     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
24650 
24651   return (ofs_lhs->per_cu == ofs_rhs->per_cu
24652 	  && ofs_lhs->sect_off == ofs_rhs->sect_off);
24653 }
24654 
24655 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
24656    table if necessary.  For convenience, return TYPE.
24657 
24658    The DIEs reading must have careful ordering to:
24659     * Not cause infinite loops trying to read in DIEs as a prerequisite for
24660       reading current DIE.
24661     * Not trying to dereference contents of still incompletely read in types
24662       while reading in other DIEs.
24663     * Enable referencing still incompletely read in types just by a pointer to
24664       the type without accessing its fields.
24665 
24666    Therefore caller should follow these rules:
24667      * Try to fetch any prerequisite types we may need to build this DIE type
24668        before building the type and calling set_die_type.
24669      * After building type call set_die_type for current DIE as soon as
24670        possible before fetching more types to complete the current type.
24671      * Make the type as complete as possible before fetching more types.  */
24672 
24673 static struct type *
24674 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
24675 	      bool skip_data_location)
24676 {
24677   dwarf2_per_objfile *per_objfile = cu->per_objfile;
24678   struct dwarf2_per_cu_offset_and_type **slot, ofs;
24679   struct objfile *objfile = per_objfile->objfile;
24680   struct attribute *attr;
24681   struct dynamic_prop prop;
24682 
24683   /* For Ada types, make sure that the gnat-specific data is always
24684      initialized (if not already set).  There are a few types where
24685      we should not be doing so, because the type-specific area is
24686      already used to hold some other piece of info (eg: TYPE_CODE_FLT
24687      where the type-specific area is used to store the floatformat).
24688      But this is not a problem, because the gnat-specific information
24689      is actually not needed for these types.  */
24690   if (need_gnat_info (cu)
24691       && type->code () != TYPE_CODE_FUNC
24692       && type->code () != TYPE_CODE_FLT
24693       && type->code () != TYPE_CODE_METHODPTR
24694       && type->code () != TYPE_CODE_MEMBERPTR
24695       && type->code () != TYPE_CODE_METHOD
24696       && type->code () != TYPE_CODE_FIXED_POINT
24697       && !HAVE_GNAT_AUX_INFO (type))
24698     INIT_GNAT_SPECIFIC (type);
24699 
24700   /* Read DW_AT_allocated and set in type.  */
24701   attr = dwarf2_attr (die, DW_AT_allocated, cu);
24702   if (attr != NULL)
24703     {
24704       struct type *prop_type = cu->addr_sized_int_type (false);
24705       if (attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
24706 	type->add_dyn_prop (DYN_PROP_ALLOCATED, prop);
24707     }
24708 
24709   /* Read DW_AT_associated and set in type.  */
24710   attr = dwarf2_attr (die, DW_AT_associated, cu);
24711   if (attr != NULL)
24712     {
24713       struct type *prop_type = cu->addr_sized_int_type (false);
24714       if (attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
24715 	type->add_dyn_prop (DYN_PROP_ASSOCIATED, prop);
24716     }
24717 
24718   /* Read DW_AT_data_location and set in type.  */
24719   if (!skip_data_location)
24720     {
24721       attr = dwarf2_attr (die, DW_AT_data_location, cu);
24722       if (attr_to_dynamic_prop (attr, die, cu, &prop, cu->addr_type ()))
24723 	type->add_dyn_prop (DYN_PROP_DATA_LOCATION, prop);
24724     }
24725 
24726   if (per_objfile->die_type_hash == NULL)
24727     per_objfile->die_type_hash
24728       = htab_up (htab_create_alloc (127,
24729 				    per_cu_offset_and_type_hash,
24730 				    per_cu_offset_and_type_eq,
24731 				    NULL, xcalloc, xfree));
24732 
24733   ofs.per_cu = cu->per_cu;
24734   ofs.sect_off = die->sect_off;
24735   ofs.type = type;
24736   slot = (struct dwarf2_per_cu_offset_and_type **)
24737     htab_find_slot (per_objfile->die_type_hash.get (), &ofs, INSERT);
24738   if (*slot)
24739     complaint (_("A problem internal to GDB: DIE %s has type already set"),
24740 	       sect_offset_str (die->sect_off));
24741   *slot = XOBNEW (&objfile->objfile_obstack,
24742 		  struct dwarf2_per_cu_offset_and_type);
24743   **slot = ofs;
24744   return type;
24745 }
24746 
24747 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
24748    or return NULL if the die does not have a saved type.  */
24749 
24750 static struct type *
24751 get_die_type_at_offset (sect_offset sect_off,
24752 			dwarf2_per_cu_data *per_cu,
24753 			dwarf2_per_objfile *per_objfile)
24754 {
24755   struct dwarf2_per_cu_offset_and_type *slot, ofs;
24756 
24757   if (per_objfile->die_type_hash == NULL)
24758     return NULL;
24759 
24760   ofs.per_cu = per_cu;
24761   ofs.sect_off = sect_off;
24762   slot = ((struct dwarf2_per_cu_offset_and_type *)
24763 	  htab_find (per_objfile->die_type_hash.get (), &ofs));
24764   if (slot)
24765     return slot->type;
24766   else
24767     return NULL;
24768 }
24769 
24770 /* Look up the type for DIE in CU in die_type_hash,
24771    or return NULL if DIE does not have a saved type.  */
24772 
24773 static struct type *
24774 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
24775 {
24776   return get_die_type_at_offset (die->sect_off, cu->per_cu, cu->per_objfile);
24777 }
24778 
24779 /* Trivial hash function for partial_die_info: the hash value of a DIE
24780    is its offset in .debug_info for this objfile.  */
24781 
24782 static hashval_t
24783 partial_die_hash (const void *item)
24784 {
24785   const struct partial_die_info *part_die
24786     = (const struct partial_die_info *) item;
24787 
24788   return to_underlying (part_die->sect_off);
24789 }
24790 
24791 /* Trivial comparison function for partial_die_info structures: two DIEs
24792    are equal if they have the same offset.  */
24793 
24794 static int
24795 partial_die_eq (const void *item_lhs, const void *item_rhs)
24796 {
24797   const struct partial_die_info *part_die_lhs
24798     = (const struct partial_die_info *) item_lhs;
24799   const struct partial_die_info *part_die_rhs
24800     = (const struct partial_die_info *) item_rhs;
24801 
24802   return part_die_lhs->sect_off == part_die_rhs->sect_off;
24803 }
24804 
24805 struct cmd_list_element *set_dwarf_cmdlist;
24806 struct cmd_list_element *show_dwarf_cmdlist;
24807 
24808 static void
24809 show_check_physname (struct ui_file *file, int from_tty,
24810 		     struct cmd_list_element *c, const char *value)
24811 {
24812   fprintf_filtered (file,
24813 		    _("Whether to check \"physname\" is %s.\n"),
24814 		    value);
24815 }
24816 
24817 void _initialize_dwarf2_read ();
24818 void
24819 _initialize_dwarf2_read ()
24820 {
24821   add_basic_prefix_cmd ("dwarf", class_maintenance, _("\
24822 Set DWARF specific variables.\n\
24823 Configure DWARF variables such as the cache size."),
24824 			&set_dwarf_cmdlist,
24825 			0/*allow-unknown*/, &maintenance_set_cmdlist);
24826 
24827   add_show_prefix_cmd ("dwarf", class_maintenance, _("\
24828 Show DWARF specific variables.\n\
24829 Show DWARF variables such as the cache size."),
24830 		       &show_dwarf_cmdlist,
24831 		       0/*allow-unknown*/, &maintenance_show_cmdlist);
24832 
24833   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24834 			    &dwarf_max_cache_age, _("\
24835 Set the upper bound on the age of cached DWARF compilation units."), _("\
24836 Show the upper bound on the age of cached DWARF compilation units."), _("\
24837 A higher limit means that cached compilation units will be stored\n\
24838 in memory longer, and more total memory will be used.  Zero disables\n\
24839 caching, which can slow down startup."),
24840 			    NULL,
24841 			    show_dwarf_max_cache_age,
24842 			    &set_dwarf_cmdlist,
24843 			    &show_dwarf_cmdlist);
24844 
24845   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24846 Set debugging of the DWARF reader."), _("\
24847 Show debugging of the DWARF reader."), _("\
24848 When enabled (non-zero), debugging messages are printed during DWARF\n\
24849 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24850 information.  A value greater than 1 provides more verbose information."),
24851 			    NULL,
24852 			    NULL,
24853 			    &setdebuglist, &showdebuglist);
24854 
24855   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24856 Set debugging of the DWARF DIE reader."), _("\
24857 Show debugging of the DWARF DIE reader."), _("\
24858 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24859 The value is the maximum depth to print."),
24860 			     NULL,
24861 			     NULL,
24862 			     &setdebuglist, &showdebuglist);
24863 
24864   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24865 Set debugging of the dwarf line reader."), _("\
24866 Show debugging of the dwarf line reader."), _("\
24867 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24868 A value of 1 (one) provides basic information.\n\
24869 A value greater than 1 provides more verbose information."),
24870 			     NULL,
24871 			     NULL,
24872 			     &setdebuglist, &showdebuglist);
24873 
24874   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24875 Set cross-checking of \"physname\" code against demangler."), _("\
24876 Show cross-checking of \"physname\" code against demangler."), _("\
24877 When enabled, GDB's internal \"physname\" code is checked against\n\
24878 the demangler."),
24879 			   NULL, show_check_physname,
24880 			   &setdebuglist, &showdebuglist);
24881 
24882   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24883 			   no_class, &use_deprecated_index_sections, _("\
24884 Set whether to use deprecated gdb_index sections."), _("\
24885 Show whether to use deprecated gdb_index sections."), _("\
24886 When enabled, deprecated .gdb_index sections are used anyway.\n\
24887 Normally they are ignored either because of a missing feature or\n\
24888 performance issue.\n\
24889 Warning: This option must be enabled before gdb reads the file."),
24890 			   NULL,
24891 			   NULL,
24892 			   &setlist, &showlist);
24893 
24894   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24895 							&dwarf2_locexpr_funcs);
24896   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24897 							&dwarf2_loclist_funcs);
24898 
24899   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24900 					&dwarf2_block_frame_base_locexpr_funcs);
24901   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24902 					&dwarf2_block_frame_base_loclist_funcs);
24903 
24904 #if GDB_SELF_TEST
24905   selftests::register_test ("dw2_expand_symtabs_matching",
24906 			    selftests::dw2_expand_symtabs_matching::run_test);
24907   selftests::register_test ("dwarf2_find_containing_comp_unit",
24908 			    selftests::find_containing_comp_unit::run_test);
24909 #endif
24910 }
24911