0940959cb5427f22ae3ad84feb789ac34437bc1a
[dragonfly.git] / contrib / gcc-8.0 / gcc / dwarf2out.c
1 /* Output Dwarf2 format symbol table information from GCC.
2    Copyright (C) 1992-2018 Free Software Foundation, Inc.
3    Contributed by Gary Funck (gary@intrepid.com).
4    Derived from DWARF 1 implementation of Ron Guilmette (rfg@monkeys.com).
5    Extensively modified by Jason Merrill (jason@cygnus.com).
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 /* TODO: Emit .debug_line header even when there are no functions, since
24            the file numbers are used by .debug_info.  Alternately, leave
25            out locations for types and decls.
26          Avoid talking about ctors and op= for PODs.
27          Factor out common prologue sequences into multiple CIEs.  */
28
29 /* The first part of this file deals with the DWARF 2 frame unwind
30    information, which is also used by the GCC efficient exception handling
31    mechanism.  The second part, controlled only by an #ifdef
32    DWARF2_DEBUGGING_INFO, deals with the other DWARF 2 debugging
33    information.  */
34
35 /* DWARF2 Abbreviation Glossary:
36
37    CFA = Canonical Frame Address
38            a fixed address on the stack which identifies a call frame.
39            We define it to be the value of SP just before the call insn.
40            The CFA register and offset, which may change during the course
41            of the function, are used to calculate its value at runtime.
42
43    CFI = Call Frame Instruction
44            an instruction for the DWARF2 abstract machine
45
46    CIE = Common Information Entry
47            information describing information common to one or more FDEs
48
49    DIE = Debugging Information Entry
50
51    FDE = Frame Description Entry
52            information describing the stack call frame, in particular,
53            how to restore registers
54
55    DW_CFA_... = DWARF2 CFA call frame instruction
56    DW_TAG_... = DWARF2 DIE tag */
57
58 #include "config.h"
59 #include "system.h"
60 #include "coretypes.h"
61 #include "target.h"
62 #include "function.h"
63 #include "rtl.h"
64 #include "tree.h"
65 #include "memmodel.h"
66 #include "tm_p.h"
67 #include "stringpool.h"
68 #include "insn-config.h"
69 #include "ira.h"
70 #include "cgraph.h"
71 #include "diagnostic.h"
72 #include "fold-const.h"
73 #include "stor-layout.h"
74 #include "varasm.h"
75 #include "version.h"
76 #include "flags.h"
77 #include "rtlhash.h"
78 #include "reload.h"
79 #include "output.h"
80 #include "expr.h"
81 #include "dwarf2out.h"
82 #include "dwarf2asm.h"
83 #include "toplev.h"
84 #include "md5.h"
85 #include "tree-pretty-print.h"
86 #include "print-rtl.h"
87 #include "debug.h"
88 #include "common/common-target.h"
89 #include "langhooks.h"
90 #include "lra.h"
91 #include "dumpfile.h"
92 #include "opts.h"
93 #include "tree-dfa.h"
94 #include "gdb/gdb-index.h"
95 #include "rtl-iter.h"
96 #include "stringpool.h"
97 #include "attribs.h"
98 #include "file-prefix-map.h" /* remap_debug_filename()  */
99
100 static void dwarf2out_source_line (unsigned int, unsigned int, const char *,
101                                    int, bool);
102 static rtx_insn *last_var_location_insn;
103 static rtx_insn *cached_next_real_insn;
104 static void dwarf2out_decl (tree);
105
106 #ifndef XCOFF_DEBUGGING_INFO
107 #define XCOFF_DEBUGGING_INFO 0
108 #endif
109
110 #ifndef HAVE_XCOFF_DWARF_EXTRAS
111 #define HAVE_XCOFF_DWARF_EXTRAS 0
112 #endif
113
114 #ifdef VMS_DEBUGGING_INFO
115 int vms_file_stats_name (const char *, long long *, long *, char *, int *);
116
117 /* Define this macro to be a nonzero value if the directory specifications
118     which are output in the debug info should end with a separator.  */
119 #define DWARF2_DIR_SHOULD_END_WITH_SEPARATOR 1
120 /* Define this macro to evaluate to a nonzero value if GCC should refrain
121    from generating indirect strings in DWARF2 debug information, for instance
122    if your target is stuck with an old version of GDB that is unable to
123    process them properly or uses VMS Debug.  */
124 #define DWARF2_INDIRECT_STRING_SUPPORT_MISSING_ON_TARGET 1
125 #else
126 #define DWARF2_DIR_SHOULD_END_WITH_SEPARATOR 0
127 #define DWARF2_INDIRECT_STRING_SUPPORT_MISSING_ON_TARGET 0
128 #endif
129
130 /* ??? Poison these here until it can be done generically.  They've been
131    totally replaced in this file; make sure it stays that way.  */
132 #undef DWARF2_UNWIND_INFO
133 #undef DWARF2_FRAME_INFO
134 #if (GCC_VERSION >= 3000)
135  #pragma GCC poison DWARF2_UNWIND_INFO DWARF2_FRAME_INFO
136 #endif
137
138 /* The size of the target's pointer type.  */
139 #ifndef PTR_SIZE
140 #define PTR_SIZE (POINTER_SIZE / BITS_PER_UNIT)
141 #endif
142
143 /* Array of RTXes referenced by the debugging information, which therefore
144    must be kept around forever.  */
145 static GTY(()) vec<rtx, va_gc> *used_rtx_array;
146
147 /* A pointer to the base of a list of incomplete types which might be
148    completed at some later time.  incomplete_types_list needs to be a
149    vec<tree, va_gc> *because we want to tell the garbage collector about
150    it.  */
151 static GTY(()) vec<tree, va_gc> *incomplete_types;
152
153 /* A pointer to the base of a table of references to declaration
154    scopes.  This table is a display which tracks the nesting
155    of declaration scopes at the current scope and containing
156    scopes.  This table is used to find the proper place to
157    define type declaration DIE's.  */
158 static GTY(()) vec<tree, va_gc> *decl_scope_table;
159
160 /* Pointers to various DWARF2 sections.  */
161 static GTY(()) section *debug_info_section;
162 static GTY(()) section *debug_skeleton_info_section;
163 static GTY(()) section *debug_abbrev_section;
164 static GTY(()) section *debug_skeleton_abbrev_section;
165 static GTY(()) section *debug_aranges_section;
166 static GTY(()) section *debug_addr_section;
167 static GTY(()) section *debug_macinfo_section;
168 static const char *debug_macinfo_section_name;
169 static unsigned macinfo_label_base = 1;
170 static GTY(()) section *debug_line_section;
171 static GTY(()) section *debug_skeleton_line_section;
172 static GTY(()) section *debug_loc_section;
173 static GTY(()) section *debug_pubnames_section;
174 static GTY(()) section *debug_pubtypes_section;
175 static GTY(()) section *debug_str_section;
176 static GTY(()) section *debug_line_str_section;
177 static GTY(()) section *debug_str_dwo_section;
178 static GTY(()) section *debug_str_offsets_section;
179 static GTY(()) section *debug_ranges_section;
180 static GTY(()) section *debug_frame_section;
181
182 /* Maximum size (in bytes) of an artificially generated label.  */
183 #define MAX_ARTIFICIAL_LABEL_BYTES      40
184
185 /* According to the (draft) DWARF 3 specification, the initial length
186    should either be 4 or 12 bytes.  When it's 12 bytes, the first 4
187    bytes are 0xffffffff, followed by the length stored in the next 8
188    bytes.
189
190    However, the SGI/MIPS ABI uses an initial length which is equal to
191    DWARF_OFFSET_SIZE.  It is defined (elsewhere) accordingly.  */
192
193 #ifndef DWARF_INITIAL_LENGTH_SIZE
194 #define DWARF_INITIAL_LENGTH_SIZE (DWARF_OFFSET_SIZE == 4 ? 4 : 12)
195 #endif
196
197 #ifndef DWARF_INITIAL_LENGTH_SIZE_STR
198 #define DWARF_INITIAL_LENGTH_SIZE_STR (DWARF_OFFSET_SIZE == 4 ? "-4" : "-12")
199 #endif
200
201 /* Round SIZE up to the nearest BOUNDARY.  */
202 #define DWARF_ROUND(SIZE,BOUNDARY) \
203   ((((SIZE) + (BOUNDARY) - 1) / (BOUNDARY)) * (BOUNDARY))
204
205 /* CIE identifier.  */
206 #if HOST_BITS_PER_WIDE_INT >= 64
207 #define DWARF_CIE_ID \
208   (unsigned HOST_WIDE_INT) (DWARF_OFFSET_SIZE == 4 ? DW_CIE_ID : DW64_CIE_ID)
209 #else
210 #define DWARF_CIE_ID DW_CIE_ID
211 #endif
212
213
214 /* A vector for a table that contains frame description
215    information for each routine.  */
216 #define NOT_INDEXED (-1U)
217 #define NO_INDEX_ASSIGNED (-2U)
218
219 static GTY(()) vec<dw_fde_ref, va_gc> *fde_vec;
220
221 struct GTY((for_user)) indirect_string_node {
222   const char *str;
223   unsigned int refcount;
224   enum dwarf_form form;
225   char *label;
226   unsigned int index;
227 };
228
229 struct indirect_string_hasher : ggc_ptr_hash<indirect_string_node>
230 {
231   typedef const char *compare_type;
232
233   static hashval_t hash (indirect_string_node *);
234   static bool equal (indirect_string_node *, const char *);
235 };
236
237 static GTY (()) hash_table<indirect_string_hasher> *debug_str_hash;
238
239 static GTY (()) hash_table<indirect_string_hasher> *debug_line_str_hash;
240
241 /* With split_debug_info, both the comp_dir and dwo_name go in the
242    main object file, rather than the dwo, similar to the force_direct
243    parameter elsewhere but with additional complications:
244
245    1) The string is needed in both the main object file and the dwo.
246    That is, the comp_dir and dwo_name will appear in both places.
247
248    2) Strings can use four forms: DW_FORM_string, DW_FORM_strp,
249    DW_FORM_line_strp or DW_FORM_GNU_str_index.
250
251    3) GCC chooses the form to use late, depending on the size and
252    reference count.
253
254    Rather than forcing the all debug string handling functions and
255    callers to deal with these complications, simply use a separate,
256    special-cased string table for any attribute that should go in the
257    main object file.  This limits the complexity to just the places
258    that need it.  */
259
260 static GTY (()) hash_table<indirect_string_hasher> *skeleton_debug_str_hash;
261
262 static GTY(()) int dw2_string_counter;
263
264 /* True if the compilation unit places functions in more than one section.  */
265 static GTY(()) bool have_multiple_function_sections = false;
266
267 /* Whether the default text and cold text sections have been used at all.  */
268 static GTY(()) bool text_section_used = false;
269 static GTY(()) bool cold_text_section_used = false;
270
271 /* The default cold text section.  */
272 static GTY(()) section *cold_text_section;
273
274 /* The DIE for C++14 'auto' in a function return type.  */
275 static GTY(()) dw_die_ref auto_die;
276
277 /* The DIE for C++14 'decltype(auto)' in a function return type.  */
278 static GTY(()) dw_die_ref decltype_auto_die;
279
280 /* Forward declarations for functions defined in this file.  */
281
282 static void output_call_frame_info (int);
283 static void dwarf2out_note_section_used (void);
284
285 /* Personality decl of current unit.  Used only when assembler does not support
286    personality CFI.  */
287 static GTY(()) rtx current_unit_personality;
288
289 /* Whether an eh_frame section is required.  */
290 static GTY(()) bool do_eh_frame = false;
291
292 /* .debug_rnglists next index.  */
293 static unsigned int rnglist_idx;
294
295 /* Data and reference forms for relocatable data.  */
296 #define DW_FORM_data (DWARF_OFFSET_SIZE == 8 ? DW_FORM_data8 : DW_FORM_data4)
297 #define DW_FORM_ref (DWARF_OFFSET_SIZE == 8 ? DW_FORM_ref8 : DW_FORM_ref4)
298
299 #ifndef DEBUG_FRAME_SECTION
300 #define DEBUG_FRAME_SECTION     ".debug_frame"
301 #endif
302
303 #ifndef FUNC_BEGIN_LABEL
304 #define FUNC_BEGIN_LABEL        "LFB"
305 #endif
306
307 #ifndef FUNC_SECOND_SECT_LABEL
308 #define FUNC_SECOND_SECT_LABEL  "LFSB"
309 #endif
310
311 #ifndef FUNC_END_LABEL
312 #define FUNC_END_LABEL          "LFE"
313 #endif
314
315 #ifndef PROLOGUE_END_LABEL
316 #define PROLOGUE_END_LABEL      "LPE"
317 #endif
318
319 #ifndef EPILOGUE_BEGIN_LABEL
320 #define EPILOGUE_BEGIN_LABEL    "LEB"
321 #endif
322
323 #ifndef FRAME_BEGIN_LABEL
324 #define FRAME_BEGIN_LABEL       "Lframe"
325 #endif
326 #define CIE_AFTER_SIZE_LABEL    "LSCIE"
327 #define CIE_END_LABEL           "LECIE"
328 #define FDE_LABEL               "LSFDE"
329 #define FDE_AFTER_SIZE_LABEL    "LASFDE"
330 #define FDE_END_LABEL           "LEFDE"
331 #define LINE_NUMBER_BEGIN_LABEL "LSLT"
332 #define LINE_NUMBER_END_LABEL   "LELT"
333 #define LN_PROLOG_AS_LABEL      "LASLTP"
334 #define LN_PROLOG_END_LABEL     "LELTP"
335 #define DIE_LABEL_PREFIX        "DW"
336 \f
337 /* Match the base name of a file to the base name of a compilation unit. */
338
339 static int
340 matches_main_base (const char *path)
341 {
342   /* Cache the last query. */
343   static const char *last_path = NULL;
344   static int last_match = 0;
345   if (path != last_path)
346     {
347       const char *base;
348       int length = base_of_path (path, &base);
349       last_path = path;
350       last_match = (length == main_input_baselength
351                     && memcmp (base, main_input_basename, length) == 0);
352     }
353   return last_match;
354 }
355
356 #ifdef DEBUG_DEBUG_STRUCT
357
358 static int
359 dump_struct_debug (tree type, enum debug_info_usage usage,
360                    enum debug_struct_file criterion, int generic,
361                    int matches, int result)
362 {
363   /* Find the type name. */
364   tree type_decl = TYPE_STUB_DECL (type);
365   tree t = type_decl;
366   const char *name = 0;
367   if (TREE_CODE (t) == TYPE_DECL)
368     t = DECL_NAME (t);
369   if (t)
370     name = IDENTIFIER_POINTER (t);
371
372   fprintf (stderr, "    struct %d %s %s %s %s %d %p %s\n",
373            criterion,
374            DECL_IN_SYSTEM_HEADER (type_decl) ? "sys" : "usr",
375            matches ? "bas" : "hdr",
376            generic ? "gen" : "ord",
377            usage == DINFO_USAGE_DFN ? ";" :
378              usage == DINFO_USAGE_DIR_USE ? "." : "*",
379            result,
380            (void*) type_decl, name);
381   return result;
382 }
383 #define DUMP_GSTRUCT(type, usage, criterion, generic, matches, result) \
384   dump_struct_debug (type, usage, criterion, generic, matches, result)
385
386 #else
387
388 #define DUMP_GSTRUCT(type, usage, criterion, generic, matches, result) \
389   (result)
390
391 #endif
392
393 /* Get the number of HOST_WIDE_INTs needed to represent the precision
394    of the number.  Some constants have a large uniform precision, so
395    we get the precision needed for the actual value of the number.  */
396
397 static unsigned int
398 get_full_len (const wide_int &op)
399 {
400   int prec = wi::min_precision (op, UNSIGNED);
401   return ((prec + HOST_BITS_PER_WIDE_INT - 1)
402           / HOST_BITS_PER_WIDE_INT);
403 }
404
405 static bool
406 should_emit_struct_debug (tree type, enum debug_info_usage usage)
407 {
408   enum debug_struct_file criterion;
409   tree type_decl;
410   bool generic = lang_hooks.types.generic_p (type);
411
412   if (generic)
413     criterion = debug_struct_generic[usage];
414   else
415     criterion = debug_struct_ordinary[usage];
416
417   if (criterion == DINFO_STRUCT_FILE_NONE)
418     return DUMP_GSTRUCT (type, usage, criterion, generic, false, false);
419   if (criterion == DINFO_STRUCT_FILE_ANY)
420     return DUMP_GSTRUCT (type, usage, criterion, generic, false, true);
421
422   type_decl = TYPE_STUB_DECL (TYPE_MAIN_VARIANT (type));
423
424   if (type_decl != NULL)
425     {
426      if (criterion == DINFO_STRUCT_FILE_SYS && DECL_IN_SYSTEM_HEADER (type_decl))
427         return DUMP_GSTRUCT (type, usage, criterion, generic, false, true);
428
429       if (matches_main_base (DECL_SOURCE_FILE (type_decl)))
430         return DUMP_GSTRUCT (type, usage, criterion, generic, true, true);
431     }
432
433   return DUMP_GSTRUCT (type, usage, criterion, generic, false, false);
434 }
435 \f
436 /* Switch [BACK] to eh_frame_section.  If we don't have an eh_frame_section,
437    switch to the data section instead, and write out a synthetic start label
438    for collect2 the first time around.  */
439
440 static void
441 switch_to_eh_frame_section (bool back ATTRIBUTE_UNUSED)
442 {
443   if (eh_frame_section == 0)
444     {
445       int flags;
446
447       if (EH_TABLES_CAN_BE_READ_ONLY)
448         {
449           int fde_encoding;
450           int per_encoding;
451           int lsda_encoding;
452
453           fde_encoding = ASM_PREFERRED_EH_DATA_FORMAT (/*code=*/1,
454                                                        /*global=*/0);
455           per_encoding = ASM_PREFERRED_EH_DATA_FORMAT (/*code=*/2,
456                                                        /*global=*/1);
457           lsda_encoding = ASM_PREFERRED_EH_DATA_FORMAT (/*code=*/0,
458                                                         /*global=*/0);
459           flags = ((! flag_pic
460                     || ((fde_encoding & 0x70) != DW_EH_PE_absptr
461                         && (fde_encoding & 0x70) != DW_EH_PE_aligned
462                         && (per_encoding & 0x70) != DW_EH_PE_absptr
463                         && (per_encoding & 0x70) != DW_EH_PE_aligned
464                         && (lsda_encoding & 0x70) != DW_EH_PE_absptr
465                         && (lsda_encoding & 0x70) != DW_EH_PE_aligned))
466                    ? 0 : SECTION_WRITE);
467         }
468       else
469         flags = SECTION_WRITE;
470
471 #ifdef EH_FRAME_SECTION_NAME
472       eh_frame_section = get_section (EH_FRAME_SECTION_NAME, flags, NULL);
473 #else
474       eh_frame_section = ((flags == SECTION_WRITE)
475                           ? data_section : readonly_data_section);
476 #endif /* EH_FRAME_SECTION_NAME */
477     }
478
479   switch_to_section (eh_frame_section);
480
481 #ifdef EH_FRAME_THROUGH_COLLECT2
482   /* We have no special eh_frame section.  Emit special labels to guide
483      collect2.  */
484   if (!back)
485     {
486       tree label = get_file_function_name ("F");
487       ASM_OUTPUT_ALIGN (asm_out_file, floor_log2 (PTR_SIZE));
488       targetm.asm_out.globalize_label (asm_out_file,
489                                         IDENTIFIER_POINTER (label));
490       ASM_OUTPUT_LABEL (asm_out_file, IDENTIFIER_POINTER (label));
491     }
492 #endif
493 }
494
495 /* Switch [BACK] to the eh or debug frame table section, depending on
496    FOR_EH.  */
497
498 static void
499 switch_to_frame_table_section (int for_eh, bool back)
500 {
501   if (for_eh)
502     switch_to_eh_frame_section (back);
503   else
504     {
505       if (!debug_frame_section)
506         debug_frame_section = get_section (DEBUG_FRAME_SECTION,
507                                            SECTION_DEBUG, NULL);
508       switch_to_section (debug_frame_section);
509     }
510 }
511
512 /* Describe for the GTY machinery what parts of dw_cfi_oprnd1 are used.  */
513
514 enum dw_cfi_oprnd_type
515 dw_cfi_oprnd1_desc (enum dwarf_call_frame_info cfi)
516 {
517   switch (cfi)
518     {
519     case DW_CFA_nop:
520     case DW_CFA_GNU_window_save:
521     case DW_CFA_remember_state:
522     case DW_CFA_restore_state:
523       return dw_cfi_oprnd_unused;
524
525     case DW_CFA_set_loc:
526     case DW_CFA_advance_loc1:
527     case DW_CFA_advance_loc2:
528     case DW_CFA_advance_loc4:
529     case DW_CFA_MIPS_advance_loc8:
530       return dw_cfi_oprnd_addr;
531
532     case DW_CFA_offset:
533     case DW_CFA_offset_extended:
534     case DW_CFA_def_cfa:
535     case DW_CFA_offset_extended_sf:
536     case DW_CFA_def_cfa_sf:
537     case DW_CFA_restore:
538     case DW_CFA_restore_extended:
539     case DW_CFA_undefined:
540     case DW_CFA_same_value:
541     case DW_CFA_def_cfa_register:
542     case DW_CFA_register:
543     case DW_CFA_expression:
544     case DW_CFA_val_expression:
545       return dw_cfi_oprnd_reg_num;
546
547     case DW_CFA_def_cfa_offset:
548     case DW_CFA_GNU_args_size:
549     case DW_CFA_def_cfa_offset_sf:
550       return dw_cfi_oprnd_offset;
551
552     case DW_CFA_def_cfa_expression:
553       return dw_cfi_oprnd_loc;
554
555     default:
556       gcc_unreachable ();
557     }
558 }
559
560 /* Describe for the GTY machinery what parts of dw_cfi_oprnd2 are used.  */
561
562 enum dw_cfi_oprnd_type
563 dw_cfi_oprnd2_desc (enum dwarf_call_frame_info cfi)
564 {
565   switch (cfi)
566     {
567     case DW_CFA_def_cfa:
568     case DW_CFA_def_cfa_sf:
569     case DW_CFA_offset:
570     case DW_CFA_offset_extended_sf:
571     case DW_CFA_offset_extended:
572       return dw_cfi_oprnd_offset;
573
574     case DW_CFA_register:
575       return dw_cfi_oprnd_reg_num;
576
577     case DW_CFA_expression:
578     case DW_CFA_val_expression:
579       return dw_cfi_oprnd_loc;
580
581     case DW_CFA_def_cfa_expression:
582       return dw_cfi_oprnd_cfa_loc;
583
584     default:
585       return dw_cfi_oprnd_unused;
586     }
587 }
588
589 /* Output one FDE.  */
590
591 static void
592 output_fde (dw_fde_ref fde, bool for_eh, bool second,
593             char *section_start_label, int fde_encoding, char *augmentation,
594             bool any_lsda_needed, int lsda_encoding)
595 {
596   const char *begin, *end;
597   static unsigned int j;
598   char l1[MAX_ARTIFICIAL_LABEL_BYTES], l2[MAX_ARTIFICIAL_LABEL_BYTES];
599
600   targetm.asm_out.emit_unwind_label (asm_out_file, fde->decl, for_eh,
601                                      /* empty */ 0);
602   targetm.asm_out.internal_label (asm_out_file, FDE_LABEL,
603                                   for_eh + j);
604   ASM_GENERATE_INTERNAL_LABEL (l1, FDE_AFTER_SIZE_LABEL, for_eh + j);
605   ASM_GENERATE_INTERNAL_LABEL (l2, FDE_END_LABEL, for_eh + j);
606   if (!XCOFF_DEBUGGING_INFO || for_eh)
607     {
608       if (DWARF_INITIAL_LENGTH_SIZE - DWARF_OFFSET_SIZE == 4 && !for_eh)
609         dw2_asm_output_data (4, 0xffffffff, "Initial length escape value"
610                              " indicating 64-bit DWARF extension");
611       dw2_asm_output_delta (for_eh ? 4 : DWARF_OFFSET_SIZE, l2, l1,
612                             "FDE Length");
613     }
614   ASM_OUTPUT_LABEL (asm_out_file, l1);
615
616   if (for_eh)
617     dw2_asm_output_delta (4, l1, section_start_label, "FDE CIE offset");
618   else
619     dw2_asm_output_offset (DWARF_OFFSET_SIZE, section_start_label,
620                            debug_frame_section, "FDE CIE offset");
621
622   begin = second ? fde->dw_fde_second_begin : fde->dw_fde_begin;
623   end = second ? fde->dw_fde_second_end : fde->dw_fde_end;
624
625   if (for_eh)
626     {
627       rtx sym_ref = gen_rtx_SYMBOL_REF (Pmode, begin);
628       SYMBOL_REF_FLAGS (sym_ref) |= SYMBOL_FLAG_LOCAL;
629       dw2_asm_output_encoded_addr_rtx (fde_encoding, sym_ref, false,
630                                        "FDE initial location");
631       dw2_asm_output_delta (size_of_encoded_value (fde_encoding),
632                             end, begin, "FDE address range");
633     }
634   else
635     {
636       dw2_asm_output_addr (DWARF2_ADDR_SIZE, begin, "FDE initial location");
637       dw2_asm_output_delta (DWARF2_ADDR_SIZE, end, begin, "FDE address range");
638     }
639
640   if (augmentation[0])
641     {
642       if (any_lsda_needed)
643         {
644           int size = size_of_encoded_value (lsda_encoding);
645
646           if (lsda_encoding == DW_EH_PE_aligned)
647             {
648               int offset = (  4         /* Length */
649                             + 4         /* CIE offset */
650                             + 2 * size_of_encoded_value (fde_encoding)
651                             + 1         /* Augmentation size */ );
652               int pad = -offset & (PTR_SIZE - 1);
653
654               size += pad;
655               gcc_assert (size_of_uleb128 (size) == 1);
656             }
657
658           dw2_asm_output_data_uleb128 (size, "Augmentation size");
659
660           if (fde->uses_eh_lsda)
661             {
662               ASM_GENERATE_INTERNAL_LABEL (l1, second ? "LLSDAC" : "LLSDA",
663                                            fde->funcdef_number);
664               dw2_asm_output_encoded_addr_rtx (lsda_encoding,
665                                                gen_rtx_SYMBOL_REF (Pmode, l1),
666                                                false,
667                                                "Language Specific Data Area");
668             }
669           else
670             {
671               if (lsda_encoding == DW_EH_PE_aligned)
672                 ASM_OUTPUT_ALIGN (asm_out_file, floor_log2 (PTR_SIZE));
673               dw2_asm_output_data (size_of_encoded_value (lsda_encoding), 0,
674                                    "Language Specific Data Area (none)");
675             }
676         }
677       else
678         dw2_asm_output_data_uleb128 (0, "Augmentation size");
679     }
680
681   /* Loop through the Call Frame Instructions associated with this FDE.  */
682   fde->dw_fde_current_label = begin;
683   {
684     size_t from, until, i;
685
686     from = 0;
687     until = vec_safe_length (fde->dw_fde_cfi);
688
689     if (fde->dw_fde_second_begin == NULL)
690       ;
691     else if (!second)
692       until = fde->dw_fde_switch_cfi_index;
693     else
694       from = fde->dw_fde_switch_cfi_index;
695
696     for (i = from; i < until; i++)
697       output_cfi ((*fde->dw_fde_cfi)[i], fde, for_eh);
698   }
699
700   /* If we are to emit a ref/link from function bodies to their frame tables,
701      do it now.  This is typically performed to make sure that tables
702      associated with functions are dragged with them and not discarded in
703      garbage collecting links. We need to do this on a per function basis to
704      cope with -ffunction-sections.  */
705
706 #ifdef ASM_OUTPUT_DWARF_TABLE_REF
707   /* Switch to the function section, emit the ref to the tables, and
708      switch *back* into the table section.  */
709   switch_to_section (function_section (fde->decl));
710   ASM_OUTPUT_DWARF_TABLE_REF (section_start_label);
711   switch_to_frame_table_section (for_eh, true);
712 #endif
713
714   /* Pad the FDE out to an address sized boundary.  */
715   ASM_OUTPUT_ALIGN (asm_out_file,
716                     floor_log2 ((for_eh ? PTR_SIZE : DWARF2_ADDR_SIZE)));
717   ASM_OUTPUT_LABEL (asm_out_file, l2);
718
719   j += 2;
720 }
721
722 /* Return true if frame description entry FDE is needed for EH.  */
723
724 static bool
725 fde_needed_for_eh_p (dw_fde_ref fde)
726 {
727   if (flag_asynchronous_unwind_tables)
728     return true;
729
730   if (TARGET_USES_WEAK_UNWIND_INFO && DECL_WEAK (fde->decl))
731     return true;
732
733   if (fde->uses_eh_lsda)
734     return true;
735
736   /* If exceptions are enabled, we have collected nothrow info.  */
737   if (flag_exceptions && (fde->all_throwers_are_sibcalls || fde->nothrow))
738     return false;
739
740   return true;
741 }
742
743 /* Output the call frame information used to record information
744    that relates to calculating the frame pointer, and records the
745    location of saved registers.  */
746
747 static void
748 output_call_frame_info (int for_eh)
749 {
750   unsigned int i;
751   dw_fde_ref fde;
752   dw_cfi_ref cfi;
753   char l1[MAX_ARTIFICIAL_LABEL_BYTES], l2[MAX_ARTIFICIAL_LABEL_BYTES];
754   char section_start_label[MAX_ARTIFICIAL_LABEL_BYTES];
755   bool any_lsda_needed = false;
756   char augmentation[6];
757   int augmentation_size;
758   int fde_encoding = DW_EH_PE_absptr;
759   int per_encoding = DW_EH_PE_absptr;
760   int lsda_encoding = DW_EH_PE_absptr;
761   int return_reg;
762   rtx personality = NULL;
763   int dw_cie_version;
764
765   /* Don't emit a CIE if there won't be any FDEs.  */
766   if (!fde_vec)
767     return;
768
769   /* Nothing to do if the assembler's doing it all.  */
770   if (dwarf2out_do_cfi_asm ())
771     return;
772
773   /* If we don't have any functions we'll want to unwind out of, don't emit
774      any EH unwind information.  If we make FDEs linkonce, we may have to
775      emit an empty label for an FDE that wouldn't otherwise be emitted.  We
776      want to avoid having an FDE kept around when the function it refers to
777      is discarded.  Example where this matters: a primary function template
778      in C++ requires EH information, an explicit specialization doesn't.  */
779   if (for_eh)
780     {
781       bool any_eh_needed = false;
782
783       FOR_EACH_VEC_ELT (*fde_vec, i, fde)
784         {
785           if (fde->uses_eh_lsda)
786             any_eh_needed = any_lsda_needed = true;
787           else if (fde_needed_for_eh_p (fde))
788             any_eh_needed = true;
789           else if (TARGET_USES_WEAK_UNWIND_INFO)
790             targetm.asm_out.emit_unwind_label (asm_out_file, fde->decl, 1, 1);
791         }
792
793       if (!any_eh_needed)
794         return;
795     }
796
797   /* We're going to be generating comments, so turn on app.  */
798   if (flag_debug_asm)
799     app_enable ();
800
801   /* Switch to the proper frame section, first time.  */
802   switch_to_frame_table_section (for_eh, false);
803
804   ASM_GENERATE_INTERNAL_LABEL (section_start_label, FRAME_BEGIN_LABEL, for_eh);
805   ASM_OUTPUT_LABEL (asm_out_file, section_start_label);
806
807   /* Output the CIE.  */
808   ASM_GENERATE_INTERNAL_LABEL (l1, CIE_AFTER_SIZE_LABEL, for_eh);
809   ASM_GENERATE_INTERNAL_LABEL (l2, CIE_END_LABEL, for_eh);
810   if (!XCOFF_DEBUGGING_INFO || for_eh)
811     {
812       if (DWARF_INITIAL_LENGTH_SIZE - DWARF_OFFSET_SIZE == 4 && !for_eh)
813         dw2_asm_output_data (4, 0xffffffff,
814           "Initial length escape value indicating 64-bit DWARF extension");
815       dw2_asm_output_delta (for_eh ? 4 : DWARF_OFFSET_SIZE, l2, l1,
816                             "Length of Common Information Entry");
817     }
818   ASM_OUTPUT_LABEL (asm_out_file, l1);
819
820   /* Now that the CIE pointer is PC-relative for EH,
821      use 0 to identify the CIE.  */
822   dw2_asm_output_data ((for_eh ? 4 : DWARF_OFFSET_SIZE),
823                        (for_eh ? 0 : DWARF_CIE_ID),
824                        "CIE Identifier Tag");
825
826   /* Use the CIE version 3 for DWARF3; allow DWARF2 to continue to
827      use CIE version 1, unless that would produce incorrect results
828      due to overflowing the return register column.  */
829   return_reg = DWARF2_FRAME_REG_OUT (DWARF_FRAME_RETURN_COLUMN, for_eh);
830   dw_cie_version = 1;
831   if (return_reg >= 256 || dwarf_version > 2)
832     dw_cie_version = 3;
833   dw2_asm_output_data (1, dw_cie_version, "CIE Version");
834
835   augmentation[0] = 0;
836   augmentation_size = 0;
837
838   personality = current_unit_personality;
839   if (for_eh)
840     {
841       char *p;
842
843       /* Augmentation:
844          z      Indicates that a uleb128 is present to size the
845                 augmentation section.
846          L      Indicates the encoding (and thus presence) of
847                 an LSDA pointer in the FDE augmentation.
848          R      Indicates a non-default pointer encoding for
849                 FDE code pointers.
850          P      Indicates the presence of an encoding + language
851                 personality routine in the CIE augmentation.  */
852
853       fde_encoding = ASM_PREFERRED_EH_DATA_FORMAT (/*code=*/1, /*global=*/0);
854       per_encoding = ASM_PREFERRED_EH_DATA_FORMAT (/*code=*/2, /*global=*/1);
855       lsda_encoding = ASM_PREFERRED_EH_DATA_FORMAT (/*code=*/0, /*global=*/0);
856
857       p = augmentation + 1;
858       if (personality)
859         {
860           *p++ = 'P';
861           augmentation_size += 1 + size_of_encoded_value (per_encoding);
862           assemble_external_libcall (personality);
863         }
864       if (any_lsda_needed)
865         {
866           *p++ = 'L';
867           augmentation_size += 1;
868         }
869       if (fde_encoding != DW_EH_PE_absptr)
870         {
871           *p++ = 'R';
872           augmentation_size += 1;
873         }
874       if (p > augmentation + 1)
875         {
876           augmentation[0] = 'z';
877           *p = '\0';
878         }
879
880       /* Ug.  Some platforms can't do unaligned dynamic relocations at all.  */
881       if (personality && per_encoding == DW_EH_PE_aligned)
882         {
883           int offset = (  4             /* Length */
884                         + 4             /* CIE Id */
885                         + 1             /* CIE version */
886                         + strlen (augmentation) + 1     /* Augmentation */
887                         + size_of_uleb128 (1)           /* Code alignment */
888                         + size_of_sleb128 (DWARF_CIE_DATA_ALIGNMENT)
889                         + 1             /* RA column */
890                         + 1             /* Augmentation size */
891                         + 1             /* Personality encoding */ );
892           int pad = -offset & (PTR_SIZE - 1);
893
894           augmentation_size += pad;
895
896           /* Augmentations should be small, so there's scarce need to
897              iterate for a solution.  Die if we exceed one uleb128 byte.  */
898           gcc_assert (size_of_uleb128 (augmentation_size) == 1);
899         }
900     }
901
902   dw2_asm_output_nstring (augmentation, -1, "CIE Augmentation");
903   if (dw_cie_version >= 4)
904     {
905       dw2_asm_output_data (1, DWARF2_ADDR_SIZE, "CIE Address Size");
906       dw2_asm_output_data (1, 0, "CIE Segment Size");
907     }
908   dw2_asm_output_data_uleb128 (1, "CIE Code Alignment Factor");
909   dw2_asm_output_data_sleb128 (DWARF_CIE_DATA_ALIGNMENT,
910                                "CIE Data Alignment Factor");
911
912   if (dw_cie_version == 1)
913     dw2_asm_output_data (1, return_reg, "CIE RA Column");
914   else
915     dw2_asm_output_data_uleb128 (return_reg, "CIE RA Column");
916
917   if (augmentation[0])
918     {
919       dw2_asm_output_data_uleb128 (augmentation_size, "Augmentation size");
920       if (personality)
921         {
922           dw2_asm_output_data (1, per_encoding, "Personality (%s)",
923                                eh_data_format_name (per_encoding));
924           dw2_asm_output_encoded_addr_rtx (per_encoding,
925                                            personality,
926                                            true, NULL);
927         }
928
929       if (any_lsda_needed)
930         dw2_asm_output_data (1, lsda_encoding, "LSDA Encoding (%s)",
931                              eh_data_format_name (lsda_encoding));
932
933       if (fde_encoding != DW_EH_PE_absptr)
934         dw2_asm_output_data (1, fde_encoding, "FDE Encoding (%s)",
935                              eh_data_format_name (fde_encoding));
936     }
937
938   FOR_EACH_VEC_ELT (*cie_cfi_vec, i, cfi)
939     output_cfi (cfi, NULL, for_eh);
940
941   /* Pad the CIE out to an address sized boundary.  */
942   ASM_OUTPUT_ALIGN (asm_out_file,
943                     floor_log2 (for_eh ? PTR_SIZE : DWARF2_ADDR_SIZE));
944   ASM_OUTPUT_LABEL (asm_out_file, l2);
945
946   /* Loop through all of the FDE's.  */
947   FOR_EACH_VEC_ELT (*fde_vec, i, fde)
948     {
949       unsigned int k;
950
951       /* Don't emit EH unwind info for leaf functions that don't need it.  */
952       if (for_eh && !fde_needed_for_eh_p (fde))
953         continue;
954
955       for (k = 0; k < (fde->dw_fde_second_begin ? 2 : 1); k++)
956         output_fde (fde, for_eh, k, section_start_label, fde_encoding,
957                     augmentation, any_lsda_needed, lsda_encoding);
958     }
959
960   if (for_eh && targetm.terminate_dw2_eh_frame_info)
961     dw2_asm_output_data (4, 0, "End of Table");
962
963   /* Turn off app to make assembly quicker.  */
964   if (flag_debug_asm)
965     app_disable ();
966 }
967
968 /* Emit .cfi_startproc and .cfi_personality/.cfi_lsda if needed.  */
969
970 static void
971 dwarf2out_do_cfi_startproc (bool second)
972 {
973   int enc;
974   rtx ref;
975
976   fprintf (asm_out_file, "\t.cfi_startproc\n");
977
978   /* .cfi_personality and .cfi_lsda are only relevant to DWARF2
979      eh unwinders.  */
980   if (targetm_common.except_unwind_info (&global_options) != UI_DWARF2)
981     return;
982
983   rtx personality = get_personality_function (current_function_decl);
984
985   if (personality)
986     {
987       enc = ASM_PREFERRED_EH_DATA_FORMAT (/*code=*/2, /*global=*/1);
988       ref = personality;
989
990       /* ??? The GAS support isn't entirely consistent.  We have to
991          handle indirect support ourselves, but PC-relative is done
992          in the assembler.  Further, the assembler can't handle any
993          of the weirder relocation types.  */
994       if (enc & DW_EH_PE_indirect)
995         ref = dw2_force_const_mem (ref, true);
996
997       fprintf (asm_out_file, "\t.cfi_personality %#x,", enc);
998       output_addr_const (asm_out_file, ref);
999       fputc ('\n', asm_out_file);
1000     }
1001
1002   if (crtl->uses_eh_lsda)
1003     {
1004       char lab[MAX_ARTIFICIAL_LABEL_BYTES];
1005
1006       enc = ASM_PREFERRED_EH_DATA_FORMAT (/*code=*/0, /*global=*/0);
1007       ASM_GENERATE_INTERNAL_LABEL (lab, second ? "LLSDAC" : "LLSDA",
1008                                    current_function_funcdef_no);
1009       ref = gen_rtx_SYMBOL_REF (Pmode, lab);
1010       SYMBOL_REF_FLAGS (ref) = SYMBOL_FLAG_LOCAL;
1011
1012       if (enc & DW_EH_PE_indirect)
1013         ref = dw2_force_const_mem (ref, true);
1014
1015       fprintf (asm_out_file, "\t.cfi_lsda %#x,", enc);
1016       output_addr_const (asm_out_file, ref);
1017       fputc ('\n', asm_out_file);
1018     }
1019 }
1020
1021 /* Allocate CURRENT_FDE.  Immediately initialize all we can, noting that
1022    this allocation may be done before pass_final.  */
1023
1024 dw_fde_ref
1025 dwarf2out_alloc_current_fde (void)
1026 {
1027   dw_fde_ref fde;
1028
1029   fde = ggc_cleared_alloc<dw_fde_node> ();
1030   fde->decl = current_function_decl;
1031   fde->funcdef_number = current_function_funcdef_no;
1032   fde->fde_index = vec_safe_length (fde_vec);
1033   fde->all_throwers_are_sibcalls = crtl->all_throwers_are_sibcalls;
1034   fde->uses_eh_lsda = crtl->uses_eh_lsda;
1035   fde->nothrow = crtl->nothrow;
1036   fde->drap_reg = INVALID_REGNUM;
1037   fde->vdrap_reg = INVALID_REGNUM;
1038
1039   /* Record the FDE associated with this function.  */
1040   cfun->fde = fde;
1041   vec_safe_push (fde_vec, fde);
1042
1043   return fde;
1044 }
1045
1046 /* Output a marker (i.e. a label) for the beginning of a function, before
1047    the prologue.  */
1048
1049 void
1050 dwarf2out_begin_prologue (unsigned int line ATTRIBUTE_UNUSED,
1051                           unsigned int column ATTRIBUTE_UNUSED,
1052                           const char *file ATTRIBUTE_UNUSED)
1053 {
1054   char label[MAX_ARTIFICIAL_LABEL_BYTES];
1055   char * dup_label;
1056   dw_fde_ref fde;
1057   section *fnsec;
1058   bool do_frame;
1059
1060   current_function_func_begin_label = NULL;
1061
1062   do_frame = dwarf2out_do_frame ();
1063
1064   /* ??? current_function_func_begin_label is also used by except.c for
1065      call-site information.  We must emit this label if it might be used.  */
1066   if (!do_frame
1067       && (!flag_exceptions
1068           || targetm_common.except_unwind_info (&global_options) == UI_SJLJ))
1069     return;
1070
1071   fnsec = function_section (current_function_decl);
1072   switch_to_section (fnsec);
1073   ASM_GENERATE_INTERNAL_LABEL (label, FUNC_BEGIN_LABEL,
1074                                current_function_funcdef_no);
1075   ASM_OUTPUT_DEBUG_LABEL (asm_out_file, FUNC_BEGIN_LABEL,
1076                           current_function_funcdef_no);
1077   dup_label = xstrdup (label);
1078   current_function_func_begin_label = dup_label;
1079
1080   /* We can elide FDE allocation if we're not emitting frame unwind info.  */
1081   if (!do_frame)
1082     return;
1083
1084   /* Unlike the debug version, the EH version of frame unwind info is a per-
1085      function setting so we need to record whether we need it for the unit.  */
1086   do_eh_frame |= dwarf2out_do_eh_frame ();
1087
1088   /* Cater to the various TARGET_ASM_OUTPUT_MI_THUNK implementations that
1089      emit insns as rtx but bypass the bulk of rest_of_compilation, which
1090      would include pass_dwarf2_frame.  If we've not created the FDE yet,
1091      do so now.  */
1092   fde = cfun->fde;
1093   if (fde == NULL)
1094     fde = dwarf2out_alloc_current_fde ();
1095
1096   /* Initialize the bits of CURRENT_FDE that were not available earlier.  */
1097   fde->dw_fde_begin = dup_label;
1098   fde->dw_fde_current_label = dup_label;
1099   fde->in_std_section = (fnsec == text_section
1100                          || (cold_text_section && fnsec == cold_text_section));
1101
1102   /* We only want to output line number information for the genuine dwarf2
1103      prologue case, not the eh frame case.  */
1104 #ifdef DWARF2_DEBUGGING_INFO
1105   if (file)
1106     dwarf2out_source_line (line, column, file, 0, true);
1107 #endif
1108
1109   if (dwarf2out_do_cfi_asm ())
1110     dwarf2out_do_cfi_startproc (false);
1111   else
1112     {
1113       rtx personality = get_personality_function (current_function_decl);
1114       if (!current_unit_personality)
1115         current_unit_personality = personality;
1116
1117       /* We cannot keep a current personality per function as without CFI
1118          asm, at the point where we emit the CFI data, there is no current
1119          function anymore.  */
1120       if (personality && current_unit_personality != personality)
1121         sorry ("multiple EH personalities are supported only with assemblers "
1122                "supporting .cfi_personality directive");
1123     }
1124 }
1125
1126 /* Output a marker (i.e. a label) for the end of the generated code
1127    for a function prologue.  This gets called *after* the prologue code has
1128    been generated.  */
1129
1130 void
1131 dwarf2out_vms_end_prologue (unsigned int line ATTRIBUTE_UNUSED,
1132                             const char *file ATTRIBUTE_UNUSED)
1133 {
1134   char label[MAX_ARTIFICIAL_LABEL_BYTES];
1135
1136   /* Output a label to mark the endpoint of the code generated for this
1137      function.  */
1138   ASM_GENERATE_INTERNAL_LABEL (label, PROLOGUE_END_LABEL,
1139                                current_function_funcdef_no);
1140   ASM_OUTPUT_DEBUG_LABEL (asm_out_file, PROLOGUE_END_LABEL,
1141                           current_function_funcdef_no);
1142   cfun->fde->dw_fde_vms_end_prologue = xstrdup (label);
1143 }
1144
1145 /* Output a marker (i.e. a label) for the beginning of the generated code
1146    for a function epilogue.  This gets called *before* the prologue code has
1147    been generated.  */
1148
1149 void
1150 dwarf2out_vms_begin_epilogue (unsigned int line ATTRIBUTE_UNUSED,
1151                           const char *file ATTRIBUTE_UNUSED)
1152 {
1153   dw_fde_ref fde = cfun->fde;
1154   char label[MAX_ARTIFICIAL_LABEL_BYTES];
1155
1156   if (fde->dw_fde_vms_begin_epilogue)
1157     return;
1158
1159   /* Output a label to mark the endpoint of the code generated for this
1160      function.  */
1161   ASM_GENERATE_INTERNAL_LABEL (label, EPILOGUE_BEGIN_LABEL,
1162                                current_function_funcdef_no);
1163   ASM_OUTPUT_DEBUG_LABEL (asm_out_file, EPILOGUE_BEGIN_LABEL,
1164                           current_function_funcdef_no);
1165   fde->dw_fde_vms_begin_epilogue = xstrdup (label);
1166 }
1167
1168 /* Output a marker (i.e. a label) for the absolute end of the generated code
1169    for a function definition.  This gets called *after* the epilogue code has
1170    been generated.  */
1171
1172 void
1173 dwarf2out_end_epilogue (unsigned int line ATTRIBUTE_UNUSED,
1174                         const char *file ATTRIBUTE_UNUSED)
1175 {
1176   dw_fde_ref fde;
1177   char label[MAX_ARTIFICIAL_LABEL_BYTES];
1178
1179   last_var_location_insn = NULL;
1180   cached_next_real_insn = NULL;
1181
1182   if (dwarf2out_do_cfi_asm ())
1183     fprintf (asm_out_file, "\t.cfi_endproc\n");
1184
1185   /* Output a label to mark the endpoint of the code generated for this
1186      function.  */
1187   ASM_GENERATE_INTERNAL_LABEL (label, FUNC_END_LABEL,
1188                                current_function_funcdef_no);
1189   ASM_OUTPUT_LABEL (asm_out_file, label);
1190   fde = cfun->fde;
1191   gcc_assert (fde != NULL);
1192   if (fde->dw_fde_second_begin == NULL)
1193     fde->dw_fde_end = xstrdup (label);
1194 }
1195
1196 void
1197 dwarf2out_frame_finish (void)
1198 {
1199   /* Output call frame information.  */
1200   if (targetm.debug_unwind_info () == UI_DWARF2)
1201     output_call_frame_info (0);
1202
1203   /* Output another copy for the unwinder.  */
1204   if (do_eh_frame)
1205     output_call_frame_info (1);
1206 }
1207
1208 /* Note that the current function section is being used for code.  */
1209
1210 static void
1211 dwarf2out_note_section_used (void)
1212 {
1213   section *sec = current_function_section ();
1214   if (sec == text_section)
1215     text_section_used = true;
1216   else if (sec == cold_text_section)
1217     cold_text_section_used = true;
1218 }
1219
1220 static void var_location_switch_text_section (void);
1221 static void set_cur_line_info_table (section *);
1222
1223 void
1224 dwarf2out_switch_text_section (void)
1225 {
1226   char label[MAX_ARTIFICIAL_LABEL_BYTES];
1227   section *sect;
1228   dw_fde_ref fde = cfun->fde;
1229
1230   gcc_assert (cfun && fde && fde->dw_fde_second_begin == NULL);
1231
1232   ASM_GENERATE_INTERNAL_LABEL (label, FUNC_SECOND_SECT_LABEL,
1233                                current_function_funcdef_no);
1234
1235   fde->dw_fde_second_begin = ggc_strdup (label);
1236   if (!in_cold_section_p)
1237     {
1238       fde->dw_fde_end = crtl->subsections.cold_section_end_label;
1239       fde->dw_fde_second_end = crtl->subsections.hot_section_end_label;
1240     }
1241   else
1242     {
1243       fde->dw_fde_end = crtl->subsections.hot_section_end_label;
1244       fde->dw_fde_second_end = crtl->subsections.cold_section_end_label;
1245     }
1246   have_multiple_function_sections = true;
1247
1248   /* There is no need to mark used sections when not debugging.  */
1249   if (cold_text_section != NULL)
1250     dwarf2out_note_section_used ();
1251
1252   if (dwarf2out_do_cfi_asm ())
1253     fprintf (asm_out_file, "\t.cfi_endproc\n");
1254
1255   /* Now do the real section switch.  */
1256   sect = current_function_section ();
1257   switch_to_section (sect);
1258
1259   fde->second_in_std_section
1260     = (sect == text_section
1261        || (cold_text_section && sect == cold_text_section));
1262
1263   if (dwarf2out_do_cfi_asm ())
1264     dwarf2out_do_cfi_startproc (true);
1265
1266   var_location_switch_text_section ();
1267
1268   if (cold_text_section != NULL)
1269     set_cur_line_info_table (sect);
1270 }
1271 \f
1272 /* And now, the subset of the debugging information support code necessary
1273    for emitting location expressions.  */
1274
1275 /* Data about a single source file.  */
1276 struct GTY((for_user)) dwarf_file_data {
1277   const char * filename;
1278   int emitted_number;
1279 };
1280
1281 /* Describe an entry into the .debug_addr section.  */
1282
1283 enum ate_kind {
1284   ate_kind_rtx,
1285   ate_kind_rtx_dtprel,
1286   ate_kind_label
1287 };
1288
1289 struct GTY((for_user)) addr_table_entry {
1290   enum ate_kind kind;
1291   unsigned int refcount;
1292   unsigned int index;
1293   union addr_table_entry_struct_union
1294     {
1295       rtx GTY ((tag ("0"))) rtl;
1296       char * GTY ((tag ("1"))) label;
1297     }
1298   GTY ((desc ("%1.kind"))) addr;
1299 };
1300
1301 typedef unsigned int var_loc_view;
1302
1303 /* Location lists are ranges + location descriptions for that range,
1304    so you can track variables that are in different places over
1305    their entire life.  */
1306 typedef struct GTY(()) dw_loc_list_struct {
1307   dw_loc_list_ref dw_loc_next;
1308   const char *begin; /* Label and addr_entry for start of range */
1309   addr_table_entry *begin_entry;
1310   const char *end;  /* Label for end of range */
1311   char *ll_symbol; /* Label for beginning of location list.
1312                       Only on head of list.  */
1313   char *vl_symbol; /* Label for beginning of view list.  Ditto.  */
1314   const char *section; /* Section this loclist is relative to */
1315   dw_loc_descr_ref expr;
1316   var_loc_view vbegin, vend;
1317   hashval_t hash;
1318   /* True if all addresses in this and subsequent lists are known to be
1319      resolved.  */
1320   bool resolved_addr;
1321   /* True if this list has been replaced by dw_loc_next.  */
1322   bool replaced;
1323   /* True if it has been emitted into .debug_loc* / .debug_loclists*
1324      section.  */
1325   unsigned char emitted : 1;
1326   /* True if hash field is index rather than hash value.  */
1327   unsigned char num_assigned : 1;
1328   /* True if .debug_loclists.dwo offset has been emitted for it already.  */
1329   unsigned char offset_emitted : 1;
1330   /* True if note_variable_value_in_expr has been called on it.  */
1331   unsigned char noted_variable_value : 1;
1332   /* True if the range should be emitted even if begin and end
1333      are the same.  */
1334   bool force;
1335 } dw_loc_list_node;
1336
1337 static dw_loc_descr_ref int_loc_descriptor (poly_int64);
1338 static dw_loc_descr_ref uint_loc_descriptor (unsigned HOST_WIDE_INT);
1339
1340 /* Convert a DWARF stack opcode into its string name.  */
1341
1342 static const char *
1343 dwarf_stack_op_name (unsigned int op)
1344 {
1345   const char *name = get_DW_OP_name (op);
1346
1347   if (name != NULL)
1348     return name;
1349
1350   return "OP_<unknown>";
1351 }
1352
1353 /* Return TRUE iff we're to output location view lists as a separate
1354    attribute next to the location lists, as an extension compatible
1355    with DWARF 2 and above.  */
1356
1357 static inline bool
1358 dwarf2out_locviews_in_attribute ()
1359 {
1360   return debug_variable_location_views == 1;
1361 }
1362
1363 /* Return TRUE iff we're to output location view lists as part of the
1364    location lists, as proposed for standardization after DWARF 5.  */
1365
1366 static inline bool
1367 dwarf2out_locviews_in_loclist ()
1368 {
1369 #ifndef DW_LLE_view_pair
1370   return false;
1371 #else
1372   return debug_variable_location_views == -1;
1373 #endif
1374 }
1375
1376 /* Return a pointer to a newly allocated location description.  Location
1377    descriptions are simple expression terms that can be strung
1378    together to form more complicated location (address) descriptions.  */
1379
1380 static inline dw_loc_descr_ref
1381 new_loc_descr (enum dwarf_location_atom op, unsigned HOST_WIDE_INT oprnd1,
1382                unsigned HOST_WIDE_INT oprnd2)
1383 {
1384   dw_loc_descr_ref descr = ggc_cleared_alloc<dw_loc_descr_node> ();
1385
1386   descr->dw_loc_opc = op;
1387   descr->dw_loc_oprnd1.val_class = dw_val_class_unsigned_const;
1388   descr->dw_loc_oprnd1.val_entry = NULL;
1389   descr->dw_loc_oprnd1.v.val_unsigned = oprnd1;
1390   descr->dw_loc_oprnd2.val_class = dw_val_class_unsigned_const;
1391   descr->dw_loc_oprnd2.val_entry = NULL;
1392   descr->dw_loc_oprnd2.v.val_unsigned = oprnd2;
1393
1394   return descr;
1395 }
1396
1397 /* Add a location description term to a location description expression.  */
1398
1399 static inline void
1400 add_loc_descr (dw_loc_descr_ref *list_head, dw_loc_descr_ref descr)
1401 {
1402   dw_loc_descr_ref *d;
1403
1404   /* Find the end of the chain.  */
1405   for (d = list_head; (*d) != NULL; d = &(*d)->dw_loc_next)
1406     ;
1407
1408   *d = descr;
1409 }
1410
1411 /* Compare two location operands for exact equality.  */
1412
1413 static bool
1414 dw_val_equal_p (dw_val_node *a, dw_val_node *b)
1415 {
1416   if (a->val_class != b->val_class)
1417     return false;
1418   switch (a->val_class)
1419     {
1420     case dw_val_class_none:
1421       return true;
1422     case dw_val_class_addr:
1423       return rtx_equal_p (a->v.val_addr, b->v.val_addr);
1424
1425     case dw_val_class_offset:
1426     case dw_val_class_unsigned_const:
1427     case dw_val_class_const:
1428     case dw_val_class_unsigned_const_implicit:
1429     case dw_val_class_const_implicit:
1430     case dw_val_class_range_list:
1431       /* These are all HOST_WIDE_INT, signed or unsigned.  */
1432       return a->v.val_unsigned == b->v.val_unsigned;
1433
1434     case dw_val_class_loc:
1435       return a->v.val_loc == b->v.val_loc;
1436     case dw_val_class_loc_list:
1437       return a->v.val_loc_list == b->v.val_loc_list;
1438     case dw_val_class_view_list:
1439       return a->v.val_view_list == b->v.val_view_list;
1440     case dw_val_class_die_ref:
1441       return a->v.val_die_ref.die == b->v.val_die_ref.die;
1442     case dw_val_class_fde_ref:
1443       return a->v.val_fde_index == b->v.val_fde_index;
1444     case dw_val_class_symview:
1445       return strcmp (a->v.val_symbolic_view, b->v.val_symbolic_view) == 0;
1446     case dw_val_class_lbl_id:
1447     case dw_val_class_lineptr:
1448     case dw_val_class_macptr:
1449     case dw_val_class_loclistsptr:
1450     case dw_val_class_high_pc:
1451       return strcmp (a->v.val_lbl_id, b->v.val_lbl_id) == 0;
1452     case dw_val_class_str:
1453       return a->v.val_str == b->v.val_str;
1454     case dw_val_class_flag:
1455       return a->v.val_flag == b->v.val_flag;
1456     case dw_val_class_file:
1457     case dw_val_class_file_implicit:
1458       return a->v.val_file == b->v.val_file;
1459     case dw_val_class_decl_ref:
1460       return a->v.val_decl_ref == b->v.val_decl_ref;
1461     
1462     case dw_val_class_const_double:
1463       return (a->v.val_double.high == b->v.val_double.high
1464               && a->v.val_double.low == b->v.val_double.low);
1465
1466     case dw_val_class_wide_int:
1467       return *a->v.val_wide == *b->v.val_wide;
1468
1469     case dw_val_class_vec:
1470       {
1471         size_t a_len = a->v.val_vec.elt_size * a->v.val_vec.length;
1472         size_t b_len = b->v.val_vec.elt_size * b->v.val_vec.length;
1473
1474         return (a_len == b_len
1475                 && !memcmp (a->v.val_vec.array, b->v.val_vec.array, a_len));
1476       }
1477
1478     case dw_val_class_data8:
1479       return memcmp (a->v.val_data8, b->v.val_data8, 8) == 0;
1480
1481     case dw_val_class_vms_delta:
1482       return (!strcmp (a->v.val_vms_delta.lbl1, b->v.val_vms_delta.lbl1)
1483               && !strcmp (a->v.val_vms_delta.lbl1, b->v.val_vms_delta.lbl1));
1484
1485     case dw_val_class_discr_value:
1486       return (a->v.val_discr_value.pos == b->v.val_discr_value.pos
1487               && a->v.val_discr_value.v.uval == b->v.val_discr_value.v.uval);
1488     case dw_val_class_discr_list:
1489       /* It makes no sense comparing two discriminant value lists.  */
1490       return false;
1491     }
1492   gcc_unreachable ();
1493 }
1494
1495 /* Compare two location atoms for exact equality.  */
1496
1497 static bool
1498 loc_descr_equal_p_1 (dw_loc_descr_ref a, dw_loc_descr_ref b)
1499 {
1500   if (a->dw_loc_opc != b->dw_loc_opc)
1501     return false;
1502
1503   /* ??? This is only ever set for DW_OP_constNu, for N equal to the
1504      address size, but since we always allocate cleared storage it
1505      should be zero for other types of locations.  */
1506   if (a->dtprel != b->dtprel)
1507     return false;
1508
1509   return (dw_val_equal_p (&a->dw_loc_oprnd1, &b->dw_loc_oprnd1)
1510           && dw_val_equal_p (&a->dw_loc_oprnd2, &b->dw_loc_oprnd2));
1511 }
1512
1513 /* Compare two complete location expressions for exact equality.  */
1514
1515 bool
1516 loc_descr_equal_p (dw_loc_descr_ref a, dw_loc_descr_ref b)
1517 {
1518   while (1)
1519     {
1520       if (a == b)
1521         return true;
1522       if (a == NULL || b == NULL)
1523         return false;
1524       if (!loc_descr_equal_p_1 (a, b))
1525         return false;
1526
1527       a = a->dw_loc_next;
1528       b = b->dw_loc_next;
1529     }
1530 }
1531
1532
1533 /* Add a constant POLY_OFFSET to a location expression.  */
1534
1535 static void
1536 loc_descr_plus_const (dw_loc_descr_ref *list_head, poly_int64 poly_offset)
1537 {
1538   dw_loc_descr_ref loc;
1539   HOST_WIDE_INT *p;
1540
1541   gcc_assert (*list_head != NULL);
1542
1543   if (known_eq (poly_offset, 0))
1544     return;
1545
1546   /* Find the end of the chain.  */
1547   for (loc = *list_head; loc->dw_loc_next != NULL; loc = loc->dw_loc_next)
1548     ;
1549
1550   HOST_WIDE_INT offset;
1551   if (!poly_offset.is_constant (&offset))
1552     {
1553       loc->dw_loc_next = int_loc_descriptor (poly_offset);
1554       add_loc_descr (&loc->dw_loc_next, new_loc_descr (DW_OP_plus, 0, 0));
1555       return;
1556     }
1557
1558   p = NULL;
1559   if (loc->dw_loc_opc == DW_OP_fbreg
1560       || (loc->dw_loc_opc >= DW_OP_breg0 && loc->dw_loc_opc <= DW_OP_breg31))
1561     p = &loc->dw_loc_oprnd1.v.val_int;
1562   else if (loc->dw_loc_opc == DW_OP_bregx)
1563     p = &loc->dw_loc_oprnd2.v.val_int;
1564
1565   /* If the last operation is fbreg, breg{0..31,x}, optimize by adjusting its
1566      offset.  Don't optimize if an signed integer overflow would happen.  */
1567   if (p != NULL
1568       && ((offset > 0 && *p <= INTTYPE_MAXIMUM (HOST_WIDE_INT) - offset)
1569           || (offset < 0 && *p >= INTTYPE_MINIMUM (HOST_WIDE_INT) - offset)))
1570     *p += offset;
1571
1572   else if (offset > 0)
1573     loc->dw_loc_next = new_loc_descr (DW_OP_plus_uconst, offset, 0);
1574
1575   else
1576     {
1577       loc->dw_loc_next
1578         = uint_loc_descriptor (-(unsigned HOST_WIDE_INT) offset);
1579       add_loc_descr (&loc->dw_loc_next, new_loc_descr (DW_OP_minus, 0, 0));
1580     }
1581 }
1582
1583 /* Return a pointer to a newly allocated location description for
1584    REG and OFFSET.  */
1585
1586 static inline dw_loc_descr_ref
1587 new_reg_loc_descr (unsigned int reg, poly_int64 offset)
1588 {
1589   HOST_WIDE_INT const_offset;
1590   if (offset.is_constant (&const_offset))
1591     {
1592       if (reg <= 31)
1593         return new_loc_descr ((enum dwarf_location_atom) (DW_OP_breg0 + reg),
1594                               const_offset, 0);
1595       else
1596         return new_loc_descr (DW_OP_bregx, reg, const_offset);
1597     }
1598   else
1599     {
1600       dw_loc_descr_ref ret = new_reg_loc_descr (reg, 0);
1601       loc_descr_plus_const (&ret, offset);
1602       return ret;
1603     }
1604 }
1605
1606 /* Add a constant OFFSET to a location list.  */
1607
1608 static void
1609 loc_list_plus_const (dw_loc_list_ref list_head, poly_int64 offset)
1610 {
1611   dw_loc_list_ref d;
1612   for (d = list_head; d != NULL; d = d->dw_loc_next)
1613     loc_descr_plus_const (&d->expr, offset);
1614 }
1615
1616 #define DWARF_REF_SIZE  \
1617   (dwarf_version == 2 ? DWARF2_ADDR_SIZE : DWARF_OFFSET_SIZE)
1618
1619 /* The number of bits that can be encoded by largest DW_FORM_dataN.
1620    In DWARF4 and earlier it is DW_FORM_data8 with 64 bits, in DWARF5
1621    DW_FORM_data16 with 128 bits.  */
1622 #define DWARF_LARGEST_DATA_FORM_BITS \
1623   (dwarf_version >= 5 ? 128 : 64)
1624
1625 /* Utility inline function for construction of ops that were GNU extension
1626    before DWARF 5.  */
1627 static inline enum dwarf_location_atom
1628 dwarf_OP (enum dwarf_location_atom op)
1629 {
1630   switch (op)
1631     {
1632     case DW_OP_implicit_pointer:
1633       if (dwarf_version < 5)
1634         return DW_OP_GNU_implicit_pointer;
1635       break;
1636
1637     case DW_OP_entry_value:
1638       if (dwarf_version < 5)
1639         return DW_OP_GNU_entry_value;
1640       break;
1641
1642     case DW_OP_const_type:
1643       if (dwarf_version < 5)
1644         return DW_OP_GNU_const_type;
1645       break;
1646
1647     case DW_OP_regval_type:
1648       if (dwarf_version < 5)
1649         return DW_OP_GNU_regval_type;
1650       break;
1651
1652     case DW_OP_deref_type:
1653       if (dwarf_version < 5)
1654         return DW_OP_GNU_deref_type;
1655       break;
1656
1657     case DW_OP_convert:
1658       if (dwarf_version < 5)
1659         return DW_OP_GNU_convert;
1660       break;
1661
1662     case DW_OP_reinterpret:
1663       if (dwarf_version < 5)
1664         return DW_OP_GNU_reinterpret;
1665       break;
1666
1667     default:
1668       break;
1669     }
1670   return op;
1671 }
1672
1673 /* Similarly for attributes.  */
1674 static inline enum dwarf_attribute
1675 dwarf_AT (enum dwarf_attribute at)
1676 {
1677   switch (at)
1678     {
1679     case DW_AT_call_return_pc:
1680       if (dwarf_version < 5)
1681         return DW_AT_low_pc;
1682       break;
1683
1684     case DW_AT_call_tail_call:
1685       if (dwarf_version < 5)
1686         return DW_AT_GNU_tail_call;
1687       break;
1688
1689     case DW_AT_call_origin:
1690       if (dwarf_version < 5)
1691         return DW_AT_abstract_origin;
1692       break;
1693
1694     case DW_AT_call_target:
1695       if (dwarf_version < 5)
1696         return DW_AT_GNU_call_site_target;
1697       break;
1698
1699     case DW_AT_call_target_clobbered:
1700       if (dwarf_version < 5)
1701         return DW_AT_GNU_call_site_target_clobbered;
1702       break;
1703
1704     case DW_AT_call_parameter:
1705       if (dwarf_version < 5)
1706         return DW_AT_abstract_origin;
1707       break;
1708
1709     case DW_AT_call_value:
1710       if (dwarf_version < 5)
1711         return DW_AT_GNU_call_site_value;
1712       break;
1713
1714     case DW_AT_call_data_value:
1715       if (dwarf_version < 5)
1716         return DW_AT_GNU_call_site_data_value;
1717       break;
1718
1719     case DW_AT_call_all_calls:
1720       if (dwarf_version < 5)
1721         return DW_AT_GNU_all_call_sites;
1722       break;
1723
1724     case DW_AT_call_all_tail_calls:
1725       if (dwarf_version < 5)
1726         return DW_AT_GNU_all_tail_call_sites;
1727       break;
1728
1729     case DW_AT_dwo_name:
1730       if (dwarf_version < 5)
1731         return DW_AT_GNU_dwo_name;
1732       break;
1733
1734     default:
1735       break;
1736     }
1737   return at;
1738 }
1739
1740 /* And similarly for tags.  */
1741 static inline enum dwarf_tag
1742 dwarf_TAG (enum dwarf_tag tag)
1743 {
1744   switch (tag)
1745     {
1746     case DW_TAG_call_site:
1747       if (dwarf_version < 5)
1748         return DW_TAG_GNU_call_site;
1749       break;
1750
1751     case DW_TAG_call_site_parameter:
1752       if (dwarf_version < 5)
1753         return DW_TAG_GNU_call_site_parameter;
1754       break;
1755
1756     default:
1757       break;
1758     }
1759   return tag;
1760 }
1761
1762 static unsigned long int get_base_type_offset (dw_die_ref);
1763
1764 /* Return the size of a location descriptor.  */
1765
1766 static unsigned long
1767 size_of_loc_descr (dw_loc_descr_ref loc)
1768 {
1769   unsigned long size = 1;
1770
1771   switch (loc->dw_loc_opc)
1772     {
1773     case DW_OP_addr:
1774       size += DWARF2_ADDR_SIZE;
1775       break;
1776     case DW_OP_GNU_addr_index:
1777     case DW_OP_GNU_const_index:
1778       gcc_assert (loc->dw_loc_oprnd1.val_entry->index != NO_INDEX_ASSIGNED);
1779       size += size_of_uleb128 (loc->dw_loc_oprnd1.val_entry->index);
1780       break;
1781     case DW_OP_const1u:
1782     case DW_OP_const1s:
1783       size += 1;
1784       break;
1785     case DW_OP_const2u:
1786     case DW_OP_const2s:
1787       size += 2;
1788       break;
1789     case DW_OP_const4u:
1790     case DW_OP_const4s:
1791       size += 4;
1792       break;
1793     case DW_OP_const8u:
1794     case DW_OP_const8s:
1795       size += 8;
1796       break;
1797     case DW_OP_constu:
1798       size += size_of_uleb128 (loc->dw_loc_oprnd1.v.val_unsigned);
1799       break;
1800     case DW_OP_consts:
1801       size += size_of_sleb128 (loc->dw_loc_oprnd1.v.val_int);
1802       break;
1803     case DW_OP_pick:
1804       size += 1;
1805       break;
1806     case DW_OP_plus_uconst:
1807       size += size_of_uleb128 (loc->dw_loc_oprnd1.v.val_unsigned);
1808       break;
1809     case DW_OP_skip:
1810     case DW_OP_bra:
1811       size += 2;
1812       break;
1813     case DW_OP_breg0:
1814     case DW_OP_breg1:
1815     case DW_OP_breg2:
1816     case DW_OP_breg3:
1817     case DW_OP_breg4:
1818     case DW_OP_breg5:
1819     case DW_OP_breg6:
1820     case DW_OP_breg7:
1821     case DW_OP_breg8:
1822     case DW_OP_breg9:
1823     case DW_OP_breg10:
1824     case DW_OP_breg11:
1825     case DW_OP_breg12:
1826     case DW_OP_breg13:
1827     case DW_OP_breg14:
1828     case DW_OP_breg15:
1829     case DW_OP_breg16:
1830     case DW_OP_breg17:
1831     case DW_OP_breg18:
1832     case DW_OP_breg19:
1833     case DW_OP_breg20:
1834     case DW_OP_breg21:
1835     case DW_OP_breg22:
1836     case DW_OP_breg23:
1837     case DW_OP_breg24:
1838     case DW_OP_breg25:
1839     case DW_OP_breg26:
1840     case DW_OP_breg27:
1841     case DW_OP_breg28:
1842     case DW_OP_breg29:
1843     case DW_OP_breg30:
1844     case DW_OP_breg31:
1845       size += size_of_sleb128 (loc->dw_loc_oprnd1.v.val_int);
1846       break;
1847     case DW_OP_regx:
1848       size += size_of_uleb128 (loc->dw_loc_oprnd1.v.val_unsigned);
1849       break;
1850     case DW_OP_fbreg:
1851       size += size_of_sleb128 (loc->dw_loc_oprnd1.v.val_int);
1852       break;
1853     case DW_OP_bregx:
1854       size += size_of_uleb128 (loc->dw_loc_oprnd1.v.val_unsigned);
1855       size += size_of_sleb128 (loc->dw_loc_oprnd2.v.val_int);
1856       break;
1857     case DW_OP_piece:
1858       size += size_of_uleb128 (loc->dw_loc_oprnd1.v.val_unsigned);
1859       break;
1860     case DW_OP_bit_piece:
1861       size += size_of_uleb128 (loc->dw_loc_oprnd1.v.val_unsigned);
1862       size += size_of_uleb128 (loc->dw_loc_oprnd2.v.val_unsigned);
1863       break;
1864     case DW_OP_deref_size:
1865     case DW_OP_xderef_size:
1866       size += 1;
1867       break;
1868     case DW_OP_call2:
1869       size += 2;
1870       break;
1871     case DW_OP_call4:
1872       size += 4;
1873       break;
1874     case DW_OP_call_ref:
1875     case DW_OP_GNU_variable_value:
1876       size += DWARF_REF_SIZE;
1877       break;
1878     case DW_OP_implicit_value:
1879       size += size_of_uleb128 (loc->dw_loc_oprnd1.v.val_unsigned)
1880               + loc->dw_loc_oprnd1.v.val_unsigned;
1881       break;
1882     case DW_OP_implicit_pointer:
1883     case DW_OP_GNU_implicit_pointer:
1884       size += DWARF_REF_SIZE + size_of_sleb128 (loc->dw_loc_oprnd2.v.val_int);
1885       break;
1886     case DW_OP_entry_value:
1887     case DW_OP_GNU_entry_value:
1888       {
1889         unsigned long op_size = size_of_locs (loc->dw_loc_oprnd1.v.val_loc);
1890         size += size_of_uleb128 (op_size) + op_size;
1891         break;
1892       }
1893     case DW_OP_const_type:
1894     case DW_OP_GNU_const_type:
1895       {
1896         unsigned long o
1897           = get_base_type_offset (loc->dw_loc_oprnd1.v.val_die_ref.die);
1898         size += size_of_uleb128 (o) + 1;
1899         switch (loc->dw_loc_oprnd2.val_class)
1900           {
1901           case dw_val_class_vec:
1902             size += loc->dw_loc_oprnd2.v.val_vec.length
1903                     * loc->dw_loc_oprnd2.v.val_vec.elt_size;
1904             break;
1905           case dw_val_class_const:
1906             size += HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT;
1907             break;
1908           case dw_val_class_const_double:
1909             size += HOST_BITS_PER_DOUBLE_INT / BITS_PER_UNIT;
1910             break;
1911           case dw_val_class_wide_int:
1912             size += (get_full_len (*loc->dw_loc_oprnd2.v.val_wide)
1913                      * HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT);
1914             break;
1915           default:
1916             gcc_unreachable ();
1917           }
1918         break;
1919       }
1920     case DW_OP_regval_type:
1921     case DW_OP_GNU_regval_type:
1922       {
1923         unsigned long o
1924           = get_base_type_offset (loc->dw_loc_oprnd2.v.val_die_ref.die);
1925         size += size_of_uleb128 (loc->dw_loc_oprnd1.v.val_unsigned)
1926                 + size_of_uleb128 (o);
1927       }
1928       break;
1929     case DW_OP_deref_type:
1930     case DW_OP_GNU_deref_type:
1931       {
1932         unsigned long o
1933           = get_base_type_offset (loc->dw_loc_oprnd2.v.val_die_ref.die);
1934         size += 1 + size_of_uleb128 (o);
1935       }
1936       break;
1937     case DW_OP_convert:
1938     case DW_OP_reinterpret:
1939     case DW_OP_GNU_convert:
1940     case DW_OP_GNU_reinterpret:
1941       if (loc->dw_loc_oprnd1.val_class == dw_val_class_unsigned_const)
1942         size += size_of_uleb128 (loc->dw_loc_oprnd1.v.val_unsigned);
1943       else
1944         {
1945           unsigned long o
1946             = get_base_type_offset (loc->dw_loc_oprnd1.v.val_die_ref.die);
1947           size += size_of_uleb128 (o);
1948         }
1949       break;
1950     case DW_OP_GNU_parameter_ref:
1951       size += 4;
1952       break;
1953     default:
1954       break;
1955     }
1956
1957   return size;
1958 }
1959
1960 /* Return the size of a series of location descriptors.  */
1961
1962 unsigned long
1963 size_of_locs (dw_loc_descr_ref loc)
1964 {
1965   dw_loc_descr_ref l;
1966   unsigned long size;
1967
1968   /* If there are no skip or bra opcodes, don't fill in the dw_loc_addr
1969      field, to avoid writing to a PCH file.  */
1970   for (size = 0, l = loc; l != NULL; l = l->dw_loc_next)
1971     {
1972       if (l->dw_loc_opc == DW_OP_skip || l->dw_loc_opc == DW_OP_bra)
1973         break;
1974       size += size_of_loc_descr (l);
1975     }
1976   if (! l)
1977     return size;
1978
1979   for (size = 0, l = loc; l != NULL; l = l->dw_loc_next)
1980     {
1981       l->dw_loc_addr = size;
1982       size += size_of_loc_descr (l);
1983     }
1984
1985   return size;
1986 }
1987
1988 /* Return the size of the value in a DW_AT_discr_value attribute.  */
1989
1990 static int
1991 size_of_discr_value (dw_discr_value *discr_value)
1992 {
1993   if (discr_value->pos)
1994     return size_of_uleb128 (discr_value->v.uval);
1995   else
1996     return size_of_sleb128 (discr_value->v.sval);
1997 }
1998
1999 /* Return the size of the value in a DW_AT_discr_list attribute.  */
2000
2001 static int
2002 size_of_discr_list (dw_discr_list_ref discr_list)
2003 {
2004   int size = 0;
2005
2006   for (dw_discr_list_ref list = discr_list;
2007        list != NULL;
2008        list = list->dw_discr_next)
2009     {
2010       /* One byte for the discriminant value descriptor, and then one or two
2011          LEB128 numbers, depending on whether it's a single case label or a
2012          range label.  */
2013       size += 1;
2014       size += size_of_discr_value (&list->dw_discr_lower_bound);
2015       if (list->dw_discr_range != 0)
2016         size += size_of_discr_value (&list->dw_discr_upper_bound);
2017     }
2018   return size;
2019 }
2020
2021 static HOST_WIDE_INT extract_int (const unsigned char *, unsigned);
2022 static void get_ref_die_offset_label (char *, dw_die_ref);
2023 static unsigned long int get_ref_die_offset (dw_die_ref);
2024
2025 /* Output location description stack opcode's operands (if any).
2026    The for_eh_or_skip parameter controls whether register numbers are
2027    converted using DWARF2_FRAME_REG_OUT, which is needed in the case that
2028    hard reg numbers have been processed via DWARF_FRAME_REGNUM (i.e. for unwind
2029    info).  This should be suppressed for the cases that have not been converted
2030    (i.e. symbolic debug info), by setting the parameter < 0.  See PR47324.  */
2031
2032 static void
2033 output_loc_operands (dw_loc_descr_ref loc, int for_eh_or_skip)
2034 {
2035   dw_val_ref val1 = &loc->dw_loc_oprnd1;
2036   dw_val_ref val2 = &loc->dw_loc_oprnd2;
2037
2038   switch (loc->dw_loc_opc)
2039     {
2040 #ifdef DWARF2_DEBUGGING_INFO
2041     case DW_OP_const2u:
2042     case DW_OP_const2s:
2043       dw2_asm_output_data (2, val1->v.val_int, NULL);
2044       break;
2045     case DW_OP_const4u:
2046       if (loc->dtprel)
2047         {
2048           gcc_assert (targetm.asm_out.output_dwarf_dtprel);
2049           targetm.asm_out.output_dwarf_dtprel (asm_out_file, 4,
2050                                                val1->v.val_addr);
2051           fputc ('\n', asm_out_file);
2052           break;
2053         }
2054       /* FALLTHRU */
2055     case DW_OP_const4s:
2056       dw2_asm_output_data (4, val1->v.val_int, NULL);
2057       break;
2058     case DW_OP_const8u:
2059       if (loc->dtprel)
2060         {
2061           gcc_assert (targetm.asm_out.output_dwarf_dtprel);
2062           targetm.asm_out.output_dwarf_dtprel (asm_out_file, 8,
2063                                                val1->v.val_addr);
2064           fputc ('\n', asm_out_file);
2065           break;
2066         }
2067       /* FALLTHRU */
2068     case DW_OP_const8s:
2069       gcc_assert (HOST_BITS_PER_WIDE_INT >= 64);
2070       dw2_asm_output_data (8, val1->v.val_int, NULL);
2071       break;
2072     case DW_OP_skip:
2073     case DW_OP_bra:
2074       {
2075         int offset;
2076
2077         gcc_assert (val1->val_class == dw_val_class_loc);
2078         offset = val1->v.val_loc->dw_loc_addr - (loc->dw_loc_addr + 3);
2079
2080         dw2_asm_output_data (2, offset, NULL);
2081       }
2082       break;
2083     case DW_OP_implicit_value:
2084       dw2_asm_output_data_uleb128 (val1->v.val_unsigned, NULL);
2085       switch (val2->val_class)
2086         {
2087         case dw_val_class_const:
2088           dw2_asm_output_data (val1->v.val_unsigned, val2->v.val_int, NULL);
2089           break;
2090         case dw_val_class_vec:
2091           {
2092             unsigned int elt_size = val2->v.val_vec.elt_size;
2093             unsigned int len = val2->v.val_vec.length;
2094             unsigned int i;
2095             unsigned char *p;
2096
2097             if (elt_size > sizeof (HOST_WIDE_INT))
2098               {
2099                 elt_size /= 2;
2100                 len *= 2;
2101               }
2102             for (i = 0, p = (unsigned char *) val2->v.val_vec.array;
2103                  i < len;
2104                  i++, p += elt_size)
2105               dw2_asm_output_data (elt_size, extract_int (p, elt_size),
2106                                    "fp or vector constant word %u", i);
2107           }
2108           break;
2109         case dw_val_class_const_double:
2110           {
2111             unsigned HOST_WIDE_INT first, second;
2112
2113             if (WORDS_BIG_ENDIAN)
2114               {
2115                 first = val2->v.val_double.high;
2116                 second = val2->v.val_double.low;
2117               }
2118             else
2119               {
2120                 first = val2->v.val_double.low;
2121                 second = val2->v.val_double.high;
2122               }
2123             dw2_asm_output_data (HOST_BITS_PER_WIDE_INT / HOST_BITS_PER_CHAR,
2124                                  first, NULL);
2125             dw2_asm_output_data (HOST_BITS_PER_WIDE_INT / HOST_BITS_PER_CHAR,
2126                                  second, NULL);
2127           }
2128           break;
2129         case dw_val_class_wide_int:
2130           {
2131             int i;
2132             int len = get_full_len (*val2->v.val_wide);
2133             if (WORDS_BIG_ENDIAN)
2134               for (i = len - 1; i >= 0; --i)
2135                 dw2_asm_output_data (HOST_BITS_PER_WIDE_INT / HOST_BITS_PER_CHAR,
2136                                      val2->v.val_wide->elt (i), NULL);
2137             else
2138               for (i = 0; i < len; ++i)
2139                 dw2_asm_output_data (HOST_BITS_PER_WIDE_INT / HOST_BITS_PER_CHAR,
2140                                      val2->v.val_wide->elt (i), NULL);
2141           }
2142           break;
2143         case dw_val_class_addr:
2144           gcc_assert (val1->v.val_unsigned == DWARF2_ADDR_SIZE);
2145           dw2_asm_output_addr_rtx (DWARF2_ADDR_SIZE, val2->v.val_addr, NULL);
2146           break;
2147         default:
2148           gcc_unreachable ();
2149         }
2150       break;
2151 #else
2152     case DW_OP_const2u:
2153     case DW_OP_const2s:
2154     case DW_OP_const4u:
2155     case DW_OP_const4s:
2156     case DW_OP_const8u:
2157     case DW_OP_const8s:
2158     case DW_OP_skip:
2159     case DW_OP_bra:
2160     case DW_OP_implicit_value:
2161       /* We currently don't make any attempt to make sure these are
2162          aligned properly like we do for the main unwind info, so
2163          don't support emitting things larger than a byte if we're
2164          only doing unwinding.  */
2165       gcc_unreachable ();
2166 #endif
2167     case DW_OP_const1u:
2168     case DW_OP_const1s:
2169       dw2_asm_output_data (1, val1->v.val_int, NULL);
2170       break;
2171     case DW_OP_constu:
2172       dw2_asm_output_data_uleb128 (val1->v.val_unsigned, NULL);
2173       break;
2174     case DW_OP_consts:
2175       dw2_asm_output_data_sleb128 (val1->v.val_int, NULL);
2176       break;
2177     case DW_OP_pick:
2178       dw2_asm_output_data (1, val1->v.val_int, NULL);
2179       break;
2180     case DW_OP_plus_uconst:
2181       dw2_asm_output_data_uleb128 (val1->v.val_unsigned, NULL);
2182       break;
2183     case DW_OP_breg0:
2184     case DW_OP_breg1:
2185     case DW_OP_breg2:
2186     case DW_OP_breg3:
2187     case DW_OP_breg4:
2188     case DW_OP_breg5:
2189     case DW_OP_breg6:
2190     case DW_OP_breg7:
2191     case DW_OP_breg8:
2192     case DW_OP_breg9:
2193     case DW_OP_breg10:
2194     case DW_OP_breg11:
2195     case DW_OP_breg12:
2196     case DW_OP_breg13:
2197     case DW_OP_breg14:
2198     case DW_OP_breg15:
2199     case DW_OP_breg16:
2200     case DW_OP_breg17:
2201     case DW_OP_breg18:
2202     case DW_OP_breg19:
2203     case DW_OP_breg20:
2204     case DW_OP_breg21:
2205     case DW_OP_breg22:
2206     case DW_OP_breg23:
2207     case DW_OP_breg24:
2208     case DW_OP_breg25:
2209     case DW_OP_breg26:
2210     case DW_OP_breg27:
2211     case DW_OP_breg28:
2212     case DW_OP_breg29:
2213     case DW_OP_breg30:
2214     case DW_OP_breg31:
2215       dw2_asm_output_data_sleb128 (val1->v.val_int, NULL);
2216       break;
2217     case DW_OP_regx:
2218       {
2219         unsigned r = val1->v.val_unsigned;
2220         if (for_eh_or_skip >= 0)
2221           r = DWARF2_FRAME_REG_OUT (r, for_eh_or_skip);
2222         gcc_assert (size_of_uleb128 (r) 
2223                     == size_of_uleb128 (val1->v.val_unsigned));
2224         dw2_asm_output_data_uleb128 (r, NULL);  
2225       }
2226       break;
2227     case DW_OP_fbreg:
2228       dw2_asm_output_data_sleb128 (val1->v.val_int, NULL);
2229       break;
2230     case DW_OP_bregx:
2231       {
2232         unsigned r = val1->v.val_unsigned;
2233         if (for_eh_or_skip >= 0)
2234           r = DWARF2_FRAME_REG_OUT (r, for_eh_or_skip);
2235         gcc_assert (size_of_uleb128 (r) 
2236                     == size_of_uleb128 (val1->v.val_unsigned));
2237         dw2_asm_output_data_uleb128 (r, NULL);  
2238         dw2_asm_output_data_sleb128 (val2->v.val_int, NULL);
2239       }
2240       break;
2241     case DW_OP_piece:
2242       dw2_asm_output_data_uleb128 (val1->v.val_unsigned, NULL);
2243       break;
2244     case DW_OP_bit_piece:
2245       dw2_asm_output_data_uleb128 (val1->v.val_unsigned, NULL);
2246       dw2_asm_output_data_uleb128 (val2->v.val_unsigned, NULL);
2247       break;
2248     case DW_OP_deref_size:
2249     case DW_OP_xderef_size:
2250       dw2_asm_output_data (1, val1->v.val_int, NULL);
2251       break;
2252
2253     case DW_OP_addr:
2254       if (loc->dtprel)
2255         {
2256           if (targetm.asm_out.output_dwarf_dtprel)
2257             {
2258               targetm.asm_out.output_dwarf_dtprel (asm_out_file,
2259                                                    DWARF2_ADDR_SIZE,
2260                                                    val1->v.val_addr);
2261               fputc ('\n', asm_out_file);
2262             }
2263           else
2264             gcc_unreachable ();
2265         }
2266       else
2267         {
2268 #ifdef DWARF2_DEBUGGING_INFO
2269           dw2_asm_output_addr_rtx (DWARF2_ADDR_SIZE, val1->v.val_addr, NULL);
2270 #else
2271           gcc_unreachable ();
2272 #endif
2273         }
2274       break;
2275
2276     case DW_OP_GNU_addr_index:
2277     case DW_OP_GNU_const_index:
2278       gcc_assert (loc->dw_loc_oprnd1.val_entry->index != NO_INDEX_ASSIGNED);
2279       dw2_asm_output_data_uleb128 (loc->dw_loc_oprnd1.val_entry->index,
2280                                    "(index into .debug_addr)");
2281       break;
2282
2283     case DW_OP_call2:
2284     case DW_OP_call4:
2285       {
2286         unsigned long die_offset
2287           = get_ref_die_offset (val1->v.val_die_ref.die);
2288         /* Make sure the offset has been computed and that we can encode it as
2289            an operand.  */
2290         gcc_assert (die_offset > 0
2291                     && die_offset <= (loc->dw_loc_opc == DW_OP_call2
2292                                      ? 0xffff
2293                                      : 0xffffffff));
2294         dw2_asm_output_data ((loc->dw_loc_opc == DW_OP_call2) ? 2 : 4,
2295                              die_offset, NULL);
2296       }
2297       break;
2298
2299     case DW_OP_call_ref:
2300     case DW_OP_GNU_variable_value:
2301       {
2302         char label[MAX_ARTIFICIAL_LABEL_BYTES
2303                    + HOST_BITS_PER_WIDE_INT / 2 + 2];
2304         gcc_assert (val1->val_class == dw_val_class_die_ref);
2305         get_ref_die_offset_label (label, val1->v.val_die_ref.die);
2306         dw2_asm_output_offset (DWARF_REF_SIZE, label, debug_info_section, NULL);
2307       }
2308       break;
2309
2310     case DW_OP_implicit_pointer:
2311     case DW_OP_GNU_implicit_pointer:
2312       {
2313         char label[MAX_ARTIFICIAL_LABEL_BYTES
2314                    + HOST_BITS_PER_WIDE_INT / 2 + 2];
2315         gcc_assert (val1->val_class == dw_val_class_die_ref);
2316         get_ref_die_offset_label (label, val1->v.val_die_ref.die);
2317         dw2_asm_output_offset (DWARF_REF_SIZE, label, debug_info_section, NULL);
2318         dw2_asm_output_data_sleb128 (val2->v.val_int, NULL);
2319       }
2320       break;
2321
2322     case DW_OP_entry_value:
2323     case DW_OP_GNU_entry_value:
2324       dw2_asm_output_data_uleb128 (size_of_locs (val1->v.val_loc), NULL);
2325       output_loc_sequence (val1->v.val_loc, for_eh_or_skip);
2326       break;
2327
2328     case DW_OP_const_type:
2329     case DW_OP_GNU_const_type:
2330       {
2331         unsigned long o = get_base_type_offset (val1->v.val_die_ref.die), l;
2332         gcc_assert (o);
2333         dw2_asm_output_data_uleb128 (o, NULL);
2334         switch (val2->val_class)
2335           {
2336           case dw_val_class_const:
2337             l = HOST_BITS_PER_WIDE_INT / HOST_BITS_PER_CHAR;
2338             dw2_asm_output_data (1, l, NULL);
2339             dw2_asm_output_data (l, val2->v.val_int, NULL);
2340             break;
2341           case dw_val_class_vec:
2342             {
2343               unsigned int elt_size = val2->v.val_vec.elt_size;
2344               unsigned int len = val2->v.val_vec.length;
2345               unsigned int i;
2346               unsigned char *p;
2347
2348               l = len * elt_size;
2349               dw2_asm_output_data (1, l, NULL);
2350               if (elt_size > sizeof (HOST_WIDE_INT))
2351                 {
2352                   elt_size /= 2;
2353                   len *= 2;
2354                 }
2355               for (i = 0, p = (unsigned char *) val2->v.val_vec.array;
2356                    i < len;
2357                    i++, p += elt_size)
2358                 dw2_asm_output_data (elt_size, extract_int (p, elt_size),
2359                                      "fp or vector constant word %u", i);
2360             }
2361             break;
2362           case dw_val_class_const_double:
2363             {
2364               unsigned HOST_WIDE_INT first, second;
2365               l = HOST_BITS_PER_WIDE_INT / HOST_BITS_PER_CHAR;
2366
2367               dw2_asm_output_data (1, 2 * l, NULL);
2368               if (WORDS_BIG_ENDIAN)
2369                 {
2370                   first = val2->v.val_double.high;
2371                   second = val2->v.val_double.low;
2372                 }
2373               else
2374                 {
2375                   first = val2->v.val_double.low;
2376                   second = val2->v.val_double.high;
2377                 }
2378               dw2_asm_output_data (l, first, NULL);
2379               dw2_asm_output_data (l, second, NULL);
2380             }
2381             break;
2382           case dw_val_class_wide_int:
2383             {
2384               int i;
2385               int len = get_full_len (*val2->v.val_wide);
2386               l = HOST_BITS_PER_WIDE_INT / HOST_BITS_PER_CHAR;
2387
2388               dw2_asm_output_data (1, len * l, NULL);
2389               if (WORDS_BIG_ENDIAN)
2390                 for (i = len - 1; i >= 0; --i)
2391                   dw2_asm_output_data (l, val2->v.val_wide->elt (i), NULL);
2392               else
2393                 for (i = 0; i < len; ++i)
2394                   dw2_asm_output_data (l, val2->v.val_wide->elt (i), NULL);
2395             }
2396             break;
2397           default:
2398             gcc_unreachable ();
2399           }
2400       }
2401       break;
2402     case DW_OP_regval_type:
2403     case DW_OP_GNU_regval_type:
2404       {
2405         unsigned r = val1->v.val_unsigned;
2406         unsigned long o = get_base_type_offset (val2->v.val_die_ref.die);
2407         gcc_assert (o);
2408         if (for_eh_or_skip >= 0)
2409           {
2410             r = DWARF2_FRAME_REG_OUT (r, for_eh_or_skip);
2411             gcc_assert (size_of_uleb128 (r)
2412                         == size_of_uleb128 (val1->v.val_unsigned));
2413           }
2414         dw2_asm_output_data_uleb128 (r, NULL);
2415         dw2_asm_output_data_uleb128 (o, NULL);
2416       }
2417       break;
2418     case DW_OP_deref_type:
2419     case DW_OP_GNU_deref_type:
2420       {
2421         unsigned long o = get_base_type_offset (val2->v.val_die_ref.die);
2422         gcc_assert (o);
2423         dw2_asm_output_data (1, val1->v.val_int, NULL);
2424         dw2_asm_output_data_uleb128 (o, NULL);
2425       }
2426       break;
2427     case DW_OP_convert:
2428     case DW_OP_reinterpret:
2429     case DW_OP_GNU_convert:
2430     case DW_OP_GNU_reinterpret:
2431       if (loc->dw_loc_oprnd1.val_class == dw_val_class_unsigned_const)
2432         dw2_asm_output_data_uleb128 (val1->v.val_unsigned, NULL);
2433       else
2434         {
2435           unsigned long o = get_base_type_offset (val1->v.val_die_ref.die);
2436           gcc_assert (o);
2437           dw2_asm_output_data_uleb128 (o, NULL);
2438         }
2439       break;
2440
2441     case DW_OP_GNU_parameter_ref:
2442       {
2443         unsigned long o;
2444         gcc_assert (val1->val_class == dw_val_class_die_ref);
2445         o = get_ref_die_offset (val1->v.val_die_ref.die);
2446         dw2_asm_output_data (4, o, NULL);
2447       }
2448       break;
2449
2450     default:
2451       /* Other codes have no operands.  */
2452       break;
2453     }
2454 }
2455
2456 /* Output a sequence of location operations.  
2457    The for_eh_or_skip parameter controls whether register numbers are
2458    converted using DWARF2_FRAME_REG_OUT, which is needed in the case that
2459    hard reg numbers have been processed via DWARF_FRAME_REGNUM (i.e. for unwind
2460    info).  This should be suppressed for the cases that have not been converted
2461    (i.e. symbolic debug info), by setting the parameter < 0.  See PR47324.  */
2462
2463 void
2464 output_loc_sequence (dw_loc_descr_ref loc, int for_eh_or_skip)
2465 {
2466   for (; loc != NULL; loc = loc->dw_loc_next)
2467     {
2468       enum dwarf_location_atom opc = loc->dw_loc_opc;
2469       /* Output the opcode.  */
2470       if (for_eh_or_skip >= 0 
2471           && opc >= DW_OP_breg0 && opc <= DW_OP_breg31)
2472         {
2473           unsigned r = (opc - DW_OP_breg0);
2474           r = DWARF2_FRAME_REG_OUT (r, for_eh_or_skip);
2475           gcc_assert (r <= 31);
2476           opc = (enum dwarf_location_atom) (DW_OP_breg0 + r);
2477         }
2478       else if (for_eh_or_skip >= 0 
2479                && opc >= DW_OP_reg0 && opc <= DW_OP_reg31)
2480         {
2481           unsigned r = (opc - DW_OP_reg0);
2482           r = DWARF2_FRAME_REG_OUT (r, for_eh_or_skip);
2483           gcc_assert (r <= 31);
2484           opc = (enum dwarf_location_atom) (DW_OP_reg0 + r);
2485         }
2486
2487       dw2_asm_output_data (1, opc,
2488                              "%s", dwarf_stack_op_name (opc));
2489
2490       /* Output the operand(s) (if any).  */
2491       output_loc_operands (loc, for_eh_or_skip);
2492     }
2493 }
2494
2495 /* Output location description stack opcode's operands (if any).
2496    The output is single bytes on a line, suitable for .cfi_escape.  */
2497
2498 static void
2499 output_loc_operands_raw (dw_loc_descr_ref loc)
2500 {
2501   dw_val_ref val1 = &loc->dw_loc_oprnd1;
2502   dw_val_ref val2 = &loc->dw_loc_oprnd2;
2503
2504   switch (loc->dw_loc_opc)
2505     {
2506     case DW_OP_addr:
2507     case DW_OP_GNU_addr_index:
2508     case DW_OP_GNU_const_index:
2509     case DW_OP_implicit_value:
2510       /* We cannot output addresses in .cfi_escape, only bytes.  */
2511       gcc_unreachable ();
2512
2513     case DW_OP_const1u:
2514     case DW_OP_const1s:
2515     case DW_OP_pick:
2516     case DW_OP_deref_size:
2517     case DW_OP_xderef_size:
2518       fputc (',', asm_out_file);
2519       dw2_asm_output_data_raw (1, val1->v.val_int);
2520       break;
2521
2522     case DW_OP_const2u:
2523     case DW_OP_const2s:
2524       fputc (',', asm_out_file);
2525       dw2_asm_output_data_raw (2, val1->v.val_int);
2526       break;
2527
2528     case DW_OP_const4u:
2529     case DW_OP_const4s:
2530       fputc (',', asm_out_file);
2531       dw2_asm_output_data_raw (4, val1->v.val_int);
2532       break;
2533
2534     case DW_OP_const8u:
2535     case DW_OP_const8s:
2536       gcc_assert (HOST_BITS_PER_WIDE_INT >= 64);
2537       fputc (',', asm_out_file);
2538       dw2_asm_output_data_raw (8, val1->v.val_int);
2539       break;
2540
2541     case DW_OP_skip:
2542     case DW_OP_bra:
2543       {
2544         int offset;
2545
2546         gcc_assert (val1->val_class == dw_val_class_loc);
2547         offset = val1->v.val_loc->dw_loc_addr - (loc->dw_loc_addr + 3);
2548
2549         fputc (',', asm_out_file);
2550         dw2_asm_output_data_raw (2, offset);
2551       }
2552       break;
2553
2554     case DW_OP_regx:
2555       {
2556         unsigned r = DWARF2_FRAME_REG_OUT (val1->v.val_unsigned, 1);
2557         gcc_assert (size_of_uleb128 (r) 
2558                     == size_of_uleb128 (val1->v.val_unsigned));
2559         fputc (',', asm_out_file);
2560         dw2_asm_output_data_uleb128_raw (r);
2561       }
2562       break;
2563       
2564     case DW_OP_constu:
2565     case DW_OP_plus_uconst:
2566     case DW_OP_piece:
2567       fputc (',', asm_out_file);
2568       dw2_asm_output_data_uleb128_raw (val1->v.val_unsigned);
2569       break;
2570
2571     case DW_OP_bit_piece:
2572       fputc (',', asm_out_file);
2573       dw2_asm_output_data_uleb128_raw (val1->v.val_unsigned);
2574       dw2_asm_output_data_uleb128_raw (val2->v.val_unsigned);
2575       break;
2576
2577     case DW_OP_consts:
2578     case DW_OP_breg0:
2579     case DW_OP_breg1:
2580     case DW_OP_breg2:
2581     case DW_OP_breg3:
2582     case DW_OP_breg4:
2583     case DW_OP_breg5:
2584     case DW_OP_breg6:
2585     case DW_OP_breg7:
2586     case DW_OP_breg8:
2587     case DW_OP_breg9:
2588     case DW_OP_breg10:
2589     case DW_OP_breg11:
2590     case DW_OP_breg12:
2591     case DW_OP_breg13:
2592     case DW_OP_breg14:
2593     case DW_OP_breg15:
2594     case DW_OP_breg16:
2595     case DW_OP_breg17:
2596     case DW_OP_breg18:
2597     case DW_OP_breg19:
2598     case DW_OP_breg20:
2599     case DW_OP_breg21:
2600     case DW_OP_breg22:
2601     case DW_OP_breg23:
2602     case DW_OP_breg24:
2603     case DW_OP_breg25:
2604     case DW_OP_breg26:
2605     case DW_OP_breg27:
2606     case DW_OP_breg28:
2607     case DW_OP_breg29:
2608     case DW_OP_breg30:
2609     case DW_OP_breg31:
2610     case DW_OP_fbreg:
2611       fputc (',', asm_out_file);
2612       dw2_asm_output_data_sleb128_raw (val1->v.val_int);
2613       break;
2614
2615     case DW_OP_bregx:
2616       {
2617         unsigned r = DWARF2_FRAME_REG_OUT (val1->v.val_unsigned, 1);
2618         gcc_assert (size_of_uleb128 (r) 
2619                     == size_of_uleb128 (val1->v.val_unsigned));
2620         fputc (',', asm_out_file);
2621         dw2_asm_output_data_uleb128_raw (r);
2622         fputc (',', asm_out_file);
2623         dw2_asm_output_data_sleb128_raw (val2->v.val_int);
2624       }
2625       break;
2626
2627     case DW_OP_implicit_pointer:
2628     case DW_OP_entry_value:
2629     case DW_OP_const_type:
2630     case DW_OP_regval_type:
2631     case DW_OP_deref_type:
2632     case DW_OP_convert:
2633     case DW_OP_reinterpret:
2634     case DW_OP_GNU_implicit_pointer:
2635     case DW_OP_GNU_entry_value:
2636     case DW_OP_GNU_const_type:
2637     case DW_OP_GNU_regval_type:
2638     case DW_OP_GNU_deref_type:
2639     case DW_OP_GNU_convert:
2640     case DW_OP_GNU_reinterpret:
2641     case DW_OP_GNU_parameter_ref:
2642       gcc_unreachable ();
2643       break;
2644
2645     default:
2646       /* Other codes have no operands.  */
2647       break;
2648     }
2649 }
2650
2651 void
2652 output_loc_sequence_raw (dw_loc_descr_ref loc)
2653 {
2654   while (1)
2655     {
2656       enum dwarf_location_atom opc = loc->dw_loc_opc;
2657       /* Output the opcode.  */
2658       if (opc >= DW_OP_breg0 && opc <= DW_OP_breg31)
2659         {
2660           unsigned r = (opc - DW_OP_breg0);
2661           r = DWARF2_FRAME_REG_OUT (r, 1);
2662           gcc_assert (r <= 31);
2663           opc = (enum dwarf_location_atom) (DW_OP_breg0 + r);
2664         }
2665       else if (opc >= DW_OP_reg0 && opc <= DW_OP_reg31)
2666         {
2667           unsigned r = (opc - DW_OP_reg0);
2668           r = DWARF2_FRAME_REG_OUT (r, 1);
2669           gcc_assert (r <= 31);
2670           opc = (enum dwarf_location_atom) (DW_OP_reg0 + r);
2671         }
2672       /* Output the opcode.  */
2673       fprintf (asm_out_file, "%#x", opc);
2674       output_loc_operands_raw (loc);
2675
2676       if (!loc->dw_loc_next)
2677         break;
2678       loc = loc->dw_loc_next;
2679
2680       fputc (',', asm_out_file);
2681     }
2682 }
2683
2684 /* This function builds a dwarf location descriptor sequence from a
2685    dw_cfa_location, adding the given OFFSET to the result of the
2686    expression.  */
2687
2688 struct dw_loc_descr_node *
2689 build_cfa_loc (dw_cfa_location *cfa, poly_int64 offset)
2690 {
2691   struct dw_loc_descr_node *head, *tmp;
2692
2693   offset += cfa->offset;
2694
2695   if (cfa->indirect)
2696     {
2697       head = new_reg_loc_descr (cfa->reg, cfa->base_offset);
2698       head->dw_loc_oprnd1.val_class = dw_val_class_const;
2699       head->dw_loc_oprnd1.val_entry = NULL;
2700       tmp = new_loc_descr (DW_OP_deref, 0, 0);
2701       add_loc_descr (&head, tmp);
2702       loc_descr_plus_const (&head, offset);
2703     }
2704   else
2705     head = new_reg_loc_descr (cfa->reg, offset);
2706
2707   return head;
2708 }
2709
2710 /* This function builds a dwarf location descriptor sequence for
2711    the address at OFFSET from the CFA when stack is aligned to
2712    ALIGNMENT byte.  */
2713
2714 struct dw_loc_descr_node *
2715 build_cfa_aligned_loc (dw_cfa_location *cfa,
2716                        poly_int64 offset, HOST_WIDE_INT alignment)
2717 {
2718   struct dw_loc_descr_node *head;
2719   unsigned int dwarf_fp
2720     = DWARF_FRAME_REGNUM (HARD_FRAME_POINTER_REGNUM);
2721
2722   /* When CFA is defined as FP+OFFSET, emulate stack alignment.  */
2723   if (cfa->reg == HARD_FRAME_POINTER_REGNUM && cfa->indirect == 0)
2724     {
2725       head = new_reg_loc_descr (dwarf_fp, 0);
2726       add_loc_descr (&head, int_loc_descriptor (alignment));
2727       add_loc_descr (&head, new_loc_descr (DW_OP_and, 0, 0));
2728       loc_descr_plus_const (&head, offset);
2729     }
2730   else
2731     head = new_reg_loc_descr (dwarf_fp, offset);
2732   return head;
2733 }
2734 \f
2735 /* And now, the support for symbolic debugging information.  */
2736
2737 /* .debug_str support.  */
2738
2739 static void dwarf2out_init (const char *);
2740 static void dwarf2out_finish (const char *);
2741 static void dwarf2out_early_finish (const char *);
2742 static void dwarf2out_assembly_start (void);
2743 static void dwarf2out_define (unsigned int, const char *);
2744 static void dwarf2out_undef (unsigned int, const char *);
2745 static void dwarf2out_start_source_file (unsigned, const char *);
2746 static void dwarf2out_end_source_file (unsigned);
2747 static void dwarf2out_function_decl (tree);
2748 static void dwarf2out_begin_block (unsigned, unsigned);
2749 static void dwarf2out_end_block (unsigned, unsigned);
2750 static bool dwarf2out_ignore_block (const_tree);
2751 static void dwarf2out_early_global_decl (tree);
2752 static void dwarf2out_late_global_decl (tree);
2753 static void dwarf2out_type_decl (tree, int);
2754 static void dwarf2out_imported_module_or_decl (tree, tree, tree, bool, bool);
2755 static void dwarf2out_imported_module_or_decl_1 (tree, tree, tree,
2756                                                  dw_die_ref);
2757 static void dwarf2out_abstract_function (tree);
2758 static void dwarf2out_var_location (rtx_insn *);
2759 static void dwarf2out_inline_entry (tree);
2760 static void dwarf2out_size_function (tree);
2761 static void dwarf2out_begin_function (tree);
2762 static void dwarf2out_end_function (unsigned int);
2763 static void dwarf2out_register_main_translation_unit (tree unit);
2764 static void dwarf2out_set_name (tree, tree);
2765 static void dwarf2out_register_external_die (tree decl, const char *sym,
2766                                              unsigned HOST_WIDE_INT off);
2767 static bool dwarf2out_die_ref_for_decl (tree decl, const char **sym,
2768                                         unsigned HOST_WIDE_INT *off);
2769
2770 /* The debug hooks structure.  */
2771
2772 const struct gcc_debug_hooks dwarf2_debug_hooks =
2773 {
2774   dwarf2out_init,
2775   dwarf2out_finish,
2776   dwarf2out_early_finish,
2777   dwarf2out_assembly_start,
2778   dwarf2out_define,
2779   dwarf2out_undef,
2780   dwarf2out_start_source_file,
2781   dwarf2out_end_source_file,
2782   dwarf2out_begin_block,
2783   dwarf2out_end_block,
2784   dwarf2out_ignore_block,
2785   dwarf2out_source_line,
2786   dwarf2out_begin_prologue,
2787 #if VMS_DEBUGGING_INFO
2788   dwarf2out_vms_end_prologue,
2789   dwarf2out_vms_begin_epilogue,
2790 #else
2791   debug_nothing_int_charstar,
2792   debug_nothing_int_charstar,
2793 #endif
2794   dwarf2out_end_epilogue,
2795   dwarf2out_begin_function,
2796   dwarf2out_end_function,       /* end_function */
2797   dwarf2out_register_main_translation_unit,
2798   dwarf2out_function_decl,      /* function_decl */
2799   dwarf2out_early_global_decl,
2800   dwarf2out_late_global_decl,
2801   dwarf2out_type_decl,          /* type_decl */
2802   dwarf2out_imported_module_or_decl,
2803   dwarf2out_die_ref_for_decl,
2804   dwarf2out_register_external_die,
2805   debug_nothing_tree,           /* deferred_inline_function */
2806   /* The DWARF 2 backend tries to reduce debugging bloat by not
2807      emitting the abstract description of inline functions until
2808      something tries to reference them.  */
2809   dwarf2out_abstract_function,  /* outlining_inline_function */
2810   debug_nothing_rtx_code_label, /* label */
2811   debug_nothing_int,            /* handle_pch */
2812   dwarf2out_var_location,
2813   dwarf2out_inline_entry,       /* inline_entry */
2814   dwarf2out_size_function,      /* size_function */
2815   dwarf2out_switch_text_section,
2816   dwarf2out_set_name,
2817   1,                            /* start_end_main_source_file */
2818   TYPE_SYMTAB_IS_DIE            /* tree_type_symtab_field */
2819 };
2820
2821 const struct gcc_debug_hooks dwarf2_lineno_debug_hooks =
2822 {
2823   dwarf2out_init,
2824   debug_nothing_charstar,
2825   debug_nothing_charstar,
2826   dwarf2out_assembly_start,
2827   debug_nothing_int_charstar,
2828   debug_nothing_int_charstar,
2829   debug_nothing_int_charstar,
2830   debug_nothing_int,
2831   debug_nothing_int_int,                 /* begin_block */
2832   debug_nothing_int_int,                 /* end_block */
2833   debug_true_const_tree,                 /* ignore_block */
2834   dwarf2out_source_line,                 /* source_line */
2835   debug_nothing_int_int_charstar,        /* begin_prologue */
2836   debug_nothing_int_charstar,            /* end_prologue */
2837   debug_nothing_int_charstar,            /* begin_epilogue */
2838   debug_nothing_int_charstar,            /* end_epilogue */
2839   debug_nothing_tree,                    /* begin_function */
2840   debug_nothing_int,                     /* end_function */
2841   debug_nothing_tree,                    /* register_main_translation_unit */
2842   debug_nothing_tree,                    /* function_decl */
2843   debug_nothing_tree,                    /* early_global_decl */
2844   debug_nothing_tree,                    /* late_global_decl */
2845   debug_nothing_tree_int,                /* type_decl */
2846   debug_nothing_tree_tree_tree_bool_bool,/* imported_module_or_decl */
2847   debug_false_tree_charstarstar_uhwistar,/* die_ref_for_decl */
2848   debug_nothing_tree_charstar_uhwi,      /* register_external_die */
2849   debug_nothing_tree,                    /* deferred_inline_function */
2850   debug_nothing_tree,                    /* outlining_inline_function */
2851   debug_nothing_rtx_code_label,          /* label */
2852   debug_nothing_int,                     /* handle_pch */
2853   debug_nothing_rtx_insn,                /* var_location */
2854   debug_nothing_tree,                    /* inline_entry */
2855   debug_nothing_tree,                    /* size_function */
2856   debug_nothing_void,                    /* switch_text_section */
2857   debug_nothing_tree_tree,               /* set_name */
2858   0,                                     /* start_end_main_source_file */
2859   TYPE_SYMTAB_IS_ADDRESS                 /* tree_type_symtab_field */
2860 };
2861 \f
2862 /* NOTE: In the comments in this file, many references are made to
2863    "Debugging Information Entries".  This term is abbreviated as `DIE'
2864    throughout the remainder of this file.  */
2865
2866 /* An internal representation of the DWARF output is built, and then
2867    walked to generate the DWARF debugging info.  The walk of the internal
2868    representation is done after the entire program has been compiled.
2869    The types below are used to describe the internal representation.  */
2870
2871 /* Whether to put type DIEs into their own section .debug_types instead
2872    of making them part of the .debug_info section.  Only supported for
2873    Dwarf V4 or higher and the user didn't disable them through
2874    -fno-debug-types-section.  It is more efficient to put them in a
2875    separate comdat sections since the linker will then be able to
2876    remove duplicates.  But not all tools support .debug_types sections
2877    yet.  For Dwarf V5 or higher .debug_types doesn't exist any more,
2878    it is DW_UT_type unit type in .debug_info section.  */
2879
2880 #define use_debug_types (dwarf_version >= 4 && flag_debug_types_section)
2881
2882 /* Various DIE's use offsets relative to the beginning of the
2883    .debug_info section to refer to each other.  */
2884
2885 typedef long int dw_offset;
2886
2887 struct comdat_type_node;
2888
2889 /* The entries in the line_info table more-or-less mirror the opcodes
2890    that are used in the real dwarf line table.  Arrays of these entries
2891    are collected per section when DWARF2_ASM_LINE_DEBUG_INFO is not
2892    supported.  */
2893
2894 enum dw_line_info_opcode {
2895   /* Emit DW_LNE_set_address; the operand is the label index.  */
2896   LI_set_address,
2897
2898   /* Emit a row to the matrix with the given line.  This may be done
2899      via any combination of DW_LNS_copy, DW_LNS_advance_line, and
2900      special opcodes.  */
2901   LI_set_line,
2902
2903   /* Emit a DW_LNS_set_file.  */
2904   LI_set_file,
2905
2906   /* Emit a DW_LNS_set_column.  */
2907   LI_set_column,
2908
2909   /* Emit a DW_LNS_negate_stmt; the operand is ignored.  */
2910   LI_negate_stmt,
2911
2912   /* Emit a DW_LNS_set_prologue_end/epilogue_begin; the operand is ignored.  */
2913   LI_set_prologue_end,
2914   LI_set_epilogue_begin,
2915
2916   /* Emit a DW_LNE_set_discriminator.  */
2917   LI_set_discriminator,
2918
2919   /* Output a Fixed Advance PC; the target PC is the label index; the
2920      base PC is the previous LI_adv_address or LI_set_address entry.
2921      We only use this when emitting debug views without assembler
2922      support, at explicit user request.  Ideally, we should only use
2923      it when the offset might be zero but we can't tell: it's the only
2924      way to maybe change the PC without resetting the view number.  */
2925   LI_adv_address
2926 };
2927
2928 typedef struct GTY(()) dw_line_info_struct {
2929   enum dw_line_info_opcode opcode;
2930   unsigned int val;
2931 } dw_line_info_entry;
2932
2933
2934 struct GTY(()) dw_line_info_table {
2935   /* The label that marks the end of this section.  */
2936   const char *end_label;
2937
2938   /* The values for the last row of the matrix, as collected in the table.
2939      These are used to minimize the changes to the next row.  */
2940   unsigned int file_num;
2941   unsigned int line_num;
2942   unsigned int column_num;
2943   int discrim_num;
2944   bool is_stmt;
2945   bool in_use;
2946
2947   /* This denotes the NEXT view number.
2948
2949      If it is 0, it is known that the NEXT view will be the first view
2950      at the given PC.
2951
2952      If it is -1, we're forcing the view number to be reset, e.g. at a
2953      function entry.
2954
2955      The meaning of other nonzero values depends on whether we're
2956      computing views internally or leaving it for the assembler to do
2957      so.  If we're emitting them internally, view denotes the view
2958      number since the last known advance of PC.  If we're leaving it
2959      for the assembler, it denotes the LVU label number that we're
2960      going to ask the assembler to assign.  */
2961   var_loc_view view;
2962
2963   /* This counts the number of symbolic views emitted in this table
2964      since the latest view reset.  Its max value, over all tables,
2965      sets symview_upper_bound.  */
2966   var_loc_view symviews_since_reset;
2967
2968 #define FORCE_RESET_NEXT_VIEW(x) ((x) = (var_loc_view)-1)
2969 #define RESET_NEXT_VIEW(x) ((x) = (var_loc_view)0)
2970 #define FORCE_RESETTING_VIEW_P(x) ((x) == (var_loc_view)-1)
2971 #define RESETTING_VIEW_P(x) ((x) == (var_loc_view)0 || FORCE_RESETTING_VIEW_P (x))
2972
2973   vec<dw_line_info_entry, va_gc> *entries;
2974 };
2975
2976 /* This is an upper bound for view numbers that the assembler may
2977    assign to symbolic views output in this translation.  It is used to
2978    decide how big a field to use to represent view numbers in
2979    symview-classed attributes.  */
2980
2981 static var_loc_view symview_upper_bound;
2982
2983 /* If we're keep track of location views and their reset points, and
2984    INSN is a reset point (i.e., it necessarily advances the PC), mark
2985    the next view in TABLE as reset.  */
2986
2987 static void
2988 maybe_reset_location_view (rtx_insn *insn, dw_line_info_table *table)
2989 {
2990   if (!debug_internal_reset_location_views)
2991     return;
2992
2993   /* Maybe turn (part of?) this test into a default target hook.  */
2994   int reset = 0;
2995
2996   if (targetm.reset_location_view)
2997     reset = targetm.reset_location_view (insn);
2998
2999   if (reset)
3000     ;
3001   else if (JUMP_TABLE_DATA_P (insn))
3002     reset = 1;
3003   else if (GET_CODE (insn) == USE
3004            || GET_CODE (insn) == CLOBBER
3005            || GET_CODE (insn) == ASM_INPUT
3006            || asm_noperands (insn) >= 0)
3007     ;
3008   else if (get_attr_min_length (insn) > 0)
3009     reset = 1;
3010
3011   if (reset > 0 && !RESETTING_VIEW_P (table->view))
3012     RESET_NEXT_VIEW (table->view);
3013 }
3014
3015 /* Each DIE attribute has a field specifying the attribute kind,
3016    a link to the next attribute in the chain, and an attribute value.
3017    Attributes are typically linked below the DIE they modify.  */
3018
3019 typedef struct GTY(()) dw_attr_struct {
3020   enum dwarf_attribute dw_attr;
3021   dw_val_node dw_attr_val;
3022 }
3023 dw_attr_node;
3024
3025
3026 /* The Debugging Information Entry (DIE) structure.  DIEs form a tree.
3027    The children of each node form a circular list linked by
3028    die_sib.  die_child points to the node *before* the "first" child node.  */
3029
3030 typedef struct GTY((chain_circular ("%h.die_sib"), for_user)) die_struct {
3031   union die_symbol_or_type_node
3032     {
3033       const char * GTY ((tag ("0"))) die_symbol;
3034       comdat_type_node *GTY ((tag ("1"))) die_type_node;
3035     }
3036   GTY ((desc ("%0.comdat_type_p"))) die_id;
3037   vec<dw_attr_node, va_gc> *die_attr;
3038   dw_die_ref die_parent;
3039   dw_die_ref die_child;
3040   dw_die_ref die_sib;
3041   dw_die_ref die_definition; /* ref from a specification to its definition */
3042   dw_offset die_offset;
3043   unsigned long die_abbrev;
3044   int die_mark;
3045   unsigned int decl_id;
3046   enum dwarf_tag die_tag;
3047   /* Die is used and must not be pruned as unused.  */
3048   BOOL_BITFIELD die_perennial_p : 1;
3049   BOOL_BITFIELD comdat_type_p : 1; /* DIE has a type signature */
3050   /* For an external ref to die_symbol if die_offset contains an extra
3051      offset to that symbol.  */
3052   BOOL_BITFIELD with_offset : 1;
3053   /* Whether this DIE was removed from the DIE tree, for example via
3054      prune_unused_types.  We don't consider those present from the
3055      DIE lookup routines.  */
3056   BOOL_BITFIELD removed : 1;
3057   /* Lots of spare bits.  */
3058 }
3059 die_node;
3060
3061 /* Set to TRUE while dwarf2out_early_global_decl is running.  */
3062 static bool early_dwarf;
3063 static bool early_dwarf_finished;
3064 struct set_early_dwarf {
3065   bool saved;
3066   set_early_dwarf () : saved(early_dwarf)
3067     {
3068       gcc_assert (! early_dwarf_finished);
3069       early_dwarf = true;
3070     }
3071   ~set_early_dwarf () { early_dwarf = saved; }
3072 };
3073
3074 /* Evaluate 'expr' while 'c' is set to each child of DIE in order.  */
3075 #define FOR_EACH_CHILD(die, c, expr) do {       \
3076   c = die->die_child;                           \
3077   if (c) do {                                   \
3078     c = c->die_sib;                             \
3079     expr;                                       \
3080   } while (c != die->die_child);                \
3081 } while (0)
3082
3083 /* The pubname structure */
3084
3085 typedef struct GTY(()) pubname_struct {
3086   dw_die_ref die;
3087   const char *name;
3088 }
3089 pubname_entry;
3090
3091
3092 struct GTY(()) dw_ranges {
3093   const char *label;
3094   /* If this is positive, it's a block number, otherwise it's a
3095      bitwise-negated index into dw_ranges_by_label.  */
3096   int num;
3097   /* Index for the range list for DW_FORM_rnglistx.  */
3098   unsigned int idx : 31;
3099   /* True if this range might be possibly in a different section
3100      from previous entry.  */
3101   unsigned int maybe_new_sec : 1;
3102 };
3103
3104 /* A structure to hold a macinfo entry.  */
3105
3106 typedef struct GTY(()) macinfo_struct {
3107   unsigned char code;
3108   unsigned HOST_WIDE_INT lineno;
3109   const char *info;
3110 }
3111 macinfo_entry;
3112
3113
3114 struct GTY(()) dw_ranges_by_label {
3115   const char *begin;
3116   const char *end;
3117 };
3118
3119 /* The comdat type node structure.  */
3120 struct GTY(()) comdat_type_node
3121 {
3122   dw_die_ref root_die;
3123   dw_die_ref type_die;
3124   dw_die_ref skeleton_die;
3125   char signature[DWARF_TYPE_SIGNATURE_SIZE];
3126   comdat_type_node *next;
3127 };
3128
3129 /* A list of DIEs for which we can't determine ancestry (parent_die
3130    field) just yet.  Later in dwarf2out_finish we will fill in the
3131    missing bits.  */
3132 typedef struct GTY(()) limbo_die_struct {
3133   dw_die_ref die;
3134   /* The tree for which this DIE was created.  We use this to
3135      determine ancestry later.  */
3136   tree created_for;
3137   struct limbo_die_struct *next;
3138 }
3139 limbo_die_node;
3140
3141 typedef struct skeleton_chain_struct
3142 {
3143   dw_die_ref old_die;
3144   dw_die_ref new_die;
3145   struct skeleton_chain_struct *parent;
3146 }
3147 skeleton_chain_node;
3148
3149 /* Define a macro which returns nonzero for a TYPE_DECL which was
3150    implicitly generated for a type.
3151
3152    Note that, unlike the C front-end (which generates a NULL named
3153    TYPE_DECL node for each complete tagged type, each array type,
3154    and each function type node created) the C++ front-end generates
3155    a _named_ TYPE_DECL node for each tagged type node created.
3156    These TYPE_DECLs have DECL_ARTIFICIAL set, so we know not to
3157    generate a DW_TAG_typedef DIE for them.  Likewise with the Ada
3158    front-end, but for each type, tagged or not.  */
3159
3160 #define TYPE_DECL_IS_STUB(decl)                         \
3161   (DECL_NAME (decl) == NULL_TREE                        \
3162    || (DECL_ARTIFICIAL (decl)                           \
3163        && ((decl == TYPE_STUB_DECL (TREE_TYPE (decl)))  \
3164            /* This is necessary for stub decls that     \
3165               appear in nested inline functions.  */    \
3166            || (DECL_ABSTRACT_ORIGIN (decl) != NULL_TREE \
3167                && (decl_ultimate_origin (decl)          \
3168                    == TYPE_STUB_DECL (TREE_TYPE (decl)))))))
3169
3170 /* Information concerning the compilation unit's programming
3171    language, and compiler version.  */
3172
3173 /* Fixed size portion of the DWARF compilation unit header.  */
3174 #define DWARF_COMPILE_UNIT_HEADER_SIZE \
3175   (DWARF_INITIAL_LENGTH_SIZE + DWARF_OFFSET_SIZE                        \
3176    + (dwarf_version >= 5 ? 4 : 3))
3177
3178 /* Fixed size portion of the DWARF comdat type unit header.  */
3179 #define DWARF_COMDAT_TYPE_UNIT_HEADER_SIZE \
3180   (DWARF_COMPILE_UNIT_HEADER_SIZE                                       \
3181    + DWARF_TYPE_SIGNATURE_SIZE + DWARF_OFFSET_SIZE)
3182
3183 /* Fixed size portion of the DWARF skeleton compilation unit header.  */
3184 #define DWARF_COMPILE_UNIT_SKELETON_HEADER_SIZE \
3185   (DWARF_COMPILE_UNIT_HEADER_SIZE + (dwarf_version >= 5 ? 8 : 0))
3186
3187 /* Fixed size portion of public names info.  */
3188 #define DWARF_PUBNAMES_HEADER_SIZE (2 * DWARF_OFFSET_SIZE + 2)
3189
3190 /* Fixed size portion of the address range info.  */
3191 #define DWARF_ARANGES_HEADER_SIZE                                       \
3192   (DWARF_ROUND (DWARF_INITIAL_LENGTH_SIZE + DWARF_OFFSET_SIZE + 4,      \
3193                 DWARF2_ADDR_SIZE * 2)                                   \
3194    - DWARF_INITIAL_LENGTH_SIZE)
3195
3196 /* Size of padding portion in the address range info.  It must be
3197    aligned to twice the pointer size.  */
3198 #define DWARF_ARANGES_PAD_SIZE \
3199   (DWARF_ROUND (DWARF_INITIAL_LENGTH_SIZE + DWARF_OFFSET_SIZE + 4, \
3200                 DWARF2_ADDR_SIZE * 2)                              \
3201    - (DWARF_INITIAL_LENGTH_SIZE + DWARF_OFFSET_SIZE + 4))
3202
3203 /* Use assembler line directives if available.  */
3204 #ifndef DWARF2_ASM_LINE_DEBUG_INFO
3205 #ifdef HAVE_AS_DWARF2_DEBUG_LINE
3206 #define DWARF2_ASM_LINE_DEBUG_INFO 1
3207 #else
3208 #define DWARF2_ASM_LINE_DEBUG_INFO 0
3209 #endif
3210 #endif
3211
3212 /* Use assembler views in line directives if available.  */
3213 #ifndef DWARF2_ASM_VIEW_DEBUG_INFO
3214 #ifdef HAVE_AS_DWARF2_DEBUG_VIEW
3215 #define DWARF2_ASM_VIEW_DEBUG_INFO 1
3216 #else
3217 #define DWARF2_ASM_VIEW_DEBUG_INFO 0
3218 #endif
3219 #endif
3220
3221 /* Return true if GCC configure detected assembler support for .loc.  */
3222
3223 bool
3224 dwarf2out_default_as_loc_support (void)
3225 {
3226   return DWARF2_ASM_LINE_DEBUG_INFO;
3227 #if (GCC_VERSION >= 3000)
3228 # undef DWARF2_ASM_LINE_DEBUG_INFO
3229 # pragma GCC poison DWARF2_ASM_LINE_DEBUG_INFO
3230 #endif
3231 }
3232
3233 /* Return true if GCC configure detected assembler support for views
3234    in .loc directives.  */
3235
3236 bool
3237 dwarf2out_default_as_locview_support (void)
3238 {
3239   return DWARF2_ASM_VIEW_DEBUG_INFO;
3240 #if (GCC_VERSION >= 3000)
3241 # undef DWARF2_ASM_VIEW_DEBUG_INFO
3242 # pragma GCC poison DWARF2_ASM_VIEW_DEBUG_INFO
3243 #endif
3244 }
3245
3246 /* A bit is set in ZERO_VIEW_P if we are using the assembler-supported
3247    view computation, and it refers to a view identifier for which we
3248    will not emit a label because it is known to map to a view number
3249    zero.  We won't allocate the bitmap if we're not using assembler
3250    support for location views, but we have to make the variable
3251    visible for GGC and for code that will be optimized out for lack of
3252    support but that's still parsed and compiled.  We could abstract it
3253    out with macros, but it's not worth it.  */
3254 static GTY(()) bitmap zero_view_p;
3255
3256 /* Evaluate to TRUE iff N is known to identify the first location view
3257    at its PC.  When not using assembler location view computation,
3258    that must be view number zero.  Otherwise, ZERO_VIEW_P is allocated
3259    and views label numbers recorded in it are the ones known to be
3260    zero.  */
3261 #define ZERO_VIEW_P(N) ((N) == (var_loc_view)0                          \
3262                         || (N) == (var_loc_view)-1                      \
3263                         || (zero_view_p                                 \
3264                             && bitmap_bit_p (zero_view_p, (N))))
3265
3266 /* Return true iff we're to emit .loc directives for the assembler to
3267    generate line number sections.
3268
3269    When we're not emitting views, all we need from the assembler is
3270    support for .loc directives.
3271
3272    If we are emitting views, we can only use the assembler's .loc
3273    support if it also supports views.
3274
3275    When the compiler is emitting the line number programs and
3276    computing view numbers itself, it resets view numbers at known PC
3277    changes and counts from that, and then it emits view numbers as
3278    literal constants in locviewlists.  There are cases in which the
3279    compiler is not sure about PC changes, e.g. when extra alignment is
3280    requested for a label.  In these cases, the compiler may not reset
3281    the view counter, and the potential PC advance in the line number
3282    program will use an opcode that does not reset the view counter
3283    even if the PC actually changes, so that compiler and debug info
3284    consumer can keep view numbers in sync.
3285
3286    When the compiler defers view computation to the assembler, it
3287    emits symbolic view numbers in locviewlists, with the exception of
3288    views known to be zero (forced resets, or reset after
3289    compiler-visible PC changes): instead of emitting symbols for
3290    these, we emit literal zero and assert the assembler agrees with
3291    the compiler's assessment.  We could use symbolic views everywhere,
3292    instead of special-casing zero views, but then we'd be unable to
3293    optimize out locviewlists that contain only zeros.  */
3294
3295 static bool
3296 output_asm_line_debug_info (void)
3297 {
3298   return (dwarf2out_as_loc_support
3299           && (dwarf2out_as_locview_support
3300               || !debug_variable_location_views));
3301 }
3302
3303 /* Minimum line offset in a special line info. opcode.
3304    This value was chosen to give a reasonable range of values.  */
3305 #define DWARF_LINE_BASE  -10
3306
3307 /* First special line opcode - leave room for the standard opcodes.  */
3308 #define DWARF_LINE_OPCODE_BASE  ((int)DW_LNS_set_isa + 1)
3309
3310 /* Range of line offsets in a special line info. opcode.  */
3311 #define DWARF_LINE_RANGE  (254-DWARF_LINE_OPCODE_BASE+1)
3312
3313 /* Flag that indicates the initial value of the is_stmt_start flag.
3314    In the present implementation, we do not mark any lines as
3315    the beginning of a source statement, because that information
3316    is not made available by the GCC front-end.  */
3317 #define DWARF_LINE_DEFAULT_IS_STMT_START 1
3318
3319 /* Maximum number of operations per instruction bundle.  */
3320 #ifndef DWARF_LINE_DEFAULT_MAX_OPS_PER_INSN
3321 #define DWARF_LINE_DEFAULT_MAX_OPS_PER_INSN 1
3322 #endif
3323
3324 /* This location is used by calc_die_sizes() to keep track
3325    the offset of each DIE within the .debug_info section.  */
3326 static unsigned long next_die_offset;
3327
3328 /* Record the root of the DIE's built for the current compilation unit.  */
3329 static GTY(()) dw_die_ref single_comp_unit_die;
3330
3331 /* A list of type DIEs that have been separated into comdat sections.  */
3332 static GTY(()) comdat_type_node *comdat_type_list;
3333
3334 /* A list of CU DIEs that have been separated.  */
3335 static GTY(()) limbo_die_node *cu_die_list;
3336
3337 /* A list of DIEs with a NULL parent waiting to be relocated.  */
3338 static GTY(()) limbo_die_node *limbo_die_list;
3339
3340 /* A list of DIEs for which we may have to generate
3341    DW_AT_{,MIPS_}linkage_name once their DECL_ASSEMBLER_NAMEs are set.  */
3342 static GTY(()) limbo_die_node *deferred_asm_name;
3343
3344 struct dwarf_file_hasher : ggc_ptr_hash<dwarf_file_data>
3345 {
3346   typedef const char *compare_type;
3347
3348   static hashval_t hash (dwarf_file_data *);
3349   static bool equal (dwarf_file_data *, const char *);
3350 };
3351
3352 /* Filenames referenced by this compilation unit.  */
3353 static GTY(()) hash_table<dwarf_file_hasher> *file_table;
3354
3355 struct decl_die_hasher : ggc_ptr_hash<die_node>
3356 {
3357   typedef tree compare_type;
3358
3359   static hashval_t hash (die_node *);
3360   static bool equal (die_node *, tree);
3361 };
3362 /* A hash table of references to DIE's that describe declarations.
3363    The key is a DECL_UID() which is a unique number identifying each decl.  */
3364 static GTY (()) hash_table<decl_die_hasher> *decl_die_table;
3365
3366 struct GTY ((for_user)) variable_value_struct {
3367   unsigned int decl_id;
3368   vec<dw_die_ref, va_gc> *dies;
3369 };
3370
3371 struct variable_value_hasher : ggc_ptr_hash<variable_value_struct>
3372 {
3373   typedef tree compare_type;
3374
3375   static hashval_t hash (variable_value_struct *);
3376   static bool equal (variable_value_struct *, tree);
3377 };
3378 /* A hash table of DIEs that contain DW_OP_GNU_variable_value with
3379    dw_val_class_decl_ref class, indexed by FUNCTION_DECLs which is
3380    DECL_CONTEXT of the referenced VAR_DECLs.  */
3381 static GTY (()) hash_table<variable_value_hasher> *variable_value_hash;
3382
3383 struct block_die_hasher : ggc_ptr_hash<die_struct>
3384 {
3385   static hashval_t hash (die_struct *);
3386   static bool equal (die_struct *, die_struct *);
3387 };
3388
3389 /* A hash table of references to DIE's that describe COMMON blocks.
3390    The key is DECL_UID() ^ die_parent.  */
3391 static GTY (()) hash_table<block_die_hasher> *common_block_die_table;
3392
3393 typedef struct GTY(()) die_arg_entry_struct {
3394     dw_die_ref die;
3395     tree arg;
3396 } die_arg_entry;
3397
3398
3399 /* Node of the variable location list.  */
3400 struct GTY ((chain_next ("%h.next"))) var_loc_node {
3401   /* Either NOTE_INSN_VAR_LOCATION, or, for SRA optimized variables,
3402      EXPR_LIST chain.  For small bitsizes, bitsize is encoded
3403      in mode of the EXPR_LIST node and first EXPR_LIST operand
3404      is either NOTE_INSN_VAR_LOCATION for a piece with a known
3405      location or NULL for padding.  For larger bitsizes,
3406      mode is 0 and first operand is a CONCAT with bitsize
3407      as first CONCAT operand and NOTE_INSN_VAR_LOCATION resp.
3408      NULL as second operand.  */
3409   rtx GTY (()) loc;
3410   const char * GTY (()) label;
3411   struct var_loc_node * GTY (()) next;
3412   var_loc_view view;
3413 };
3414
3415 /* Variable location list.  */
3416 struct GTY ((for_user)) var_loc_list_def {
3417   struct var_loc_node * GTY (()) first;
3418
3419   /* Pointer to the last but one or last element of the
3420      chained list.  If the list is empty, both first and
3421      last are NULL, if the list contains just one node
3422      or the last node certainly is not redundant, it points
3423      to the last node, otherwise points to the last but one.
3424      Do not mark it for GC because it is marked through the chain.  */
3425   struct var_loc_node * GTY ((skip ("%h"))) last;
3426
3427   /* Pointer to the last element before section switch,
3428      if NULL, either sections weren't switched or first
3429      is after section switch.  */
3430   struct var_loc_node * GTY ((skip ("%h"))) last_before_switch;
3431
3432   /* DECL_UID of the variable decl.  */
3433   unsigned int decl_id;
3434 };
3435 typedef struct var_loc_list_def var_loc_list;
3436
3437 /* Call argument location list.  */
3438 struct GTY ((chain_next ("%h.next"))) call_arg_loc_node {
3439   rtx GTY (()) call_arg_loc_note;
3440   const char * GTY (()) label;
3441   tree GTY (()) block;
3442   bool tail_call_p;
3443   rtx GTY (()) symbol_ref;
3444   struct call_arg_loc_node * GTY (()) next;
3445 };
3446
3447
3448 struct decl_loc_hasher : ggc_ptr_hash<var_loc_list>
3449 {
3450   typedef const_tree compare_type;
3451
3452   static hashval_t hash (var_loc_list *);
3453   static bool equal (var_loc_list *, const_tree);
3454 };
3455
3456 /* Table of decl location linked lists.  */
3457 static GTY (()) hash_table<decl_loc_hasher> *decl_loc_table;
3458
3459 /* Head and tail of call_arg_loc chain.  */
3460 static GTY (()) struct call_arg_loc_node *call_arg_locations;
3461 static struct call_arg_loc_node *call_arg_loc_last;
3462
3463 /* Number of call sites in the current function.  */
3464 static int call_site_count = -1;
3465 /* Number of tail call sites in the current function.  */
3466 static int tail_call_site_count = -1;
3467
3468 /* A cached location list.  */
3469 struct GTY ((for_user)) cached_dw_loc_list_def {
3470   /* The DECL_UID of the decl that this entry describes.  */
3471   unsigned int decl_id;
3472
3473   /* The cached location list.  */
3474   dw_loc_list_ref loc_list;
3475 };
3476 typedef struct cached_dw_loc_list_def cached_dw_loc_list;
3477
3478 struct dw_loc_list_hasher : ggc_ptr_hash<cached_dw_loc_list>
3479 {
3480
3481   typedef const_tree compare_type;
3482   
3483   static hashval_t hash (cached_dw_loc_list *);
3484   static bool equal (cached_dw_loc_list *, const_tree);
3485 };
3486
3487 /* Table of cached location lists.  */
3488 static GTY (()) hash_table<dw_loc_list_hasher> *cached_dw_loc_list_table;
3489
3490 /* A vector of references to DIE's that are uniquely identified by their tag,
3491    presence/absence of children DIE's, and list of attribute/value pairs.  */
3492 static GTY(()) vec<dw_die_ref, va_gc> *abbrev_die_table;
3493
3494 /* A hash map to remember the stack usage for DWARF procedures.  The value
3495    stored is the stack size difference between before the DWARF procedure
3496    invokation and after it returned.  In other words, for a DWARF procedure
3497    that consumes N stack slots and that pushes M ones, this stores M - N.  */
3498 static hash_map<dw_die_ref, int> *dwarf_proc_stack_usage_map;
3499
3500 /* A global counter for generating labels for line number data.  */
3501 static unsigned int line_info_label_num;
3502
3503 /* The current table to which we should emit line number information
3504    for the current function.  This will be set up at the beginning of
3505    assembly for the function.  */
3506 static GTY(()) dw_line_info_table *cur_line_info_table;
3507
3508 /* The two default tables of line number info.  */
3509 static GTY(()) dw_line_info_table *text_section_line_info;
3510 static GTY(()) dw_line_info_table *cold_text_section_line_info;
3511
3512 /* The set of all non-default tables of line number info.  */
3513 static GTY(()) vec<dw_line_info_table *, va_gc> *separate_line_info;
3514
3515 /* A flag to tell pubnames/types export if there is an info section to
3516    refer to.  */
3517 static bool info_section_emitted;
3518
3519 /* A pointer to the base of a table that contains a list of publicly
3520    accessible names.  */
3521 static GTY (()) vec<pubname_entry, va_gc> *pubname_table;
3522
3523 /* A pointer to the base of a table that contains a list of publicly
3524    accessible types.  */
3525 static GTY (()) vec<pubname_entry, va_gc> *pubtype_table;
3526
3527 /* A pointer to the base of a table that contains a list of macro
3528    defines/undefines (and file start/end markers).  */
3529 static GTY (()) vec<macinfo_entry, va_gc> *macinfo_table;
3530
3531 /* True if .debug_macinfo or .debug_macros section is going to be
3532    emitted.  */
3533 #define have_macinfo \
3534   ((!XCOFF_DEBUGGING_INFO || HAVE_XCOFF_DWARF_EXTRAS) \
3535    && debug_info_level >= DINFO_LEVEL_VERBOSE \
3536    && !macinfo_table->is_empty ())
3537
3538 /* Vector of dies for which we should generate .debug_ranges info.  */
3539 static GTY (()) vec<dw_ranges, va_gc> *ranges_table;
3540
3541 /* Vector of pairs of labels referenced in ranges_table.  */
3542 static GTY (()) vec<dw_ranges_by_label, va_gc> *ranges_by_label;
3543
3544 /* Whether we have location lists that need outputting */
3545 static GTY(()) bool have_location_lists;
3546
3547 /* Unique label counter.  */
3548 static GTY(()) unsigned int loclabel_num;
3549
3550 /* Unique label counter for point-of-call tables.  */
3551 static GTY(()) unsigned int poc_label_num;
3552
3553 /* The last file entry emitted by maybe_emit_file().  */
3554 static GTY(()) struct dwarf_file_data * last_emitted_file;
3555
3556 /* Number of internal labels generated by gen_internal_sym().  */
3557 static GTY(()) int label_num;
3558
3559 static GTY(()) vec<die_arg_entry, va_gc> *tmpl_value_parm_die_table;
3560
3561 /* Instances of generic types for which we need to generate debug
3562    info that describe their generic parameters and arguments. That
3563    generation needs to happen once all types are properly laid out so
3564    we do it at the end of compilation.  */
3565 static GTY(()) vec<tree, va_gc> *generic_type_instances;
3566
3567 /* Offset from the "steady-state frame pointer" to the frame base,
3568    within the current function.  */
3569 static poly_int64 frame_pointer_fb_offset;
3570 static bool frame_pointer_fb_offset_valid;
3571
3572 static vec<dw_die_ref> base_types;
3573
3574 /* Flags to represent a set of attribute classes for attributes that represent
3575    a scalar value (bounds, pointers, ...).  */
3576 enum dw_scalar_form
3577 {
3578   dw_scalar_form_constant = 0x01,
3579   dw_scalar_form_exprloc = 0x02,
3580   dw_scalar_form_reference = 0x04
3581 };
3582
3583 /* Forward declarations for functions defined in this file.  */
3584
3585 static int is_pseudo_reg (const_rtx);
3586 static tree type_main_variant (tree);
3587 static int is_tagged_type (const_tree);
3588 static const char *dwarf_tag_name (unsigned);
3589 static const char *dwarf_attr_name (unsigned);
3590 static const char *dwarf_form_name (unsigned);
3591 static tree decl_ultimate_origin (const_tree);
3592 static tree decl_class_context (tree);
3593 static void add_dwarf_attr (dw_die_ref, dw_attr_node *);
3594 static inline enum dw_val_class AT_class (dw_attr_node *);
3595 static inline unsigned int AT_index (dw_attr_node *);
3596 static void add_AT_flag (dw_die_ref, enum dwarf_attribute, unsigned);
3597 static inline unsigned AT_flag (dw_attr_node *);
3598 static void add_AT_int (dw_die_ref, enum dwarf_attribute, HOST_WIDE_INT);
3599 static inline HOST_WIDE_INT AT_int (dw_attr_node *);
3600 static void add_AT_unsigned (dw_die_ref, enum dwarf_attribute, unsigned HOST_WIDE_INT);
3601 static inline unsigned HOST_WIDE_INT AT_unsigned (dw_attr_node *);
3602 static void add_AT_double (dw_die_ref, enum dwarf_attribute,
3603                            HOST_WIDE_INT, unsigned HOST_WIDE_INT);
3604 static inline void add_AT_vec (dw_die_ref, enum dwarf_attribute, unsigned int,
3605                                unsigned int, unsigned char *);
3606 static void add_AT_data8 (dw_die_ref, enum dwarf_attribute, unsigned char *);
3607 static void add_AT_string (dw_die_ref, enum dwarf_attribute, const char *);
3608 static inline const char *AT_string (dw_attr_node *);
3609 static enum dwarf_form AT_string_form (dw_attr_node *);
3610 static void add_AT_die_ref (dw_die_ref, enum dwarf_attribute, dw_die_ref);
3611 static void add_AT_specification (dw_die_ref, dw_die_ref);
3612 static inline dw_die_ref AT_ref (dw_attr_node *);
3613 static inline int AT_ref_external (dw_attr_node *);
3614 static inline void set_AT_ref_external (dw_attr_node *, int);
3615 static void add_AT_fde_ref (dw_die_ref, enum dwarf_attribute, unsigned);
3616 static void add_AT_loc (dw_die_ref, enum dwarf_attribute, dw_loc_descr_ref);
3617 static inline dw_loc_descr_ref AT_loc (dw_attr_node *);
3618 static void add_AT_loc_list (dw_die_ref, enum dwarf_attribute,
3619                              dw_loc_list_ref);
3620 static inline dw_loc_list_ref AT_loc_list (dw_attr_node *);
3621 static void add_AT_view_list (dw_die_ref, enum dwarf_attribute);
3622 static inline dw_loc_list_ref AT_loc_list (dw_attr_node *);
3623 static addr_table_entry *add_addr_table_entry (void *, enum ate_kind);
3624 static void remove_addr_table_entry (addr_table_entry *);
3625 static void add_AT_addr (dw_die_ref, enum dwarf_attribute, rtx, bool);
3626 static inline rtx AT_addr (dw_attr_node *);
3627 static void add_AT_symview (dw_die_ref, enum dwarf_attribute, const char *);
3628 static void add_AT_lbl_id (dw_die_ref, enum dwarf_attribute, const char *);
3629 static void add_AT_lineptr (dw_die_ref, enum dwarf_attribute, const char *);
3630 static void add_AT_macptr (dw_die_ref, enum dwarf_attribute, const char *);
3631 static void add_AT_loclistsptr (dw_die_ref, enum dwarf_attribute,
3632                                 const char *);
3633 static void add_AT_offset (dw_die_ref, enum dwarf_attribute,
3634                            unsigned HOST_WIDE_INT);
3635 static void add_AT_range_list (dw_die_ref, enum dwarf_attribute,
3636                                unsigned long, bool);
3637 static inline const char *AT_lbl (dw_attr_node *);
3638 static dw_attr_node *get_AT (dw_die_ref, enum dwarf_attribute);
3639 static const char *get_AT_low_pc (dw_die_ref);
3640 static const char *get_AT_hi_pc (dw_die_ref);
3641 static const char *get_AT_string (dw_die_ref, enum dwarf_attribute);
3642 static int get_AT_flag (dw_die_ref, enum dwarf_attribute);
3643 static unsigned get_AT_unsigned (dw_die_ref, enum dwarf_attribute);
3644 static inline dw_die_ref get_AT_ref (dw_die_ref, enum dwarf_attribute);
3645 static bool is_cxx (void);
3646 static bool is_cxx (const_tree);
3647 static bool is_fortran (void);
3648 static bool is_ada (void);
3649 static bool remove_AT (dw_die_ref, enum dwarf_attribute);
3650 static void remove_child_TAG (dw_die_ref, enum dwarf_tag);
3651 static void add_child_die (dw_die_ref, dw_die_ref);
3652 static dw_die_ref new_die (enum dwarf_tag, dw_die_ref, tree);
3653 static dw_die_ref lookup_type_die (tree);
3654 static dw_die_ref strip_naming_typedef (tree, dw_die_ref);
3655 static dw_die_ref lookup_type_die_strip_naming_typedef (tree);
3656 static void equate_type_number_to_die (tree, dw_die_ref);
3657 static dw_die_ref lookup_decl_die (tree);
3658 static var_loc_list *lookup_decl_loc (const_tree);
3659 static void equate_decl_number_to_die (tree, dw_die_ref);
3660 static struct var_loc_node *add_var_loc_to_decl (tree, rtx, const char *, var_loc_view);
3661 static void print_spaces (FILE *);
3662 static void print_die (dw_die_ref, FILE *);
3663 static void loc_checksum (dw_loc_descr_ref, struct md5_ctx *);
3664 static void attr_checksum (dw_attr_node *, struct md5_ctx *, int *);
3665 static void die_checksum (dw_die_ref, struct md5_ctx *, int *);
3666 static void checksum_sleb128 (HOST_WIDE_INT, struct md5_ctx *);
3667 static void checksum_uleb128 (unsigned HOST_WIDE_INT, struct md5_ctx *);
3668 static void loc_checksum_ordered (dw_loc_descr_ref, struct md5_ctx *);
3669 static void attr_checksum_ordered (enum dwarf_tag, dw_attr_node *,
3670                                    struct md5_ctx *, int *);
3671 struct checksum_attributes;
3672 static void collect_checksum_attributes (struct checksum_attributes *, dw_die_ref);
3673 static void die_checksum_ordered (dw_die_ref, struct md5_ctx *, int *);
3674 static void checksum_die_context (dw_die_ref, struct md5_ctx *);
3675 static void generate_type_signature (dw_die_ref, comdat_type_node *);
3676 static int same_loc_p (dw_loc_descr_ref, dw_loc_descr_ref, int *);
3677 static int same_dw_val_p (const dw_val_node *, const dw_val_node *, int *);
3678 static int same_attr_p (dw_attr_node *, dw_attr_node *, int *);
3679 static int same_die_p (dw_die_ref, dw_die_ref, int *);
3680 static int is_type_die (dw_die_ref);
3681 static int is_comdat_die (dw_die_ref);
3682 static inline bool is_template_instantiation (dw_die_ref);
3683 static int is_declaration_die (dw_die_ref);
3684 static int should_move_die_to_comdat (dw_die_ref);
3685 static dw_die_ref clone_as_declaration (dw_die_ref);
3686 static dw_die_ref clone_die (dw_die_ref);
3687 static dw_die_ref clone_tree (dw_die_ref);
3688 static dw_die_ref copy_declaration_context (dw_die_ref, dw_die_ref);
3689 static void generate_skeleton_ancestor_tree (skeleton_chain_node *);
3690 static void generate_skeleton_bottom_up (skeleton_chain_node *);
3691 static dw_die_ref generate_skeleton (dw_die_ref);
3692 static dw_die_ref remove_child_or_replace_with_skeleton (dw_die_ref,
3693                                                          dw_die_ref,
3694                                                          dw_die_ref);
3695 static void break_out_comdat_types (dw_die_ref);
3696 static void copy_decls_for_unworthy_types (dw_die_ref);
3697
3698 static void add_sibling_attributes (dw_die_ref);
3699 static void output_location_lists (dw_die_ref);
3700 static int constant_size (unsigned HOST_WIDE_INT);
3701 static unsigned long size_of_die (dw_die_ref);
3702 static void calc_die_sizes (dw_die_ref);
3703 static void calc_base_type_die_sizes (void);
3704 static void mark_dies (dw_die_ref);
3705 static void unmark_dies (dw_die_ref);
3706 static void unmark_all_dies (dw_die_ref);
3707 static unsigned long size_of_pubnames (vec<pubname_entry, va_gc> *);
3708 static unsigned long size_of_aranges (void);
3709 static enum dwarf_form value_format (dw_attr_node *);
3710 static void output_value_format (dw_attr_node *);
3711 static void output_abbrev_section (void);
3712 static void output_die_abbrevs (unsigned long, dw_die_ref);
3713 static void output_die (dw_die_ref);
3714 static void output_compilation_unit_header (enum dwarf_unit_type);
3715 static void output_comp_unit (dw_die_ref, int, const unsigned char *);
3716 static void output_comdat_type_unit (comdat_type_node *);
3717 static const char *dwarf2_name (tree, int);
3718 static void add_pubname (tree, dw_die_ref);
3719 static void add_enumerator_pubname (const char *, dw_die_ref);
3720 static void add_pubname_string (const char *, dw_die_ref);
3721 static void add_pubtype (tree, dw_die_ref);
3722 static void output_pubnames (vec<pubname_entry, va_gc> *);
3723 static void output_aranges (void);
3724 static unsigned int add_ranges (const_tree, bool = false);
3725 static void add_ranges_by_labels (dw_die_ref, const char *, const char *,
3726                                   bool *, bool);
3727 static void output_ranges (void);
3728 static dw_line_info_table *new_line_info_table (void);
3729 static void output_line_info (bool);
3730 static void output_file_names (void);
3731 static dw_die_ref base_type_die (tree, bool);
3732 static int is_base_type (tree);
3733 static dw_die_ref subrange_type_die (tree, tree, tree, tree, dw_die_ref);
3734 static int decl_quals (const_tree);
3735 static dw_die_ref modified_type_die (tree, int, bool, dw_die_ref);
3736 static dw_die_ref generic_parameter_die (tree, tree, bool, dw_die_ref);
3737 static dw_die_ref template_parameter_pack_die (tree, tree, dw_die_ref);
3738 static int type_is_enum (const_tree);
3739 static unsigned int dbx_reg_number (const_rtx);
3740 static void add_loc_descr_op_piece (dw_loc_descr_ref *, int);
3741 static dw_loc_descr_ref reg_loc_descriptor (rtx, enum var_init_status);
3742 static dw_loc_descr_ref one_reg_loc_descriptor (unsigned int,
3743                                                 enum var_init_status);
3744 static dw_loc_descr_ref multiple_reg_loc_descriptor (rtx, rtx,
3745                                                      enum var_init_status);
3746 static dw_loc_descr_ref based_loc_descr (rtx, poly_int64,
3747                                          enum var_init_status);
3748 static int is_based_loc (const_rtx);
3749 static bool resolve_one_addr (rtx *);
3750 static dw_loc_descr_ref concat_loc_descriptor (rtx, rtx,
3751                                                enum var_init_status);
3752 static dw_loc_descr_ref loc_descriptor (rtx, machine_mode mode,
3753                                         enum var_init_status);
3754 struct loc_descr_context;
3755 static void add_loc_descr_to_each (dw_loc_list_ref list, dw_loc_descr_ref ref);
3756 static void add_loc_list (dw_loc_list_ref *ret, dw_loc_list_ref list);
3757 static dw_loc_list_ref loc_list_from_tree (tree, int,
3758                                            struct loc_descr_context *);
3759 static dw_loc_descr_ref loc_descriptor_from_tree (tree, int,
3760                                                   struct loc_descr_context *);
3761 static HOST_WIDE_INT ceiling (HOST_WIDE_INT, unsigned int);
3762 static tree field_type (const_tree);
3763 static unsigned int simple_type_align_in_bits (const_tree);
3764 static unsigned int simple_decl_align_in_bits (const_tree);
3765 static unsigned HOST_WIDE_INT simple_type_size_in_bits (const_tree);
3766 struct vlr_context;
3767 static dw_loc_descr_ref field_byte_offset (const_tree, struct vlr_context *,
3768                                            HOST_WIDE_INT *);
3769 static void add_AT_location_description (dw_die_ref, enum dwarf_attribute,
3770                                          dw_loc_list_ref);
3771 static void add_data_member_location_attribute (dw_die_ref, tree,
3772                                                 struct vlr_context *);
3773 static bool add_const_value_attribute (dw_die_ref, rtx);
3774 static void insert_int (HOST_WIDE_INT, unsigned, unsigned char *);
3775 static void insert_wide_int (const wide_int &, unsigned char *, int);
3776 static void insert_float (const_rtx, unsigned char *);
3777 static rtx rtl_for_decl_location (tree);
3778 static bool add_location_or_const_value_attribute (dw_die_ref, tree, bool);
3779 static bool tree_add_const_value_attribute (dw_die_ref, tree);
3780 static bool tree_add_const_value_attribute_for_decl (dw_die_ref, tree);
3781 static void add_name_attribute (dw_die_ref, const char *);
3782 static void add_gnat_descriptive_type_attribute (dw_die_ref, tree, dw_die_ref);
3783 static void add_comp_dir_attribute (dw_die_ref);
3784 static void add_scalar_info (dw_die_ref, enum dwarf_attribute, tree, int,
3785                              struct loc_descr_context *);
3786 static void add_bound_info (dw_die_ref, enum dwarf_attribute, tree,
3787                             struct loc_descr_context *);
3788 static void add_subscript_info (dw_die_ref, tree, bool);
3789 static void add_byte_size_attribute (dw_die_ref, tree);
3790 static void add_alignment_attribute (dw_die_ref, tree);
3791 static inline void add_bit_offset_attribute (dw_die_ref, tree,
3792                                              struct vlr_context *);
3793 static void add_bit_size_attribute (dw_die_ref, tree);
3794 static void add_prototyped_attribute (dw_die_ref, tree);
3795 static dw_die_ref add_abstract_origin_attribute (dw_die_ref, tree);
3796 static void add_pure_or_virtual_attribute (dw_die_ref, tree);
3797 static void add_src_coords_attributes (dw_die_ref, tree);
3798 static void add_name_and_src_coords_attributes (dw_die_ref, tree, bool = false);
3799 static void add_discr_value (dw_die_ref, dw_discr_value *);
3800 static void add_discr_list (dw_die_ref, dw_discr_list_ref);
3801 static inline dw_discr_list_ref AT_discr_list (dw_attr_node *);
3802 static void push_decl_scope (tree);
3803 static void pop_decl_scope (void);
3804 static dw_die_ref scope_die_for (tree, dw_die_ref);
3805 static inline int local_scope_p (dw_die_ref);
3806 static inline int class_scope_p (dw_die_ref);
3807 static inline int class_or_namespace_scope_p (dw_die_ref);
3808 static void add_type_attribute (dw_die_ref, tree, int, bool, dw_die_ref);
3809 static void add_calling_convention_attribute (dw_die_ref, tree);
3810 static const char *type_tag (const_tree);
3811 static tree member_declared_type (const_tree);
3812 #if 0
3813 static const char *decl_start_label (tree);
3814 #endif
3815 static void gen_array_type_die (tree, dw_die_ref);
3816 static void gen_descr_array_type_die (tree, struct array_descr_info *, dw_die_ref);
3817 #if 0
3818 static void gen_entry_point_die (tree, dw_die_ref);
3819 #endif
3820 static dw_die_ref gen_enumeration_type_die (tree, dw_die_ref);
3821 static dw_die_ref gen_formal_parameter_die (tree, tree, bool, dw_die_ref);
3822 static dw_die_ref gen_formal_parameter_pack_die  (tree, tree, dw_die_ref, tree*);
3823 static void gen_unspecified_parameters_die (tree, dw_die_ref);
3824 static void gen_formal_types_die (tree, dw_die_ref);
3825 static void gen_subprogram_die (tree, dw_die_ref);
3826 static void gen_variable_die (tree, tree, dw_die_ref);
3827 static void gen_const_die (tree, dw_die_ref);
3828 static void gen_label_die (tree, dw_die_ref);
3829 static void gen_lexical_block_die (tree, dw_die_ref);
3830 static void gen_inlined_subroutine_die (tree, dw_die_ref);
3831 static void gen_field_die (tree, struct vlr_context *, dw_die_ref);
3832 static void gen_ptr_to_mbr_type_die (tree, dw_die_ref);
3833 static dw_die_ref gen_compile_unit_die (const char *);
3834 static void gen_inheritance_die (tree, tree, tree, dw_die_ref);
3835 static void gen_member_die (tree, dw_die_ref);
3836 static void gen_struct_or_union_type_die (tree, dw_die_ref,
3837                                                 enum debug_info_usage);
3838 static void gen_subroutine_type_die (tree, dw_die_ref);
3839 static void gen_typedef_die (tree, dw_die_ref);
3840 static void gen_type_die (tree, dw_die_ref);
3841 static void gen_block_die (tree, dw_die_ref);
3842 static void decls_for_scope (tree, dw_die_ref);
3843 static bool is_naming_typedef_decl (const_tree);
3844 static inline dw_die_ref get_context_die (tree);
3845 static void gen_namespace_die (tree, dw_die_ref);
3846 static dw_die_ref gen_namelist_decl (tree, dw_die_ref, tree);
3847 static dw_die_ref gen_decl_die (tree, tree, struct vlr_context *, dw_die_ref);
3848 static dw_die_ref force_decl_die (tree);
3849 static dw_die_ref force_type_die (tree);
3850 static dw_die_ref setup_namespace_context (tree, dw_die_ref);
3851 static dw_die_ref declare_in_namespace (tree, dw_die_ref);
3852 static struct dwarf_file_data * lookup_filename (const char *);
3853 static void retry_incomplete_types (void);
3854 static void gen_type_die_for_member (tree, tree, dw_die_ref);
3855 static void gen_generic_params_dies (tree);
3856 static void gen_tagged_type_die (tree, dw_die_ref, enum debug_info_usage);
3857 static void gen_type_die_with_usage (tree, dw_die_ref, enum debug_info_usage);
3858 static void splice_child_die (dw_die_ref, dw_die_ref);
3859 static int file_info_cmp (const void *, const void *);
3860 static dw_loc_list_ref new_loc_list (dw_loc_descr_ref, const char *, var_loc_view,
3861                                      const char *, var_loc_view, const char *);
3862 static void output_loc_list (dw_loc_list_ref);
3863 static char *gen_internal_sym (const char *);
3864 static bool want_pubnames (void);
3865
3866 static void prune_unmark_dies (dw_die_ref);
3867 static void prune_unused_types_mark_generic_parms_dies (dw_die_ref);
3868 static void prune_unused_types_mark (dw_die_ref, int);
3869 static void prune_unused_types_walk (dw_die_ref);
3870 static void prune_unused_types_walk_attribs (dw_die_ref);
3871 static void prune_unused_types_prune (dw_die_ref);
3872 static void prune_unused_types (void);
3873 static int maybe_emit_file (struct dwarf_file_data *fd);
3874 static inline const char *AT_vms_delta1 (dw_attr_node *);
3875 static inline const char *AT_vms_delta2 (dw_attr_node *);
3876 static inline void add_AT_vms_delta (dw_die_ref, enum dwarf_attribute,
3877                                      const char *, const char *);
3878 static void append_entry_to_tmpl_value_parm_die_table (dw_die_ref, tree);
3879 static void gen_remaining_tmpl_value_param_die_attribute (void);
3880 static bool generic_type_p (tree);
3881 static void schedule_generic_params_dies_gen (tree t);
3882 static void gen_scheduled_generic_parms_dies (void);
3883 static void resolve_variable_values (void);
3884
3885 static const char *comp_dir_string (void);
3886
3887 static void hash_loc_operands (dw_loc_descr_ref, inchash::hash &);
3888
3889 /* enum for tracking thread-local variables whose address is really an offset
3890    relative to the TLS pointer, which will need link-time relocation, but will
3891    not need relocation by the DWARF consumer.  */
3892
3893 enum dtprel_bool
3894 {
3895   dtprel_false = 0,
3896   dtprel_true = 1
3897 };
3898
3899 /* Return the operator to use for an address of a variable.  For dtprel_true, we
3900    use DW_OP_const*.  For regular variables, which need both link-time
3901    relocation and consumer-level relocation (e.g., to account for shared objects
3902    loaded at a random address), we use DW_OP_addr*.  */
3903
3904 static inline enum dwarf_location_atom
3905 dw_addr_op (enum dtprel_bool dtprel)
3906 {
3907   if (dtprel == dtprel_true)
3908     return (dwarf_split_debug_info ? DW_OP_GNU_const_index
3909             : (DWARF2_ADDR_SIZE == 4 ? DW_OP_const4u : DW_OP_const8u));
3910   else
3911     return dwarf_split_debug_info ? DW_OP_GNU_addr_index : DW_OP_addr;
3912 }
3913
3914 /* Return a pointer to a newly allocated address location description.  If
3915    dwarf_split_debug_info is true, then record the address with the appropriate
3916    relocation.  */
3917 static inline dw_loc_descr_ref
3918 new_addr_loc_descr (rtx addr, enum dtprel_bool dtprel)
3919 {
3920   dw_loc_descr_ref ref = new_loc_descr (dw_addr_op (dtprel), 0, 0);
3921
3922   ref->dw_loc_oprnd1.val_class = dw_val_class_addr;
3923   ref->dw_loc_oprnd1.v.val_addr = addr;
3924   ref->dtprel = dtprel;
3925   if (dwarf_split_debug_info)
3926     ref->dw_loc_oprnd1.val_entry
3927       = add_addr_table_entry (addr,
3928                               dtprel ? ate_kind_rtx_dtprel : ate_kind_rtx);
3929   else
3930     ref->dw_loc_oprnd1.val_entry = NULL;
3931
3932   return ref;
3933 }
3934
3935 /* Section names used to hold DWARF debugging information.  */
3936
3937 #ifndef DEBUG_INFO_SECTION
3938 #define DEBUG_INFO_SECTION      ".debug_info"
3939 #endif
3940 #ifndef DEBUG_DWO_INFO_SECTION
3941 #define DEBUG_DWO_INFO_SECTION ".debug_info.dwo"
3942 #endif
3943 #ifndef DEBUG_LTO_INFO_SECTION
3944 #define DEBUG_LTO_INFO_SECTION  ".gnu.debuglto_.debug_info"
3945 #endif
3946 #ifndef DEBUG_LTO_DWO_INFO_SECTION
3947 #define DEBUG_LTO_DWO_INFO_SECTION ".gnu.debuglto_.debug_info.dwo"
3948 #endif
3949 #ifndef DEBUG_ABBREV_SECTION
3950 #define DEBUG_ABBREV_SECTION    ".debug_abbrev"
3951 #endif
3952 #ifndef DEBUG_LTO_ABBREV_SECTION
3953 #define DEBUG_LTO_ABBREV_SECTION ".gnu.debuglto_.debug_abbrev"
3954 #endif
3955 #ifndef DEBUG_DWO_ABBREV_SECTION
3956 #define DEBUG_DWO_ABBREV_SECTION ".debug_abbrev.dwo"
3957 #endif
3958 #ifndef DEBUG_LTO_DWO_ABBREV_SECTION
3959 #define DEBUG_LTO_DWO_ABBREV_SECTION ".gnu.debuglto_.debug_abbrev.dwo"
3960 #endif
3961 #ifndef DEBUG_ARANGES_SECTION
3962 #define DEBUG_ARANGES_SECTION   ".debug_aranges"
3963 #endif
3964 #ifndef DEBUG_ADDR_SECTION
3965 #define DEBUG_ADDR_SECTION     ".debug_addr"
3966 #endif
3967 #ifndef DEBUG_MACINFO_SECTION
3968 #define DEBUG_MACINFO_SECTION     ".debug_macinfo"
3969 #endif
3970 #ifndef DEBUG_LTO_MACINFO_SECTION
3971 #define DEBUG_LTO_MACINFO_SECTION      ".gnu.debuglto_.debug_macinfo"
3972 #endif
3973 #ifndef DEBUG_DWO_MACINFO_SECTION
3974 #define DEBUG_DWO_MACINFO_SECTION      ".debug_macinfo.dwo"
3975 #endif
3976 #ifndef DEBUG_LTO_DWO_MACINFO_SECTION
3977 #define DEBUG_LTO_DWO_MACINFO_SECTION  ".gnu.debuglto_.debug_macinfo.dwo"
3978 #endif
3979 #ifndef DEBUG_MACRO_SECTION
3980 #define DEBUG_MACRO_SECTION     ".debug_macro"
3981 #endif
3982 #ifndef DEBUG_LTO_MACRO_SECTION
3983 #define DEBUG_LTO_MACRO_SECTION ".gnu.debuglto_.debug_macro"
3984 #endif
3985 #ifndef DEBUG_DWO_MACRO_SECTION
3986 #define DEBUG_DWO_MACRO_SECTION        ".debug_macro.dwo"
3987 #endif
3988 #ifndef DEBUG_LTO_DWO_MACRO_SECTION
3989 #define DEBUG_LTO_DWO_MACRO_SECTION    ".gnu.debuglto_.debug_macro.dwo"
3990 #endif
3991 #ifndef DEBUG_LINE_SECTION
3992 #define DEBUG_LINE_SECTION      ".debug_line"
3993 #endif
3994 #ifndef DEBUG_LTO_LINE_SECTION
3995 #define DEBUG_LTO_LINE_SECTION ".gnu.debuglto_.debug_line"
3996 #endif
3997 #ifndef DEBUG_DWO_LINE_SECTION
3998 #define DEBUG_DWO_LINE_SECTION ".debug_line.dwo"
3999 #endif
4000 #ifndef DEBUG_LTO_DWO_LINE_SECTION
4001 #define DEBUG_LTO_DWO_LINE_SECTION ".gnu.debuglto_.debug_line.dwo"
4002 #endif
4003 #ifndef DEBUG_LOC_SECTION
4004 #define DEBUG_LOC_SECTION       ".debug_loc"
4005 #endif
4006 #ifndef DEBUG_DWO_LOC_SECTION
4007 #define DEBUG_DWO_LOC_SECTION  ".debug_loc.dwo"
4008 #endif
4009 #ifndef DEBUG_LOCLISTS_SECTION
4010 #define DEBUG_LOCLISTS_SECTION  ".debug_loclists"
4011 #endif
4012 #ifndef DEBUG_DWO_LOCLISTS_SECTION
4013 #define DEBUG_DWO_LOCLISTS_SECTION  ".debug_loclists.dwo"
4014 #endif
4015 #ifndef DEBUG_PUBNAMES_SECTION
4016 #define DEBUG_PUBNAMES_SECTION  \
4017   ((debug_generate_pub_sections == 2) \
4018    ? ".debug_gnu_pubnames" : ".debug_pubnames")
4019 #endif
4020 #ifndef DEBUG_PUBTYPES_SECTION
4021 #define DEBUG_PUBTYPES_SECTION  \
4022   ((debug_generate_pub_sections == 2) \
4023    ? ".debug_gnu_pubtypes" : ".debug_pubtypes")
4024 #endif
4025 #ifndef DEBUG_STR_OFFSETS_SECTION
4026 #define DEBUG_STR_OFFSETS_SECTION ".debug_str_offsets"
4027 #endif
4028 #ifndef DEBUG_DWO_STR_OFFSETS_SECTION
4029 #define DEBUG_DWO_STR_OFFSETS_SECTION ".debug_str_offsets.dwo"
4030 #endif
4031 #ifndef DEBUG_LTO_DWO_STR_OFFSETS_SECTION
4032 #define DEBUG_LTO_DWO_STR_OFFSETS_SECTION ".gnu.debuglto_.debug_str_offsets.dwo"
4033 #endif
4034 #ifndef DEBUG_STR_SECTION
4035 #define DEBUG_STR_SECTION  ".debug_str"
4036 #endif
4037 #ifndef DEBUG_LTO_STR_SECTION
4038 #define DEBUG_LTO_STR_SECTION ".gnu.debuglto_.debug_str"
4039 #endif
4040 #ifndef DEBUG_STR_DWO_SECTION
4041 #define DEBUG_STR_DWO_SECTION   ".debug_str.dwo"
4042 #endif
4043 #ifndef DEBUG_LTO_STR_DWO_SECTION
4044 #define DEBUG_LTO_STR_DWO_SECTION ".gnu.debuglto_.debug_str.dwo"
4045 #endif
4046 #ifndef DEBUG_RANGES_SECTION
4047 #define DEBUG_RANGES_SECTION    ".debug_ranges"
4048 #endif
4049 #ifndef DEBUG_RNGLISTS_SECTION
4050 #define DEBUG_RNGLISTS_SECTION  ".debug_rnglists"
4051 #endif
4052 #ifndef DEBUG_LINE_STR_SECTION
4053 #define DEBUG_LINE_STR_SECTION  ".debug_line_str"
4054 #endif
4055 #ifndef DEBUG_LTO_LINE_STR_SECTION
4056 #define DEBUG_LTO_LINE_STR_SECTION  ".gnu.debuglto_.debug_line_str"
4057 #endif
4058
4059 /* Standard ELF section names for compiled code and data.  */
4060 #ifndef TEXT_SECTION_NAME
4061 #define TEXT_SECTION_NAME       ".text"
4062 #endif
4063
4064 /* Section flags for .debug_str section.  */
4065 #define DEBUG_STR_SECTION_FLAGS                                 \
4066   (HAVE_GAS_SHF_MERGE && flag_merge_debug_strings               \
4067    ? SECTION_DEBUG | SECTION_MERGE | SECTION_STRINGS | 1        \
4068    : SECTION_DEBUG)
4069
4070 /* Section flags for .debug_str.dwo section.  */
4071 #define DEBUG_STR_DWO_SECTION_FLAGS (SECTION_DEBUG | SECTION_EXCLUDE)
4072
4073 /* Attribute used to refer to the macro section.  */
4074 #define DEBUG_MACRO_ATTRIBUTE (dwarf_version >= 5 ? DW_AT_macros \
4075                    : dwarf_strict ? DW_AT_macro_info : DW_AT_GNU_macros)
4076
4077 /* Labels we insert at beginning sections we can reference instead of
4078    the section names themselves.  */
4079
4080 #ifndef TEXT_SECTION_LABEL
4081 #define TEXT_SECTION_LABEL                 "Ltext"
4082 #endif
4083 #ifndef COLD_TEXT_SECTION_LABEL
4084 #define COLD_TEXT_SECTION_LABEL             "Ltext_cold"
4085 #endif
4086 #ifndef DEBUG_LINE_SECTION_LABEL
4087 #define DEBUG_LINE_SECTION_LABEL           "Ldebug_line"
4088 #endif
4089 #ifndef DEBUG_SKELETON_LINE_SECTION_LABEL
4090 #define DEBUG_SKELETON_LINE_SECTION_LABEL   "Lskeleton_debug_line"
4091 #endif
4092 #ifndef DEBUG_INFO_SECTION_LABEL
4093 #define DEBUG_INFO_SECTION_LABEL           "Ldebug_info"
4094 #endif
4095 #ifndef DEBUG_SKELETON_INFO_SECTION_LABEL
4096 #define DEBUG_SKELETON_INFO_SECTION_LABEL   "Lskeleton_debug_info"
4097 #endif
4098 #ifndef DEBUG_ABBREV_SECTION_LABEL
4099 #define DEBUG_ABBREV_SECTION_LABEL         "Ldebug_abbrev"
4100 #endif
4101 #ifndef DEBUG_SKELETON_ABBREV_SECTION_LABEL
4102 #define DEBUG_SKELETON_ABBREV_SECTION_LABEL "Lskeleton_debug_abbrev"
4103 #endif
4104 #ifndef DEBUG_ADDR_SECTION_LABEL
4105 #define DEBUG_ADDR_SECTION_LABEL           "Ldebug_addr"
4106 #endif
4107 #ifndef DEBUG_LOC_SECTION_LABEL
4108 #define DEBUG_LOC_SECTION_LABEL                    "Ldebug_loc"
4109 #endif
4110 #ifndef DEBUG_RANGES_SECTION_LABEL
4111 #define DEBUG_RANGES_SECTION_LABEL         "Ldebug_ranges"
4112 #endif
4113 #ifndef DEBUG_MACINFO_SECTION_LABEL
4114 #define DEBUG_MACINFO_SECTION_LABEL         "Ldebug_macinfo"
4115 #endif
4116 #ifndef DEBUG_MACRO_SECTION_LABEL
4117 #define DEBUG_MACRO_SECTION_LABEL          "Ldebug_macro"
4118 #endif
4119 #define SKELETON_COMP_DIE_ABBREV 1
4120 #define SKELETON_TYPE_DIE_ABBREV 2
4121
4122 /* Definitions of defaults for formats and names of various special
4123    (artificial) labels which may be generated within this file (when the -g
4124    options is used and DWARF2_DEBUGGING_INFO is in effect.
4125    If necessary, these may be overridden from within the tm.h file, but
4126    typically, overriding these defaults is unnecessary.  */
4127
4128 static char text_end_label[MAX_ARTIFICIAL_LABEL_BYTES];
4129 static char text_section_label[MAX_ARTIFICIAL_LABEL_BYTES];
4130 static char cold_text_section_label[MAX_ARTIFICIAL_LABEL_BYTES];
4131 static char cold_end_label[MAX_ARTIFICIAL_LABEL_BYTES];
4132 static char abbrev_section_label[MAX_ARTIFICIAL_LABEL_BYTES];
4133 static char debug_info_section_label[MAX_ARTIFICIAL_LABEL_BYTES];
4134 static char debug_skeleton_info_section_label[MAX_ARTIFICIAL_LABEL_BYTES];
4135 static char debug_skeleton_abbrev_section_label[MAX_ARTIFICIAL_LABEL_BYTES];
4136 static char debug_line_section_label[MAX_ARTIFICIAL_LABEL_BYTES];
4137 static char debug_addr_section_label[MAX_ARTIFICIAL_LABEL_BYTES];
4138 static char debug_skeleton_line_section_label[MAX_ARTIFICIAL_LABEL_BYTES];
4139 static char macinfo_section_label[MAX_ARTIFICIAL_LABEL_BYTES];
4140 static char loc_section_label[MAX_ARTIFICIAL_LABEL_BYTES];
4141 static char ranges_section_label[2 * MAX_ARTIFICIAL_LABEL_BYTES];
4142 static char ranges_base_label[2 * MAX_ARTIFICIAL_LABEL_BYTES];
4143
4144 #ifndef TEXT_END_LABEL
4145 #define TEXT_END_LABEL          "Letext"
4146 #endif
4147 #ifndef COLD_END_LABEL
4148 #define COLD_END_LABEL          "Letext_cold"
4149 #endif
4150 #ifndef BLOCK_BEGIN_LABEL
4151 #define BLOCK_BEGIN_LABEL       "LBB"
4152 #endif
4153 #ifndef BLOCK_INLINE_ENTRY_LABEL
4154 #define BLOCK_INLINE_ENTRY_LABEL "LBI"
4155 #endif
4156 #ifndef BLOCK_END_LABEL
4157 #define BLOCK_END_LABEL         "LBE"
4158 #endif
4159 #ifndef LINE_CODE_LABEL
4160 #define LINE_CODE_LABEL         "LM"
4161 #endif
4162
4163 \f
4164 /* Return the root of the DIE's built for the current compilation unit.  */
4165 static dw_die_ref
4166 comp_unit_die (void)
4167 {
4168   if (!single_comp_unit_die)
4169     single_comp_unit_die = gen_compile_unit_die (NULL);
4170   return single_comp_unit_die;
4171 }
4172
4173 /* We allow a language front-end to designate a function that is to be
4174    called to "demangle" any name before it is put into a DIE.  */
4175
4176 static const char *(*demangle_name_func) (const char *);
4177
4178 void
4179 dwarf2out_set_demangle_name_func (const char *(*func) (const char *))
4180 {
4181   demangle_name_func = func;
4182 }
4183
4184 /* Test if rtl node points to a pseudo register.  */
4185
4186 static inline int
4187 is_pseudo_reg (const_rtx rtl)
4188 {
4189   return ((REG_P (rtl) && REGNO (rtl) >= FIRST_PSEUDO_REGISTER)
4190           || (GET_CODE (rtl) == SUBREG
4191               && REGNO (SUBREG_REG (rtl)) >= FIRST_PSEUDO_REGISTER));
4192 }
4193
4194 /* Return a reference to a type, with its const and volatile qualifiers
4195    removed.  */
4196
4197 static inline tree
4198 type_main_variant (tree type)
4199 {
4200   type = TYPE_MAIN_VARIANT (type);
4201
4202   /* ??? There really should be only one main variant among any group of
4203      variants of a given type (and all of the MAIN_VARIANT values for all
4204      members of the group should point to that one type) but sometimes the C
4205      front-end messes this up for array types, so we work around that bug
4206      here.  */
4207   if (TREE_CODE (type) == ARRAY_TYPE)
4208     while (type != TYPE_MAIN_VARIANT (type))
4209       type = TYPE_MAIN_VARIANT (type);
4210
4211   return type;
4212 }
4213
4214 /* Return nonzero if the given type node represents a tagged type.  */
4215
4216 static inline int
4217 is_tagged_type (const_tree type)
4218 {
4219   enum tree_code code = TREE_CODE (type);
4220
4221   return (code == RECORD_TYPE || code == UNION_TYPE
4222           || code == QUAL_UNION_TYPE || code == ENUMERAL_TYPE);
4223 }
4224
4225 /* Set label to debug_info_section_label + die_offset of a DIE reference.  */
4226
4227 static void
4228 get_ref_die_offset_label (char *label, dw_die_ref ref)
4229 {
4230   sprintf (label, "%s+%ld", debug_info_section_label, ref->die_offset);
4231 }
4232
4233 /* Return die_offset of a DIE reference to a base type.  */
4234
4235 static unsigned long int
4236 get_base_type_offset (dw_die_ref ref)
4237 {
4238   if (ref->die_offset)
4239     return ref->die_offset;
4240   if (comp_unit_die ()->die_abbrev)
4241     {
4242       calc_base_type_die_sizes ();
4243       gcc_assert (ref->die_offset);
4244     }
4245   return ref->die_offset;
4246 }
4247
4248 /* Return die_offset of a DIE reference other than base type.  */
4249
4250 static unsigned long int
4251 get_ref_die_offset (dw_die_ref ref)
4252 {
4253   gcc_assert (ref->die_offset);
4254   return ref->die_offset;
4255 }
4256
4257 /* Convert a DIE tag into its string name.  */
4258
4259 static const char *
4260 dwarf_tag_name (unsigned int tag)
4261 {
4262   const char *name = get_DW_TAG_name (tag);
4263
4264   if (name != NULL)
4265     return name;
4266
4267   return "DW_TAG_<unknown>";
4268 }
4269
4270 /* Convert a DWARF attribute code into its string name.  */
4271
4272 static const char *
4273 dwarf_attr_name (unsigned int attr)
4274 {
4275   const char *name;
4276
4277   switch (attr)
4278     {
4279 #if VMS_DEBUGGING_INFO
4280     case DW_AT_HP_prologue:
4281       return "DW_AT_HP_prologue";
4282 #else
4283     case DW_AT_MIPS_loop_unroll_factor:
4284       return "DW_AT_MIPS_loop_unroll_factor";
4285 #endif
4286
4287 #if VMS_DEBUGGING_INFO
4288     case DW_AT_HP_epilogue:
4289       return "DW_AT_HP_epilogue";
4290 #else
4291     case DW_AT_MIPS_stride:
4292       return "DW_AT_MIPS_stride";
4293 #endif
4294     }
4295
4296   name = get_DW_AT_name (attr);
4297
4298   if (name != NULL)
4299     return name;
4300
4301   return "DW_AT_<unknown>";
4302 }
4303
4304 /* Convert a DWARF value form code into its string name.  */
4305
4306 static const char *
4307 dwarf_form_name (unsigned int form)
4308 {
4309   const char *name = get_DW_FORM_name (form);
4310
4311   if (name != NULL)
4312     return name;
4313
4314   return "DW_FORM_<unknown>";
4315 }
4316 \f
4317 /* Determine the "ultimate origin" of a decl.  The decl may be an inlined
4318    instance of an inlined instance of a decl which is local to an inline
4319    function, so we have to trace all of the way back through the origin chain
4320    to find out what sort of node actually served as the original seed for the
4321    given block.  */
4322
4323 static tree
4324 decl_ultimate_origin (const_tree decl)
4325 {
4326   if (!CODE_CONTAINS_STRUCT (TREE_CODE (decl), TS_DECL_COMMON))
4327     return NULL_TREE;
4328
4329   /* DECL_ABSTRACT_ORIGIN can point to itself; ignore that if
4330      we're trying to output the abstract instance of this function.  */
4331   if (DECL_ABSTRACT_P (decl) && DECL_ABSTRACT_ORIGIN (decl) == decl)
4332     return NULL_TREE;
4333
4334   /* Since the DECL_ABSTRACT_ORIGIN for a DECL is supposed to be the
4335      most distant ancestor, this should never happen.  */
4336   gcc_assert (!DECL_FROM_INLINE (DECL_ORIGIN (decl)));
4337
4338   return DECL_ABSTRACT_ORIGIN (decl);
4339 }
4340
4341 /* Get the class to which DECL belongs, if any.  In g++, the DECL_CONTEXT
4342    of a virtual function may refer to a base class, so we check the 'this'
4343    parameter.  */
4344
4345 static tree
4346 decl_class_context (tree decl)
4347 {
4348   tree context = NULL_TREE;
4349
4350   if (TREE_CODE (decl) != FUNCTION_DECL || ! DECL_VINDEX (decl))
4351     context = DECL_CONTEXT (decl);
4352   else
4353     context = TYPE_MAIN_VARIANT
4354       (TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (decl)))));
4355
4356   if (context && !TYPE_P (context))
4357     context = NULL_TREE;
4358
4359   return context;
4360 }
4361 \f
4362 /* Add an attribute/value pair to a DIE.  */
4363
4364 static inline void
4365 add_dwarf_attr (dw_die_ref die, dw_attr_node *attr)
4366 {
4367   /* Maybe this should be an assert?  */
4368   if (die == NULL)
4369     return;
4370
4371   if (flag_checking)
4372     {
4373       /* Check we do not add duplicate attrs.  Can't use get_AT here
4374          because that recurses to the specification/abstract origin DIE.  */
4375       dw_attr_node *a;
4376       unsigned ix;
4377       FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
4378         gcc_assert (a->dw_attr != attr->dw_attr);
4379     }
4380
4381   vec_safe_reserve (die->die_attr, 1);
4382   vec_safe_push (die->die_attr, *attr);
4383 }
4384
4385 static inline enum dw_val_class
4386 AT_class (dw_attr_node *a)
4387 {
4388   return a->dw_attr_val.val_class;
4389 }
4390
4391 /* Return the index for any attribute that will be referenced with a
4392    DW_FORM_GNU_addr_index or DW_FORM_GNU_str_index.  String indices
4393    are stored in dw_attr_val.v.val_str for reference counting
4394    pruning.  */
4395
4396 static inline unsigned int
4397 AT_index (dw_attr_node *a)
4398 {
4399   if (AT_class (a) == dw_val_class_str)
4400     return a->dw_attr_val.v.val_str->index;
4401   else if (a->dw_attr_val.val_entry != NULL)
4402     return a->dw_attr_val.val_entry->index;
4403   return NOT_INDEXED;
4404 }
4405
4406 /* Add a flag value attribute to a DIE.  */
4407
4408 static inline void
4409 add_AT_flag (dw_die_ref die, enum dwarf_attribute attr_kind, unsigned int flag)
4410 {
4411   dw_attr_node attr;
4412
4413   attr.dw_attr = attr_kind;
4414   attr.dw_attr_val.val_class = dw_val_class_flag;
4415   attr.dw_attr_val.val_entry = NULL;
4416   attr.dw_attr_val.v.val_flag = flag;
4417   add_dwarf_attr (die, &attr);
4418 }
4419
4420 static inline unsigned
4421 AT_flag (dw_attr_node *a)
4422 {
4423   gcc_assert (a && AT_class (a) == dw_val_class_flag);
4424   return a->dw_attr_val.v.val_flag;
4425 }
4426
4427 /* Add a signed integer attribute value to a DIE.  */
4428
4429 static inline void
4430 add_AT_int (dw_die_ref die, enum dwarf_attribute attr_kind, HOST_WIDE_INT int_val)
4431 {
4432   dw_attr_node attr;
4433
4434   attr.dw_attr = attr_kind;
4435   attr.dw_attr_val.val_class = dw_val_class_const;
4436   attr.dw_attr_val.val_entry = NULL;
4437   attr.dw_attr_val.v.val_int = int_val;
4438   add_dwarf_attr (die, &attr);
4439 }
4440
4441 static inline HOST_WIDE_INT
4442 AT_int (dw_attr_node *a)
4443 {
4444   gcc_assert (a && (AT_class (a) == dw_val_class_const
4445                     || AT_class (a) == dw_val_class_const_implicit));
4446   return a->dw_attr_val.v.val_int;
4447 }
4448
4449 /* Add an unsigned integer attribute value to a DIE.  */
4450
4451 static inline void
4452 add_AT_unsigned (dw_die_ref die, enum dwarf_attribute attr_kind,
4453                  unsigned HOST_WIDE_INT unsigned_val)
4454 {
4455   dw_attr_node attr;
4456
4457   attr.dw_attr = attr_kind;
4458   attr.dw_attr_val.val_class = dw_val_class_unsigned_const;
4459   attr.dw_attr_val.val_entry = NULL;
4460   attr.dw_attr_val.v.val_unsigned = unsigned_val;
4461   add_dwarf_attr (die, &attr);
4462 }
4463
4464 static inline unsigned HOST_WIDE_INT
4465 AT_unsigned (dw_attr_node *a)
4466 {
4467   gcc_assert (a && (AT_class (a) == dw_val_class_unsigned_const
4468                     || AT_class (a) == dw_val_class_unsigned_const_implicit));
4469   return a->dw_attr_val.v.val_unsigned;
4470 }
4471
4472 /* Add an unsigned wide integer attribute value to a DIE.  */
4473
4474 static inline void
4475 add_AT_wide (dw_die_ref die, enum dwarf_attribute attr_kind,
4476              const wide_int& w)
4477 {
4478   dw_attr_node attr;
4479
4480   attr.dw_attr = attr_kind;
4481   attr.dw_attr_val.val_class = dw_val_class_wide_int;
4482   attr.dw_attr_val.val_entry = NULL;
4483   attr.dw_attr_val.v.val_wide = ggc_alloc<wide_int> ();
4484   *attr.dw_attr_val.v.val_wide = w;
4485   add_dwarf_attr (die, &attr);
4486 }
4487
4488 /* Add an unsigned double integer attribute value to a DIE.  */
4489
4490 static inline void
4491 add_AT_double (dw_die_ref die, enum dwarf_attribute attr_kind,
4492                HOST_WIDE_INT high, unsigned HOST_WIDE_INT low)
4493 {
4494   dw_attr_node attr;
4495
4496   attr.dw_attr = attr_kind;
4497   attr.dw_attr_val.val_class = dw_val_class_const_double;
4498   attr.dw_attr_val.val_entry = NULL;
4499   attr.dw_attr_val.v.val_double.high = high;
4500   attr.dw_attr_val.v.val_double.low = low;
4501   add_dwarf_attr (die, &attr);
4502 }
4503
4504 /* Add a floating point attribute value to a DIE and return it.  */
4505
4506 static inline void
4507 add_AT_vec (dw_die_ref die, enum dwarf_attribute attr_kind,
4508             unsigned int length, unsigned int elt_size, unsigned char *array)
4509 {
4510   dw_attr_node attr;
4511
4512   attr.dw_attr = attr_kind;
4513   attr.dw_attr_val.val_class = dw_val_class_vec;
4514   attr.dw_attr_val.val_entry = NULL;
4515   attr.dw_attr_val.v.val_vec.length = length;
4516   attr.dw_attr_val.v.val_vec.elt_size = elt_size;
4517   attr.dw_attr_val.v.val_vec.array = array;
4518   add_dwarf_attr (die, &attr);
4519 }
4520
4521 /* Add an 8-byte data attribute value to a DIE.  */
4522
4523 static inline void
4524 add_AT_data8 (dw_die_ref die, enum dwarf_attribute attr_kind,
4525               unsigned char data8[8])
4526 {
4527   dw_attr_node attr;
4528
4529   attr.dw_attr = attr_kind;
4530   attr.dw_attr_val.val_class = dw_val_class_data8;
4531   attr.dw_attr_val.val_entry = NULL;
4532   memcpy (attr.dw_attr_val.v.val_data8, data8, 8);
4533   add_dwarf_attr (die, &attr);
4534 }
4535
4536 /* Add DW_AT_low_pc and DW_AT_high_pc to a DIE.  When using
4537    dwarf_split_debug_info, address attributes in dies destined for the
4538    final executable have force_direct set to avoid using indexed
4539    references.  */
4540
4541 static inline void
4542 add_AT_low_high_pc (dw_die_ref die, const char *lbl_low, const char *lbl_high,
4543                     bool force_direct)
4544 {
4545   dw_attr_node attr;
4546   char * lbl_id;
4547
4548   lbl_id = xstrdup (lbl_low);
4549   attr.dw_attr = DW_AT_low_pc;
4550   attr.dw_attr_val.val_class = dw_val_class_lbl_id;
4551   attr.dw_attr_val.v.val_lbl_id = lbl_id;
4552   if (dwarf_split_debug_info && !force_direct)
4553     attr.dw_attr_val.val_entry
4554       = add_addr_table_entry (lbl_id, ate_kind_label);
4555   else
4556     attr.dw_attr_val.val_entry = NULL;
4557   add_dwarf_attr (die, &attr);
4558
4559   attr.dw_attr = DW_AT_high_pc;
4560   if (dwarf_version < 4)
4561     attr.dw_attr_val.val_class = dw_val_class_lbl_id;
4562   else
4563     attr.dw_attr_val.val_class = dw_val_class_high_pc;
4564   lbl_id = xstrdup (lbl_high);
4565   attr.dw_attr_val.v.val_lbl_id = lbl_id;
4566   if (attr.dw_attr_val.val_class == dw_val_class_lbl_id
4567       && dwarf_split_debug_info && !force_direct)
4568     attr.dw_attr_val.val_entry
4569       = add_addr_table_entry (lbl_id, ate_kind_label);
4570   else
4571     attr.dw_attr_val.val_entry = NULL;
4572   add_dwarf_attr (die, &attr);
4573 }
4574
4575 /* Hash and equality functions for debug_str_hash.  */
4576
4577 hashval_t
4578 indirect_string_hasher::hash (indirect_string_node *x)
4579 {
4580   return htab_hash_string (x->str);
4581 }
4582
4583 bool
4584 indirect_string_hasher::equal (indirect_string_node *x1, const char *x2)
4585 {
4586   return strcmp (x1->str, x2) == 0;
4587 }
4588
4589 /* Add STR to the given string hash table.  */
4590
4591 static struct indirect_string_node *
4592 find_AT_string_in_table (const char *str,
4593                          hash_table<indirect_string_hasher> *table)
4594 {
4595   struct indirect_string_node *node;
4596
4597   indirect_string_node **slot
4598     = table->find_slot_with_hash (str, htab_hash_string (str), INSERT);
4599   if (*slot == NULL)
4600     {
4601       node = ggc_cleared_alloc<indirect_string_node> ();
4602       node->str = ggc_strdup (str);
4603       *slot = node;
4604     }
4605   else
4606     node = *slot;
4607
4608   node->refcount++;
4609   return node;
4610 }
4611
4612 /* Add STR to the indirect string hash table.  */
4613
4614 static struct indirect_string_node *
4615 find_AT_string (const char *str)
4616 {
4617   if (! debug_str_hash)
4618     debug_str_hash = hash_table<indirect_string_hasher>::create_ggc (10);
4619
4620   return find_AT_string_in_table (str, debug_str_hash);
4621 }
4622
4623 /* Add a string attribute value to a DIE.  */
4624
4625 static inline void
4626 add_AT_string (dw_die_ref die, enum dwarf_attribute attr_kind, const char *str)
4627 {
4628   dw_attr_node attr;
4629   struct indirect_string_node *node;
4630
4631   node = find_AT_string (str);
4632
4633   attr.dw_attr = attr_kind;
4634   attr.dw_attr_val.val_class = dw_val_class_str;
4635   attr.dw_attr_val.val_entry = NULL;
4636   attr.dw_attr_val.v.val_str = node;
4637   add_dwarf_attr (die, &attr);
4638 }
4639
4640 static inline const char *
4641 AT_string (dw_attr_node *a)
4642 {
4643   gcc_assert (a && AT_class (a) == dw_val_class_str);
4644   return a->dw_attr_val.v.val_str->str;
4645 }
4646
4647 /* Call this function directly to bypass AT_string_form's logic to put
4648    the string inline in the die. */
4649
4650 static void
4651 set_indirect_string (struct indirect_string_node *node)
4652 {
4653   char label[MAX_ARTIFICIAL_LABEL_BYTES];
4654   /* Already indirect is a no op.  */
4655   if (node->form == DW_FORM_strp
4656       || node->form == DW_FORM_line_strp
4657       || node->form == DW_FORM_GNU_str_index)
4658     {
4659       gcc_assert (node->label);
4660       return;
4661     }
4662   ASM_GENERATE_INTERNAL_LABEL (label, "LASF", dw2_string_counter);
4663   ++dw2_string_counter;
4664   node->label = xstrdup (label);
4665
4666   if (!dwarf_split_debug_info)
4667     {
4668       node->form = DW_FORM_strp;
4669       node->index = NOT_INDEXED;
4670     }
4671   else
4672     {
4673       node->form = DW_FORM_GNU_str_index;
4674       node->index = NO_INDEX_ASSIGNED;
4675     }
4676 }
4677
4678 /* A helper function for dwarf2out_finish, called to reset indirect
4679    string decisions done for early LTO dwarf output before fat object
4680    dwarf output.  */
4681
4682 int
4683 reset_indirect_string (indirect_string_node **h, void *)
4684 {
4685   struct indirect_string_node *node = *h;
4686   if (node->form == DW_FORM_strp || node->form == DW_FORM_GNU_str_index)
4687     {
4688       free (node->label);
4689       node->label = NULL;
4690       node->form = (dwarf_form) 0;
4691       node->index = 0;
4692     }
4693   return 1;
4694 }
4695
4696 /* Find out whether a string should be output inline in DIE
4697    or out-of-line in .debug_str section.  */
4698
4699 static enum dwarf_form
4700 find_string_form (struct indirect_string_node *node)
4701 {
4702   unsigned int len;
4703
4704   if (node->form)
4705     return node->form;
4706
4707   len = strlen (node->str) + 1;
4708
4709   /* If the string is shorter or equal to the size of the reference, it is
4710      always better to put it inline.  */
4711   if (len <= DWARF_OFFSET_SIZE || node->refcount == 0)
4712     return node->form = DW_FORM_string;
4713
4714   /* If we cannot expect the linker to merge strings in .debug_str
4715      section, only put it into .debug_str if it is worth even in this
4716      single module.  */
4717   if (DWARF2_INDIRECT_STRING_SUPPORT_MISSING_ON_TARGET
4718       || ((debug_str_section->common.flags & SECTION_MERGE) == 0
4719           && (len - DWARF_OFFSET_SIZE) * node->refcount <= len))
4720     return node->form = DW_FORM_string;
4721
4722   set_indirect_string (node);
4723
4724   return node->form;
4725 }
4726
4727 /* Find out whether the string referenced from the attribute should be
4728    output inline in DIE or out-of-line in .debug_str section.  */
4729
4730 static enum dwarf_form
4731 AT_string_form (dw_attr_node *a)
4732 {
4733   gcc_assert (a && AT_class (a) == dw_val_class_str);
4734   return find_string_form (a->dw_attr_val.v.val_str);
4735 }
4736
4737 /* Add a DIE reference attribute value to a DIE.  */
4738
4739 static inline void
4740 add_AT_die_ref (dw_die_ref die, enum dwarf_attribute attr_kind, dw_die_ref targ_die)
4741 {
4742   dw_attr_node attr;
4743   gcc_checking_assert (targ_die != NULL);
4744
4745   /* With LTO we can end up trying to reference something we didn't create
4746      a DIE for.  Avoid crashing later on a NULL referenced DIE.  */
4747   if (targ_die == NULL)
4748     return;
4749
4750   attr.dw_attr = attr_kind;
4751   attr.dw_attr_val.val_class = dw_val_class_die_ref;
4752   attr.dw_attr_val.val_entry = NULL;
4753   attr.dw_attr_val.v.val_die_ref.die = targ_die;
4754   attr.dw_attr_val.v.val_die_ref.external = 0;
4755   add_dwarf_attr (die, &attr);
4756 }
4757
4758 /* Change DIE reference REF to point to NEW_DIE instead.  */
4759
4760 static inline void
4761 change_AT_die_ref (dw_attr_node *ref, dw_die_ref new_die)
4762 {
4763   gcc_assert (ref->dw_attr_val.val_class == dw_val_class_die_ref);
4764   ref->dw_attr_val.v.val_die_ref.die = new_die;
4765   ref->dw_attr_val.v.val_die_ref.external = 0;
4766 }
4767
4768 /* Add an AT_specification attribute to a DIE, and also make the back
4769    pointer from the specification to the definition.  */
4770
4771 static inline void
4772 add_AT_specification (dw_die_ref die, dw_die_ref targ_die)
4773 {
4774   add_AT_die_ref (die, DW_AT_specification, targ_die);
4775   gcc_assert (!targ_die->die_definition);
4776   targ_die->die_definition = die;
4777 }
4778
4779 static inline dw_die_ref
4780 AT_ref (dw_attr_node *a)
4781 {
4782   gcc_assert (a && AT_class (a) == dw_val_class_die_ref);
4783   return a->dw_attr_val.v.val_die_ref.die;
4784 }
4785
4786 static inline int
4787 AT_ref_external (dw_attr_node *a)
4788 {
4789   if (a && AT_class (a) == dw_val_class_die_ref)
4790     return a->dw_attr_val.v.val_die_ref.external;
4791
4792   return 0;
4793 }
4794
4795 static inline void
4796 set_AT_ref_external (dw_attr_node *a, int i)
4797 {
4798   gcc_assert (a && AT_class (a) == dw_val_class_die_ref);
4799   a->dw_attr_val.v.val_die_ref.external = i;
4800 }
4801
4802 /* Add an FDE reference attribute value to a DIE.  */
4803
4804 static inline void
4805 add_AT_fde_ref (dw_die_ref die, enum dwarf_attribute attr_kind, unsigned int targ_fde)
4806 {
4807   dw_attr_node attr;
4808
4809   attr.dw_attr = attr_kind;
4810   attr.dw_attr_val.val_class = dw_val_class_fde_ref;
4811   attr.dw_attr_val.val_entry = NULL;
4812   attr.dw_attr_val.v.val_fde_index = targ_fde;
4813   add_dwarf_attr (die, &attr);
4814 }
4815
4816 /* Add a location description attribute value to a DIE.  */
4817
4818 static inline void
4819 add_AT_loc (dw_die_ref die, enum dwarf_attribute attr_kind, dw_loc_descr_ref loc)
4820 {
4821   dw_attr_node attr;
4822
4823   attr.dw_attr = attr_kind;
4824   attr.dw_attr_val.val_class = dw_val_class_loc;
4825   attr.dw_attr_val.val_entry = NULL;
4826   attr.dw_attr_val.v.val_loc = loc;
4827   add_dwarf_attr (die, &attr);
4828 }
4829
4830 static inline dw_loc_descr_ref
4831 AT_loc (dw_attr_node *a)
4832 {
4833   gcc_assert (a && AT_class (a) == dw_val_class_loc);
4834   return a->dw_attr_val.v.val_loc;
4835 }
4836
4837 static inline void
4838 add_AT_loc_list (dw_die_ref die, enum dwarf_attribute attr_kind, dw_loc_list_ref loc_list)
4839 {
4840   dw_attr_node attr;
4841
4842   if (XCOFF_DEBUGGING_INFO && !HAVE_XCOFF_DWARF_EXTRAS)
4843     return;
4844
4845   attr.dw_attr = attr_kind;
4846   attr.dw_attr_val.val_class = dw_val_class_loc_list;
4847   attr.dw_attr_val.val_entry = NULL;
4848   attr.dw_attr_val.v.val_loc_list = loc_list;
4849   add_dwarf_attr (die, &attr);
4850   have_location_lists = true;
4851 }
4852
4853 static inline dw_loc_list_ref
4854 AT_loc_list (dw_attr_node *a)
4855 {
4856   gcc_assert (a && AT_class (a) == dw_val_class_loc_list);
4857   return a->dw_attr_val.v.val_loc_list;
4858 }
4859
4860 /* Add a view list attribute to DIE.  It must have a DW_AT_location
4861    attribute, because the view list complements the location list.  */
4862
4863 static inline void
4864 add_AT_view_list (dw_die_ref die, enum dwarf_attribute attr_kind)
4865 {
4866   dw_attr_node attr;
4867
4868   if (XCOFF_DEBUGGING_INFO && !HAVE_XCOFF_DWARF_EXTRAS)
4869     return;
4870
4871   attr.dw_attr = attr_kind;
4872   attr.dw_attr_val.val_class = dw_val_class_view_list;
4873   attr.dw_attr_val.val_entry = NULL;
4874   attr.dw_attr_val.v.val_view_list = die;
4875   add_dwarf_attr (die, &attr);
4876   gcc_checking_assert (get_AT (die, DW_AT_location));
4877   gcc_assert (have_location_lists);
4878 }
4879
4880 /* Return a pointer to the location list referenced by the attribute.
4881    If the named attribute is a view list, look up the corresponding
4882    DW_AT_location attribute and return its location list.  */
4883
4884 static inline dw_loc_list_ref *
4885 AT_loc_list_ptr (dw_attr_node *a)
4886 {
4887   gcc_assert (a);
4888   switch (AT_class (a))
4889     {
4890     case dw_val_class_loc_list:
4891       return &a->dw_attr_val.v.val_loc_list;
4892     case dw_val_class_view_list:
4893       {
4894         dw_attr_node *l;
4895         l = get_AT (a->dw_attr_val.v.val_view_list, DW_AT_location);
4896         if (!l)
4897           return NULL;
4898         gcc_checking_assert (l + 1 == a);
4899         return AT_loc_list_ptr (l);
4900       }
4901     default:
4902       gcc_unreachable ();
4903     }
4904 }
4905
4906 /* Return the location attribute value associated with a view list
4907    attribute value.  */
4908
4909 static inline dw_val_node *
4910 view_list_to_loc_list_val_node (dw_val_node *val)
4911 {
4912   gcc_assert (val->val_class == dw_val_class_view_list);
4913   dw_attr_node *loc = get_AT (val->v.val_view_list, DW_AT_location);
4914   if (!loc)
4915     return NULL;
4916   gcc_checking_assert (&(loc + 1)->dw_attr_val == val);
4917   gcc_assert (AT_class (loc) == dw_val_class_loc_list);
4918   return &loc->dw_attr_val;
4919 }
4920
4921 struct addr_hasher : ggc_ptr_hash<addr_table_entry>
4922 {
4923   static hashval_t hash (addr_table_entry *);
4924   static bool equal (addr_table_entry *, addr_table_entry *);
4925 };
4926
4927 /* Table of entries into the .debug_addr section.  */
4928
4929 static GTY (()) hash_table<addr_hasher> *addr_index_table;
4930
4931 /* Hash an address_table_entry.  */
4932
4933 hashval_t
4934 addr_hasher::hash (addr_table_entry *a)
4935 {
4936   inchash::hash hstate;
4937   switch (a->kind)
4938     {
4939       case ate_kind_rtx:
4940         hstate.add_int (0);
4941         break;
4942       case ate_kind_rtx_dtprel:
4943         hstate.add_int (1);
4944         break;
4945       case ate_kind_label:
4946         return htab_hash_string (a->addr.label);
4947       default:
4948         gcc_unreachable ();
4949     }
4950   inchash::add_rtx (a->addr.rtl, hstate);
4951   return hstate.end ();
4952 }
4953
4954 /* Determine equality for two address_table_entries.  */
4955
4956 bool
4957 addr_hasher::equal (addr_table_entry *a1, addr_table_entry *a2)
4958 {
4959   if (a1->kind != a2->kind)
4960     return 0;
4961   switch (a1->kind)
4962     {
4963       case ate_kind_rtx:
4964       case ate_kind_rtx_dtprel:
4965         return rtx_equal_p (a1->addr.rtl, a2->addr.rtl);
4966       case ate_kind_label:
4967         return strcmp (a1->addr.label, a2->addr.label) == 0;
4968       default:
4969         gcc_unreachable ();
4970     }
4971 }
4972
4973 /* Initialize an addr_table_entry.  */
4974
4975 void
4976 init_addr_table_entry (addr_table_entry *e, enum ate_kind kind, void *addr)
4977 {
4978   e->kind = kind;
4979   switch (kind)
4980     {
4981       case ate_kind_rtx:
4982       case ate_kind_rtx_dtprel:
4983         e->addr.rtl = (rtx) addr;
4984         break;
4985       case ate_kind_label:
4986         e->addr.label = (char *) addr;
4987         break;
4988     }
4989   e->refcount = 0;
4990   e->index = NO_INDEX_ASSIGNED;
4991 }
4992
4993 /* Add attr to the address table entry to the table.  Defer setting an
4994    index until output time.  */
4995
4996 static addr_table_entry *
4997 add_addr_table_entry (void *addr, enum ate_kind kind)
4998 {
4999   addr_table_entry *node;
5000   addr_table_entry finder;
5001
5002   gcc_assert (dwarf_split_debug_info);
5003   if (! addr_index_table)
5004     addr_index_table = hash_table<addr_hasher>::create_ggc (10);
5005   init_addr_table_entry (&finder, kind, addr);
5006   addr_table_entry **slot = addr_index_table->find_slot (&finder, INSERT);
5007
5008   if (*slot == HTAB_EMPTY_ENTRY)
5009     {
5010       node = ggc_cleared_alloc<addr_table_entry> ();
5011       init_addr_table_entry (node, kind, addr);
5012       *slot = node;
5013     }
5014   else
5015     node = *slot;
5016
5017   node->refcount++;
5018   return node;
5019 }
5020
5021 /* Remove an entry from the addr table by decrementing its refcount.
5022    Strictly, decrementing the refcount would be enough, but the
5023    assertion that the entry is actually in the table has found
5024    bugs.  */
5025
5026 static void
5027 remove_addr_table_entry (addr_table_entry *entry)
5028 {
5029   gcc_assert (dwarf_split_debug_info && addr_index_table);
5030   /* After an index is assigned, the table is frozen.  */
5031   gcc_assert (entry->refcount > 0 && entry->index == NO_INDEX_ASSIGNED);
5032   entry->refcount--;
5033 }
5034
5035 /* Given a location list, remove all addresses it refers to from the
5036    address_table.  */
5037
5038 static void
5039 remove_loc_list_addr_table_entries (dw_loc_descr_ref descr)
5040 {
5041   for (; descr; descr = descr->dw_loc_next)
5042     if (descr->dw_loc_oprnd1.val_entry != NULL)
5043       {
5044         gcc_assert (descr->dw_loc_oprnd1.val_entry->index == NO_INDEX_ASSIGNED);
5045         remove_addr_table_entry (descr->dw_loc_oprnd1.val_entry);
5046       }
5047 }
5048
5049 /* A helper function for dwarf2out_finish called through
5050    htab_traverse.  Assign an addr_table_entry its index.  All entries
5051    must be collected into the table when this function is called,
5052    because the indexing code relies on htab_traverse to traverse nodes
5053    in the same order for each run. */
5054
5055 int
5056 index_addr_table_entry (addr_table_entry **h, unsigned int *index)
5057 {
5058   addr_table_entry *node = *h;
5059
5060   /* Don't index unreferenced nodes.  */
5061   if (node->refcount == 0)
5062     return 1;
5063
5064   gcc_assert (node->index == NO_INDEX_ASSIGNED);
5065   node->index = *index;
5066   *index += 1;
5067
5068   return 1;
5069 }
5070
5071 /* Add an address constant attribute value to a DIE.  When using
5072    dwarf_split_debug_info, address attributes in dies destined for the
5073    final executable should be direct references--setting the parameter
5074    force_direct ensures this behavior.  */
5075
5076 static inline void
5077 add_AT_addr (dw_die_ref die, enum dwarf_attribute attr_kind, rtx addr,
5078              bool force_direct)
5079 {
5080   dw_attr_node attr;
5081
5082   attr.dw_attr = attr_kind;
5083   attr.dw_attr_val.val_class = dw_val_class_addr;
5084   attr.dw_attr_val.v.val_addr = addr;
5085   if (dwarf_split_debug_info && !force_direct)
5086     attr.dw_attr_val.val_entry = add_addr_table_entry (addr, ate_kind_rtx);
5087   else
5088     attr.dw_attr_val.val_entry = NULL;
5089   add_dwarf_attr (die, &attr);
5090 }
5091
5092 /* Get the RTX from to an address DIE attribute.  */
5093
5094 static inline rtx
5095 AT_addr (dw_attr_node *a)
5096 {
5097   gcc_assert (a && AT_class (a) == dw_val_class_addr);
5098   return a->dw_attr_val.v.val_addr;
5099 }
5100
5101 /* Add a file attribute value to a DIE.  */
5102
5103 static inline void
5104 add_AT_file (dw_die_ref die, enum dwarf_attribute attr_kind,
5105              struct dwarf_file_data *fd)
5106 {
5107   dw_attr_node attr;
5108
5109   attr.dw_attr = attr_kind;
5110   attr.dw_attr_val.val_class = dw_val_class_file;
5111   attr.dw_attr_val.val_entry = NULL;
5112   attr.dw_attr_val.v.val_file = fd;
5113   add_dwarf_attr (die, &attr);
5114 }
5115
5116 /* Get the dwarf_file_data from a file DIE attribute.  */
5117
5118 static inline struct dwarf_file_data *
5119 AT_file (dw_attr_node *a)
5120 {
5121   gcc_assert (a && (AT_class (a) == dw_val_class_file
5122                     || AT_class (a) == dw_val_class_file_implicit));
5123   return a->dw_attr_val.v.val_file;
5124 }
5125
5126 /* Add a vms delta attribute value to a DIE.  */
5127
5128 static inline void
5129 add_AT_vms_delta (dw_die_ref die, enum dwarf_attribute attr_kind,
5130                   const char *lbl1, const char *lbl2)
5131 {
5132   dw_attr_node attr;
5133
5134   attr.dw_attr = attr_kind;
5135   attr.dw_attr_val.val_class = dw_val_class_vms_delta;
5136   attr.dw_attr_val.val_entry = NULL;
5137   attr.dw_attr_val.v.val_vms_delta.lbl1 = xstrdup (lbl1);
5138   attr.dw_attr_val.v.val_vms_delta.lbl2 = xstrdup (lbl2);
5139   add_dwarf_attr (die, &attr);
5140 }
5141
5142 /* Add a symbolic view identifier attribute value to a DIE.  */
5143
5144 static inline void
5145 add_AT_symview (dw_die_ref die, enum dwarf_attribute attr_kind,
5146                const char *view_label)
5147 {
5148   dw_attr_node attr;
5149
5150   attr.dw_attr = attr_kind;
5151   attr.dw_attr_val.val_class = dw_val_class_symview;
5152   attr.dw_attr_val.val_entry = NULL;
5153   attr.dw_attr_val.v.val_symbolic_view = xstrdup (view_label);
5154   add_dwarf_attr (die, &attr);
5155 }
5156
5157 /* Add a label identifier attribute value to a DIE.  */
5158
5159 static inline void
5160 add_AT_lbl_id (dw_die_ref die, enum dwarf_attribute attr_kind,
5161                const char *lbl_id)
5162 {
5163   dw_attr_node attr;
5164
5165   attr.dw_attr = attr_kind;
5166   attr.dw_attr_val.val_class = dw_val_class_lbl_id;
5167   attr.dw_attr_val.val_entry = NULL;
5168   attr.dw_attr_val.v.val_lbl_id = xstrdup (lbl_id);
5169   if (dwarf_split_debug_info)
5170     attr.dw_attr_val.val_entry
5171         = add_addr_table_entry (attr.dw_attr_val.v.val_lbl_id,
5172                                 ate_kind_label);
5173   add_dwarf_attr (die, &attr);
5174 }
5175
5176 /* Add a section offset attribute value to a DIE, an offset into the
5177    debug_line section.  */
5178
5179 static inline void
5180 add_AT_lineptr (dw_die_ref die, enum dwarf_attribute attr_kind,
5181                 const char *label)
5182 {
5183   dw_attr_node attr;
5184
5185   attr.dw_attr = attr_kind;
5186   attr.dw_attr_val.val_class = dw_val_class_lineptr;
5187   attr.dw_attr_val.val_entry = NULL;
5188   attr.dw_attr_val.v.val_lbl_id = xstrdup (label);
5189   add_dwarf_attr (die, &attr);
5190 }
5191
5192 /* Add a section offset attribute value to a DIE, an offset into the
5193    debug_loclists section.  */
5194
5195 static inline void
5196 add_AT_loclistsptr (dw_die_ref die, enum dwarf_attribute attr_kind,
5197                     const char *label)
5198 {
5199   dw_attr_node attr;
5200
5201   attr.dw_attr = attr_kind;
5202   attr.dw_attr_val.val_class = dw_val_class_loclistsptr;
5203   attr.dw_attr_val.val_entry = NULL;
5204   attr.dw_attr_val.v.val_lbl_id = xstrdup (label);
5205   add_dwarf_attr (die, &attr);
5206 }
5207
5208 /* Add a section offset attribute value to a DIE, an offset into the
5209    debug_macinfo section.  */
5210
5211 static inline void
5212 add_AT_macptr (dw_die_ref die, enum dwarf_attribute attr_kind,
5213                const char *label)
5214 {
5215   dw_attr_node attr;
5216
5217   attr.dw_attr = attr_kind;
5218   attr.dw_attr_val.val_class = dw_val_class_macptr;
5219   attr.dw_attr_val.val_entry = NULL;
5220   attr.dw_attr_val.v.val_lbl_id = xstrdup (label);
5221   add_dwarf_attr (die, &attr);
5222 }
5223
5224 /* Add an offset attribute value to a DIE.  */
5225
5226 static inline void
5227 add_AT_offset (dw_die_ref die, enum dwarf_attribute attr_kind,
5228                unsigned HOST_WIDE_INT offset)
5229 {
5230   dw_attr_node attr;
5231
5232   attr.dw_attr = attr_kind;
5233   attr.dw_attr_val.val_class = dw_val_class_offset;
5234   attr.dw_attr_val.val_entry = NULL;
5235   attr.dw_attr_val.v.val_offset = offset;
5236   add_dwarf_attr (die, &attr);
5237 }
5238
5239 /* Add a range_list attribute value to a DIE.  When using
5240    dwarf_split_debug_info, address attributes in dies destined for the
5241    final executable should be direct references--setting the parameter
5242    force_direct ensures this behavior.  */
5243
5244 #define UNRELOCATED_OFFSET ((addr_table_entry *) 1)
5245 #define RELOCATED_OFFSET (NULL)
5246
5247 static void
5248 add_AT_range_list (dw_die_ref die, enum dwarf_attribute attr_kind,
5249                    long unsigned int offset, bool force_direct)
5250 {
5251   dw_attr_node attr;
5252
5253   attr.dw_attr = attr_kind;
5254   attr.dw_attr_val.val_class = dw_val_class_range_list;
5255   /* For the range_list attribute, use val_entry to store whether the
5256      offset should follow split-debug-info or normal semantics.  This
5257      value is read in output_range_list_offset.  */
5258   if (dwarf_split_debug_info && !force_direct)
5259     attr.dw_attr_val.val_entry = UNRELOCATED_OFFSET;
5260   else
5261     attr.dw_attr_val.val_entry = RELOCATED_OFFSET;
5262   attr.dw_attr_val.v.val_offset = offset;
5263   add_dwarf_attr (die, &attr);
5264 }
5265
5266 /* Return the start label of a delta attribute.  */
5267
5268 static inline const char *
5269 AT_vms_delta1 (dw_attr_node *a)
5270 {
5271   gcc_assert (a && (AT_class (a) == dw_val_class_vms_delta));
5272   return a->dw_attr_val.v.val_vms_delta.lbl1;
5273 }
5274
5275 /* Return the end label of a delta attribute.  */
5276
5277 static inline const char *
5278 AT_vms_delta2 (dw_attr_node *a)
5279 {
5280   gcc_assert (a && (AT_class (a) == dw_val_class_vms_delta));
5281   return a->dw_attr_val.v.val_vms_delta.lbl2;
5282 }
5283
5284 static inline const char *
5285 AT_lbl (dw_attr_node *a)
5286 {
5287   gcc_assert (a && (AT_class (a) == dw_val_class_lbl_id
5288                     || AT_class (a) == dw_val_class_lineptr
5289                     || AT_class (a) == dw_val_class_macptr
5290                     || AT_class (a) == dw_val_class_loclistsptr
5291                     || AT_class (a) == dw_val_class_high_pc));
5292   return a->dw_attr_val.v.val_lbl_id;
5293 }
5294
5295 /* Get the attribute of type attr_kind.  */
5296
5297 static dw_attr_node *
5298 get_AT (dw_die_ref die, enum dwarf_attribute attr_kind)
5299 {
5300   dw_attr_node *a;
5301   unsigned ix;
5302   dw_die_ref spec = NULL;
5303
5304   if (! die)
5305     return NULL;
5306
5307   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
5308     if (a->dw_attr == attr_kind)
5309       return a;
5310     else if (a->dw_attr == DW_AT_specification
5311              || a->dw_attr == DW_AT_abstract_origin)
5312       spec = AT_ref (a);
5313
5314   if (spec)
5315     return get_AT (spec, attr_kind);
5316
5317   return NULL;
5318 }
5319
5320 /* Returns the parent of the declaration of DIE.  */
5321
5322 static dw_die_ref
5323 get_die_parent (dw_die_ref die)
5324 {
5325   dw_die_ref t;
5326
5327   if (!die)
5328     return NULL;
5329
5330   if ((t = get_AT_ref (die, DW_AT_abstract_origin))
5331       || (t = get_AT_ref (die, DW_AT_specification)))
5332     die = t;
5333
5334   return die->die_parent;
5335 }
5336
5337 /* Return the "low pc" attribute value, typically associated with a subprogram
5338    DIE.  Return null if the "low pc" attribute is either not present, or if it
5339    cannot be represented as an assembler label identifier.  */
5340
5341 static inline const char *
5342 get_AT_low_pc (dw_die_ref die)
5343 {
5344   dw_attr_node *a = get_AT (die, DW_AT_low_pc);
5345
5346   return a ? AT_lbl (a) : NULL;
5347 }
5348
5349 /* Return the "high pc" attribute value, typically associated with a subprogram
5350    DIE.  Return null if the "high pc" attribute is either not present, or if it
5351    cannot be represented as an assembler label identifier.  */
5352
5353 static inline const char *
5354 get_AT_hi_pc (dw_die_ref die)
5355 {
5356   dw_attr_node *a = get_AT (die, DW_AT_high_pc);
5357
5358   return a ? AT_lbl (a) : NULL;
5359 }
5360
5361 /* Return the value of the string attribute designated by ATTR_KIND, or
5362    NULL if it is not present.  */
5363
5364 static inline const char *
5365 get_AT_string (dw_die_ref die, enum dwarf_attribute attr_kind)
5366 {
5367   dw_attr_node *a = get_AT (die, attr_kind);
5368
5369   return a ? AT_string (a) : NULL;
5370 }
5371
5372 /* Return the value of the flag attribute designated by ATTR_KIND, or -1
5373    if it is not present.  */
5374
5375 static inline int
5376 get_AT_flag (dw_die_ref die, enum dwarf_attribute attr_kind)
5377 {
5378   dw_attr_node *a = get_AT (die, attr_kind);
5379
5380   return a ? AT_flag (a) : 0;
5381 }
5382
5383 /* Return the value of the unsigned attribute designated by ATTR_KIND, or 0
5384    if it is not present.  */
5385
5386 static inline unsigned
5387 get_AT_unsigned (dw_die_ref die, enum dwarf_attribute attr_kind)
5388 {
5389   dw_attr_node *a = get_AT (die, attr_kind);
5390
5391   return a ? AT_unsigned (a) : 0;
5392 }
5393
5394 static inline dw_die_ref
5395 get_AT_ref (dw_die_ref die, enum dwarf_attribute attr_kind)
5396 {
5397   dw_attr_node *a = get_AT (die, attr_kind);
5398
5399   return a ? AT_ref (a) : NULL;
5400 }
5401
5402 static inline struct dwarf_file_data *
5403 get_AT_file (dw_die_ref die, enum dwarf_attribute attr_kind)
5404 {
5405   dw_attr_node *a = get_AT (die, attr_kind);
5406
5407   return a ? AT_file (a) : NULL;
5408 }
5409
5410 /* Return TRUE if the language is C++.  */
5411
5412 static inline bool
5413 is_cxx (void)
5414 {
5415   unsigned int lang = get_AT_unsigned (comp_unit_die (), DW_AT_language);
5416
5417   return (lang == DW_LANG_C_plus_plus || lang == DW_LANG_ObjC_plus_plus
5418           || lang == DW_LANG_C_plus_plus_11 || lang == DW_LANG_C_plus_plus_14);
5419 }
5420
5421 /* Return TRUE if DECL was created by the C++ frontend.  */
5422
5423 static bool
5424 is_cxx (const_tree decl)
5425 {
5426   if (in_lto_p)
5427     {
5428       const_tree context = get_ultimate_context (decl);
5429       if (context && TRANSLATION_UNIT_LANGUAGE (context))
5430         return strncmp (TRANSLATION_UNIT_LANGUAGE (context), "GNU C++", 7) == 0;
5431     }
5432   return is_cxx ();
5433 }
5434
5435 /* Return TRUE if the language is Fortran.  */
5436
5437 static inline bool
5438 is_fortran (void)
5439 {
5440   unsigned int lang = get_AT_unsigned (comp_unit_die (), DW_AT_language);
5441
5442   return (lang == DW_LANG_Fortran77
5443           || lang == DW_LANG_Fortran90
5444           || lang == DW_LANG_Fortran95
5445           || lang == DW_LANG_Fortran03
5446           || lang == DW_LANG_Fortran08);
5447 }
5448
5449 static inline bool
5450 is_fortran (const_tree decl)
5451 {
5452   if (in_lto_p)
5453     {
5454       const_tree context = get_ultimate_context (decl);
5455       if (context && TRANSLATION_UNIT_LANGUAGE (context))
5456         return (strncmp (TRANSLATION_UNIT_LANGUAGE (context),
5457                          "GNU Fortran", 11) == 0
5458                 || strcmp (TRANSLATION_UNIT_LANGUAGE (context),
5459                            "GNU F77") == 0);
5460     }
5461   return is_fortran ();
5462 }
5463
5464 /* Return TRUE if the language is Ada.  */
5465
5466 static inline bool
5467 is_ada (void)
5468 {
5469   unsigned int lang = get_AT_unsigned (comp_unit_die (), DW_AT_language);
5470
5471   return lang == DW_LANG_Ada95 || lang == DW_LANG_Ada83;
5472 }
5473
5474 /* Remove the specified attribute if present.  Return TRUE if removal
5475    was successful.  */
5476
5477 static bool
5478 remove_AT (dw_die_ref die, enum dwarf_attribute attr_kind)
5479 {
5480   dw_attr_node *a;
5481   unsigned ix;
5482
5483   if (! die)
5484     return false;
5485
5486   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
5487     if (a->dw_attr == attr_kind)
5488       {
5489         if (AT_class (a) == dw_val_class_str)
5490           if (a->dw_attr_val.v.val_str->refcount)
5491             a->dw_attr_val.v.val_str->refcount--;
5492
5493         /* vec::ordered_remove should help reduce the number of abbrevs
5494            that are needed.  */
5495         die->die_attr->ordered_remove (ix);
5496         return true;
5497       }
5498   return false;
5499 }
5500
5501 /* Remove CHILD from its parent.  PREV must have the property that
5502    PREV->DIE_SIB == CHILD.  Does not alter CHILD.  */
5503
5504 static void
5505 remove_child_with_prev (dw_die_ref child, dw_die_ref prev)
5506 {
5507   gcc_assert (child->die_parent == prev->die_parent);
5508   gcc_assert (prev->die_sib == child);
5509   if (prev == child)
5510     {
5511       gcc_assert (child->die_parent->die_child == child);
5512       prev = NULL;
5513     }
5514   else
5515     prev->die_sib = child->die_sib;
5516   if (child->die_parent->die_child == child)
5517     child->die_parent->die_child = prev;
5518   child->die_sib = NULL;
5519 }
5520
5521 /* Replace OLD_CHILD with NEW_CHILD.  PREV must have the property that
5522    PREV->DIE_SIB == OLD_CHILD.  Does not alter OLD_CHILD.  */
5523
5524 static void
5525 replace_child (dw_die_ref old_child, dw_die_ref new_child, dw_die_ref prev)
5526 {
5527   dw_die_ref parent = old_child->die_parent;
5528
5529   gcc_assert (parent == prev->die_parent);
5530   gcc_assert (prev->die_sib == old_child);
5531
5532   new_child->die_parent = parent;
5533   if (prev == old_child)
5534     {
5535       gcc_assert (parent->die_child == old_child);
5536       new_child->die_sib = new_child;
5537     }
5538   else
5539     {
5540       prev->die_sib = new_child;
5541       new_child->die_sib = old_child->die_sib;
5542     }
5543   if (old_child->die_parent->die_child == old_child)
5544     old_child->die_parent->die_child = new_child;
5545   old_child->die_sib = NULL;
5546 }
5547
5548 /* Move all children from OLD_PARENT to NEW_PARENT.  */
5549
5550 static void
5551 move_all_children (dw_die_ref old_parent, dw_die_ref new_parent)
5552 {
5553   dw_die_ref c;
5554   new_parent->die_child = old_parent->die_child;
5555   old_parent->die_child = NULL;
5556   FOR_EACH_CHILD (new_parent, c, c->die_parent = new_parent);
5557 }
5558
5559 /* Remove child DIE whose die_tag is TAG.  Do nothing if no child
5560    matches TAG.  */
5561
5562 static void
5563 remove_child_TAG (dw_die_ref die, enum dwarf_tag tag)
5564 {
5565   dw_die_ref c;
5566
5567   c = die->die_child;
5568   if (c) do {
5569     dw_die_ref prev = c;
5570     c = c->die_sib;
5571     while (c->die_tag == tag)
5572       {
5573         remove_child_with_prev (c, prev);
5574         c->die_parent = NULL;
5575         /* Might have removed every child.  */
5576         if (die->die_child == NULL)
5577           return;
5578         c = prev->die_sib;
5579       }
5580   } while (c != die->die_child);
5581 }
5582
5583 /* Add a CHILD_DIE as the last child of DIE.  */
5584
5585 static void
5586 add_child_die (dw_die_ref die, dw_die_ref child_die)
5587 {
5588   /* FIXME this should probably be an assert.  */
5589   if (! die || ! child_die)
5590     return;
5591   gcc_assert (die != child_die);
5592
5593   child_die->die_parent = die;
5594   if (die->die_child)
5595     {
5596       child_die->die_sib = die->die_child->die_sib;
5597       die->die_child->die_sib = child_die;
5598     }
5599   else
5600     child_die->die_sib = child_die;
5601   die->die_child = child_die;
5602 }
5603
5604 /* Like add_child_die, but put CHILD_DIE after AFTER_DIE.  */
5605
5606 static void
5607 add_child_die_after (dw_die_ref die, dw_die_ref child_die,
5608                      dw_die_ref after_die)
5609 {
5610   gcc_assert (die
5611               && child_die
5612               && after_die
5613               && die->die_child
5614               && die != child_die);
5615
5616   child_die->die_parent = die;
5617   child_die->die_sib = after_die->die_sib;
5618   after_die->die_sib = child_die;
5619   if (die->die_child == after_die)
5620     die->die_child = child_die;
5621 }
5622
5623 /* Unassociate CHILD from its parent, and make its parent be
5624    NEW_PARENT.  */
5625
5626 static void
5627 reparent_child (dw_die_ref child, dw_die_ref new_parent)
5628 {
5629   for (dw_die_ref p = child->die_parent->die_child; ; p = p->die_sib)
5630     if (p->die_sib == child)
5631       {
5632         remove_child_with_prev (child, p);
5633         break;
5634       }
5635   add_child_die (new_parent, child);
5636 }
5637
5638 /* Move CHILD, which must be a child of PARENT or the DIE for which PARENT
5639    is the specification, to the end of PARENT's list of children.
5640    This is done by removing and re-adding it.  */
5641
5642 static void
5643 splice_child_die (dw_die_ref parent, dw_die_ref child)
5644 {
5645   /* We want the declaration DIE from inside the class, not the
5646      specification DIE at toplevel.  */
5647   if (child->die_parent != parent)
5648     {
5649       dw_die_ref tmp = get_AT_ref (child, DW_AT_specification);
5650
5651       if (tmp)
5652         child = tmp;
5653     }
5654
5655   gcc_assert (child->die_parent == parent
5656               || (child->die_parent
5657                   == get_AT_ref (parent, DW_AT_specification)));
5658
5659   reparent_child (child, parent);
5660 }
5661
5662 /* Create and return a new die with TAG_VALUE as tag.  */
5663  
5664 static inline dw_die_ref
5665 new_die_raw (enum dwarf_tag tag_value)
5666 {
5667   dw_die_ref die = ggc_cleared_alloc<die_node> ();
5668   die->die_tag = tag_value;
5669   return die;
5670 }
5671
5672 /* Create and return a new die with a parent of PARENT_DIE.  If
5673    PARENT_DIE is NULL, the new DIE is placed in limbo and an
5674    associated tree T must be supplied to determine parenthood
5675    later.  */
5676
5677 static inline dw_die_ref
5678 new_die (enum dwarf_tag tag_value, dw_die_ref parent_die, tree t)
5679 {
5680   dw_die_ref die = new_die_raw (tag_value);
5681
5682   if (parent_die != NULL)
5683     add_child_die (parent_die, die);
5684   else
5685     {
5686       limbo_die_node *limbo_node;
5687
5688       /* No DIEs created after early dwarf should end up in limbo,
5689          because the limbo list should not persist past LTO
5690          streaming.  */
5691       if (tag_value != DW_TAG_compile_unit
5692           /* These are allowed because they're generated while
5693              breaking out COMDAT units late.  */
5694           && tag_value != DW_TAG_type_unit
5695           && tag_value != DW_TAG_skeleton_unit
5696           && !early_dwarf
5697           /* Allow nested functions to live in limbo because they will
5698              only temporarily live there, as decls_for_scope will fix
5699              them up.  */
5700           && (TREE_CODE (t) != FUNCTION_DECL
5701               || !decl_function_context (t))
5702           /* Same as nested functions above but for types.  Types that
5703              are local to a function will be fixed in
5704              decls_for_scope.  */
5705           && (!RECORD_OR_UNION_TYPE_P (t)
5706               || !TYPE_CONTEXT (t)
5707               || TREE_CODE (TYPE_CONTEXT (t)) != FUNCTION_DECL)
5708           /* FIXME debug-early: Allow late limbo DIE creation for LTO,
5709              especially in the ltrans stage, but once we implement LTO
5710              dwarf streaming, we should remove this exception.  */
5711           && !in_lto_p)
5712         {
5713           fprintf (stderr, "symbol ended up in limbo too late:");
5714           debug_generic_stmt (t);
5715           gcc_unreachable ();
5716         }
5717
5718       limbo_node = ggc_cleared_alloc<limbo_die_node> ();
5719       limbo_node->die = die;
5720       limbo_node->created_for = t;
5721       limbo_node->next = limbo_die_list;
5722       limbo_die_list = limbo_node;
5723     }
5724
5725   return die;
5726 }
5727
5728 /* Return the DIE associated with the given type specifier.  */
5729
5730 static inline dw_die_ref
5731 lookup_type_die (tree type)
5732 {
5733   dw_die_ref die = TYPE_SYMTAB_DIE (type);
5734   if (die && die->removed)
5735     {
5736       TYPE_SYMTAB_DIE (type) = NULL;
5737       return NULL;
5738     }
5739   return die;
5740 }
5741
5742 /* Given a TYPE_DIE representing the type TYPE, if TYPE is an
5743    anonymous type named by the typedef TYPE_DIE, return the DIE of the
5744    anonymous type instead the one of the naming typedef.  */
5745
5746 static inline dw_die_ref
5747 strip_naming_typedef (tree type, dw_die_ref type_die)
5748 {
5749   if (type
5750       && TREE_CODE (type) == RECORD_TYPE
5751       && type_die
5752       && type_die->die_tag == DW_TAG_typedef
5753       && is_naming_typedef_decl (TYPE_NAME (type)))
5754     type_die = get_AT_ref (type_die, DW_AT_type);
5755   return type_die;
5756 }
5757
5758 /* Like lookup_type_die, but if type is an anonymous type named by a
5759    typedef[1], return the DIE of the anonymous type instead the one of
5760    the naming typedef.  This is because in gen_typedef_die, we did
5761    equate the anonymous struct named by the typedef with the DIE of
5762    the naming typedef. So by default, lookup_type_die on an anonymous
5763    struct yields the DIE of the naming typedef.
5764
5765    [1]: Read the comment of is_naming_typedef_decl to learn about what
5766    a naming typedef is.  */
5767
5768 static inline dw_die_ref
5769 lookup_type_die_strip_naming_typedef (tree type)
5770 {
5771   dw_die_ref die = lookup_type_die (type);
5772   return strip_naming_typedef (type, die);
5773 }
5774
5775 /* Equate a DIE to a given type specifier.  */
5776
5777 static inline void
5778 equate_type_number_to_die (tree type, dw_die_ref type_die)
5779 {
5780   TYPE_SYMTAB_DIE (type) = type_die;
5781 }
5782
5783 /* Returns a hash value for X (which really is a die_struct).  */
5784
5785 inline hashval_t
5786 decl_die_hasher::hash (die_node *x)
5787 {
5788   return (hashval_t) x->decl_id;
5789 }
5790
5791 /* Return nonzero if decl_id of die_struct X is the same as UID of decl *Y.  */
5792
5793 inline bool
5794 decl_die_hasher::equal (die_node *x, tree y)
5795 {
5796   return (x->decl_id == DECL_UID (y));
5797 }
5798
5799 /* Return the DIE associated with a given declaration.  */
5800
5801 static inline dw_die_ref
5802 lookup_decl_die (tree decl)
5803 {
5804   dw_die_ref *die = decl_die_table->find_slot_with_hash (decl, DECL_UID (decl),
5805                                                          NO_INSERT);
5806   if (!die)
5807     return NULL;
5808   if ((*die)->removed)
5809     {
5810       decl_die_table->clear_slot (die);
5811       return NULL;
5812     }
5813   return *die;
5814 }
5815
5816
5817 /* For DECL which might have early dwarf output query a SYMBOL + OFFSET
5818    style reference.  Return true if we found one refering to a DIE for
5819    DECL, otherwise return false.  */
5820
5821 static bool
5822 dwarf2out_die_ref_for_decl (tree decl, const char **sym,
5823                             unsigned HOST_WIDE_INT *off)
5824 {
5825   dw_die_ref die;
5826
5827   if (flag_wpa && !decl_die_table)
5828     return false;
5829
5830   if (TREE_CODE (decl) == BLOCK)
5831     die = BLOCK_DIE (decl);
5832   else
5833     die = lookup_decl_die (decl);
5834   if (!die)
5835     return false;
5836
5837   /* During WPA stage we currently use DIEs to store the
5838      decl <-> label + offset map.  That's quite inefficient but it
5839      works for now.  */
5840   if (flag_wpa)
5841     {
5842       dw_die_ref ref = get_AT_ref (die, DW_AT_abstract_origin);
5843       if (!ref)
5844         {
5845           gcc_assert (die == comp_unit_die ());
5846           return false;
5847         }
5848       *off = ref->die_offset;
5849       *sym = ref->die_id.die_symbol;
5850       return true;
5851     }
5852
5853   /* Similar to get_ref_die_offset_label, but using the "correct"
5854      label.  */
5855   *off = die->die_offset;
5856   while (die->die_parent)
5857     die = die->die_parent;
5858   /* For the containing CU DIE we compute a die_symbol in
5859      compute_comp_unit_symbol.  */
5860   gcc_assert (die->die_tag == DW_TAG_compile_unit
5861               && die->die_id.die_symbol != NULL);
5862   *sym = die->die_id.die_symbol;
5863   return true;
5864 }
5865
5866 /* Add a reference of kind ATTR_KIND to a DIE at SYMBOL + OFFSET to DIE.  */
5867
5868 static void
5869 add_AT_external_die_ref (dw_die_ref die, enum dwarf_attribute attr_kind,
5870                          const char *symbol, HOST_WIDE_INT offset)
5871 {
5872   /* Create a fake DIE that contains the reference.  Don't use
5873      new_die because we don't want to end up in the limbo list.  */
5874   dw_die_ref ref = new_die_raw (die->die_tag);
5875   ref->die_id.die_symbol = IDENTIFIER_POINTER (get_identifier (symbol));
5876   ref->die_offset = offset;
5877   ref->with_offset = 1;
5878   add_AT_die_ref (die, attr_kind, ref);
5879 }
5880
5881 /* Create a DIE for DECL if required and add a reference to a DIE
5882    at SYMBOL + OFFSET which contains attributes dumped early.  */
5883
5884 static void
5885 dwarf2out_register_external_die (tree decl, const char *sym,
5886                                  unsigned HOST_WIDE_INT off)
5887 {
5888   if (debug_info_level == DINFO_LEVEL_NONE)
5889     return;
5890
5891   if (flag_wpa && !decl_die_table)
5892     decl_die_table = hash_table<decl_die_hasher>::create_ggc (1000);
5893
5894   dw_die_ref die
5895     = TREE_CODE (decl) == BLOCK ? BLOCK_DIE (decl) : lookup_decl_die (decl);
5896   gcc_assert (!die);
5897
5898   tree ctx;
5899   dw_die_ref parent = NULL;
5900   /* Need to lookup a DIE for the decls context - the containing
5901      function or translation unit.  */
5902   if (TREE_CODE (decl) == BLOCK)
5903     {
5904       ctx = BLOCK_SUPERCONTEXT (decl);
5905       /* ???  We do not output DIEs for all scopes thus skip as
5906          many DIEs as needed.  */
5907       while (TREE_CODE (ctx) == BLOCK
5908              && !BLOCK_DIE (ctx))
5909         ctx = BLOCK_SUPERCONTEXT (ctx);
5910     }
5911   else
5912     ctx = DECL_CONTEXT (decl);
5913   /* Peel types in the context stack.  */
5914   while (ctx && TYPE_P (ctx))
5915     ctx = TYPE_CONTEXT (ctx);
5916   /* Likewise namespaces in case we do not want to emit DIEs for them.  */
5917   if (debug_info_level <= DINFO_LEVEL_TERSE)
5918     while (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5919       ctx = DECL_CONTEXT (ctx);
5920   if (ctx)
5921     {
5922       if (TREE_CODE (ctx) == BLOCK)
5923         parent = BLOCK_DIE (ctx);
5924       else if (TREE_CODE (ctx) == TRANSLATION_UNIT_DECL
5925                /* Keep the 1:1 association during WPA.  */
5926                && !flag_wpa)
5927         /* Otherwise all late annotations go to the main CU which
5928            imports the original CUs.  */
5929         parent = comp_unit_die ();
5930       else if (TREE_CODE (ctx) == FUNCTION_DECL
5931                && TREE_CODE (decl) != PARM_DECL
5932                && TREE_CODE (decl) != BLOCK)
5933         /* Leave function local entities parent determination to when
5934            we process scope vars.  */
5935         ;
5936       else
5937         parent = lookup_decl_die (ctx);
5938     }
5939   else
5940     /* In some cases the FEs fail to set DECL_CONTEXT properly.
5941        Handle this case gracefully by globalizing stuff.  */
5942     parent = comp_unit_die ();
5943   /* Create a DIE "stub".  */
5944   switch (TREE_CODE (decl))
5945     {
5946     case TRANSLATION_UNIT_DECL:
5947       if (! flag_wpa)
5948         {
5949           die = comp_unit_die ();
5950           dw_die_ref import = new_die (DW_TAG_imported_unit, die, NULL_TREE);
5951           add_AT_external_die_ref (import, DW_AT_import, sym, off);
5952           /* We re-target all CU decls to the LTRANS CU DIE, so no need
5953              to create a DIE for the original CUs.  */
5954           return;
5955         }
5956       /* Keep the 1:1 association during WPA.  */
5957       die = new_die (DW_TAG_compile_unit, NULL, decl);
5958       break;
5959     case NAMESPACE_DECL:
5960       if (is_fortran (decl))
5961         die = new_die (DW_TAG_module, parent, decl);
5962       else
5963         die = new_die (DW_TAG_namespace, parent, decl);
5964       break;
5965     case FUNCTION_DECL:
5966       die = new_die (DW_TAG_subprogram, parent, decl);
5967       break;
5968     case VAR_DECL:
5969       die = new_die (DW_TAG_variable, parent, decl);
5970       break;
5971     case RESULT_DECL:
5972       die = new_die (DW_TAG_variable, parent, decl);
5973       break;
5974     case PARM_DECL:
5975       die = new_die (DW_TAG_formal_parameter, parent, decl);
5976       break;
5977     case CONST_DECL:
5978       die = new_die (DW_TAG_constant, parent, decl);
5979       break;
5980     case LABEL_DECL:
5981       die = new_die (DW_TAG_label, parent, decl);
5982       break;
5983     case BLOCK:
5984       die = new_die (DW_TAG_lexical_block, parent, decl);
5985       break;
5986     default:
5987       gcc_unreachable ();
5988     }
5989   if (TREE_CODE (decl) == BLOCK)
5990     BLOCK_DIE (decl) = die;
5991   else
5992     equate_decl_number_to_die (decl, die);
5993
5994   /* Add a reference to the DIE providing early debug at $sym + off.  */
5995   add_AT_external_die_ref (die, DW_AT_abstract_origin, sym, off);
5996 }
5997
5998 /* Returns a hash value for X (which really is a var_loc_list).  */
5999
6000 inline hashval_t
6001 decl_loc_hasher::hash (var_loc_list *x)
6002 {
6003   return (hashval_t) x->decl_id;
6004 }
6005
6006 /* Return nonzero if decl_id of var_loc_list X is the same as
6007    UID of decl *Y.  */
6008
6009 inline bool
6010 decl_loc_hasher::equal (var_loc_list *x, const_tree y)
6011 {
6012   return (x->decl_id == DECL_UID (y));
6013 }
6014
6015 /* Return the var_loc list associated with a given declaration.  */
6016
6017 static inline var_loc_list *
6018 lookup_decl_loc (const_tree decl)
6019 {
6020   if (!decl_loc_table)
6021     return NULL;
6022   return decl_loc_table->find_with_hash (decl, DECL_UID (decl));
6023 }
6024
6025 /* Returns a hash value for X (which really is a cached_dw_loc_list_list).  */
6026
6027 inline hashval_t
6028 dw_loc_list_hasher::hash (cached_dw_loc_list *x)
6029 {
6030   return (hashval_t) x->decl_id;
6031 }
6032
6033 /* Return nonzero if decl_id of cached_dw_loc_list X is the same as
6034    UID of decl *Y.  */
6035
6036 inline bool
6037 dw_loc_list_hasher::equal (cached_dw_loc_list *x, const_tree y)
6038 {
6039   return (x->decl_id == DECL_UID (y));
6040 }
6041
6042 /* Equate a DIE to a particular declaration.  */
6043
6044 static void
6045 equate_decl_number_to_die (tree decl, dw_die_ref decl_die)
6046 {
6047   unsigned int decl_id = DECL_UID (decl);
6048
6049   *decl_die_table->find_slot_with_hash (decl, decl_id, INSERT) = decl_die;
6050   decl_die->decl_id = decl_id;
6051 }
6052
6053 /* Return how many bits covers PIECE EXPR_LIST.  */
6054
6055 static HOST_WIDE_INT
6056 decl_piece_bitsize (rtx piece)
6057 {
6058   int ret = (int) GET_MODE (piece);
6059   if (ret)
6060     return ret;
6061   gcc_assert (GET_CODE (XEXP (piece, 0)) == CONCAT
6062               && CONST_INT_P (XEXP (XEXP (piece, 0), 0)));
6063   return INTVAL (XEXP (XEXP (piece, 0), 0));
6064 }
6065
6066 /* Return pointer to the location of location note in PIECE EXPR_LIST.  */
6067
6068 static rtx *
6069 decl_piece_varloc_ptr (rtx piece)
6070 {
6071   if ((int) GET_MODE (piece))
6072     return &XEXP (piece, 0);
6073   else
6074     return &XEXP (XEXP (piece, 0), 1);
6075 }
6076
6077 /* Create an EXPR_LIST for location note LOC_NOTE covering BITSIZE bits.
6078    Next is the chain of following piece nodes.  */
6079
6080 static rtx_expr_list *
6081 decl_piece_node (rtx loc_note, HOST_WIDE_INT bitsize, rtx next)
6082 {
6083   if (bitsize > 0 && bitsize <= (int) MAX_MACHINE_MODE)
6084     return alloc_EXPR_LIST (bitsize, loc_note, next);
6085   else
6086     return alloc_EXPR_LIST (0, gen_rtx_CONCAT (VOIDmode,
6087                                                GEN_INT (bitsize),
6088                                                loc_note), next);
6089 }
6090
6091 /* Return rtx that should be stored into loc field for
6092    LOC_NOTE and BITPOS/BITSIZE.  */
6093
6094 static rtx
6095 construct_piece_list (rtx loc_note, HOST_WIDE_INT bitpos,
6096                       HOST_WIDE_INT bitsize)
6097 {
6098   if (bitsize != -1)
6099     {
6100       loc_note = decl_piece_node (loc_note, bitsize, NULL_RTX);
6101       if (bitpos != 0)
6102         loc_note = decl_piece_node (NULL_RTX, bitpos, loc_note);
6103     }
6104   return loc_note;
6105 }
6106
6107 /* This function either modifies location piece list *DEST in
6108    place (if SRC and INNER is NULL), or copies location piece list
6109    *SRC to *DEST while modifying it.  Location BITPOS is modified
6110    to contain LOC_NOTE, any pieces overlapping it are removed resp.
6111    not copied and if needed some padding around it is added.
6112    When modifying in place, DEST should point to EXPR_LIST where
6113    earlier pieces cover PIECE_BITPOS bits, when copying SRC points
6114    to the start of the whole list and INNER points to the EXPR_LIST
6115    where earlier pieces cover PIECE_BITPOS bits.  */
6116
6117 static void
6118 adjust_piece_list (rtx *dest, rtx *src, rtx *inner,
6119                    HOST_WIDE_INT bitpos, HOST_WIDE_INT piece_bitpos,
6120                    HOST_WIDE_INT bitsize, rtx loc_note)
6121 {
6122   HOST_WIDE_INT diff;
6123   bool copy = inner != NULL;
6124
6125   if (copy)
6126     {
6127       /* First copy all nodes preceding the current bitpos.  */
6128       while (src != inner)
6129         {
6130           *dest = decl_piece_node (*decl_piece_varloc_ptr (*src),
6131                                    decl_piece_bitsize (*src), NULL_RTX);
6132           dest = &XEXP (*dest, 1);
6133           src = &XEXP (*src, 1);
6134         }
6135     }
6136   /* Add padding if needed.  */
6137   if (bitpos != piece_bitpos)
6138     {
6139       *dest = decl_piece_node (NULL_RTX, bitpos - piece_bitpos,
6140                                copy ? NULL_RTX : *dest);
6141       dest = &XEXP (*dest, 1);
6142     }
6143   else if (*dest && decl_piece_bitsize (*dest) == bitsize)
6144     {
6145       gcc_assert (!copy);
6146       /* A piece with correct bitpos and bitsize already exist,
6147          just update the location for it and return.  */
6148       *decl_piece_varloc_ptr (*dest) = loc_note;
6149       return;
6150     }
6151   /* Add the piece that changed.  */
6152   *dest = decl_piece_node (loc_note, bitsize, copy ? NULL_RTX : *dest);
6153   dest = &XEXP (*dest, 1);
6154   /* Skip over pieces that overlap it.  */
6155   diff = bitpos - piece_bitpos + bitsize;
6156   if (!copy)
6157     src = dest;
6158   while (diff > 0 && *src)
6159     {
6160       rtx piece = *src;
6161       diff -= decl_piece_bitsize (piece);
6162       if (copy)
6163         src = &XEXP (piece, 1);
6164       else
6165         {
6166           *src = XEXP (piece, 1);
6167           free_EXPR_LIST_node (piece);
6168         }
6169     }
6170   /* Add padding if needed.  */
6171   if (diff < 0 && *src)
6172     {
6173       if (!copy)
6174         dest = src;
6175       *dest = decl_piece_node (NULL_RTX, -diff, copy ? NULL_RTX : *dest);
6176       dest = &XEXP (*dest, 1);
6177     }
6178   if (!copy)
6179     return;
6180   /* Finally copy all nodes following it.  */
6181   while (*src)
6182     {
6183       *dest = decl_piece_node (*decl_piece_varloc_ptr (*src),
6184                                decl_piece_bitsize (*src), NULL_RTX);
6185       dest = &XEXP (*dest, 1);
6186       src = &XEXP (*src, 1);
6187     }
6188 }
6189
6190 /* Add a variable location node to the linked list for DECL.  */
6191
6192 static struct var_loc_node *
6193 add_var_loc_to_decl (tree decl, rtx loc_note, const char *label, var_loc_view view)
6194 {
6195   unsigned int decl_id;
6196   var_loc_list *temp;
6197   struct var_loc_node *loc = NULL;
6198   HOST_WIDE_INT bitsize = -1, bitpos = -1;
6199
6200   if (VAR_P (decl) && DECL_HAS_DEBUG_EXPR_P (decl))
6201     {
6202       tree realdecl = DECL_DEBUG_EXPR (decl);
6203       if (handled_component_p (realdecl)
6204           || (TREE_CODE (realdecl) == MEM_REF
6205               && TREE_CODE (TREE_OPERAND (realdecl, 0)) == ADDR_EXPR))
6206         {
6207           bool reverse;
6208           tree innerdecl = get_ref_base_and_extent_hwi (realdecl, &bitpos,
6209                                                         &bitsize, &reverse);
6210           if (!innerdecl
6211               || !DECL_P (innerdecl)
6212               || DECL_IGNORED_P (innerdecl)
6213               || TREE_STATIC (innerdecl)
6214               || bitsize == 0
6215               || bitpos + bitsize > 256)
6216             return NULL;
6217           decl = innerdecl;
6218         }
6219     }
6220
6221   decl_id = DECL_UID (decl);
6222   var_loc_list **slot
6223     = decl_loc_table->find_slot_with_hash (decl, decl_id, INSERT);
6224   if (*slot == NULL)
6225     {
6226       temp = ggc_cleared_alloc<var_loc_list> ();
6227       temp->decl_id = decl_id;
6228       *slot = temp;
6229     }
6230   else
6231     temp = *slot;
6232
6233   /* For PARM_DECLs try to keep around the original incoming value,
6234      even if that means we'll emit a zero-range .debug_loc entry.  */
6235   if (temp->last
6236       && temp->first == temp->last
6237       && TREE_CODE (decl) == PARM_DECL
6238       && NOTE_P (temp->first->loc)
6239       && NOTE_VAR_LOCATION_DECL (temp->first->loc) == decl
6240       && DECL_INCOMING_RTL (decl)
6241       && NOTE_VAR_LOCATION_LOC (temp->first->loc)
6242       && GET_CODE (NOTE_VAR_LOCATION_LOC (temp->first->loc))
6243          == GET_CODE (DECL_INCOMING_RTL (decl))
6244       && prev_real_insn (as_a<rtx_insn *> (temp->first->loc)) == NULL_RTX
6245       && (bitsize != -1
6246           || !rtx_equal_p (NOTE_VAR_LOCATION_LOC (temp->first->loc),
6247                            NOTE_VAR_LOCATION_LOC (loc_note))
6248           || (NOTE_VAR_LOCATION_STATUS (temp->first->loc)
6249               != NOTE_VAR_LOCATION_STATUS (loc_note))))
6250     {
6251       loc = ggc_cleared_alloc<var_loc_node> ();
6252       temp->first->next = loc;
6253       temp->last = loc;
6254       loc->loc = construct_piece_list (loc_note, bitpos, bitsize);
6255     }
6256   else if (temp->last)
6257     {
6258       struct var_loc_node *last = temp->last, *unused = NULL;
6259       rtx *piece_loc = NULL, last_loc_note;
6260       HOST_WIDE_INT piece_bitpos = 0;
6261       if (last->next)
6262         {
6263           last = last->next;
6264           gcc_assert (last->next == NULL);
6265         }
6266       if (bitsize != -1 && GET_CODE (last->loc) == EXPR_LIST)
6267         {
6268           piece_loc = &last->loc;
6269           do
6270             {
6271               HOST_WIDE_INT cur_bitsize = decl_piece_bitsize (*piece_loc);
6272               if (piece_bitpos + cur_bitsize > bitpos)
6273                 break;
6274               piece_bitpos += cur_bitsize;
6275               piece_loc = &XEXP (*piece_loc, 1);
6276             }
6277           while (*piece_loc);
6278         }
6279       /* TEMP->LAST here is either pointer to the last but one or
6280          last element in the chained list, LAST is pointer to the
6281          last element.  */
6282       if (label && strcmp (last->label, label) == 0 && last->view == view)
6283         {
6284           /* For SRA optimized variables if there weren't any real
6285              insns since last note, just modify the last node.  */
6286           if (piece_loc != NULL)
6287             {
6288               adjust_piece_list (piece_loc, NULL, NULL,
6289                                  bitpos, piece_bitpos, bitsize, loc_note);
6290               return NULL;
6291             }
6292           /* If the last note doesn't cover any instructions, remove it.  */
6293           if (temp->last != last)
6294             {
6295               temp->last->next = NULL;
6296               unused = last;
6297               last = temp->last;
6298               gcc_assert (strcmp (last->label, label) != 0 || last->view != view);
6299             }
6300           else
6301             {
6302               gcc_assert (temp->first == temp->last
6303                           || (temp->first->next == temp->last
6304                               && TREE_CODE (decl) == PARM_DECL));
6305               memset (temp->last, '\0', sizeof (*temp->last));
6306               temp->last->loc = construct_piece_list (loc_note, bitpos, bitsize);
6307               return temp->last;
6308             }
6309         }
6310       if (bitsize == -1 && NOTE_P (last->loc))
6311         last_loc_note = last->loc;
6312       else if (piece_loc != NULL
6313                && *piece_loc != NULL_RTX
6314                && piece_bitpos == bitpos
6315                && decl_piece_bitsize (*piece_loc) == bitsize)
6316         last_loc_note = *decl_piece_varloc_ptr (*piece_loc);
6317       else
6318         last_loc_note = NULL_RTX;
6319       /* If the current location is the same as the end of the list,
6320          and either both or neither of the locations is uninitialized,
6321          we have nothing to do.  */
6322       if (last_loc_note == NULL_RTX
6323           || (!rtx_equal_p (NOTE_VAR_LOCATION_LOC (last_loc_note),
6324                             NOTE_VAR_LOCATION_LOC (loc_note)))
6325           || ((NOTE_VAR_LOCATION_STATUS (last_loc_note)
6326                != NOTE_VAR_LOCATION_STATUS (loc_note))
6327               && ((NOTE_VAR_LOCATION_STATUS (last_loc_note)
6328                    == VAR_INIT_STATUS_UNINITIALIZED)
6329                   || (NOTE_VAR_LOCATION_STATUS (loc_note)
6330                       == VAR_INIT_STATUS_UNINITIALIZED))))
6331         {
6332           /* Add LOC to the end of list and update LAST.  If the last
6333              element of the list has been removed above, reuse its
6334              memory for the new node, otherwise allocate a new one.  */
6335           if (unused)
6336             {
6337               loc = unused;
6338               memset (loc, '\0', sizeof (*loc));
6339             }
6340           else
6341             loc = ggc_cleared_alloc<var_loc_node> ();
6342           if (bitsize == -1 || piece_loc == NULL)
6343             loc->loc = construct_piece_list (loc_note, bitpos, bitsize);
6344           else
6345             adjust_piece_list (&loc->loc, &last->loc, piece_loc,
6346                                bitpos, piece_bitpos, bitsize, loc_note);
6347           last->next = loc;
6348           /* Ensure TEMP->LAST will point either to the new last but one
6349              element of the chain, or to the last element in it.  */
6350           if (last != temp->last)
6351             temp->last = last;
6352         }
6353       else if (unused)
6354         ggc_free (unused);
6355     }
6356   else
6357     {
6358       loc = ggc_cleared_alloc<var_loc_node> ();
6359       temp->first = loc;
6360       temp->last = loc;
6361       loc->loc = construct_piece_list (loc_note, bitpos, bitsize);
6362     }
6363   return loc;
6364 }
6365 \f
6366 /* Keep track of the number of spaces used to indent the
6367    output of the debugging routines that print the structure of
6368    the DIE internal representation.  */
6369 static int print_indent;
6370
6371 /* Indent the line the number of spaces given by print_indent.  */
6372
6373 static inline void
6374 print_spaces (FILE *outfile)
6375 {
6376   fprintf (outfile, "%*s", print_indent, "");
6377 }
6378
6379 /* Print a type signature in hex.  */
6380
6381 static inline void
6382 print_signature (FILE *outfile, char *sig)
6383 {
6384   int i;
6385
6386   for (i = 0; i < DWARF_TYPE_SIGNATURE_SIZE; i++)
6387     fprintf (outfile, "%02x", sig[i] & 0xff);
6388 }
6389
6390 static inline void
6391 print_discr_value (FILE *outfile, dw_discr_value *discr_value)
6392 {
6393   if (discr_value->pos)
6394     fprintf (outfile, HOST_WIDE_INT_PRINT_UNSIGNED, discr_value->v.sval);
6395   else
6396     fprintf (outfile, HOST_WIDE_INT_PRINT_DEC, discr_value->v.uval);
6397 }
6398
6399 static void print_loc_descr (dw_loc_descr_ref, FILE *);
6400
6401 /* Print the value associated to the VAL DWARF value node to OUTFILE.  If
6402    RECURSE, output location descriptor operations.  */
6403
6404 static void
6405 print_dw_val (dw_val_node *val, bool recurse, FILE *outfile)
6406 {
6407   switch (val->val_class)
6408     {
6409     case dw_val_class_addr:
6410       fprintf (outfile, "address");
6411       break;
6412     case dw_val_class_offset:
6413       fprintf (outfile, "offset");
6414       break;
6415     case dw_val_class_loc:
6416       fprintf (outfile, "location descriptor");
6417       if (val->v.val_loc == NULL)
6418         fprintf (outfile, " -> <null>\n");
6419       else if (recurse)
6420         {
6421           fprintf (outfile, ":\n");
6422           print_indent += 4;
6423           print_loc_descr (val->v.val_loc, outfile);
6424           print_indent -= 4;
6425         }
6426       else
6427         fprintf (outfile, " (%p)\n", (void *) val->v.val_loc);
6428       break;
6429     case dw_val_class_loc_list:
6430       fprintf (outfile, "location list -> label:%s",
6431                val->v.val_loc_list->ll_symbol);
6432       break;
6433     case dw_val_class_view_list:
6434       val = view_list_to_loc_list_val_node (val);
6435       fprintf (outfile, "location list with views -> labels:%s and %s",
6436                val->v.val_loc_list->ll_symbol,
6437                val->v.val_loc_list->vl_symbol);
6438       break;
6439     case dw_val_class_range_list:
6440       fprintf (outfile, "range list");
6441       break;
6442     case dw_val_class_const:
6443     case dw_val_class_const_implicit:
6444       fprintf (outfile, HOST_WIDE_INT_PRINT_DEC, val->v.val_int);
6445       break;
6446     case dw_val_class_unsigned_const:
6447     case dw_val_class_unsigned_const_implicit:
6448       fprintf (outfile, HOST_WIDE_INT_PRINT_UNSIGNED, val->v.val_unsigned);
6449       break;
6450     case dw_val_class_const_double:
6451       fprintf (outfile, "constant (" HOST_WIDE_INT_PRINT_DEC","\
6452                         HOST_WIDE_INT_PRINT_UNSIGNED")",
6453                val->v.val_double.high,
6454                val->v.val_double.low);
6455       break;
6456     case dw_val_class_wide_int:
6457       {
6458         int i = val->v.val_wide->get_len ();
6459         fprintf (outfile, "constant (");
6460         gcc_assert (i > 0);
6461         if (val->v.val_wide->elt (i - 1) == 0)
6462           fprintf (outfile, "0x");
6463         fprintf (outfile, HOST_WIDE_INT_PRINT_HEX,
6464                  val->v.val_wide->elt (--i));
6465         while (--i >= 0)
6466           fprintf (outfile, HOST_WIDE_INT_PRINT_PADDED_HEX,
6467                    val->v.val_wide->elt (i));
6468         fprintf (outfile, ")");
6469         break;
6470       }
6471     case dw_val_class_vec:
6472       fprintf (outfile, "floating-point or vector constant");
6473       break;
6474     case dw_val_class_flag:
6475       fprintf (outfile, "%u", val->v.val_flag);
6476       break;
6477     case dw_val_class_die_ref:
6478       if (val->v.val_die_ref.die != NULL)
6479         {
6480           dw_die_ref die = val->v.val_die_ref.die;
6481
6482           if (die->comdat_type_p)
6483             {
6484               fprintf (outfile, "die -> signature: ");
6485               print_signature (outfile,
6486                                die->die_id.die_type_node->signature);
6487             }
6488           else if (die->die_id.die_symbol)
6489             {
6490               fprintf (outfile, "die -> label: %s", die->die_id.die_symbol);
6491               if (die->with_offset)
6492                 fprintf (outfile, " + %ld", die->die_offset);
6493             }
6494           else
6495             fprintf (outfile, "die -> %ld", die->die_offset);
6496           fprintf (outfile, " (%p)", (void *) die);
6497         }
6498       else
6499         fprintf (outfile, "die -> <null>");
6500       break;
6501     case dw_val_class_vms_delta:
6502       fprintf (outfile, "delta: @slotcount(%s-%s)",
6503                val->v.val_vms_delta.lbl2, val->v.val_vms_delta.lbl1);
6504       break;
6505     case dw_val_class_symview:
6506       fprintf (outfile, "view: %s", val->v.val_symbolic_view);
6507       break;
6508     case dw_val_class_lbl_id:
6509     case dw_val_class_lineptr:
6510     case dw_val_class_macptr:
6511     case dw_val_class_loclistsptr:
6512     case dw_val_class_high_pc:
6513       fprintf (outfile, "label: %s", val->v.val_lbl_id);
6514       break;
6515     case dw_val_class_str:
6516       if (val->v.val_str->str != NULL)
6517         fprintf (outfile, "\"%s\"", val->v.val_str->str);
6518       else
6519         fprintf (outfile, "<null>");
6520       break;
6521     case dw_val_class_file:
6522     case dw_val_class_file_implicit:
6523       fprintf (outfile, "\"%s\" (%d)", val->v.val_file->filename,
6524                val->v.val_file->emitted_number);
6525       break;
6526     case dw_val_class_data8:
6527       {
6528         int i;
6529
6530         for (i = 0; i < 8; i++)
6531           fprintf (outfile, "%02x", val->v.val_data8[i]);
6532         break;
6533       }
6534     case dw_val_class_discr_value:
6535       print_discr_value (outfile, &val->v.val_discr_value);
6536       break;
6537     case dw_val_class_discr_list:
6538       for (dw_discr_list_ref node = val->v.val_discr_list;
6539            node != NULL;
6540            node = node->dw_discr_next)
6541         {
6542           if (node->dw_discr_range)
6543             {
6544               fprintf (outfile, " .. ");
6545               print_discr_value (outfile, &node->dw_discr_lower_bound);
6546               print_discr_value (outfile, &node->dw_discr_upper_bound);
6547             }
6548           else
6549             print_discr_value (outfile, &node->dw_discr_lower_bound);
6550
6551           if (node->dw_discr_next != NULL)
6552             fprintf (outfile, " | ");
6553         }
6554     default:
6555       break;
6556     }
6557 }
6558
6559 /* Likewise, for a DIE attribute.  */
6560
6561 static void
6562 print_attribute (dw_attr_node *a, bool recurse, FILE *outfile)
6563 {
6564   print_dw_val (&a->dw_attr_val, recurse, outfile);
6565 }
6566
6567
6568 /* Print the list of operands in the LOC location description to OUTFILE.  This
6569    routine is a debugging aid only.  */
6570
6571 static void
6572 print_loc_descr (dw_loc_descr_ref loc, FILE *outfile)
6573 {
6574   dw_loc_descr_ref l = loc;
6575
6576   if (loc == NULL)
6577     {
6578       print_spaces (outfile);
6579       fprintf (outfile, "<null>\n");
6580       return;
6581     }
6582
6583   for (l = loc; l != NULL; l = l->dw_loc_next)
6584     {
6585       print_spaces (outfile);
6586       fprintf (outfile, "(%p) %s",
6587                (void *) l,
6588                dwarf_stack_op_name (l->dw_loc_opc));
6589       if (l->dw_loc_oprnd1.val_class != dw_val_class_none)
6590         {
6591           fprintf (outfile, " ");
6592           print_dw_val (&l->dw_loc_oprnd1, false, outfile);
6593         }
6594       if (l->dw_loc_oprnd2.val_class != dw_val_class_none)
6595         {
6596           fprintf (outfile, ", ");
6597           print_dw_val (&l->dw_loc_oprnd2, false, outfile);
6598         }
6599       fprintf (outfile, "\n");
6600     }
6601 }
6602
6603 /* Print the information associated with a given DIE, and its children.
6604    This routine is a debugging aid only.  */
6605
6606 static void
6607 print_die (dw_die_ref die, FILE *outfile)
6608 {
6609   dw_attr_node *a;
6610   dw_die_ref c;
6611   unsigned ix;
6612
6613   print_spaces (outfile);
6614   fprintf (outfile, "DIE %4ld: %s (%p)\n",
6615            die->die_offset, dwarf_tag_name (die->die_tag),
6616            (void*) die);
6617   print_spaces (outfile);
6618   fprintf (outfile, "  abbrev id: %lu", die->die_abbrev);
6619   fprintf (outfile, " offset: %ld", die->die_offset);
6620   fprintf (outfile, " mark: %d\n", die->die_mark);
6621
6622   if (die->comdat_type_p)
6623     {
6624       print_spaces (outfile);
6625       fprintf (outfile, "  signature: ");
6626       print_signature (outfile, die->die_id.die_type_node->signature);
6627       fprintf (outfile, "\n");
6628     }
6629
6630   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
6631     {
6632       print_spaces (outfile);
6633       fprintf (outfile, "  %s: ", dwarf_attr_name (a->dw_attr));
6634
6635       print_attribute (a, true, outfile);
6636       fprintf (outfile, "\n");
6637     }
6638
6639   if (die->die_child != NULL)
6640     {
6641       print_indent += 4;
6642       FOR_EACH_CHILD (die, c, print_die (c, outfile));
6643       print_indent -= 4;
6644     }
6645   if (print_indent == 0)
6646     fprintf (outfile, "\n");
6647 }
6648
6649 /* Print the list of operations in the LOC location description.  */
6650
6651 DEBUG_FUNCTION void
6652 debug_dwarf_loc_descr (dw_loc_descr_ref loc)
6653 {
6654   print_loc_descr (loc, stderr);
6655 }
6656
6657 /* Print the information collected for a given DIE.  */
6658
6659 DEBUG_FUNCTION void
6660 debug_dwarf_die (dw_die_ref die)
6661 {
6662   print_die (die, stderr);
6663 }
6664
6665 DEBUG_FUNCTION void
6666 debug (die_struct &ref)
6667 {
6668   print_die (&ref, stderr);
6669 }
6670
6671 DEBUG_FUNCTION void
6672 debug (die_struct *ptr)
6673 {
6674   if (ptr)
6675     debug (*ptr);
6676   else
6677     fprintf (stderr, "<nil>\n");
6678 }
6679
6680
6681 /* Print all DWARF information collected for the compilation unit.
6682    This routine is a debugging aid only.  */
6683
6684 DEBUG_FUNCTION void
6685 debug_dwarf (void)
6686 {
6687   print_indent = 0;
6688   print_die (comp_unit_die (), stderr);
6689 }
6690
6691 /* Verify the DIE tree structure.  */
6692
6693 DEBUG_FUNCTION void
6694 verify_die (dw_die_ref die)
6695 {
6696   gcc_assert (!die->die_mark);
6697   if (die->die_parent == NULL
6698       && die->die_sib == NULL)
6699     return;
6700   /* Verify the die_sib list is cyclic.  */
6701   dw_die_ref x = die;
6702   do
6703     {
6704       x->die_mark = 1;
6705       x = x->die_sib;
6706     }
6707   while (x && !x->die_mark);
6708   gcc_assert (x == die);
6709   x = die;
6710   do
6711     {
6712       /* Verify all dies have the same parent.  */
6713       gcc_assert (x->die_parent == die->die_parent);
6714       if (x->die_child)
6715         {
6716           /* Verify the child has the proper parent and recurse.  */
6717           gcc_assert (x->die_child->die_parent == x);
6718           verify_die (x->die_child);
6719         }
6720       x->die_mark = 0;
6721       x = x->die_sib;
6722     }
6723   while (x && x->die_mark);
6724 }
6725
6726 /* Sanity checks on DIEs.  */
6727
6728 static void
6729 check_die (dw_die_ref die)
6730 {
6731   unsigned ix;
6732   dw_attr_node *a;
6733   bool inline_found = false;
6734   int n_location = 0, n_low_pc = 0, n_high_pc = 0, n_artificial = 0;
6735   int n_decl_line = 0, n_decl_column = 0, n_decl_file = 0;
6736   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
6737     {
6738       switch (a->dw_attr)
6739         {
6740         case DW_AT_inline:
6741           if (a->dw_attr_val.v.val_unsigned)
6742             inline_found = true;
6743           break;
6744         case DW_AT_location:
6745           ++n_location;
6746           break;
6747         case DW_AT_low_pc:
6748           ++n_low_pc;
6749           break;
6750         case DW_AT_high_pc:
6751           ++n_high_pc;
6752           break;
6753         case DW_AT_artificial:
6754           ++n_artificial;
6755           break;
6756         case DW_AT_decl_column:
6757           ++n_decl_column;
6758           break;
6759         case DW_AT_decl_line:
6760           ++n_decl_line;
6761           break;
6762         case DW_AT_decl_file:
6763           ++n_decl_file;
6764           break;
6765         default:
6766           break;
6767         }
6768     }
6769   if (n_location > 1 || n_low_pc > 1 || n_high_pc > 1 || n_artificial > 1
6770       || n_decl_column > 1 || n_decl_line > 1 || n_decl_file > 1)
6771     {
6772       fprintf (stderr, "Duplicate attributes in DIE:\n");
6773       debug_dwarf_die (die);
6774       gcc_unreachable ();
6775     }
6776   if (inline_found)
6777     {
6778       /* A debugging information entry that is a member of an abstract
6779          instance tree [that has DW_AT_inline] should not contain any
6780          attributes which describe aspects of the subroutine which vary
6781          between distinct inlined expansions or distinct out-of-line
6782          expansions.  */
6783       FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
6784         gcc_assert (a->dw_attr != DW_AT_low_pc
6785                     && a->dw_attr != DW_AT_high_pc
6786                     && a->dw_attr != DW_AT_location
6787                     && a->dw_attr != DW_AT_frame_base
6788                     && a->dw_attr != DW_AT_call_all_calls
6789                     && a->dw_attr != DW_AT_GNU_all_call_sites);
6790     }
6791 }
6792 \f
6793 #define CHECKSUM(FOO) md5_process_bytes (&(FOO), sizeof (FOO), ctx)
6794 #define CHECKSUM_BLOCK(FOO, SIZE) md5_process_bytes ((FOO), (SIZE), ctx)
6795 #define CHECKSUM_STRING(FOO) md5_process_bytes ((FOO), strlen (FOO), ctx)
6796
6797 /* Calculate the checksum of a location expression.  */
6798
6799 static inline void
6800 loc_checksum (dw_loc_descr_ref loc, struct md5_ctx *ctx)
6801 {
6802   int tem;
6803   inchash::hash hstate;
6804   hashval_t hash;
6805
6806   tem = (loc->dtprel << 8) | ((unsigned int) loc->dw_loc_opc);
6807   CHECKSUM (tem);
6808   hash_loc_operands (loc, hstate);
6809   hash = hstate.end();
6810   CHECKSUM (hash);
6811 }
6812
6813 /* Calculate the checksum of an attribute.  */
6814
6815 static void
6816 attr_checksum (dw_attr_node *at, struct md5_ctx *ctx, int *mark)
6817 {
6818   dw_loc_descr_ref loc;
6819   rtx r;
6820
6821   CHECKSUM (at->dw_attr);
6822
6823   /* We don't care that this was compiled with a different compiler
6824      snapshot; if the output is the same, that's what matters.  */
6825   if (at->dw_attr == DW_AT_producer)
6826     return;
6827
6828   switch (AT_class (at))
6829     {
6830     case dw_val_class_const:
6831     case dw_val_class_const_implicit:
6832       CHECKSUM (at->dw_attr_val.v.val_int);
6833       break;
6834     case dw_val_class_unsigned_const:
6835     case dw_val_class_unsigned_const_implicit:
6836       CHECKSUM (at->dw_attr_val.v.val_unsigned);
6837       break;
6838     case dw_val_class_const_double:
6839       CHECKSUM (at->dw_attr_val.v.val_double);
6840       break;
6841     case dw_val_class_wide_int:
6842       CHECKSUM_BLOCK (at->dw_attr_val.v.val_wide->get_val (),
6843                       get_full_len (*at->dw_attr_val.v.val_wide)
6844                       * HOST_BITS_PER_WIDE_INT / HOST_BITS_PER_CHAR);
6845       break;
6846     case dw_val_class_vec:
6847       CHECKSUM_BLOCK (at->dw_attr_val.v.val_vec.array,
6848                       (at->dw_attr_val.v.val_vec.length
6849                        * at->dw_attr_val.v.val_vec.elt_size));
6850       break;
6851     case dw_val_class_flag:
6852       CHECKSUM (at->dw_attr_val.v.val_flag);
6853       break;
6854     case dw_val_class_str:
6855       CHECKSUM_STRING (AT_string (at));
6856       break;
6857
6858     case dw_val_class_addr:
6859       r = AT_addr (at);
6860       gcc_assert (GET_CODE (r) == SYMBOL_REF);
6861       CHECKSUM_STRING (XSTR (r, 0));
6862       break;
6863
6864     case dw_val_class_offset:
6865       CHECKSUM (at->dw_attr_val.v.val_offset);
6866       break;
6867
6868     case dw_val_class_loc:
6869       for (loc = AT_loc (at); loc; loc = loc->dw_loc_next)
6870         loc_checksum (loc, ctx);
6871       break;
6872
6873     case dw_val_class_die_ref:
6874       die_checksum (AT_ref (at), ctx, mark);
6875       break;
6876
6877     case dw_val_class_fde_ref:
6878     case dw_val_class_vms_delta:
6879     case dw_val_class_symview:
6880     case dw_val_class_lbl_id:
6881     case dw_val_class_lineptr:
6882     case dw_val_class_macptr:
6883     case dw_val_class_loclistsptr:
6884     case dw_val_class_high_pc:
6885       break;
6886
6887     case dw_val_class_file:
6888     case dw_val_class_file_implicit:
6889       CHECKSUM_STRING (AT_file (at)->filename);
6890       break;
6891
6892     case dw_val_class_data8:
6893       CHECKSUM (at->dw_attr_val.v.val_data8);
6894       break;
6895
6896     default:
6897       break;
6898     }
6899 }
6900
6901 /* Calculate the checksum of a DIE.  */
6902
6903 static void
6904 die_checksum (dw_die_ref die, struct md5_ctx *ctx, int *mark)
6905 {
6906   dw_die_ref c;
6907   dw_attr_node *a;
6908   unsigned ix;
6909
6910   /* To avoid infinite recursion.  */
6911   if (die->die_mark)
6912     {
6913       CHECKSUM (die->die_mark);
6914       return;
6915     }
6916   die->die_mark = ++(*mark);
6917
6918   CHECKSUM (die->die_tag);
6919
6920   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
6921     attr_checksum (a, ctx, mark);
6922
6923   FOR_EACH_CHILD (die, c, die_checksum (c, ctx, mark));
6924 }
6925
6926 #undef CHECKSUM
6927 #undef CHECKSUM_BLOCK
6928 #undef CHECKSUM_STRING
6929
6930 /* For DWARF-4 types, include the trailing NULL when checksumming strings.  */
6931 #define CHECKSUM(FOO) md5_process_bytes (&(FOO), sizeof (FOO), ctx)
6932 #define CHECKSUM_BLOCK(FOO, SIZE) md5_process_bytes ((FOO), (SIZE), ctx)
6933 #define CHECKSUM_STRING(FOO) md5_process_bytes ((FOO), strlen (FOO) + 1, ctx)
6934 #define CHECKSUM_SLEB128(FOO) checksum_sleb128 ((FOO), ctx)
6935 #define CHECKSUM_ULEB128(FOO) checksum_uleb128 ((FOO), ctx)
6936 #define CHECKSUM_ATTR(FOO) \
6937   if (FOO) attr_checksum_ordered (die->die_tag, (FOO), ctx, mark)
6938
6939 /* Calculate the checksum of a number in signed LEB128 format.  */
6940
6941 static void
6942 checksum_sleb128 (HOST_WIDE_INT value, struct md5_ctx *ctx)
6943 {
6944   unsigned char byte;
6945   bool more;
6946
6947   while (1)
6948     {
6949       byte = (value & 0x7f);
6950       value >>= 7;
6951       more = !((value == 0 && (byte & 0x40) == 0)
6952                 || (value == -1 && (byte & 0x40) != 0));
6953       if (more)
6954         byte |= 0x80;
6955       CHECKSUM (byte);
6956       if (!more)
6957         break;
6958     }
6959 }
6960
6961 /* Calculate the checksum of a number in unsigned LEB128 format.  */
6962
6963 static void
6964 checksum_uleb128 (unsigned HOST_WIDE_INT value, struct md5_ctx *ctx)
6965 {
6966   while (1)
6967     {
6968       unsigned char byte = (value & 0x7f);
6969       value >>= 7;
6970       if (value != 0)
6971         /* More bytes to follow.  */
6972         byte |= 0x80;
6973       CHECKSUM (byte);
6974       if (value == 0)
6975         break;
6976     }
6977 }
6978
6979 /* Checksum the context of the DIE.  This adds the names of any
6980    surrounding namespaces or structures to the checksum.  */
6981
6982 static void
6983 checksum_die_context (dw_die_ref die, struct md5_ctx *ctx)
6984 {
6985   const char *name;
6986   dw_die_ref spec;
6987   int tag = die->die_tag;
6988
6989   if (tag != DW_TAG_namespace
6990       && tag != DW_TAG_structure_type
6991       && tag != DW_TAG_class_type)
6992     return;
6993
6994   name = get_AT_string (die, DW_AT_name);
6995
6996   spec = get_AT_ref (die, DW_AT_specification);
6997   if (spec != NULL)
6998     die = spec;
6999
7000   if (die->die_parent != NULL)
7001     checksum_die_context (die->die_parent, ctx);
7002
7003   CHECKSUM_ULEB128 ('C');
7004   CHECKSUM_ULEB128 (tag);
7005   if (name != NULL)
7006     CHECKSUM_STRING (name);
7007 }
7008
7009 /* Calculate the checksum of a location expression.  */
7010
7011 static inline void
7012 loc_checksum_ordered (dw_loc_descr_ref loc, struct md5_ctx *ctx)
7013 {
7014   /* Special case for lone DW_OP_plus_uconst: checksum as if the location
7015      were emitted as a DW_FORM_sdata instead of a location expression.  */
7016   if (loc->dw_loc_opc == DW_OP_plus_uconst && loc->dw_loc_next == NULL)
7017     {
7018       CHECKSUM_ULEB128 (DW_FORM_sdata);
7019       CHECKSUM_SLEB128 ((HOST_WIDE_INT) loc->dw_loc_oprnd1.v.val_unsigned);
7020       return;
7021     }
7022
7023   /* Otherwise, just checksum the raw location expression.  */
7024   while (loc != NULL)
7025     {
7026       inchash::hash hstate;
7027       hashval_t hash;
7028
7029       CHECKSUM_ULEB128 (loc->dtprel);
7030       CHECKSUM_ULEB128 (loc->dw_loc_opc);
7031       hash_loc_operands (loc, hstate);
7032       hash = hstate.end ();
7033       CHECKSUM (hash);
7034       loc = loc->dw_loc_next;
7035     }
7036 }
7037
7038 /* Calculate the checksum of an attribute.  */
7039
7040 static void
7041 attr_checksum_ordered (enum dwarf_tag tag, dw_attr_node *at,
7042                        struct md5_ctx *ctx, int *mark)
7043 {
7044   dw_loc_descr_ref loc;
7045   rtx r;
7046
7047   if (AT_class (at) == dw_val_class_die_ref)
7048     {
7049       dw_die_ref target_die = AT_ref (at);
7050
7051       /* For pointer and reference types, we checksum only the (qualified)
7052          name of the target type (if there is a name).  For friend entries,
7053          we checksum only the (qualified) name of the target type or function.
7054          This allows the checksum to remain the same whether the target type
7055          is complete or not.  */
7056       if ((at->dw_attr == DW_AT_type
7057            && (tag == DW_TAG_pointer_type
7058                || tag == DW_TAG_reference_type
7059                || tag == DW_TAG_rvalue_reference_type
7060                || tag == DW_TAG_ptr_to_member_type))
7061           || (at->dw_attr == DW_AT_friend
7062               && tag == DW_TAG_friend))
7063         {
7064           dw_attr_node *name_attr = get_AT (target_die, DW_AT_name);
7065
7066           if (name_attr != NULL)
7067             {
7068               dw_die_ref decl = get_AT_ref (target_die, DW_AT_specification);
7069
7070               if (decl == NULL)
7071                 decl = target_die;
7072               CHECKSUM_ULEB128 ('N');
7073               CHECKSUM_ULEB128 (at->dw_attr);
7074               if (decl->die_parent != NULL)
7075                 checksum_die_context (decl->die_parent, ctx);
7076               CHECKSUM_ULEB128 ('E');
7077               CHECKSUM_STRING (AT_string (name_attr));
7078               return;
7079             }
7080         }
7081
7082       /* For all other references to another DIE, we check to see if the
7083          target DIE has already been visited.  If it has, we emit a
7084          backward reference; if not, we descend recursively.  */
7085       if (target_die->die_mark > 0)
7086         {
7087           CHECKSUM_ULEB128 ('R');
7088           CHECKSUM_ULEB128 (at->dw_attr);
7089           CHECKSUM_ULEB128 (target_die->die_mark);
7090         }
7091       else
7092         {
7093           dw_die_ref decl = get_AT_ref (target_die, DW_AT_specification);
7094
7095           if (decl == NULL)
7096             decl = target_die;
7097           target_die->die_mark = ++(*mark);
7098           CHECKSUM_ULEB128 ('T');
7099           CHECKSUM_ULEB128 (at->dw_attr);
7100           if (decl->die_parent != NULL)
7101             checksum_die_context (decl->die_parent, ctx);
7102           die_checksum_ordered (target_die, ctx, mark);
7103         }
7104       return;
7105     }
7106
7107   CHECKSUM_ULEB128 ('A');
7108   CHECKSUM_ULEB128 (at->dw_attr);
7109
7110   switch (AT_class (at))
7111     {
7112     case dw_val_class_const:
7113     case dw_val_class_const_implicit:
7114       CHECKSUM_ULEB128 (DW_FORM_sdata);
7115       CHECKSUM_SLEB128 (at->dw_attr_val.v.val_int);
7116       break;
7117
7118     case dw_val_class_unsigned_const:
7119     case dw_val_class_unsigned_const_implicit:
7120       CHECKSUM_ULEB128 (DW_FORM_sdata);
7121       CHECKSUM_SLEB128 ((int) at->dw_attr_val.v.val_unsigned);
7122       break;
7123
7124     case dw_val_class_const_double:
7125       CHECKSUM_ULEB128 (DW_FORM_block);
7126       CHECKSUM_ULEB128 (sizeof (at->dw_attr_val.v.val_double));
7127       CHECKSUM (at->dw_attr_val.v.val_double);
7128       break;
7129
7130     case dw_val_class_wide_int:
7131       CHECKSUM_ULEB128 (DW_FORM_block);
7132       CHECKSUM_ULEB128 (get_full_len (*at->dw_attr_val.v.val_wide)
7133                         * HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT);
7134       CHECKSUM_BLOCK (at->dw_attr_val.v.val_wide->get_val (),
7135                       get_full_len (*at->dw_attr_val.v.val_wide)
7136                       * HOST_BITS_PER_WIDE_INT / HOST_BITS_PER_CHAR);
7137       break;
7138
7139     case dw_val_class_vec:
7140       CHECKSUM_ULEB128 (DW_FORM_block);
7141       CHECKSUM_ULEB128 (at->dw_attr_val.v.val_vec.length
7142                         * at->dw_attr_val.v.val_vec.elt_size);
7143       CHECKSUM_BLOCK (at->dw_attr_val.v.val_vec.array,
7144                       (at->dw_attr_val.v.val_vec.length
7145                        * at->dw_attr_val.v.val_vec.elt_size));
7146       break;
7147
7148     case dw_val_class_flag:
7149       CHECKSUM_ULEB128 (DW_FORM_flag);
7150       CHECKSUM_ULEB128 (at->dw_attr_val.v.val_flag ? 1 : 0);
7151       break;
7152
7153     case dw_val_class_str:
7154       CHECKSUM_ULEB128 (DW_FORM_string);
7155       CHECKSUM_STRING (AT_string (at));
7156       break;
7157
7158     case dw_val_class_addr:
7159       r = AT_addr (at);
7160       gcc_assert (GET_CODE (r) == SYMBOL_REF);
7161       CHECKSUM_ULEB128 (DW_FORM_string);
7162       CHECKSUM_STRING (XSTR (r, 0));
7163       break;
7164
7165     case dw_val_class_offset:
7166       CHECKSUM_ULEB128 (DW_FORM_sdata);
7167       CHECKSUM_ULEB128 (at->dw_attr_val.v.val_offset);
7168       break;
7169
7170     case dw_val_class_loc:
7171       for (loc = AT_loc (at); loc; loc = loc->dw_loc_next)
7172         loc_checksum_ordered (loc, ctx);
7173       break;
7174
7175     case dw_val_class_fde_ref:
7176     case dw_val_class_symview:
7177     case dw_val_class_lbl_id:
7178     case dw_val_class_lineptr:
7179     case dw_val_class_macptr:
7180     case dw_val_class_loclistsptr:
7181     case dw_val_class_high_pc:
7182       break;
7183
7184     case dw_val_class_file:
7185     case dw_val_class_file_implicit:
7186       CHECKSUM_ULEB128 (DW_FORM_string);
7187       CHECKSUM_STRING (AT_file (at)->filename);
7188       break;
7189
7190     case dw_val_class_data8:
7191       CHECKSUM (at->dw_attr_val.v.val_data8);
7192       break;
7193
7194     default:
7195       break;
7196     }
7197 }
7198
7199 struct checksum_attributes
7200 {
7201   dw_attr_node *at_name;
7202   dw_attr_node *at_type;
7203   dw_attr_node *at_friend;
7204   dw_attr_node *at_accessibility;
7205   dw_attr_node *at_address_class;
7206   dw_attr_node *at_alignment;
7207   dw_attr_node *at_allocated;
7208   dw_attr_node *at_artificial;
7209   dw_attr_node *at_associated;
7210   dw_attr_node *at_binary_scale;
7211   dw_attr_node *at_bit_offset;
7212   dw_attr_node *at_bit_size;
7213   dw_attr_node *at_bit_stride;
7214   dw_attr_node *at_byte_size;
7215   dw_attr_node *at_byte_stride;
7216   dw_attr_node *at_const_value;
7217   dw_attr_node *at_containing_type;
7218   dw_attr_node *at_count;
7219   dw_attr_node *at_data_location;
7220   dw_attr_node *at_data_member_location;
7221   dw_attr_node *at_decimal_scale;
7222   dw_attr_node *at_decimal_sign;
7223   dw_attr_node *at_default_value;
7224   dw_attr_node *at_digit_count;
7225   dw_attr_node *at_discr;
7226   dw_attr_node *at_discr_list;
7227   dw_attr_node *at_discr_value;
7228   dw_attr_node *at_encoding;
7229   dw_attr_node *at_endianity;
7230   dw_attr_node *at_explicit;
7231   dw_attr_node *at_is_optional;
7232   dw_attr_node *at_location;
7233   dw_attr_node *at_lower_bound;
7234   dw_attr_node *at_mutable;
7235   dw_attr_node *at_ordering;
7236   dw_attr_node *at_picture_string;
7237   dw_attr_node *at_prototyped;
7238   dw_attr_node *at_small;
7239   dw_attr_node *at_segment;
7240   dw_attr_node *at_string_length;
7241   dw_attr_node *at_string_length_bit_size;
7242   dw_attr_node *at_string_length_byte_size;
7243   dw_attr_node *at_threads_scaled;
7244   dw_attr_node *at_upper_bound;
7245   dw_attr_node *at_use_location;
7246   dw_attr_node *at_use_UTF8;
7247   dw_attr_node *at_variable_parameter;
7248   dw_attr_node *at_virtuality;
7249   dw_attr_node *at_visibility;
7250   dw_attr_node *at_vtable_elem_location;
7251 };
7252
7253 /* Collect the attributes that we will want to use for the checksum.  */
7254
7255 static void
7256 collect_checksum_attributes (struct checksum_attributes *attrs, dw_die_ref die)
7257 {
7258   dw_attr_node *a;
7259   unsigned ix;
7260
7261   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
7262     {
7263       switch (a->dw_attr)
7264         {
7265         case DW_AT_name:
7266           attrs->at_name = a;
7267           break;
7268         case DW_AT_type:
7269           attrs->at_type = a;
7270           break;
7271         case DW_AT_friend:
7272           attrs->at_friend = a;
7273           break;
7274         case DW_AT_accessibility:
7275           attrs->at_accessibility = a;
7276           break;
7277         case DW_AT_address_class:
7278           attrs->at_address_class = a;
7279           break;
7280         case DW_AT_alignment:
7281           attrs->at_alignment = a;
7282           break;
7283         case DW_AT_allocated:
7284           attrs->at_allocated = a;
7285           break;
7286         case DW_AT_artificial:
7287           attrs->at_artificial = a;
7288           break;
7289         case DW_AT_associated:
7290           attrs->at_associated = a;
7291           break;
7292         case DW_AT_binary_scale:
7293           attrs->at_binary_scale = a;
7294           break;
7295         case DW_AT_bit_offset:
7296           attrs->at_bit_offset = a;
7297           break;
7298         case DW_AT_bit_size:
7299           attrs->at_bit_size = a;
7300           break;
7301         case DW_AT_bit_stride:
7302           attrs->at_bit_stride = a;
7303           break;
7304         case DW_AT_byte_size:
7305           attrs->at_byte_size = a;
7306           break;
7307         case DW_AT_byte_stride:
7308           attrs->at_byte_stride = a;
7309           break;
7310         case DW_AT_const_value:
7311           attrs->at_const_value = a;
7312           break;
7313         case DW_AT_containing_type:
7314           attrs->at_containing_type = a;
7315           break;
7316         case DW_AT_count:
7317           attrs->at_count = a;
7318           break;
7319         case DW_AT_data_location:
7320           attrs->at_data_location = a;
7321           break;
7322         case DW_AT_data_member_location:
7323           attrs->at_data_member_location = a;
7324           break;
7325         case DW_AT_decimal_scale:
7326           attrs->at_decimal_scale = a;
7327           break;
7328         case DW_AT_decimal_sign:
7329           attrs->at_decimal_sign = a;
7330           break;
7331         case DW_AT_default_value:
7332           attrs->at_default_value = a;
7333           break;
7334         case DW_AT_digit_count:
7335           attrs->at_digit_count = a;
7336           break;
7337         case DW_AT_discr:
7338           attrs->at_discr = a;
7339           break;
7340         case DW_AT_discr_list:
7341           attrs->at_discr_list = a;
7342           break;
7343         case DW_AT_discr_value:
7344           attrs->at_discr_value = a;
7345           break;
7346         case DW_AT_encoding:
7347           attrs->at_encoding = a;
7348           break;
7349         case DW_AT_endianity:
7350           attrs->at_endianity = a;
7351           break;
7352         case DW_AT_explicit:
7353           attrs->at_explicit = a;
7354           break;
7355         case DW_AT_is_optional:
7356           attrs->at_is_optional = a;
7357           break;
7358         case DW_AT_location:
7359           attrs->at_location = a;
7360           break;
7361         case DW_AT_lower_bound:
7362           attrs->at_lower_bound = a;
7363           break;
7364         case DW_AT_mutable:
7365           attrs->at_mutable = a;
7366           break;
7367         case DW_AT_ordering:
7368           attrs->at_ordering = a;
7369           break;
7370         case DW_AT_picture_string:
7371           attrs->at_picture_string = a;
7372           break;
7373         case DW_AT_prototyped:
7374           attrs->at_prototyped = a;
7375           break;
7376         case DW_AT_small:
7377           attrs->at_small = a;
7378           break;
7379         case DW_AT_segment:
7380           attrs->at_segment = a;
7381           break;
7382         case DW_AT_string_length:
7383           attrs->at_string_length = a;
7384           break;
7385         case DW_AT_string_length_bit_size:
7386           attrs->at_string_length_bit_size = a;
7387           break;
7388         case DW_AT_string_length_byte_size:
7389           attrs->at_string_length_byte_size = a;
7390           break;
7391         case DW_AT_threads_scaled:
7392           attrs->at_threads_scaled = a;
7393           break;
7394         case DW_AT_upper_bound:
7395           attrs->at_upper_bound = a;
7396           break;
7397         case DW_AT_use_location:
7398           attrs->at_use_location = a;
7399           break;
7400         case DW_AT_use_UTF8:
7401           attrs->at_use_UTF8 = a;
7402           break;
7403         case DW_AT_variable_parameter:
7404           attrs->at_variable_parameter = a;
7405           break;
7406         case DW_AT_virtuality:
7407           attrs->at_virtuality = a;
7408           break;
7409         case DW_AT_visibility:
7410           attrs->at_visibility = a;
7411           break;
7412         case DW_AT_vtable_elem_location:
7413           attrs->at_vtable_elem_location = a;
7414           break;
7415         default:
7416           break;
7417         }
7418     }
7419 }
7420
7421 /* Calculate the checksum of a DIE, using an ordered subset of attributes.  */
7422
7423 static void
7424 die_checksum_ordered (dw_die_ref die, struct md5_ctx *ctx, int *mark)
7425 {
7426   dw_die_ref c;
7427   dw_die_ref decl;
7428   struct checksum_attributes attrs;
7429
7430   CHECKSUM_ULEB128 ('D');
7431   CHECKSUM_ULEB128 (die->die_tag);
7432
7433   memset (&attrs, 0, sizeof (attrs));
7434
7435   decl = get_AT_ref (die, DW_AT_specification);
7436   if (decl != NULL)
7437     collect_checksum_attributes (&attrs, decl);
7438   collect_checksum_attributes (&attrs, die);
7439
7440   CHECKSUM_ATTR (attrs.at_name);
7441   CHECKSUM_ATTR (attrs.at_accessibility);
7442   CHECKSUM_ATTR (attrs.at_address_class);
7443   CHECKSUM_ATTR (attrs.at_allocated);
7444   CHECKSUM_ATTR (attrs.at_artificial);
7445   CHECKSUM_ATTR (attrs.at_associated);
7446   CHECKSUM_ATTR (attrs.at_binary_scale);
7447   CHECKSUM_ATTR (attrs.at_bit_offset);
7448   CHECKSUM_ATTR (attrs.at_bit_size);
7449   CHECKSUM_ATTR (attrs.at_bit_stride);
7450   CHECKSUM_ATTR (attrs.at_byte_size);
7451   CHECKSUM_ATTR (attrs.at_byte_stride);
7452   CHECKSUM_ATTR (attrs.at_const_value);
7453   CHECKSUM_ATTR (attrs.at_containing_type);
7454   CHECKSUM_ATTR (attrs.at_count);
7455   CHECKSUM_ATTR (attrs.at_data_location);
7456   CHECKSUM_ATTR (attrs.at_data_member_location);
7457   CHECKSUM_ATTR (attrs.at_decimal_scale);
7458   CHECKSUM_ATTR (attrs.at_decimal_sign);
7459   CHECKSUM_ATTR (attrs.at_default_value);
7460   CHECKSUM_ATTR (attrs.at_digit_count);
7461   CHECKSUM_ATTR (attrs.at_discr);
7462   CHECKSUM_ATTR (attrs.at_discr_list);
7463   CHECKSUM_ATTR (attrs.at_discr_value);
7464   CHECKSUM_ATTR (attrs.at_encoding);
7465   CHECKSUM_ATTR (attrs.at_endianity);
7466   CHECKSUM_ATTR (attrs.at_explicit);
7467   CHECKSUM_ATTR (attrs.at_is_optional);
7468   CHECKSUM_ATTR (attrs.at_location);
7469   CHECKSUM_ATTR (attrs.at_lower_bound);
7470   CHECKSUM_ATTR (attrs.at_mutable);
7471   CHECKSUM_ATTR (attrs.at_ordering);
7472   CHECKSUM_ATTR (attrs.at_picture_string);
7473   CHECKSUM_ATTR (attrs.at_prototyped);
7474   CHECKSUM_ATTR (attrs.at_small);
7475   CHECKSUM_ATTR (attrs.at_segment);
7476   CHECKSUM_ATTR (attrs.at_string_length);
7477   CHECKSUM_ATTR (attrs.at_string_length_bit_size);
7478   CHECKSUM_ATTR (attrs.at_string_length_byte_size);
7479   CHECKSUM_ATTR (attrs.at_threads_scaled);
7480   CHECKSUM_ATTR (attrs.at_upper_bound);
7481   CHECKSUM_ATTR (attrs.at_use_location);
7482   CHECKSUM_ATTR (attrs.at_use_UTF8);
7483   CHECKSUM_ATTR (attrs.at_variable_parameter);
7484   CHECKSUM_ATTR (attrs.at_virtuality);
7485   CHECKSUM_ATTR (attrs.at_visibility);
7486   CHECKSUM_ATTR (attrs.at_vtable_elem_location);
7487   CHECKSUM_ATTR (attrs.at_type);
7488   CHECKSUM_ATTR (attrs.at_friend);
7489   CHECKSUM_ATTR (attrs.at_alignment);
7490
7491   /* Checksum the child DIEs.  */
7492   c = die->die_child;
7493   if (c) do {
7494     dw_attr_node *name_attr;
7495
7496     c = c->die_sib;
7497     name_attr = get_AT (c, DW_AT_name);
7498     if (is_template_instantiation (c))
7499       {
7500         /* Ignore instantiations of member type and function templates.  */
7501       }
7502     else if (name_attr != NULL
7503              && (is_type_die (c) || c->die_tag == DW_TAG_subprogram))
7504       {
7505         /* Use a shallow checksum for named nested types and member
7506            functions.  */
7507         CHECKSUM_ULEB128 ('S');
7508         CHECKSUM_ULEB128 (c->die_tag);
7509         CHECKSUM_STRING (AT_string (name_attr));
7510       }
7511     else
7512       {
7513         /* Use a deep checksum for other children.  */
7514         /* Mark this DIE so it gets processed when unmarking.  */
7515         if (c->die_mark == 0)
7516           c->die_mark = -1;
7517         die_checksum_ordered (c, ctx, mark);
7518       }
7519   } while (c != die->die_child);
7520
7521   CHECKSUM_ULEB128 (0);
7522 }
7523
7524 /* Add a type name and tag to a hash.  */
7525 static void
7526 die_odr_checksum (int tag, const char *name, md5_ctx *ctx)
7527 {
7528   CHECKSUM_ULEB128 (tag);
7529   CHECKSUM_STRING (name);
7530 }
7531
7532 #undef CHECKSUM
7533 #undef CHECKSUM_STRING
7534 #undef CHECKSUM_ATTR
7535 #undef CHECKSUM_LEB128
7536 #undef CHECKSUM_ULEB128
7537
7538 /* Generate the type signature for DIE.  This is computed by generating an
7539    MD5 checksum over the DIE's tag, its relevant attributes, and its
7540    children.  Attributes that are references to other DIEs are processed
7541    by recursion, using the MARK field to prevent infinite recursion.
7542    If the DIE is nested inside a namespace or another type, we also
7543    need to include that context in the signature.  The lower 64 bits
7544    of the resulting MD5 checksum comprise the signature.  */
7545
7546 static void
7547 generate_type_signature (dw_die_ref die, comdat_type_node *type_node)
7548 {
7549   int mark;
7550   const char *name;
7551   unsigned char checksum[16];
7552   struct md5_ctx ctx;
7553   dw_die_ref decl;
7554   dw_die_ref parent;
7555
7556   name = get_AT_string (die, DW_AT_name);
7557   decl = get_AT_ref (die, DW_AT_specification);
7558   parent = get_die_parent (die);
7559
7560   /* First, compute a signature for just the type name (and its surrounding
7561      context, if any.  This is stored in the type unit DIE for link-time
7562      ODR (one-definition rule) checking.  */
7563
7564   if (is_cxx () && name != NULL)
7565     {
7566       md5_init_ctx (&ctx);
7567
7568       /* Checksum the names of surrounding namespaces and structures.  */
7569       if (parent != NULL)
7570         checksum_die_context (parent, &ctx);
7571
7572       /* Checksum the current DIE. */
7573       die_odr_checksum (die->die_tag, name, &ctx);
7574       md5_finish_ctx (&ctx, checksum);
7575
7576       add_AT_data8 (type_node->root_die, DW_AT_GNU_odr_signature, &checksum[8]);
7577     }
7578
7579   /* Next, compute the complete type signature.  */
7580
7581   md5_init_ctx (&ctx);
7582   mark = 1;
7583   die->die_mark = mark;
7584
7585   /* Checksum the names of surrounding namespaces and structures.  */
7586   if (parent != NULL)
7587     checksum_die_context (parent, &ctx);
7588
7589   /* Checksum the DIE and its children.  */
7590   die_checksum_ordered (die, &ctx, &mark);
7591   unmark_all_dies (die);
7592   md5_finish_ctx (&ctx, checksum);
7593
7594   /* Store the signature in the type node and link the type DIE and the
7595      type node together.  */
7596   memcpy (type_node->signature, &checksum[16 - DWARF_TYPE_SIGNATURE_SIZE],
7597           DWARF_TYPE_SIGNATURE_SIZE);
7598   die->comdat_type_p = true;
7599   die->die_id.die_type_node = type_node;
7600   type_node->type_die = die;
7601
7602   /* If the DIE is a specification, link its declaration to the type node
7603      as well.  */
7604   if (decl != NULL)
7605     {
7606       decl->comdat_type_p = true;
7607       decl->die_id.die_type_node = type_node;
7608     }
7609 }
7610
7611 /* Do the location expressions look same?  */
7612 static inline int
7613 same_loc_p (dw_loc_descr_ref loc1, dw_loc_descr_ref loc2, int *mark)
7614 {
7615   return loc1->dw_loc_opc == loc2->dw_loc_opc
7616          && same_dw_val_p (&loc1->dw_loc_oprnd1, &loc2->dw_loc_oprnd1, mark)
7617          && same_dw_val_p (&loc1->dw_loc_oprnd2, &loc2->dw_loc_oprnd2, mark);
7618 }
7619
7620 /* Do the values look the same?  */
7621 static int
7622 same_dw_val_p (const dw_val_node *v1, const dw_val_node *v2, int *mark)
7623 {
7624   dw_loc_descr_ref loc1, loc2;
7625   rtx r1, r2;
7626
7627   if (v1->val_class != v2->val_class)
7628     return 0;
7629
7630   switch (v1->val_class)
7631     {
7632     case dw_val_class_const:
7633     case dw_val_class_const_implicit:
7634       return v1->v.val_int == v2->v.val_int;
7635     case dw_val_class_unsigned_const:
7636     case dw_val_class_unsigned_const_implicit:
7637       return v1->v.val_unsigned == v2->v.val_unsigned;
7638     case dw_val_class_const_double:
7639       return v1->v.val_double.high == v2->v.val_double.high
7640              && v1->v.val_double.low == v2->v.val_double.low;
7641     case dw_val_class_wide_int:
7642       return *v1->v.val_wide == *v2->v.val_wide;
7643     case dw_val_class_vec:
7644       if (v1->v.val_vec.length != v2->v.val_vec.length
7645           || v1->v.val_vec.elt_size != v2->v.val_vec.elt_size)
7646         return 0;
7647       if (memcmp (v1->v.val_vec.array, v2->v.val_vec.array,
7648                   v1->v.val_vec.length * v1->v.val_vec.elt_size))
7649         return 0;
7650       return 1;
7651     case dw_val_class_flag:
7652       return v1->v.val_flag == v2->v.val_flag;
7653     case dw_val_class_str:
7654       return !strcmp (v1->v.val_str->str, v2->v.val_str->str);
7655
7656     case dw_val_class_addr:
7657       r1 = v1->v.val_addr;
7658       r2 = v2->v.val_addr;
7659       if (GET_CODE (r1) != GET_CODE (r2))
7660         return 0;
7661       return !rtx_equal_p (r1, r2);
7662
7663     case dw_val_class_offset:
7664       return v1->v.val_offset == v2->v.val_offset;
7665
7666     case dw_val_class_loc:
7667       for (loc1 = v1->v.val_loc, loc2 = v2->v.val_loc;
7668            loc1 && loc2;
7669            loc1 = loc1->dw_loc_next, loc2 = loc2->dw_loc_next)
7670         if (!same_loc_p (loc1, loc2, mark))
7671           return 0;
7672       return !loc1 && !loc2;
7673
7674     case dw_val_class_die_ref:
7675       return same_die_p (v1->v.val_die_ref.die, v2->v.val_die_ref.die, mark);
7676
7677     case dw_val_class_symview:
7678       return strcmp (v1->v.val_symbolic_view, v2->v.val_symbolic_view) == 0;
7679
7680     case dw_val_class_fde_ref:
7681     case dw_val_class_vms_delta:
7682     case dw_val_class_lbl_id:
7683     case dw_val_class_lineptr:
7684     case dw_val_class_macptr:
7685     case dw_val_class_loclistsptr:
7686     case dw_val_class_high_pc:
7687       return 1;
7688
7689     case dw_val_class_file:
7690     case dw_val_class_file_implicit:
7691       return v1->v.val_file == v2->v.val_file;
7692
7693     case dw_val_class_data8:
7694       return !memcmp (v1->v.val_data8, v2->v.val_data8, 8);
7695
7696     default:
7697       return 1;
7698     }
7699 }
7700
7701 /* Do the attributes look the same?  */
7702
7703 static int
7704 same_attr_p (dw_attr_node *at1, dw_attr_node *at2, int *mark)
7705 {
7706   if (at1->dw_attr != at2->dw_attr)
7707     return 0;
7708
7709   /* We don't care that this was compiled with a different compiler
7710      snapshot; if the output is the same, that's what matters. */
7711   if (at1->dw_attr == DW_AT_producer)
7712     return 1;
7713
7714   return same_dw_val_p (&at1->dw_attr_val, &at2->dw_attr_val, mark);
7715 }
7716
7717 /* Do the dies look the same?  */
7718
7719 static int
7720 same_die_p (dw_die_ref die1, dw_die_ref die2, int *mark)
7721 {
7722   dw_die_ref c1, c2;
7723   dw_attr_node *a1;
7724   unsigned ix;
7725
7726   /* To avoid infinite recursion.  */
7727   if (die1->die_mark)
7728     return die1->die_mark == die2->die_mark;
7729   die1->die_mark = die2->die_mark = ++(*mark);
7730
7731   if (die1->die_tag != die2->die_tag)
7732     return 0;
7733
7734   if (vec_safe_length (die1->die_attr) != vec_safe_length (die2->die_attr))
7735     return 0;
7736
7737   FOR_EACH_VEC_SAFE_ELT (die1->die_attr, ix, a1)
7738     if (!same_attr_p (a1, &(*die2->die_attr)[ix], mark))
7739       return 0;
7740
7741   c1 = die1->die_child;
7742   c2 = die2->die_child;
7743   if (! c1)
7744     {
7745       if (c2)
7746         return 0;
7747     }
7748   else
7749     for (;;)
7750       {
7751         if (!same_die_p (c1, c2, mark))
7752           return 0;
7753         c1 = c1->die_sib;
7754         c2 = c2->die_sib;
7755         if (c1 == die1->die_child)
7756           {
7757             if (c2 == die2->die_child)
7758               break;
7759             else
7760               return 0;
7761           }
7762     }
7763
7764   return 1;
7765 }
7766
7767 /* Calculate the MD5 checksum of the compilation unit DIE UNIT_DIE and its
7768    children, and set die_symbol.  */
7769
7770 static void
7771 compute_comp_unit_symbol (dw_die_ref unit_die)
7772 {
7773   const char *die_name = get_AT_string (unit_die, DW_AT_name);
7774   const char *base = die_name ? lbasename (die_name) : "anonymous";
7775   char *name = XALLOCAVEC (char, strlen (base) + 64);
7776   char *p;
7777   int i, mark;
7778   unsigned char checksum[16];
7779   struct md5_ctx ctx;
7780
7781   /* Compute the checksum of the DIE, then append part of it as hex digits to
7782      the name filename of the unit.  */
7783
7784   md5_init_ctx (&ctx);
7785   mark = 0;
7786   die_checksum (unit_die, &ctx, &mark);
7787   unmark_all_dies (unit_die);
7788   md5_finish_ctx (&ctx, checksum);
7789
7790   /* When we this for comp_unit_die () we have a DW_AT_name that might
7791      not start with a letter but with anything valid for filenames and
7792      clean_symbol_name doesn't fix that up.  Prepend 'g' if the first
7793      character is not a letter.  */
7794   sprintf (name, "%s%s.", ISALPHA (*base) ? "" : "g", base);
7795   clean_symbol_name (name);
7796
7797   p = name + strlen (name);
7798   for (i = 0; i < 4; i++)
7799     {
7800       sprintf (p, "%.2x", checksum[i]);
7801       p += 2;
7802     }
7803
7804   unit_die->die_id.die_symbol = xstrdup (name);
7805 }
7806
7807 /* Returns nonzero if DIE represents a type, in the sense of TYPE_P.  */
7808
7809 static int
7810 is_type_die (dw_die_ref die)
7811 {
7812   switch (die->die_tag)
7813     {
7814     case DW_TAG_array_type:
7815     case DW_TAG_class_type:
7816     case DW_TAG_interface_type:
7817     case DW_TAG_enumeration_type:
7818     case DW_TAG_pointer_type:
7819     case DW_TAG_reference_type:
7820     case DW_TAG_rvalue_reference_type:
7821     case DW_TAG_string_type:
7822     case DW_TAG_structure_type:
7823     case DW_TAG_subroutine_type:
7824     case DW_TAG_union_type:
7825     case DW_TAG_ptr_to_member_type:
7826     case DW_TAG_set_type:
7827     case DW_TAG_subrange_type:
7828     case DW_TAG_base_type:
7829     case DW_TAG_const_type:
7830     case DW_TAG_file_type:
7831     case DW_TAG_packed_type:
7832     case DW_TAG_volatile_type:
7833     case DW_TAG_typedef:
7834       return 1;
7835     default:
7836       return 0;
7837     }
7838 }
7839
7840 /* Returns 1 iff C is the sort of DIE that should go into a COMDAT CU.
7841    Basically, we want to choose the bits that are likely to be shared between
7842    compilations (types) and leave out the bits that are specific to individual
7843    compilations (functions).  */
7844
7845 static int
7846 is_comdat_die (dw_die_ref c)
7847 {
7848   /* I think we want to leave base types and __vtbl_ptr_type in the main CU, as
7849      we do for stabs.  The advantage is a greater likelihood of sharing between
7850      objects that don't include headers in the same order (and therefore would
7851      put the base types in a different comdat).  jason 8/28/00 */
7852
7853   if (c->die_tag == DW_TAG_base_type)
7854     return 0;
7855
7856   if (c->die_tag == DW_TAG_pointer_type
7857       || c->die_tag == DW_TAG_reference_type
7858       || c->die_tag == DW_TAG_rvalue_reference_type
7859       || c->die_tag == DW_TAG_const_type
7860       || c->die_tag == DW_TAG_volatile_type)
7861     {
7862       dw_die_ref t = get_AT_ref (c, DW_AT_type);
7863
7864       return t ? is_comdat_die (t) : 0;
7865     }
7866
7867   return is_type_die (c);
7868 }
7869
7870 /* Returns true iff C is a compile-unit DIE.  */
7871
7872 static inline bool
7873 is_cu_die (dw_die_ref c)
7874 {
7875   return c && (c->die_tag == DW_TAG_compile_unit
7876                || c->die_tag == DW_TAG_skeleton_unit);
7877 }
7878
7879 /* Returns true iff C is a unit DIE of some sort.  */
7880
7881 static inline bool
7882 is_unit_die (dw_die_ref c)
7883 {
7884   return c && (c->die_tag == DW_TAG_compile_unit
7885                || c->die_tag == DW_TAG_partial_unit
7886                || c->die_tag == DW_TAG_type_unit
7887                || c->die_tag == DW_TAG_skeleton_unit);
7888 }
7889
7890 /* Returns true iff C is a namespace DIE.  */
7891
7892 static inline bool
7893 is_namespace_die (dw_die_ref c)
7894 {
7895   return c && c->die_tag == DW_TAG_namespace;
7896 }
7897
7898 /* Returns true iff C is a class or structure DIE.  */
7899
7900 static inline bool
7901 is_class_die (dw_die_ref c)
7902 {
7903   return c && (c->die_tag == DW_TAG_class_type
7904                || c->die_tag == DW_TAG_structure_type);
7905 }
7906
7907 /* Return non-zero if this DIE is a template parameter.  */
7908
7909 static inline bool
7910 is_template_parameter (dw_die_ref die)
7911 {
7912   switch (die->die_tag)
7913     {
7914     case DW_TAG_template_type_param:
7915     case DW_TAG_template_value_param:
7916     case DW_TAG_GNU_template_template_param:
7917     case DW_TAG_GNU_template_parameter_pack:
7918       return true;
7919     default:
7920       return false;
7921     }
7922 }
7923
7924 /* Return non-zero if this DIE represents a template instantiation.  */
7925
7926 static inline bool
7927 is_template_instantiation (dw_die_ref die)
7928 {
7929   dw_die_ref c;
7930
7931   if (!is_type_die (die) && die->die_tag != DW_TAG_subprogram)
7932     return false;
7933   FOR_EACH_CHILD (die, c, if (is_template_parameter (c)) return true);
7934   return false;
7935 }
7936
7937 static char *
7938 gen_internal_sym (const char *prefix)
7939 {
7940   char buf[MAX_ARTIFICIAL_LABEL_BYTES];
7941
7942   ASM_GENERATE_INTERNAL_LABEL (buf, prefix, label_num++);
7943   return xstrdup (buf);
7944 }
7945
7946 /* Return non-zero if this DIE is a declaration.  */
7947
7948 static int
7949 is_declaration_die (dw_die_ref die)
7950 {
7951   dw_attr_node *a;
7952   unsigned ix;
7953
7954   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
7955     if (a->dw_attr == DW_AT_declaration)
7956       return 1;
7957
7958   return 0;
7959 }
7960
7961 /* Return non-zero if this DIE is nested inside a subprogram.  */
7962
7963 static int
7964 is_nested_in_subprogram (dw_die_ref die)
7965 {
7966   dw_die_ref decl = get_AT_ref (die, DW_AT_specification);
7967
7968   if (decl == NULL)
7969     decl = die;
7970   return local_scope_p (decl);
7971 }
7972
7973 /* Return non-zero if this DIE contains a defining declaration of a
7974    subprogram.  */
7975
7976 static int
7977 contains_subprogram_definition (dw_die_ref die)
7978 {
7979   dw_die_ref c;
7980
7981   if (die->die_tag == DW_TAG_subprogram && ! is_declaration_die (die))
7982     return 1;
7983   FOR_EACH_CHILD (die, c, if (contains_subprogram_definition (c)) return 1);
7984   return 0;
7985 }
7986
7987 /* Return non-zero if this is a type DIE that should be moved to a
7988    COMDAT .debug_types section or .debug_info section with DW_UT_*type
7989    unit type.  */
7990
7991 static int
7992 should_move_die_to_comdat (dw_die_ref die)
7993 {
7994   switch (die->die_tag)
7995     {
7996     case DW_TAG_class_type:
7997     case DW_TAG_structure_type:
7998     case DW_TAG_enumeration_type:
7999     case DW_TAG_union_type:
8000       /* Don't move declarations, inlined instances, types nested in a
8001          subprogram, or types that contain subprogram definitions.  */
8002       if (is_declaration_die (die)
8003           || get_AT (die, DW_AT_abstract_origin)
8004           || is_nested_in_subprogram (die)
8005           || contains_subprogram_definition (die))
8006         return 0;
8007       return 1;
8008     case DW_TAG_array_type:
8009     case DW_TAG_interface_type:
8010     case DW_TAG_pointer_type:
8011     case DW_TAG_reference_type:
8012     case DW_TAG_rvalue_reference_type:
8013     case DW_TAG_string_type:
8014     case DW_TAG_subroutine_type:
8015     case DW_TAG_ptr_to_member_type:
8016     case DW_TAG_set_type:
8017     case DW_TAG_subrange_type:
8018     case DW_TAG_base_type:
8019     case DW_TAG_const_type:
8020     case DW_TAG_file_type:
8021     case DW_TAG_packed_type:
8022     case DW_TAG_volatile_type:
8023     case DW_TAG_typedef:
8024     default:
8025       return 0;
8026     }
8027 }
8028
8029 /* Make a clone of DIE.  */
8030
8031 static dw_die_ref
8032 clone_die (dw_die_ref die)
8033 {
8034   dw_die_ref clone = new_die_raw (die->die_tag);
8035   dw_attr_node *a;
8036   unsigned ix;
8037
8038   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
8039     add_dwarf_attr (clone, a);
8040
8041   return clone;
8042 }
8043
8044 /* Make a clone of the tree rooted at DIE.  */
8045
8046 static dw_die_ref
8047 clone_tree (dw_die_ref die)
8048 {
8049   dw_die_ref c;
8050   dw_die_ref clone = clone_die (die);
8051
8052   FOR_EACH_CHILD (die, c, add_child_die (clone, clone_tree (c)));
8053
8054   return clone;
8055 }
8056
8057 /* Make a clone of DIE as a declaration.  */
8058
8059 static dw_die_ref
8060 clone_as_declaration (dw_die_ref die)
8061 {
8062   dw_die_ref clone;
8063   dw_die_ref decl;
8064   dw_attr_node *a;
8065   unsigned ix;
8066
8067   /* If the DIE is already a declaration, just clone it.  */
8068   if (is_declaration_die (die))
8069     return clone_die (die);
8070
8071   /* If the DIE is a specification, just clone its declaration DIE.  */
8072   decl = get_AT_ref (die, DW_AT_specification);
8073   if (decl != NULL)
8074     {
8075       clone = clone_die (decl);
8076       if (die->comdat_type_p)
8077         add_AT_die_ref (clone, DW_AT_signature, die);
8078       return clone;
8079     }
8080
8081   clone = new_die_raw (die->die_tag);
8082
8083   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
8084     {
8085       /* We don't want to copy over all attributes.
8086          For example we don't want DW_AT_byte_size because otherwise we will no
8087          longer have a declaration and GDB will treat it as a definition.  */
8088
8089       switch (a->dw_attr)
8090         {
8091         case DW_AT_abstract_origin:
8092         case DW_AT_artificial:
8093         case DW_AT_containing_type:
8094         case DW_AT_external:
8095         case DW_AT_name:
8096         case DW_AT_type:
8097         case DW_AT_virtuality:
8098         case DW_AT_linkage_name:
8099         case DW_AT_MIPS_linkage_name:
8100           add_dwarf_attr (clone, a);
8101           break;
8102         case DW_AT_byte_size:
8103         case DW_AT_alignment:
8104         default:
8105           break;
8106         }
8107     }
8108
8109   if (die->comdat_type_p)
8110     add_AT_die_ref (clone, DW_AT_signature, die);
8111
8112   add_AT_flag (clone, DW_AT_declaration, 1);
8113   return clone;
8114 }
8115
8116
8117 /* Structure to map a DIE in one CU to its copy in a comdat type unit.  */
8118
8119 struct decl_table_entry
8120 {
8121   dw_die_ref orig;
8122   dw_die_ref copy;
8123 };
8124
8125 /* Helpers to manipulate hash table of copied declarations.  */
8126
8127 /* Hashtable helpers.  */
8128
8129 struct decl_table_entry_hasher : free_ptr_hash <decl_table_entry>
8130 {
8131   typedef die_struct *compare_type;
8132   static inline hashval_t hash (const decl_table_entry *);
8133   static inline bool equal (const decl_table_entry *, const die_struct *);
8134 };
8135
8136 inline hashval_t
8137 decl_table_entry_hasher::hash (const decl_table_entry *entry)
8138 {
8139   return htab_hash_pointer (entry->orig);
8140 }
8141
8142 inline bool
8143 decl_table_entry_hasher::equal (const decl_table_entry *entry1,
8144                                 const die_struct *entry2)
8145 {
8146   return entry1->orig == entry2;
8147 }
8148
8149 typedef hash_table<decl_table_entry_hasher> decl_hash_type;
8150
8151 /* Copy DIE and its ancestors, up to, but not including, the compile unit
8152    or type unit entry, to a new tree.  Adds the new tree to UNIT and returns
8153    a pointer to the copy of DIE.  If DECL_TABLE is provided, it is used
8154    to check if the ancestor has already been copied into UNIT.  */
8155
8156 static dw_die_ref
8157 copy_ancestor_tree (dw_die_ref unit, dw_die_ref die,
8158                     decl_hash_type *decl_table)
8159 {
8160   dw_die_ref parent = die->die_parent;
8161   dw_die_ref new_parent = unit;
8162   dw_die_ref copy;
8163   decl_table_entry **slot = NULL;
8164   struct decl_table_entry *entry = NULL;
8165
8166   /* If DIE refers to a stub unfold that so we get the appropriate
8167      DIE registered as orig in decl_table.  */
8168   if (dw_die_ref c = get_AT_ref (die, DW_AT_signature))
8169     die = c;
8170
8171   if (decl_table)
8172     {
8173       /* Check if the entry has already been copied to UNIT.  */
8174       slot = decl_table->find_slot_with_hash (die, htab_hash_pointer (die),
8175                                               INSERT);
8176       if (*slot != HTAB_EMPTY_ENTRY)
8177         {
8178           entry = *slot;
8179           return entry->copy;
8180         }
8181
8182       /* Record in DECL_TABLE that DIE has been copied to UNIT.  */
8183       entry = XCNEW (struct decl_table_entry);
8184       entry->orig = die;
8185       entry->copy = NULL;
8186       *slot = entry;
8187     }
8188
8189   if (parent != NULL)
8190     {
8191       dw_die_ref spec = get_AT_ref (parent, DW_AT_specification);
8192       if (spec != NULL)
8193         parent = spec;
8194       if (!is_unit_die (parent))
8195         new_parent = copy_ancestor_tree (unit, parent, decl_table);
8196     }
8197
8198   copy = clone_as_declaration (die);
8199   add_child_die (new_parent, copy);
8200
8201   if (decl_table)
8202     {
8203       /* Record the pointer to the copy.  */
8204       entry->copy = copy;
8205     }
8206
8207   return copy;
8208 }
8209 /* Copy the declaration context to the new type unit DIE.  This includes
8210    any surrounding namespace or type declarations.  If the DIE has an
8211    AT_specification attribute, it also includes attributes and children
8212    attached to the specification, and returns a pointer to the original
8213    parent of the declaration DIE.  Returns NULL otherwise.  */
8214
8215 static dw_die_ref
8216 copy_declaration_context (dw_die_ref unit, dw_die_ref die)
8217 {
8218   dw_die_ref decl;
8219   dw_die_ref new_decl;
8220   dw_die_ref orig_parent = NULL;
8221
8222   decl = get_AT_ref (die, DW_AT_specification);
8223   if (decl == NULL)
8224     decl = die;
8225   else
8226     {
8227       unsigned ix;
8228       dw_die_ref c;
8229       dw_attr_node *a;
8230
8231       /* The original DIE will be changed to a declaration, and must
8232          be moved to be a child of the original declaration DIE.  */
8233       orig_parent = decl->die_parent;
8234
8235       /* Copy the type node pointer from the new DIE to the original
8236          declaration DIE so we can forward references later.  */
8237       decl->comdat_type_p = true;
8238       decl->die_id.die_type_node = die->die_id.die_type_node;
8239
8240       remove_AT (die, DW_AT_specification);
8241
8242       FOR_EACH_VEC_SAFE_ELT (decl->die_attr, ix, a)
8243         {
8244           if (a->dw_attr != DW_AT_name
8245               && a->dw_attr != DW_AT_declaration
8246               && a->dw_attr != DW_AT_external)
8247             add_dwarf_attr (die, a);
8248         }
8249
8250       FOR_EACH_CHILD (decl, c, add_child_die (die, clone_tree (c)));
8251     }
8252
8253   if (decl->die_parent != NULL
8254       && !is_unit_die (decl->die_parent))
8255     {
8256       new_decl = copy_ancestor_tree (unit, decl, NULL);
8257       if (new_decl != NULL)
8258         {
8259           remove_AT (new_decl, DW_AT_signature);
8260           add_AT_specification (die, new_decl);
8261         }
8262     }
8263
8264   return orig_parent;
8265 }
8266
8267 /* Generate the skeleton ancestor tree for the given NODE, then clone
8268    the DIE and add the clone into the tree.  */
8269
8270 static void
8271 generate_skeleton_ancestor_tree (skeleton_chain_node *node)
8272 {
8273   if (node->new_die != NULL)
8274     return;
8275
8276   node->new_die = clone_as_declaration (node->old_die);
8277
8278   if (node->parent != NULL)
8279     {
8280       generate_skeleton_ancestor_tree (node->parent);
8281       add_child_die (node->parent->new_die, node->new_die);
8282     }
8283 }
8284
8285 /* Generate a skeleton tree of DIEs containing any declarations that are
8286    found in the original tree.  We traverse the tree looking for declaration
8287    DIEs, and construct the skeleton from the bottom up whenever we find one.  */
8288
8289 static void
8290 generate_skeleton_bottom_up (skeleton_chain_node *parent)
8291 {
8292   skeleton_chain_node node;
8293   dw_die_ref c;
8294   dw_die_ref first;
8295   dw_die_ref prev = NULL;
8296   dw_die_ref next = NULL;
8297
8298   node.parent = parent;
8299
8300   first = c = parent->old_die->die_child;
8301   if (c)
8302     next = c->die_sib;
8303   if (c) do {
8304     if (prev == NULL || prev->die_sib == c)
8305       prev = c;
8306     c = next;
8307     next = (c == first ? NULL : c->die_sib);
8308     node.old_die = c;
8309     node.new_die = NULL;
8310     if (is_declaration_die (c))
8311       {
8312         if (is_template_instantiation (c))
8313           {
8314             /* Instantiated templates do not need to be cloned into the
8315                type unit.  Just move the DIE and its children back to
8316                the skeleton tree (in the main CU).  */
8317             remove_child_with_prev (c, prev);
8318             add_child_die (parent->new_die, c);
8319             c = prev;
8320           }
8321         else if (c->comdat_type_p)
8322           {
8323             /* This is the skeleton of earlier break_out_comdat_types
8324                type.  Clone the existing DIE, but keep the children
8325                under the original (which is in the main CU).  */
8326             dw_die_ref clone = clone_die (c);
8327
8328             replace_child (c, clone, prev);
8329             generate_skeleton_ancestor_tree (parent);
8330             add_child_die (parent->new_die, c);
8331             c = clone;
8332             continue;
8333           }
8334         else
8335           {
8336             /* Clone the existing DIE, move the original to the skeleton
8337                tree (which is in the main CU), and put the clone, with
8338                all the original's children, where the original came from
8339                (which is about to be moved to the type unit).  */
8340             dw_die_ref clone = clone_die (c);
8341             move_all_children (c, clone);
8342
8343             /* If the original has a DW_AT_object_pointer attribute,
8344                it would now point to a child DIE just moved to the
8345                cloned tree, so we need to remove that attribute from
8346                the original.  */
8347             remove_AT (c, DW_AT_object_pointer);
8348
8349             replace_child (c, clone, prev);
8350             generate_skeleton_ancestor_tree (parent);
8351             add_child_die (parent->new_die, c);
8352             node.old_die = clone;
8353             node.new_die = c;
8354             c = clone;
8355           }
8356       }
8357     generate_skeleton_bottom_up (&node);
8358   } while (next != NULL);
8359 }
8360
8361 /* Wrapper function for generate_skeleton_bottom_up.  */
8362
8363 static dw_die_ref
8364 generate_skeleton (dw_die_ref die)
8365 {
8366   skeleton_chain_node node;
8367
8368   node.old_die = die;
8369   node.new_die = NULL;
8370   node.parent = NULL;
8371
8372   /* If this type definition is nested inside another type,
8373      and is not an instantiation of a template, always leave
8374      at least a declaration in its place.  */
8375   if (die->die_parent != NULL
8376       && is_type_die (die->die_parent)
8377       && !is_template_instantiation (die))
8378     node.new_die = clone_as_declaration (die);
8379
8380   generate_skeleton_bottom_up (&node);
8381   return node.new_die;
8382 }
8383
8384 /* Remove the CHILD DIE from its parent, possibly replacing it with a cloned
8385    declaration.  The original DIE is moved to a new compile unit so that
8386    existing references to it follow it to the new location.  If any of the
8387    original DIE's descendants is a declaration, we need to replace the
8388    original DIE with a skeleton tree and move the declarations back into the
8389    skeleton tree.  */
8390
8391 static dw_die_ref
8392 remove_child_or_replace_with_skeleton (dw_die_ref unit, dw_die_ref child,
8393                                        dw_die_ref prev)
8394 {
8395   dw_die_ref skeleton, orig_parent;
8396
8397   /* Copy the declaration context to the type unit DIE.  If the returned
8398      ORIG_PARENT is not NULL, the skeleton needs to be added as a child of
8399      that DIE.  */
8400   orig_parent = copy_declaration_context (unit, child);
8401
8402   skeleton = generate_skeleton (child);
8403   if (skeleton == NULL)
8404     remove_child_with_prev (child, prev);
8405   else
8406     {
8407       skeleton->comdat_type_p = true;
8408       skeleton->die_id.die_type_node = child->die_id.die_type_node;
8409
8410       /* If the original DIE was a specification, we need to put
8411          the skeleton under the parent DIE of the declaration.
8412          This leaves the original declaration in the tree, but
8413          it will be pruned later since there are no longer any
8414          references to it.  */
8415       if (orig_parent != NULL)
8416         {
8417           remove_child_with_prev (child, prev);
8418           add_child_die (orig_parent, skeleton);
8419         }
8420       else
8421         replace_child (child, skeleton, prev);
8422     }
8423
8424   return skeleton;
8425 }
8426
8427 static void
8428 copy_dwarf_procs_ref_in_attrs (dw_die_ref die,
8429                                comdat_type_node *type_node,
8430                                hash_map<dw_die_ref, dw_die_ref> &copied_dwarf_procs);
8431
8432 /* Helper for copy_dwarf_procs_ref_in_dies.  Make a copy of the DIE DWARF
8433    procedure, put it under TYPE_NODE and return the copy.  Continue looking for
8434    DWARF procedure references in the DW_AT_location attribute.  */
8435
8436 static dw_die_ref
8437 copy_dwarf_procedure (dw_die_ref die,
8438                       comdat_type_node *type_node,
8439                       hash_map<dw_die_ref, dw_die_ref> &copied_dwarf_procs)
8440 {
8441   gcc_assert (die->die_tag == DW_TAG_dwarf_procedure);
8442
8443   /* DWARF procedures are not supposed to have children...  */
8444   gcc_assert (die->die_child == NULL);
8445
8446   /* ... and they are supposed to have only one attribute: DW_AT_location.  */
8447   gcc_assert (vec_safe_length (die->die_attr) == 1
8448               && ((*die->die_attr)[0].dw_attr == DW_AT_location));
8449
8450   /* Do not copy more than once DWARF procedures.  */
8451   bool existed;
8452   dw_die_ref &die_copy = copied_dwarf_procs.get_or_insert (die, &existed);
8453   if (existed)
8454     return die_copy;
8455
8456   die_copy = clone_die (die);
8457   add_child_die (type_node->root_die, die_copy);
8458   copy_dwarf_procs_ref_in_attrs (die_copy, type_node, copied_dwarf_procs);
8459   return die_copy;
8460 }
8461
8462 /* Helper for copy_dwarf_procs_ref_in_dies.  Look for references to DWARF
8463    procedures in DIE's attributes.  */
8464
8465 static void
8466 copy_dwarf_procs_ref_in_attrs (dw_die_ref die,
8467                                comdat_type_node *type_node,
8468                                hash_map<dw_die_ref, dw_die_ref> &copied_dwarf_procs)
8469 {
8470   dw_attr_node *a;
8471   unsigned i;
8472
8473   FOR_EACH_VEC_SAFE_ELT (die->die_attr, i, a)
8474     {
8475       dw_loc_descr_ref loc;
8476
8477       if (a->dw_attr_val.val_class != dw_val_class_loc)
8478         continue;
8479
8480       for (loc = a->dw_attr_val.v.val_loc; loc != NULL; loc = loc->dw_loc_next)
8481         {
8482           switch (loc->dw_loc_opc)
8483             {
8484             case DW_OP_call2:
8485             case DW_OP_call4:
8486             case DW_OP_call_ref:
8487               gcc_assert (loc->dw_loc_oprnd1.val_class
8488                           == dw_val_class_die_ref);
8489               loc->dw_loc_oprnd1.v.val_die_ref.die
8490                 = copy_dwarf_procedure (loc->dw_loc_oprnd1.v.val_die_ref.die,
8491                                         type_node,
8492                                         copied_dwarf_procs);
8493
8494             default:
8495               break;
8496             }
8497         }
8498     }
8499 }
8500
8501 /* Copy DWARF procedures that are referenced by the DIE tree to TREE_NODE and
8502    rewrite references to point to the copies.
8503
8504    References are looked for in DIE's attributes and recursively in all its
8505    children attributes that are location descriptions. COPIED_DWARF_PROCS is a
8506    mapping from old DWARF procedures to their copy. It is used not to copy
8507    twice the same DWARF procedure under TYPE_NODE.  */
8508
8509 static void
8510 copy_dwarf_procs_ref_in_dies (dw_die_ref die,
8511                               comdat_type_node *type_node,
8512                               hash_map<dw_die_ref, dw_die_ref> &copied_dwarf_procs)
8513 {
8514   dw_die_ref c;
8515
8516   copy_dwarf_procs_ref_in_attrs (die, type_node, copied_dwarf_procs);
8517   FOR_EACH_CHILD (die, c, copy_dwarf_procs_ref_in_dies (c,
8518                                                         type_node,
8519                                                         copied_dwarf_procs));
8520 }
8521
8522 /* Traverse the DIE and set up additional .debug_types or .debug_info
8523    DW_UT_*type sections for each type worthy of being placed in a COMDAT
8524    section.  */
8525
8526 static void
8527 break_out_comdat_types (dw_die_ref die)
8528 {
8529   dw_die_ref c;
8530   dw_die_ref first;
8531   dw_die_ref prev = NULL;
8532   dw_die_ref next = NULL;
8533   dw_die_ref unit = NULL;
8534
8535   first = c = die->die_child;
8536   if (c)
8537     next = c->die_sib;
8538   if (c) do {
8539     if (prev == NULL || prev->die_sib == c)
8540       prev = c;
8541     c = next;
8542     next = (c == first ? NULL : c->die_sib);
8543     if (should_move_die_to_comdat (c))
8544       {
8545         dw_die_ref replacement;
8546         comdat_type_node *type_node;
8547
8548         /* Break out nested types into their own type units.  */
8549         break_out_comdat_types (c);
8550
8551         /* Create a new type unit DIE as the root for the new tree, and
8552            add it to the list of comdat types.  */
8553         unit = new_die (DW_TAG_type_unit, NULL, NULL);
8554         add_AT_unsigned (unit, DW_AT_language,
8555                          get_AT_unsigned (comp_unit_die (), DW_AT_language));
8556         type_node = ggc_cleared_alloc<comdat_type_node> ();
8557         type_node->root_die = unit;
8558         type_node->next = comdat_type_list;
8559         comdat_type_list = type_node;
8560
8561         /* Generate the type signature.  */
8562         generate_type_signature (c, type_node);
8563
8564         /* Copy the declaration context, attributes, and children of the
8565            declaration into the new type unit DIE, then remove this DIE
8566            from the main CU (or replace it with a skeleton if necessary).  */
8567         replacement = remove_child_or_replace_with_skeleton (unit, c, prev);
8568         type_node->skeleton_die = replacement;
8569
8570         /* Add the DIE to the new compunit.  */
8571         add_child_die (unit, c);
8572
8573         /* Types can reference DWARF procedures for type size or data location
8574            expressions.  Calls in DWARF expressions cannot target procedures
8575            that are not in the same section.  So we must copy DWARF procedures
8576            along with this type and then rewrite references to them.  */
8577         hash_map<dw_die_ref, dw_die_ref> copied_dwarf_procs;
8578         copy_dwarf_procs_ref_in_dies (c, type_node, copied_dwarf_procs);
8579
8580         if (replacement != NULL)
8581           c = replacement;
8582       }
8583     else if (c->die_tag == DW_TAG_namespace
8584              || c->die_tag == DW_TAG_class_type
8585              || c->die_tag == DW_TAG_structure_type
8586              || c->die_tag == DW_TAG_union_type)
8587       {
8588         /* Look for nested types that can be broken out.  */
8589         break_out_comdat_types (c);
8590       }
8591   } while (next != NULL);
8592 }
8593
8594 /* Like clone_tree, but copy DW_TAG_subprogram DIEs as declarations.
8595    Enter all the cloned children into the hash table decl_table.  */
8596
8597 static dw_die_ref
8598 clone_tree_partial (dw_die_ref die, decl_hash_type *decl_table)
8599 {
8600   dw_die_ref c;
8601   dw_die_ref clone;
8602   struct decl_table_entry *entry;
8603   decl_table_entry **slot;
8604
8605   if (die->die_tag == DW_TAG_subprogram)
8606     clone = clone_as_declaration (die);
8607   else
8608     clone = clone_die (die);
8609
8610   slot = decl_table->find_slot_with_hash (die,
8611                                           htab_hash_pointer (die), INSERT);
8612
8613   /* Assert that DIE isn't in the hash table yet.  If it would be there
8614      before, the ancestors would be necessarily there as well, therefore
8615      clone_tree_partial wouldn't be called.  */
8616   gcc_assert (*slot == HTAB_EMPTY_ENTRY);
8617
8618   entry = XCNEW (struct decl_table_entry);
8619   entry->orig = die;
8620   entry->copy = clone;
8621   *slot = entry;
8622
8623   if (die->die_tag != DW_TAG_subprogram)
8624     FOR_EACH_CHILD (die, c,
8625                     add_child_die (clone, clone_tree_partial (c, decl_table)));
8626
8627   return clone;
8628 }
8629
8630 /* Walk the DIE and its children, looking for references to incomplete
8631    or trivial types that are unmarked (i.e., that are not in the current
8632    type_unit).  */
8633
8634 static void
8635 copy_decls_walk (dw_die_ref unit, dw_die_ref die, decl_hash_type *decl_table)
8636 {
8637   dw_die_ref c;
8638   dw_attr_node *a;
8639   unsigned ix;
8640
8641   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
8642     {
8643       if (AT_class (a) == dw_val_class_die_ref)
8644         {
8645           dw_die_ref targ = AT_ref (a);
8646           decl_table_entry **slot;
8647           struct decl_table_entry *entry;
8648
8649           if (targ->die_mark != 0 || targ->comdat_type_p)
8650             continue;
8651
8652           slot = decl_table->find_slot_with_hash (targ,
8653                                                   htab_hash_pointer (targ),
8654                                                   INSERT);
8655
8656           if (*slot != HTAB_EMPTY_ENTRY)
8657             {
8658               /* TARG has already been copied, so we just need to
8659                  modify the reference to point to the copy.  */
8660               entry = *slot;
8661               a->dw_attr_val.v.val_die_ref.die = entry->copy;
8662             }
8663           else
8664             {
8665               dw_die_ref parent = unit;
8666               dw_die_ref copy = clone_die (targ);
8667
8668               /* Record in DECL_TABLE that TARG has been copied.
8669                  Need to do this now, before the recursive call,
8670                  because DECL_TABLE may be expanded and SLOT
8671                  would no longer be a valid pointer.  */
8672               entry = XCNEW (struct decl_table_entry);
8673               entry->orig = targ;
8674               entry->copy = copy;
8675               *slot = entry;
8676
8677               /* If TARG is not a declaration DIE, we need to copy its
8678                  children.  */
8679               if (!is_declaration_die (targ))
8680                 {
8681                   FOR_EACH_CHILD (
8682                       targ, c,
8683                       add_child_die (copy,
8684                                      clone_tree_partial (c, decl_table)));
8685                 }
8686
8687               /* Make sure the cloned tree is marked as part of the
8688                  type unit.  */
8689               mark_dies (copy);
8690
8691               /* If TARG has surrounding context, copy its ancestor tree
8692                  into the new type unit.  */
8693               if (targ->die_parent != NULL
8694                   && !is_unit_die (targ->die_parent))
8695                 parent = copy_ancestor_tree (unit, targ->die_parent,
8696                                              decl_table);
8697
8698               add_child_die (parent, copy);
8699               a->dw_attr_val.v.val_die_ref.die = copy;
8700
8701               /* Make sure the newly-copied DIE is walked.  If it was
8702                  installed in a previously-added context, it won't
8703                  get visited otherwise.  */
8704               if (parent != unit)
8705                 {
8706                   /* Find the highest point of the newly-added tree,
8707                      mark each node along the way, and walk from there.  */
8708                   parent->die_mark = 1;
8709                   while (parent->die_parent
8710                          && parent->die_parent->die_mark == 0)
8711                     {
8712                       parent = parent->die_parent;
8713                       parent->die_mark = 1;
8714                     }
8715                   copy_decls_walk (unit, parent, decl_table);
8716                 }
8717             }
8718         }
8719     }
8720
8721   FOR_EACH_CHILD (die, c, copy_decls_walk (unit, c, decl_table));
8722 }
8723
8724 /* Collect skeleton dies in DIE created by break_out_comdat_types already
8725    and record them in DECL_TABLE.  */
8726
8727 static void
8728 collect_skeleton_dies (dw_die_ref die, decl_hash_type *decl_table)
8729 {
8730   dw_die_ref c;
8731
8732   if (dw_attr_node *a = get_AT (die, DW_AT_signature))
8733     {
8734       dw_die_ref targ = AT_ref (a);
8735       gcc_assert (targ->die_mark == 0 && targ->comdat_type_p);
8736       decl_table_entry **slot
8737         = decl_table->find_slot_with_hash (targ,
8738                                            htab_hash_pointer (targ),
8739                                            INSERT);
8740       gcc_assert (*slot == HTAB_EMPTY_ENTRY);
8741       /* Record in DECL_TABLE that TARG has been already copied
8742          by remove_child_or_replace_with_skeleton.  */
8743       decl_table_entry *entry = XCNEW (struct decl_table_entry);
8744       entry->orig = targ;
8745       entry->copy = die;
8746       *slot = entry;
8747     }
8748   FOR_EACH_CHILD (die, c, collect_skeleton_dies (c, decl_table));
8749 }
8750
8751 /* Copy declarations for "unworthy" types into the new comdat section.
8752    Incomplete types, modified types, and certain other types aren't broken
8753    out into comdat sections of their own, so they don't have a signature,
8754    and we need to copy the declaration into the same section so that we
8755    don't have an external reference.  */
8756
8757 static void
8758 copy_decls_for_unworthy_types (dw_die_ref unit)
8759 {
8760   mark_dies (unit);
8761   decl_hash_type decl_table (10);
8762   collect_skeleton_dies (unit, &decl_table);
8763   copy_decls_walk (unit, unit, &decl_table);
8764   unmark_dies (unit);
8765 }
8766
8767 /* Traverse the DIE and add a sibling attribute if it may have the
8768    effect of speeding up access to siblings.  To save some space,
8769    avoid generating sibling attributes for DIE's without children.  */
8770
8771 static void
8772 add_sibling_attributes (dw_die_ref die)
8773 {
8774   dw_die_ref c;
8775
8776   if (! die->die_child)
8777     return;
8778
8779   if (die->die_parent && die != die->die_parent->die_child)
8780     add_AT_die_ref (die, DW_AT_sibling, die->die_sib);
8781
8782   FOR_EACH_CHILD (die, c, add_sibling_attributes (c));
8783 }
8784
8785 /* Output all location lists for the DIE and its children.  */
8786
8787 static void
8788 output_location_lists (dw_die_ref die)
8789 {
8790   dw_die_ref c;
8791   dw_attr_node *a;
8792   unsigned ix;
8793
8794   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
8795     if (AT_class (a) == dw_val_class_loc_list)
8796       output_loc_list (AT_loc_list (a));
8797
8798   FOR_EACH_CHILD (die, c, output_location_lists (c));
8799 }
8800
8801 /* During assign_location_list_indexes and output_loclists_offset the
8802    current index, after it the number of assigned indexes (i.e. how
8803    large the .debug_loclists* offset table should be).  */
8804 static unsigned int loc_list_idx;
8805
8806 /* Output all location list offsets for the DIE and its children.  */
8807
8808 static void
8809 output_loclists_offsets (dw_die_ref die)
8810 {
8811   dw_die_ref c;
8812   dw_attr_node *a;
8813   unsigned ix;
8814
8815   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
8816     if (AT_class (a) == dw_val_class_loc_list)
8817       {
8818         dw_loc_list_ref l = AT_loc_list (a);
8819         if (l->offset_emitted)
8820           continue;
8821         dw2_asm_output_delta (DWARF_OFFSET_SIZE, l->ll_symbol,
8822                               loc_section_label, NULL);
8823         gcc_assert (l->hash == loc_list_idx);
8824         loc_list_idx++;
8825         l->offset_emitted = true;
8826       }
8827
8828   FOR_EACH_CHILD (die, c, output_loclists_offsets (c));
8829 }
8830
8831 /* Recursively set indexes of location lists.  */
8832
8833 static void
8834 assign_location_list_indexes (dw_die_ref die)
8835 {
8836   dw_die_ref c;
8837   dw_attr_node *a;
8838   unsigned ix;
8839
8840   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
8841     if (AT_class (a) == dw_val_class_loc_list)
8842       {
8843         dw_loc_list_ref list = AT_loc_list (a);
8844         if (!list->num_assigned)
8845           {
8846             list->num_assigned = true;
8847             list->hash = loc_list_idx++;
8848           }
8849       }
8850
8851   FOR_EACH_CHILD (die, c, assign_location_list_indexes (c));
8852 }
8853
8854 /* We want to limit the number of external references, because they are
8855    larger than local references: a relocation takes multiple words, and
8856    even a sig8 reference is always eight bytes, whereas a local reference
8857    can be as small as one byte (though DW_FORM_ref is usually 4 in GCC).
8858    So if we encounter multiple external references to the same type DIE, we
8859    make a local typedef stub for it and redirect all references there.
8860
8861    This is the element of the hash table for keeping track of these
8862    references.  */
8863
8864 struct external_ref
8865 {
8866   dw_die_ref type;
8867   dw_die_ref stub;
8868   unsigned n_refs;
8869 };
8870
8871 /* Hashtable helpers.  */
8872
8873 struct external_ref_hasher : free_ptr_hash <external_ref>
8874 {
8875   static inline hashval_t hash (const external_ref *);
8876   static inline bool equal (const external_ref *, const external_ref *);
8877 };
8878
8879 inline hashval_t
8880 external_ref_hasher::hash (const external_ref *r)
8881 {
8882   dw_die_ref die = r->type;
8883   hashval_t h = 0;
8884
8885   /* We can't use the address of the DIE for hashing, because
8886      that will make the order of the stub DIEs non-deterministic.  */
8887   if (! die->comdat_type_p)
8888     /* We have a symbol; use it to compute a hash.  */
8889     h = htab_hash_string (die->die_id.die_symbol);
8890   else
8891     {
8892       /* We have a type signature; use a subset of the bits as the hash.
8893          The 8-byte signature is at least as large as hashval_t.  */
8894       comdat_type_node *type_node = die->die_id.die_type_node;
8895       memcpy (&h, type_node->signature, sizeof (h));
8896     }
8897   return h;
8898 }
8899
8900 inline bool
8901 external_ref_hasher::equal (const external_ref *r1, const external_ref *r2)
8902 {
8903   return r1->type == r2->type;
8904 }
8905
8906 typedef hash_table<external_ref_hasher> external_ref_hash_type;
8907
8908 /* Return a pointer to the external_ref for references to DIE.  */
8909
8910 static struct external_ref *
8911 lookup_external_ref (external_ref_hash_type *map, dw_die_ref die)
8912 {
8913   struct external_ref ref, *ref_p;
8914   external_ref **slot;
8915
8916   ref.type = die;
8917   slot = map->find_slot (&ref, INSERT);
8918   if (*slot != HTAB_EMPTY_ENTRY)
8919     return *slot;
8920
8921   ref_p = XCNEW (struct external_ref);
8922   ref_p->type = die;
8923   *slot = ref_p;
8924   return ref_p;
8925 }
8926
8927 /* Subroutine of optimize_external_refs, below.
8928
8929    If we see a type skeleton, record it as our stub.  If we see external
8930    references, remember how many we've seen.  */
8931
8932 static void
8933 optimize_external_refs_1 (dw_die_ref die, external_ref_hash_type *map)
8934 {
8935   dw_die_ref c;
8936   dw_attr_node *a;
8937   unsigned ix;
8938   struct external_ref *ref_p;
8939
8940   if (is_type_die (die)
8941       && (c = get_AT_ref (die, DW_AT_signature)))
8942     {
8943       /* This is a local skeleton; use it for local references.  */
8944       ref_p = lookup_external_ref (map, c);
8945       ref_p->stub = die;
8946     }
8947
8948   /* Scan the DIE references, and remember any that refer to DIEs from
8949      other CUs (i.e. those which are not marked).  */
8950   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
8951     if (AT_class (a) == dw_val_class_die_ref
8952         && (c = AT_ref (a))->die_mark == 0
8953         && is_type_die (c))
8954       {
8955         ref_p = lookup_external_ref (map, c);
8956         ref_p->n_refs++;
8957       }
8958
8959   FOR_EACH_CHILD (die, c, optimize_external_refs_1 (c, map));
8960 }
8961
8962 /* htab_traverse callback function for optimize_external_refs, below.  SLOT
8963    points to an external_ref, DATA is the CU we're processing.  If we don't
8964    already have a local stub, and we have multiple refs, build a stub.  */
8965
8966 int
8967 dwarf2_build_local_stub (external_ref **slot, dw_die_ref data)
8968 {
8969   struct external_ref *ref_p = *slot;
8970
8971   if (ref_p->stub == NULL && ref_p->n_refs > 1 && !dwarf_strict)
8972     {
8973       /* We have multiple references to this type, so build a small stub.
8974          Both of these forms are a bit dodgy from the perspective of the
8975          DWARF standard, since technically they should have names.  */
8976       dw_die_ref cu = data;
8977       dw_die_ref type = ref_p->type;
8978       dw_die_ref stub = NULL;
8979
8980       if (type->comdat_type_p)
8981         {
8982           /* If we refer to this type via sig8, use AT_signature.  */
8983           stub = new_die (type->die_tag, cu, NULL_TREE);
8984           add_AT_die_ref (stub, DW_AT_signature, type);
8985         }
8986       else
8987         {
8988           /* Otherwise, use a typedef with no name.  */
8989           stub = new_die (DW_TAG_typedef, cu, NULL_TREE);
8990           add_AT_die_ref (stub, DW_AT_type, type);
8991         }
8992
8993       stub->die_mark++;
8994       ref_p->stub = stub;
8995     }
8996   return 1;
8997 }
8998
8999 /* DIE is a unit; look through all the DIE references to see if there are
9000    any external references to types, and if so, create local stubs for
9001    them which will be applied in build_abbrev_table.  This is useful because
9002    references to local DIEs are smaller.  */
9003
9004 static external_ref_hash_type *
9005 optimize_external_refs (dw_die_ref die)
9006 {
9007   external_ref_hash_type *map = new external_ref_hash_type (10);
9008   optimize_external_refs_1 (die, map);
9009   map->traverse <dw_die_ref, dwarf2_build_local_stub> (die);
9010   return map;
9011 }
9012
9013 /* The following 3 variables are temporaries that are computed only during the
9014    build_abbrev_table call and used and released during the following
9015    optimize_abbrev_table call.  */
9016
9017 /* First abbrev_id that can be optimized based on usage.  */
9018 static unsigned int abbrev_opt_start;
9019
9020 /* Maximum abbrev_id of a base type plus one (we can't optimize DIEs with
9021    abbrev_id smaller than this, because they must be already sized
9022    during build_abbrev_table).  */
9023 static unsigned int abbrev_opt_base_type_end;
9024
9025 /* Vector of usage counts during build_abbrev_table.  Indexed by
9026    abbrev_id - abbrev_opt_start.  */
9027 static vec<unsigned int> abbrev_usage_count;
9028
9029 /* Vector of all DIEs added with die_abbrev >= abbrev_opt_start.  */
9030 static vec<dw_die_ref> sorted_abbrev_dies;
9031
9032 /* The format of each DIE (and its attribute value pairs) is encoded in an
9033    abbreviation table.  This routine builds the abbreviation table and assigns
9034    a unique abbreviation id for each abbreviation entry.  The children of each
9035    die are visited recursively.  */
9036
9037 static void
9038 build_abbrev_table (dw_die_ref die, external_ref_hash_type *extern_map)
9039 {
9040   unsigned int abbrev_id = 0;
9041   dw_die_ref c;
9042   dw_attr_node *a;
9043   unsigned ix;
9044   dw_die_ref abbrev;
9045
9046   /* Scan the DIE references, and replace any that refer to
9047      DIEs from other CUs (i.e. those which are not marked) with
9048      the local stubs we built in optimize_external_refs.  */
9049   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
9050     if (AT_class (a) == dw_val_class_die_ref
9051         && (c = AT_ref (a))->die_mark == 0)
9052       {
9053         struct external_ref *ref_p;
9054         gcc_assert (AT_ref (a)->comdat_type_p || AT_ref (a)->die_id.die_symbol);
9055
9056         if (is_type_die (c)
9057             && (ref_p = lookup_external_ref (extern_map, c))
9058             && ref_p->stub && ref_p->stub != die
9059             && a->dw_attr != DW_AT_signature)
9060           change_AT_die_ref (a, ref_p->stub);
9061         else
9062           /* We aren't changing this reference, so mark it external.  */
9063           set_AT_ref_external (a, 1);
9064       }
9065
9066   FOR_EACH_VEC_SAFE_ELT (abbrev_die_table, abbrev_id, abbrev)
9067     {
9068       dw_attr_node *die_a, *abbrev_a;
9069       unsigned ix;
9070       bool ok = true;
9071
9072       if (abbrev_id == 0)
9073         continue;
9074       if (abbrev->die_tag != die->die_tag)
9075         continue;
9076       if ((abbrev->die_child != NULL) != (die->die_child != NULL))
9077         continue;
9078
9079       if (vec_safe_length (abbrev->die_attr) != vec_safe_length (die->die_attr))
9080         continue;
9081
9082       FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, die_a)
9083         {
9084           abbrev_a = &(*abbrev->die_attr)[ix];
9085           if ((abbrev_a->dw_attr != die_a->dw_attr)
9086               || (value_format (abbrev_a) != value_format (die_a)))
9087             {
9088               ok = false;
9089               break;
9090             }
9091         }
9092       if (ok)
9093         break;
9094     }
9095
9096   if (abbrev_id >= vec_safe_length (abbrev_die_table))
9097     {
9098       vec_safe_push (abbrev_die_table, die);
9099       if (abbrev_opt_start)
9100         abbrev_usage_count.safe_push (0);
9101     }
9102   if (abbrev_opt_start && abbrev_id >= abbrev_opt_start)
9103     {
9104       abbrev_usage_count[abbrev_id - abbrev_opt_start]++;
9105       sorted_abbrev_dies.safe_push (die);
9106     }
9107
9108   die->die_abbrev = abbrev_id;
9109   FOR_EACH_CHILD (die, c, build_abbrev_table (c, extern_map));
9110 }
9111
9112 /* Callback function for sorted_abbrev_dies vector sorting.  We sort
9113    by die_abbrev's usage count, from the most commonly used
9114    abbreviation to the least.  */
9115
9116 static int
9117 die_abbrev_cmp (const void *p1, const void *p2)
9118 {
9119   dw_die_ref die1 = *(const dw_die_ref *) p1;
9120   dw_die_ref die2 = *(const dw_die_ref *) p2;
9121
9122   gcc_checking_assert (die1->die_abbrev >= abbrev_opt_start);
9123   gcc_checking_assert (die2->die_abbrev >= abbrev_opt_start);
9124
9125   if (die1->die_abbrev >= abbrev_opt_base_type_end
9126       && die2->die_abbrev >= abbrev_opt_base_type_end)
9127     {
9128       if (abbrev_usage_count[die1->die_abbrev - abbrev_opt_start]
9129           > abbrev_usage_count[die2->die_abbrev - abbrev_opt_start])
9130         return -1;
9131       if (abbrev_usage_count[die1->die_abbrev - abbrev_opt_start]
9132           < abbrev_usage_count[die2->die_abbrev - abbrev_opt_start])
9133         return 1;
9134     }
9135
9136   /* Stabilize the sort.  */
9137   if (die1->die_abbrev < die2->die_abbrev)
9138     return -1;
9139   if (die1->die_abbrev > die2->die_abbrev)
9140     return 1;
9141
9142   return 0;
9143 }
9144
9145 /* Convert dw_val_class_const and dw_val_class_unsigned_const class attributes
9146    of DIEs in between sorted_abbrev_dies[first_id] and abbrev_dies[end_id - 1]
9147    into dw_val_class_const_implicit or
9148    dw_val_class_unsigned_const_implicit.  */
9149
9150 static void
9151 optimize_implicit_const (unsigned int first_id, unsigned int end,
9152                          vec<bool> &implicit_consts)
9153 {
9154   /* It never makes sense if there is just one DIE using the abbreviation.  */
9155   if (end < first_id + 2)
9156     return;
9157
9158   dw_attr_node *a;
9159   unsigned ix, i;
9160   dw_die_ref die = sorted_abbrev_dies[first_id];
9161   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
9162     if (implicit_consts[ix])
9163       {
9164         enum dw_val_class new_class = dw_val_class_none;
9165         switch (AT_class (a))
9166           {
9167           case dw_val_class_unsigned_const:
9168             if ((HOST_WIDE_INT) AT_unsigned (a) < 0)
9169               continue;
9170
9171             /* The .debug_abbrev section will grow by
9172                size_of_sleb128 (AT_unsigned (a)) and we avoid the constants
9173                in all the DIEs using that abbreviation.  */
9174             if (constant_size (AT_unsigned (a)) * (end - first_id)
9175                 <= (unsigned) size_of_sleb128 (AT_unsigned (a)))
9176               continue;
9177
9178             new_class = dw_val_class_unsigned_const_implicit;
9179             break;
9180
9181           case dw_val_class_const:
9182             new_class = dw_val_class_const_implicit;
9183             break;
9184
9185           case dw_val_class_file:
9186             new_class = dw_val_class_file_implicit;
9187             break;
9188
9189           default:
9190             continue;
9191           }
9192         for (i = first_id; i < end; i++)
9193           (*sorted_abbrev_dies[i]->die_attr)[ix].dw_attr_val.val_class
9194             = new_class;
9195       }
9196 }
9197
9198 /* Attempt to optimize abbreviation table from abbrev_opt_start
9199    abbreviation above.  */
9200
9201 static void
9202 optimize_abbrev_table (void)
9203 {
9204   if (abbrev_opt_start
9205       && vec_safe_length (abbrev_die_table) > abbrev_opt_start
9206       && (dwarf_version >= 5 || vec_safe_length (abbrev_die_table) > 127))
9207     {
9208       auto_vec<bool, 32> implicit_consts;
9209       sorted_abbrev_dies.qsort (die_abbrev_cmp);
9210
9211       unsigned int abbrev_id = abbrev_opt_start - 1;
9212       unsigned int first_id = ~0U;
9213       unsigned int last_abbrev_id = 0;
9214       unsigned int i;
9215       dw_die_ref die;
9216       if (abbrev_opt_base_type_end > abbrev_opt_start)
9217         abbrev_id = abbrev_opt_base_type_end - 1;
9218       /* Reassign abbreviation ids from abbrev_opt_start above, so that
9219          most commonly used abbreviations come first.  */
9220       FOR_EACH_VEC_ELT (sorted_abbrev_dies, i, die)
9221         {
9222           dw_attr_node *a;
9223           unsigned ix;
9224
9225           /* If calc_base_type_die_sizes has been called, the CU and
9226              base types after it can't be optimized, because we've already
9227              calculated their DIE offsets.  We've sorted them first.  */
9228           if (die->die_abbrev < abbrev_opt_base_type_end)
9229             continue;
9230           if (die->die_abbrev != last_abbrev_id)
9231             {
9232               last_abbrev_id = die->die_abbrev;
9233               if (dwarf_version >= 5 && first_id != ~0U)
9234                 optimize_implicit_const (first_id, i, implicit_consts);
9235               abbrev_id++;
9236               (*abbrev_die_table)[abbrev_id] = die;
9237               if (dwarf_version >= 5)
9238                 {
9239                   first_id = i;
9240                   implicit_consts.truncate (0);
9241
9242                   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
9243                     switch (AT_class (a))
9244                       {
9245                       case dw_val_class_const:
9246                       case dw_val_class_unsigned_const:
9247                       case dw_val_class_file:
9248                         implicit_consts.safe_push (true);
9249                         break;
9250                       default:
9251                         implicit_consts.safe_push (false);
9252                         break;
9253                       }
9254                 }
9255             }
9256           else if (dwarf_version >= 5)
9257             {
9258               FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
9259                 if (!implicit_consts[ix])
9260                   continue;
9261                 else
9262                   {
9263                     dw_attr_node *other_a
9264                       = &(*(*abbrev_die_table)[abbrev_id]->die_attr)[ix];
9265                     if (!dw_val_equal_p (&a->dw_attr_val,
9266                                          &other_a->dw_attr_val))
9267                       implicit_consts[ix] = false;
9268                   }
9269             }
9270           die->die_abbrev = abbrev_id;
9271         }
9272       gcc_assert (abbrev_id == vec_safe_length (abbrev_die_table) - 1);
9273       if (dwarf_version >= 5 && first_id != ~0U)
9274         optimize_implicit_const (first_id, i, implicit_consts);
9275     }
9276
9277   abbrev_opt_start = 0;
9278   abbrev_opt_base_type_end = 0;
9279   abbrev_usage_count.release ();
9280   sorted_abbrev_dies.release ();
9281 }
9282 \f
9283 /* Return the power-of-two number of bytes necessary to represent VALUE.  */
9284
9285 static int
9286 constant_size (unsigned HOST_WIDE_INT value)
9287 {
9288   int log;
9289
9290   if (value == 0)
9291     log = 0;
9292   else
9293     log = floor_log2 (value);
9294
9295   log = log / 8;
9296   log = 1 << (floor_log2 (log) + 1);
9297
9298   return log;
9299 }
9300
9301 /* Return the size of a DIE as it is represented in the
9302    .debug_info section.  */
9303
9304 static unsigned long
9305 size_of_die (dw_die_ref die)
9306 {
9307   unsigned long size = 0;
9308   dw_attr_node *a;
9309   unsigned ix;
9310   enum dwarf_form form;
9311
9312   size += size_of_uleb128 (die->die_abbrev);
9313   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
9314     {
9315       switch (AT_class (a))
9316         {
9317         case dw_val_class_addr:
9318           if (dwarf_split_debug_info && AT_index (a) != NOT_INDEXED)
9319             {
9320               gcc_assert (AT_index (a) != NO_INDEX_ASSIGNED);
9321               size += size_of_uleb128 (AT_index (a));
9322             }
9323           else
9324             size += DWARF2_ADDR_SIZE;
9325           break;
9326         case dw_val_class_offset:
9327           size += DWARF_OFFSET_SIZE;
9328           break;
9329         case dw_val_class_loc:
9330           {
9331             unsigned long lsize = size_of_locs (AT_loc (a));
9332
9333             /* Block length.  */
9334             if (dwarf_version >= 4)
9335               size += size_of_uleb128 (lsize);
9336             else
9337               size += constant_size (lsize);
9338             size += lsize;
9339           }
9340           break;
9341         case dw_val_class_loc_list:
9342         case dw_val_class_view_list:
9343           if (dwarf_split_debug_info && dwarf_version >= 5)
9344             {
9345               gcc_assert (AT_loc_list (a)->num_assigned);
9346               size += size_of_uleb128 (AT_loc_list (a)->hash);
9347             }
9348           else
9349             size += DWARF_OFFSET_SIZE;
9350           break;
9351         case dw_val_class_range_list:
9352           if (value_format (a) == DW_FORM_rnglistx)
9353             {
9354               gcc_assert (rnglist_idx);
9355               dw_ranges *r = &(*ranges_table)[a->dw_attr_val.v.val_offset];
9356               size += size_of_uleb128 (r->idx);
9357             }
9358           else
9359             size += DWARF_OFFSET_SIZE;
9360           break;
9361         case dw_val_class_const:
9362           size += size_of_sleb128 (AT_int (a));
9363           break;
9364         case dw_val_class_unsigned_const:
9365           {
9366             int csize = constant_size (AT_unsigned (a));
9367             if (dwarf_version == 3
9368                 && a->dw_attr == DW_AT_data_member_location
9369                 && csize >= 4)
9370               size += size_of_uleb128 (AT_unsigned (a));
9371             else
9372               size += csize;
9373           }
9374           break;
9375         case dw_val_class_symview:
9376           if (symview_upper_bound <= 0xff)
9377             size += 1;
9378           else if (symview_upper_bound <= 0xffff)
9379             size += 2;
9380           else if (symview_upper_bound <= 0xffffffff)
9381             size += 4;
9382           else
9383             size += 8;
9384           break;
9385         case dw_val_class_const_implicit:
9386         case dw_val_class_unsigned_const_implicit:
9387         case dw_val_class_file_implicit:
9388           /* These occupy no size in the DIE, just an extra sleb128 in
9389              .debug_abbrev.  */
9390           break;
9391         case dw_val_class_const_double:
9392           size += HOST_BITS_PER_DOUBLE_INT / HOST_BITS_PER_CHAR;
9393           if (HOST_BITS_PER_WIDE_INT >= DWARF_LARGEST_DATA_FORM_BITS)
9394             size++; /* block */
9395           break;
9396         case dw_val_class_wide_int:
9397           size += (get_full_len (*a->dw_attr_val.v.val_wide)
9398                    * HOST_BITS_PER_WIDE_INT / HOST_BITS_PER_CHAR);
9399           if (get_full_len (*a->dw_attr_val.v.val_wide)
9400               * HOST_BITS_PER_WIDE_INT > DWARF_LARGEST_DATA_FORM_BITS)
9401             size++; /* block */
9402           break;
9403         case dw_val_class_vec:
9404           size += constant_size (a->dw_attr_val.v.val_vec.length
9405                                  * a->dw_attr_val.v.val_vec.elt_size)
9406                   + a->dw_attr_val.v.val_vec.length
9407                     * a->dw_attr_val.v.val_vec.elt_size; /* block */
9408           break;
9409         case dw_val_class_flag:
9410           if (dwarf_version >= 4)
9411             /* Currently all add_AT_flag calls pass in 1 as last argument,
9412                so DW_FORM_flag_present can be used.  If that ever changes,
9413                we'll need to use DW_FORM_flag and have some optimization
9414                in build_abbrev_table that will change those to
9415                DW_FORM_flag_present if it is set to 1 in all DIEs using
9416                the same abbrev entry.  */
9417             gcc_assert (a->dw_attr_val.v.val_flag == 1);
9418           else
9419             size += 1;
9420           break;
9421         case dw_val_class_die_ref:
9422           if (AT_ref_external (a))
9423             {
9424               /* In DWARF4, we use DW_FORM_ref_sig8; for earlier versions
9425                  we use DW_FORM_ref_addr.  In DWARF2, DW_FORM_ref_addr
9426                  is sized by target address length, whereas in DWARF3
9427                  it's always sized as an offset.  */
9428               if (use_debug_types)
9429                 size += DWARF_TYPE_SIGNATURE_SIZE;
9430               else if (dwarf_version == 2)
9431                 size += DWARF2_ADDR_SIZE;
9432               else
9433                 size += DWARF_OFFSET_SIZE;
9434             }
9435           else
9436             size += DWARF_OFFSET_SIZE;
9437           break;
9438         case dw_val_class_fde_ref:
9439           size += DWARF_OFFSET_SIZE;
9440           break;
9441         case dw_val_class_lbl_id:
9442           if (dwarf_split_debug_info && AT_index (a) != NOT_INDEXED)
9443             {
9444               gcc_assert (AT_index (a) != NO_INDEX_ASSIGNED);
9445               size += size_of_uleb128 (AT_index (a));
9446             }
9447           else
9448             size += DWARF2_ADDR_SIZE;
9449           break;
9450         case dw_val_class_lineptr:
9451         case dw_val_class_macptr:
9452         case dw_val_class_loclistsptr:
9453           size += DWARF_OFFSET_SIZE;
9454           break;
9455         case dw_val_class_str:
9456           form = AT_string_form (a);
9457           if (form == DW_FORM_strp || form == DW_FORM_line_strp)
9458             size += DWARF_OFFSET_SIZE;
9459           else if (form == DW_FORM_GNU_str_index)
9460             size += size_of_uleb128 (AT_index (a));
9461           else
9462             size += strlen (a->dw_attr_val.v.val_str->str) + 1;
9463           break;
9464         case dw_val_class_file:
9465           size += constant_size (maybe_emit_file (a->dw_attr_val.v.val_file));
9466           break;
9467         case dw_val_class_data8:
9468           size += 8;
9469           break;
9470         case dw_val_class_vms_delta:
9471           size += DWARF_OFFSET_SIZE;
9472           break;
9473         case dw_val_class_high_pc:
9474           size += DWARF2_ADDR_SIZE;
9475           break;
9476         case dw_val_class_discr_value:
9477           size += size_of_discr_value (&a->dw_attr_val.v.val_discr_value);
9478           break;
9479         case dw_val_class_discr_list:
9480             {
9481               unsigned block_size = size_of_discr_list (AT_discr_list (a));
9482
9483               /* This is a block, so we have the block length and then its
9484                  data.  */
9485               size += constant_size (block_size) + block_size;
9486             }
9487           break;
9488         default:
9489           gcc_unreachable ();
9490         }
9491     }
9492
9493   return size;
9494 }
9495
9496 /* Size the debugging information associated with a given DIE.  Visits the
9497    DIE's children recursively.  Updates the global variable next_die_offset, on
9498    each time through.  Uses the current value of next_die_offset to update the
9499    die_offset field in each DIE.  */
9500
9501 static void
9502 calc_die_sizes (dw_die_ref die)
9503 {
9504   dw_die_ref c;
9505
9506   gcc_assert (die->die_offset == 0
9507               || (unsigned long int) die->die_offset == next_die_offset);
9508   die->die_offset = next_die_offset;
9509   next_die_offset += size_of_die (die);
9510
9511   FOR_EACH_CHILD (die, c, calc_die_sizes (c));
9512
9513   if (die->die_child != NULL)
9514     /* Count the null byte used to terminate sibling lists.  */
9515     next_die_offset += 1;
9516 }
9517
9518 /* Size just the base type children at the start of the CU.
9519    This is needed because build_abbrev needs to size locs
9520    and sizing of type based stack ops needs to know die_offset
9521    values for the base types.  */
9522
9523 static void
9524 calc_base_type_die_sizes (void)
9525 {
9526   unsigned long die_offset = (dwarf_split_debug_info
9527                               ? DWARF_COMPILE_UNIT_SKELETON_HEADER_SIZE
9528                               : DWARF_COMPILE_UNIT_HEADER_SIZE);
9529   unsigned int i;
9530   dw_die_ref base_type;
9531 #if ENABLE_ASSERT_CHECKING
9532   dw_die_ref prev = comp_unit_die ()->die_child;
9533 #endif
9534
9535   die_offset += size_of_die (comp_unit_die ());
9536   for (i = 0; base_types.iterate (i, &base_type); i++)
9537     {
9538 #if ENABLE_ASSERT_CHECKING
9539       gcc_assert (base_type->die_offset == 0
9540                   && prev->die_sib == base_type
9541                   && base_type->die_child == NULL
9542                   && base_type->die_abbrev);
9543       prev = base_type;
9544 #endif
9545       if (abbrev_opt_start
9546           && base_type->die_abbrev >= abbrev_opt_base_type_end)
9547         abbrev_opt_base_type_end = base_type->die_abbrev + 1;
9548       base_type->die_offset = die_offset;
9549       die_offset += size_of_die (base_type);
9550     }
9551 }
9552
9553 /* Set the marks for a die and its children.  We do this so
9554    that we know whether or not a reference needs to use FORM_ref_addr; only
9555    DIEs in the same CU will be marked.  We used to clear out the offset
9556    and use that as the flag, but ran into ordering problems.  */
9557
9558 static void
9559 mark_dies (dw_die_ref die)
9560 {
9561   dw_die_ref c;
9562
9563   gcc_assert (!die->die_mark);
9564
9565   die->die_mark = 1;
9566   FOR_EACH_CHILD (die, c, mark_dies (c));
9567 }
9568
9569 /* Clear the marks for a die and its children.  */
9570
9571 static void
9572 unmark_dies (dw_die_ref die)
9573 {
9574   dw_die_ref c;
9575
9576   if (! use_debug_types)
9577     gcc_assert (die->die_mark);
9578
9579   die->die_mark = 0;
9580   FOR_EACH_CHILD (die, c, unmark_dies (c));
9581 }
9582
9583 /* Clear the marks for a die, its children and referred dies.  */
9584
9585 static void
9586 unmark_all_dies (dw_die_ref die)
9587 {
9588   dw_die_ref c;
9589   dw_attr_node *a;
9590   unsigned ix;
9591
9592   if (!die->die_mark)
9593     return;
9594   die->die_mark = 0;
9595
9596   FOR_EACH_CHILD (die, c, unmark_all_dies (c));
9597
9598   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
9599     if (AT_class (a) == dw_val_class_die_ref)
9600       unmark_all_dies (AT_ref (a));
9601 }
9602
9603 /* Calculate if the entry should appear in the final output file.  It may be
9604    from a pruned a type.  */
9605
9606 static bool
9607 include_pubname_in_output (vec<pubname_entry, va_gc> *table, pubname_entry *p)
9608 {
9609   /* By limiting gnu pubnames to definitions only, gold can generate a
9610      gdb index without entries for declarations, which don't include
9611      enough information to be useful.  */
9612   if (debug_generate_pub_sections == 2 && is_declaration_die (p->die))
9613     return false;
9614
9615   if (table == pubname_table)
9616     {
9617       /* Enumerator names are part of the pubname table, but the
9618          parent DW_TAG_enumeration_type die may have been pruned.
9619          Don't output them if that is the case.  */
9620       if (p->die->die_tag == DW_TAG_enumerator &&
9621           (p->die->die_parent == NULL
9622            || !p->die->die_parent->die_perennial_p))
9623         return false;
9624
9625       /* Everything else in the pubname table is included.  */
9626       return true;
9627     }
9628
9629   /* The pubtypes table shouldn't include types that have been
9630      pruned.  */
9631   return (p->die->die_offset != 0
9632           || !flag_eliminate_unused_debug_types);
9633 }
9634
9635 /* Return the size of the .debug_pubnames or .debug_pubtypes table
9636    generated for the compilation unit.  */
9637
9638 static unsigned long
9639 size_of_pubnames (vec<pubname_entry, va_gc> *names)
9640 {
9641   unsigned long size;
9642   unsigned i;
9643   pubname_entry *p;
9644   int space_for_flags = (debug_generate_pub_sections == 2) ? 1 : 0;
9645
9646   size = DWARF_PUBNAMES_HEADER_SIZE;
9647   FOR_EACH_VEC_ELT (*names, i, p)
9648     if (include_pubname_in_output (names, p))
9649       size += strlen (p->name) + DWARF_OFFSET_SIZE + 1 + space_for_flags;
9650
9651   size += DWARF_OFFSET_SIZE;
9652   return size;
9653 }
9654
9655 /* Return the size of the information in the .debug_aranges section.  */
9656
9657 static unsigned long
9658 size_of_aranges (void)
9659 {
9660   unsigned long size;
9661
9662   size = DWARF_ARANGES_HEADER_SIZE;
9663
9664   /* Count the address/length pair for this compilation unit.  */
9665   if (text_section_used)
9666     size += 2 * DWARF2_ADDR_SIZE;
9667   if (cold_text_section_used)
9668     size += 2 * DWARF2_ADDR_SIZE;
9669   if (have_multiple_function_sections)
9670     {
9671       unsigned fde_idx;
9672       dw_fde_ref fde;
9673
9674       FOR_EACH_VEC_ELT (*fde_vec, fde_idx, fde)
9675         {
9676           if (DECL_IGNORED_P (fde->decl))
9677             continue;
9678           if (!fde->in_std_section)
9679             size += 2 * DWARF2_ADDR_SIZE;
9680           if (fde->dw_fde_second_begin && !fde->second_in_std_section)
9681             size += 2 * DWARF2_ADDR_SIZE;
9682         }
9683     }
9684
9685   /* Count the two zero words used to terminated the address range table.  */
9686   size += 2 * DWARF2_ADDR_SIZE;
9687   return size;
9688 }
9689 \f
9690 /* Select the encoding of an attribute value.  */
9691
9692 static enum dwarf_form
9693 value_format (dw_attr_node *a)
9694 {
9695   switch (AT_class (a))
9696     {
9697     case dw_val_class_addr:
9698       /* Only very few attributes allow DW_FORM_addr.  */
9699       switch (a->dw_attr)
9700         {
9701         case DW_AT_low_pc:
9702         case DW_AT_high_pc:
9703         case DW_AT_entry_pc:
9704         case DW_AT_trampoline:
9705           return (AT_index (a) == NOT_INDEXED
9706                   ? DW_FORM_addr : DW_FORM_GNU_addr_index);
9707         default:
9708           break;
9709         }
9710       switch (DWARF2_ADDR_SIZE)
9711         {
9712         case 1:
9713           return DW_FORM_data1;
9714         case 2:
9715           return DW_FORM_data2;
9716         case 4:
9717           return DW_FORM_data4;
9718         case 8:
9719           return DW_FORM_data8;
9720         default:
9721           gcc_unreachable ();
9722         }
9723     case dw_val_class_loc_list:
9724     case dw_val_class_view_list:
9725       if (dwarf_split_debug_info
9726           && dwarf_version >= 5
9727           && AT_loc_list (a)->num_assigned)
9728         return DW_FORM_loclistx;
9729       /* FALLTHRU */
9730     case dw_val_class_range_list:
9731       /* For range lists in DWARF 5, use DW_FORM_rnglistx from .debug_info.dwo
9732          but in .debug_info use DW_FORM_sec_offset, which is shorter if we
9733          care about sizes of .debug* sections in shared libraries and
9734          executables and don't take into account relocations that affect just
9735          relocatable objects - for DW_FORM_rnglistx we'd have to emit offset
9736          table in the .debug_rnglists section.  */
9737       if (dwarf_split_debug_info
9738           && dwarf_version >= 5
9739           && AT_class (a) == dw_val_class_range_list
9740           && rnglist_idx
9741           && a->dw_attr_val.val_entry != RELOCATED_OFFSET)
9742         return DW_FORM_rnglistx;
9743       if (dwarf_version >= 4)
9744         return DW_FORM_sec_offset;
9745       /* FALLTHRU */
9746     case dw_val_class_vms_delta:
9747     case dw_val_class_offset:
9748       switch (DWARF_OFFSET_SIZE)
9749         {
9750         case 4:
9751           return DW_FORM_data4;
9752         case 8:
9753           return DW_FORM_data8;
9754         default:
9755           gcc_unreachable ();
9756         }
9757     case dw_val_class_loc:
9758       if (dwarf_version >= 4)
9759         return DW_FORM_exprloc;
9760       switch (constant_size (size_of_locs (AT_loc (a))))
9761         {
9762         case 1:
9763           return DW_FORM_block1;
9764         case 2:
9765           return DW_FORM_block2;
9766         case 4:
9767           return DW_FORM_block4;
9768         default:
9769           gcc_unreachable ();
9770         }
9771     case dw_val_class_const:
9772       return DW_FORM_sdata;
9773     case dw_val_class_unsigned_const:
9774       switch (constant_size (AT_unsigned (a)))
9775         {
9776         case 1:
9777           return DW_FORM_data1;
9778         case 2:
9779           return DW_FORM_data2;
9780         case 4:
9781           /* In DWARF3 DW_AT_data_member_location with
9782              DW_FORM_data4 or DW_FORM_data8 is a loclistptr, not
9783              constant, so we need to use DW_FORM_udata if we need
9784              a large constant.  */
9785           if (dwarf_version == 3 && a->dw_attr == DW_AT_data_member_location)
9786             return DW_FORM_udata;
9787           return DW_FORM_data4;
9788         case 8:
9789           if (dwarf_version == 3 && a->dw_attr == DW_AT_data_member_location)
9790             return DW_FORM_udata;
9791           return DW_FORM_data8;
9792         default:
9793           gcc_unreachable ();
9794         }
9795     case dw_val_class_const_implicit:
9796     case dw_val_class_unsigned_const_implicit:
9797     case dw_val_class_file_implicit:
9798       return DW_FORM_implicit_const;
9799     case dw_val_class_const_double:
9800       switch (HOST_BITS_PER_WIDE_INT)
9801         {
9802         case 8:
9803           return DW_FORM_data2;
9804         case 16:
9805           return DW_FORM_data4;
9806         case 32:
9807           return DW_FORM_data8;
9808         case 64:
9809           if (dwarf_version >= 5)
9810             return DW_FORM_data16;
9811           /* FALLTHRU */
9812         default:
9813           return DW_FORM_block1;
9814         }
9815     case dw_val_class_wide_int:
9816       switch (get_full_len (*a->dw_attr_val.v.val_wide) * HOST_BITS_PER_WIDE_INT)
9817         {
9818         case 8:
9819           return DW_FORM_data1;
9820         case 16:
9821           return DW_FORM_data2;
9822         case 32:
9823           return DW_FORM_data4;
9824         case 64:
9825           return DW_FORM_data8;
9826         case 128:
9827           if (dwarf_version >= 5)
9828             return DW_FORM_data16;
9829           /* FALLTHRU */
9830         default:
9831           return DW_FORM_block1;
9832         }
9833     case dw_val_class_symview:
9834       /* ??? We might use uleb128, but then we'd have to compute
9835          .debug_info offsets in the assembler.  */
9836       if (symview_upper_bound <= 0xff)
9837         return DW_FORM_data1;
9838       else if (symview_upper_bound <= 0xffff)
9839         return DW_FORM_data2;
9840       else if (symview_upper_bound <= 0xffffffff)
9841         return DW_FORM_data4;
9842       else
9843         return DW_FORM_data8;
9844     case dw_val_class_vec:
9845       switch (constant_size (a->dw_attr_val.v.val_vec.length
9846                              * a->dw_attr_val.v.val_vec.elt_size))
9847         {
9848         case 1:
9849           return DW_FORM_block1;
9850         case 2:
9851           return DW_FORM_block2;
9852         case 4:
9853           return DW_FORM_block4;
9854         default:
9855           gcc_unreachable ();
9856         }
9857     case dw_val_class_flag:
9858       if (dwarf_version >= 4)
9859         {
9860           /* Currently all add_AT_flag calls pass in 1 as last argument,
9861              so DW_FORM_flag_present can be used.  If that ever changes,
9862              we'll need to use DW_FORM_flag and have some optimization
9863              in build_abbrev_table that will change those to
9864              DW_FORM_flag_present if it is set to 1 in all DIEs using
9865              the same abbrev entry.  */
9866           gcc_assert (a->dw_attr_val.v.val_flag == 1);
9867           return DW_FORM_flag_present;
9868         }
9869       return DW_FORM_flag;
9870     case dw_val_class_die_ref:
9871       if (AT_ref_external (a))
9872         return use_debug_types ? DW_FORM_ref_sig8 : DW_FORM_ref_addr;
9873       else
9874         return DW_FORM_ref;
9875     case dw_val_class_fde_ref:
9876       return DW_FORM_data;
9877     case dw_val_class_lbl_id:
9878       return (AT_index (a) == NOT_INDEXED
9879               ? DW_FORM_addr : DW_FORM_GNU_addr_index);
9880     case dw_val_class_lineptr:
9881     case dw_val_class_macptr:
9882     case dw_val_class_loclistsptr:
9883       return dwarf_version >= 4 ? DW_FORM_sec_offset : DW_FORM_data;
9884     case dw_val_class_str:
9885       return AT_string_form (a);
9886     case dw_val_class_file:
9887       switch (constant_size (maybe_emit_file (a->dw_attr_val.v.val_file)))
9888         {
9889         case 1:
9890           return DW_FORM_data1;
9891         case 2:
9892           return DW_FORM_data2;
9893         case 4:
9894           return DW_FORM_data4;
9895         default:
9896           gcc_unreachable ();
9897         }
9898
9899     case dw_val_class_data8:
9900       return DW_FORM_data8;
9901
9902     case dw_val_class_high_pc:
9903       switch (DWARF2_ADDR_SIZE)
9904         {
9905         case 1:
9906           return DW_FORM_data1;
9907         case 2:
9908           return DW_FORM_data2;
9909         case 4:
9910           return DW_FORM_data4;
9911         case 8:
9912           return DW_FORM_data8;
9913         default:
9914           gcc_unreachable ();
9915         }
9916
9917     case dw_val_class_discr_value:
9918       return (a->dw_attr_val.v.val_discr_value.pos
9919               ? DW_FORM_udata
9920               : DW_FORM_sdata);
9921     case dw_val_class_discr_list:
9922       switch (constant_size (size_of_discr_list (AT_discr_list (a))))
9923         {
9924         case 1:
9925           return DW_FORM_block1;
9926         case 2:
9927           return DW_FORM_block2;
9928         case 4:
9929           return DW_FORM_block4;
9930         default:
9931           gcc_unreachable ();
9932         }
9933
9934     default:
9935       gcc_unreachable ();
9936     }
9937 }
9938
9939 /* Output the encoding of an attribute value.  */
9940
9941 static void
9942 output_value_format (dw_attr_node *a)
9943 {
9944   enum dwarf_form form = value_format (a);
9945
9946   dw2_asm_output_data_uleb128 (form, "(%s)", dwarf_form_name (form));
9947 }
9948
9949 /* Given a die and id, produce the appropriate abbreviations.  */
9950
9951 static void
9952 output_die_abbrevs (unsigned long abbrev_id, dw_die_ref abbrev)
9953 {
9954   unsigned ix;
9955   dw_attr_node *a_attr;
9956
9957   dw2_asm_output_data_uleb128 (abbrev_id, "(abbrev code)");
9958   dw2_asm_output_data_uleb128 (abbrev->die_tag, "(TAG: %s)",
9959                                dwarf_tag_name (abbrev->die_tag));
9960
9961   if (abbrev->die_child != NULL)
9962     dw2_asm_output_data (1, DW_children_yes, "DW_children_yes");
9963   else
9964     dw2_asm_output_data (1, DW_children_no, "DW_children_no");
9965
9966   for (ix = 0; vec_safe_iterate (abbrev->die_attr, ix, &a_attr); ix++)
9967     {
9968       dw2_asm_output_data_uleb128 (a_attr->dw_attr, "(%s)",
9969                                    dwarf_attr_name (a_attr->dw_attr));
9970       output_value_format (a_attr);
9971       if (value_format (a_attr) == DW_FORM_implicit_const)
9972         {
9973           if (AT_class (a_attr) == dw_val_class_file_implicit)
9974             {
9975               int f = maybe_emit_file (a_attr->dw_attr_val.v.val_file);
9976               const char *filename = a_attr->dw_attr_val.v.val_file->filename;
9977               dw2_asm_output_data_sleb128 (f, "(%s)", filename);
9978             }
9979           else
9980             dw2_asm_output_data_sleb128 (a_attr->dw_attr_val.v.val_int, NULL);
9981         }
9982     }
9983
9984   dw2_asm_output_data (1, 0, NULL);
9985   dw2_asm_output_data (1, 0, NULL);
9986 }
9987
9988
9989 /* Output the .debug_abbrev section which defines the DIE abbreviation
9990    table.  */
9991
9992 static void
9993 output_abbrev_section (void)
9994 {
9995   unsigned int abbrev_id;
9996   dw_die_ref abbrev;
9997
9998   FOR_EACH_VEC_SAFE_ELT (abbrev_die_table, abbrev_id, abbrev)
9999     if (abbrev_id != 0)
10000       output_die_abbrevs (abbrev_id, abbrev);
10001
10002   /* Terminate the table.  */
10003   dw2_asm_output_data (1, 0, NULL);
10004 }
10005
10006 /* Return a new location list, given the begin and end range, and the
10007    expression.  */
10008
10009 static inline dw_loc_list_ref
10010 new_loc_list (dw_loc_descr_ref expr, const char *begin, var_loc_view vbegin,
10011               const char *end, var_loc_view vend,
10012               const char *section)
10013 {
10014   dw_loc_list_ref retlist = ggc_cleared_alloc<dw_loc_list_node> ();
10015
10016   retlist->begin = begin;
10017   retlist->begin_entry = NULL;
10018   retlist->end = end;
10019   retlist->expr = expr;
10020   retlist->section = section;
10021   retlist->vbegin = vbegin;
10022   retlist->vend = vend;
10023
10024   return retlist;
10025 }
10026
10027 /* Return true iff there's any nonzero view number in the loc list.
10028
10029    ??? When views are not enabled, we'll often extend a single range
10030    to the entire function, so that we emit a single location
10031    expression rather than a location list.  With views, even with a
10032    single range, we'll output a list if start or end have a nonzero
10033    view.  If we change this, we may want to stop splitting a single
10034    range in dw_loc_list just because of a nonzero view, even if it
10035    straddles across hot/cold partitions.  */
10036
10037 static bool
10038 loc_list_has_views (dw_loc_list_ref list)
10039 {
10040   if (!debug_variable_location_views)
10041     return false;
10042
10043   for (dw_loc_list_ref loc = list;
10044        loc != NULL; loc = loc->dw_loc_next)
10045     if (!ZERO_VIEW_P (loc->vbegin) || !ZERO_VIEW_P (loc->vend))
10046       return true;
10047
10048   return false;
10049 }
10050
10051 /* Generate a new internal symbol for this location list node, if it
10052    hasn't got one yet.  */
10053
10054 static inline void
10055 gen_llsym (dw_loc_list_ref list)
10056 {
10057   gcc_assert (!list->ll_symbol);
10058   list->ll_symbol = gen_internal_sym ("LLST");
10059
10060   if (!loc_list_has_views (list))
10061     return;
10062
10063   if (dwarf2out_locviews_in_attribute ())
10064     {
10065       /* Use the same label_num for the view list.  */
10066       label_num--;
10067       list->vl_symbol = gen_internal_sym ("LVUS");
10068     }
10069   else
10070     list->vl_symbol = list->ll_symbol;
10071 }
10072
10073 /* Generate a symbol for the list, but only if we really want to emit
10074    it as a list.  */
10075
10076 static inline void
10077 maybe_gen_llsym (dw_loc_list_ref list)
10078 {
10079   if (!list || (!list->dw_loc_next && !loc_list_has_views (list)))
10080     return;
10081
10082   gen_llsym (list);
10083 }
10084
10085 /* Determine whether or not to skip loc_list entry CURR.  If SIZEP is
10086    NULL, don't consider size of the location expression.  If we're not
10087    to skip it, and SIZEP is non-null, store the size of CURR->expr's
10088    representation in *SIZEP.  */
10089
10090 static bool
10091 skip_loc_list_entry (dw_loc_list_ref curr, unsigned long *sizep = NULL)
10092 {
10093   /* Don't output an entry that starts and ends at the same address.  */
10094   if (strcmp (curr->begin, curr->end) == 0
10095       && curr->vbegin == curr->vend && !curr->force)
10096     return true;
10097
10098   if (!sizep)
10099     return false;
10100
10101   unsigned long size = size_of_locs (curr->expr);
10102
10103   /* If the expression is too large, drop it on the floor.  We could
10104      perhaps put it into DW_TAG_dwarf_procedure and refer to that
10105      in the expression, but >= 64KB expressions for a single value
10106      in a single range are unlikely very useful.  */
10107   if (dwarf_version < 5 && size > 0xffff)
10108     return true;
10109
10110   *sizep = size;
10111
10112   return false;
10113 }
10114
10115 /* Output a view pair loclist entry for CURR, if it requires one.  */
10116
10117 static void
10118 dwarf2out_maybe_output_loclist_view_pair (dw_loc_list_ref curr)
10119 {
10120   if (!dwarf2out_locviews_in_loclist ())
10121     return;
10122
10123   if (ZERO_VIEW_P (curr->vbegin) && ZERO_VIEW_P (curr->vend))
10124     return;
10125
10126 #ifdef DW_LLE_view_pair
10127   dw2_asm_output_data (1, DW_LLE_view_pair, "DW_LLE_view_pair");
10128
10129   if (dwarf2out_as_locview_support)
10130     {
10131       if (ZERO_VIEW_P (curr->vbegin))
10132         dw2_asm_output_data_uleb128 (0, "Location view begin");
10133       else
10134         {
10135           char label[MAX_ARTIFICIAL_LABEL_BYTES];
10136           ASM_GENERATE_INTERNAL_LABEL (label, "LVU", curr->vbegin);
10137           dw2_asm_output_symname_uleb128 (label, "Location view begin");
10138         }
10139
10140       if (ZERO_VIEW_P (curr->vend))
10141         dw2_asm_output_data_uleb128 (0, "Location view end");
10142       else
10143         {
10144           char label[MAX_ARTIFICIAL_LABEL_BYTES];
10145           ASM_GENERATE_INTERNAL_LABEL (label, "LVU", curr->vend);
10146           dw2_asm_output_symname_uleb128 (label, "Location view end");
10147         }
10148     }
10149   else
10150     {
10151       dw2_asm_output_data_uleb128 (curr->vbegin, "Location view begin");
10152       dw2_asm_output_data_uleb128 (curr->vend, "Location view end");
10153     }
10154 #endif /* DW_LLE_view_pair */
10155
10156   return;
10157 }
10158
10159 /* Output the location list given to us.  */
10160
10161 static void
10162 output_loc_list (dw_loc_list_ref list_head)
10163 {
10164   int vcount = 0, lcount = 0;
10165
10166   if (list_head->emitted)
10167     return;
10168   list_head->emitted = true;
10169
10170   if (list_head->vl_symbol && dwarf2out_locviews_in_attribute ())
10171     {
10172       ASM_OUTPUT_LABEL (asm_out_file, list_head->vl_symbol);
10173
10174       for (dw_loc_list_ref curr = list_head; curr != NULL;
10175            curr = curr->dw_loc_next)
10176         {
10177           unsigned long size;
10178
10179           if (skip_loc_list_entry (curr, &size))
10180             continue;
10181
10182           vcount++;
10183
10184           /* ?? dwarf_split_debug_info?  */
10185           if (dwarf2out_as_locview_support)
10186             {
10187               char label[MAX_ARTIFICIAL_LABEL_BYTES];
10188
10189               if (!ZERO_VIEW_P (curr->vbegin))
10190                 {
10191                   ASM_GENERATE_INTERNAL_LABEL (label, "LVU", curr->vbegin);
10192                   dw2_asm_output_symname_uleb128 (label,
10193                                                   "View list begin (%s)",
10194                                                   list_head->vl_symbol);
10195                 }
10196               else
10197                 dw2_asm_output_data_uleb128 (0,
10198                                              "View list begin (%s)",
10199                                              list_head->vl_symbol);
10200
10201               if (!ZERO_VIEW_P (curr->vend))
10202                 {
10203                   ASM_GENERATE_INTERNAL_LABEL (label, "LVU", curr->vend);
10204                   dw2_asm_output_symname_uleb128 (label,
10205                                                   "View list end (%s)",
10206                                                   list_head->vl_symbol);
10207                 }
10208               else
10209                 dw2_asm_output_data_uleb128 (0,
10210                                              "View list end (%s)",
10211                                              list_head->vl_symbol);
10212             }
10213           else
10214             {
10215               dw2_asm_output_data_uleb128 (curr->vbegin,
10216                                            "View list begin (%s)",
10217                                            list_head->vl_symbol);
10218               dw2_asm_output_data_uleb128 (curr->vend,
10219                                            "View list end (%s)",
10220                                            list_head->vl_symbol);
10221             }
10222         }
10223     }
10224
10225   ASM_OUTPUT_LABEL (asm_out_file, list_head->ll_symbol);
10226
10227   const char *last_section = NULL;
10228   const char *base_label = NULL;
10229
10230   /* Walk the location list, and output each range + expression.  */
10231   for (dw_loc_list_ref curr = list_head; curr != NULL;
10232        curr = curr->dw_loc_next)
10233     {
10234       unsigned long size;
10235
10236       /* Skip this entry?  If we skip it here, we must skip it in the
10237          view list above as well. */
10238       if (skip_loc_list_entry (curr, &size))
10239         continue;
10240
10241       lcount++;
10242
10243       if (dwarf_version >= 5)
10244         {
10245           if (dwarf_split_debug_info)
10246             {
10247               dwarf2out_maybe_output_loclist_view_pair (curr);
10248               /* For -gsplit-dwarf, emit DW_LLE_starx_length, which has
10249                  uleb128 index into .debug_addr and uleb128 length.  */
10250               dw2_asm_output_data (1, DW_LLE_startx_length,
10251                                    "DW_LLE_startx_length (%s)",
10252                                    list_head->ll_symbol);
10253               dw2_asm_output_data_uleb128 (curr->begin_entry->index,
10254                                            "Location list range start index "
10255                                            "(%s)", curr->begin);
10256               /* FIXME: This will ICE ifndef HAVE_AS_LEB128.
10257                  For that case we probably need to emit DW_LLE_startx_endx,
10258                  but we'd need 2 .debug_addr entries rather than just one.  */
10259               dw2_asm_output_delta_uleb128 (curr->end, curr->begin,
10260                                             "Location list length (%s)",
10261                                             list_head->ll_symbol);
10262             }
10263           else if (!have_multiple_function_sections && HAVE_AS_LEB128)
10264             {
10265               dwarf2out_maybe_output_loclist_view_pair (curr);
10266               /* If all code is in .text section, the base address is
10267                  already provided by the CU attributes.  Use
10268                  DW_LLE_offset_pair where both addresses are uleb128 encoded
10269                  offsets against that base.  */
10270               dw2_asm_output_data (1, DW_LLE_offset_pair,
10271                                    "DW_LLE_offset_pair (%s)",
10272                                    list_head->ll_symbol);
10273               dw2_asm_output_delta_uleb128 (curr->begin, curr->section,
10274                                             "Location list begin address (%s)",
10275                                             list_head->ll_symbol);
10276               dw2_asm_output_delta_uleb128 (curr->end, curr->section,
10277                                             "Location list end address (%s)",
10278                                             list_head->ll_symbol);
10279             }
10280           else if (HAVE_AS_LEB128)
10281             {
10282               /* Otherwise, find out how many consecutive entries could share
10283                  the same base entry.  If just one, emit DW_LLE_start_length,
10284                  otherwise emit DW_LLE_base_address for the base address
10285                  followed by a series of DW_LLE_offset_pair.  */
10286               if (last_section == NULL || curr->section != last_section)
10287                 {
10288                   dw_loc_list_ref curr2;
10289                   for (curr2 = curr->dw_loc_next; curr2 != NULL;
10290                        curr2 = curr2->dw_loc_next)
10291                     {
10292                       if (strcmp (curr2->begin, curr2->end) == 0
10293                           && !curr2->force)
10294                         continue;
10295                       break;
10296                     }
10297                   if (curr2 == NULL || curr->section != curr2->section)
10298                     last_section = NULL;
10299                   else
10300                     {
10301                       last_section = curr->section;
10302                       base_label = curr->begin;
10303                       dw2_asm_output_data (1, DW_LLE_base_address,
10304                                            "DW_LLE_base_address (%s)",
10305                                            list_head->ll_symbol);
10306                       dw2_asm_output_addr (DWARF2_ADDR_SIZE, base_label,
10307                                            "Base address (%s)",
10308                                            list_head->ll_symbol);
10309                     }
10310                 }
10311               /* Only one entry with the same base address.  Use
10312                  DW_LLE_start_length with absolute address and uleb128
10313                  length.  */
10314               if (last_section == NULL)
10315                 {
10316                   dwarf2out_maybe_output_loclist_view_pair (curr);
10317                   dw2_asm_output_data (1, DW_LLE_start_length,
10318                                        "DW_LLE_start_length (%s)",
10319                                        list_head->ll_symbol);
10320                   dw2_asm_output_addr (DWARF2_ADDR_SIZE, curr->begin,
10321                                        "Location list begin address (%s)",
10322                                        list_head->ll_symbol);
10323                   dw2_asm_output_delta_uleb128 (curr->end, curr->begin,
10324                                                 "Location list length "
10325                                                 "(%s)", list_head->ll_symbol);
10326                 }
10327               /* Otherwise emit DW_LLE_offset_pair, relative to above emitted
10328                  DW_LLE_base_address.  */
10329               else
10330                 {
10331                   dwarf2out_maybe_output_loclist_view_pair (curr);
10332                   dw2_asm_output_data (1, DW_LLE_offset_pair,
10333                                        "DW_LLE_offset_pair (%s)",
10334                                        list_head->ll_symbol);
10335                   dw2_asm_output_delta_uleb128 (curr->begin, base_label,
10336                                                 "Location list begin address "
10337                                                 "(%s)", list_head->ll_symbol);
10338                   dw2_asm_output_delta_uleb128 (curr->end, base_label,
10339                                                 "Location list end address "
10340                                                 "(%s)", list_head->ll_symbol);
10341                 }
10342             }
10343           /* The assembler does not support .uleb128 directive.  Emit
10344              DW_LLE_start_end with a pair of absolute addresses.  */
10345           else
10346             {
10347               dwarf2out_maybe_output_loclist_view_pair (curr);
10348               dw2_asm_output_data (1, DW_LLE_start_end,
10349                                    "DW_LLE_start_end (%s)",
10350                                    list_head->ll_symbol);
10351               dw2_asm_output_addr (DWARF2_ADDR_SIZE, curr->begin,
10352                                    "Location list begin address (%s)",
10353                                    list_head->ll_symbol);
10354               dw2_asm_output_addr (DWARF2_ADDR_SIZE, curr->end,
10355                                    "Location list end address (%s)",
10356                                    list_head->ll_symbol);
10357             }
10358         }
10359       else if (dwarf_split_debug_info)
10360         {
10361           /* For -gsplit-dwarf -gdwarf-{2,3,4} emit index into .debug_addr
10362              and 4 byte length.  */
10363           dw2_asm_output_data (1, DW_LLE_GNU_start_length_entry,
10364                                "Location list start/length entry (%s)",
10365                                list_head->ll_symbol);
10366           dw2_asm_output_data_uleb128 (curr->begin_entry->index,
10367                                        "Location list range start index (%s)",
10368                                        curr->begin);
10369           /* The length field is 4 bytes.  If we ever need to support
10370              an 8-byte length, we can add a new DW_LLE code or fall back
10371              to DW_LLE_GNU_start_end_entry.  */
10372           dw2_asm_output_delta (4, curr->end, curr->begin,
10373                                 "Location list range length (%s)",
10374                                 list_head->ll_symbol);
10375         }
10376       else if (!have_multiple_function_sections)
10377         {
10378           /* Pair of relative addresses against start of text section.  */
10379           dw2_asm_output_delta (DWARF2_ADDR_SIZE, curr->begin, curr->section,
10380                                 "Location list begin address (%s)",
10381                                 list_head->ll_symbol);
10382           dw2_asm_output_delta (DWARF2_ADDR_SIZE, curr->end, curr->section,
10383                                 "Location list end address (%s)",
10384                                 list_head->ll_symbol);
10385         }
10386       else
10387         {
10388           /* Pair of absolute addresses.  */
10389           dw2_asm_output_addr (DWARF2_ADDR_SIZE, curr->begin,
10390                                "Location list begin address (%s)",
10391                                list_head->ll_symbol);
10392           dw2_asm_output_addr (DWARF2_ADDR_SIZE, curr->end,
10393                                "Location list end address (%s)",
10394                                list_head->ll_symbol);
10395         }
10396
10397       /* Output the block length for this list of location operations.  */
10398       if (dwarf_version >= 5)
10399         dw2_asm_output_data_uleb128 (size, "Location expression size");
10400       else
10401         {
10402           gcc_assert (size <= 0xffff);
10403           dw2_asm_output_data (2, size, "Location expression size");
10404         }
10405
10406       output_loc_sequence (curr->expr, -1);
10407     }
10408
10409   /* And finally list termination.  */
10410   if (dwarf_version >= 5)
10411     dw2_asm_output_data (1, DW_LLE_end_of_list,
10412                          "DW_LLE_end_of_list (%s)", list_head->ll_symbol);
10413   else if (dwarf_split_debug_info)
10414     dw2_asm_output_data (1, DW_LLE_GNU_end_of_list_entry,
10415                          "Location list terminator (%s)",
10416                          list_head->ll_symbol);
10417   else
10418     {
10419       dw2_asm_output_data (DWARF2_ADDR_SIZE, 0,
10420                            "Location list terminator begin (%s)",
10421                            list_head->ll_symbol);
10422       dw2_asm_output_data (DWARF2_ADDR_SIZE, 0,
10423                            "Location list terminator end (%s)",
10424                            list_head->ll_symbol);
10425     }
10426
10427   gcc_assert (!list_head->vl_symbol
10428               || vcount == lcount * (dwarf2out_locviews_in_attribute () ? 1 : 0));
10429 }
10430
10431 /* Output a range_list offset into the .debug_ranges or .debug_rnglists
10432    section.  Emit a relocated reference if val_entry is NULL, otherwise,
10433    emit an indirect reference.  */
10434
10435 static void
10436 output_range_list_offset (dw_attr_node *a)
10437 {
10438   const char *name = dwarf_attr_name (a->dw_attr);
10439
10440   if (a->dw_attr_val.val_entry == RELOCATED_OFFSET)
10441     {
10442       if (dwarf_version >= 5)
10443         {
10444           dw_ranges *r = &(*ranges_table)[a->dw_attr_val.v.val_offset];
10445           dw2_asm_output_offset (DWARF_OFFSET_SIZE, r->label,
10446                                  debug_ranges_section, "%s", name);
10447         }
10448       else
10449         {
10450           char *p = strchr (ranges_section_label, '\0');
10451           sprintf (p, "+" HOST_WIDE_INT_PRINT_HEX,
10452                    a->dw_attr_val.v.val_offset * 2 * DWARF2_ADDR_SIZE);
10453           dw2_asm_output_offset (DWARF_OFFSET_SIZE, ranges_section_label,
10454                                  debug_ranges_section, "%s", name);
10455           *p = '\0';
10456         }
10457     }
10458   else if (dwarf_version >= 5)
10459     {
10460       dw_ranges *r = &(*ranges_table)[a->dw_attr_val.v.val_offset];
10461       gcc_assert (rnglist_idx);
10462       dw2_asm_output_data_uleb128 (r->idx, "%s", name);
10463     }
10464   else
10465     dw2_asm_output_data (DWARF_OFFSET_SIZE,
10466                          a->dw_attr_val.v.val_offset * 2 * DWARF2_ADDR_SIZE,
10467                          "%s (offset from %s)", name, ranges_section_label);
10468 }
10469
10470 /* Output the offset into the debug_loc section.  */
10471
10472 static void
10473 output_loc_list_offset (dw_attr_node *a)
10474 {
10475   char *sym = AT_loc_list (a)->ll_symbol;
10476
10477   gcc_assert (sym);
10478   if (!dwarf_split_debug_info)
10479     dw2_asm_output_offset (DWARF_OFFSET_SIZE, sym, debug_loc_section,
10480                            "%s", dwarf_attr_name (a->dw_attr));
10481   else if (dwarf_version >= 5)
10482     {
10483       gcc_assert (AT_loc_list (a)->num_assigned);
10484       dw2_asm_output_data_uleb128 (AT_loc_list (a)->hash, "%s (%s)",
10485                                    dwarf_attr_name (a->dw_attr),
10486                                    sym);
10487     }
10488   else
10489     dw2_asm_output_delta (DWARF_OFFSET_SIZE, sym, loc_section_label,
10490                           "%s", dwarf_attr_name (a->dw_attr));
10491 }
10492
10493 /* Output the offset into the debug_loc section.  */
10494
10495 static void
10496 output_view_list_offset (dw_attr_node *a)
10497 {
10498   char *sym = (*AT_loc_list_ptr (a))->vl_symbol;
10499
10500   gcc_assert (sym);
10501   if (dwarf_split_debug_info)
10502     dw2_asm_output_delta (DWARF_OFFSET_SIZE, sym, loc_section_label,
10503                           "%s", dwarf_attr_name (a->dw_attr));
10504   else
10505     dw2_asm_output_offset (DWARF_OFFSET_SIZE, sym, debug_loc_section,
10506                            "%s", dwarf_attr_name (a->dw_attr));
10507 }
10508
10509 /* Output an attribute's index or value appropriately.  */
10510
10511 static void
10512 output_attr_index_or_value (dw_attr_node *a)
10513 {
10514   const char *name = dwarf_attr_name (a->dw_attr);
10515
10516   if (dwarf_split_debug_info && AT_index (a) != NOT_INDEXED)
10517     {
10518       dw2_asm_output_data_uleb128 (AT_index (a), "%s", name);
10519       return;
10520     }
10521   switch (AT_class (a))
10522     {
10523     case dw_val_class_addr:
10524       dw2_asm_output_addr_rtx (DWARF2_ADDR_SIZE, AT_addr (a), "%s", name);
10525       break;
10526     case dw_val_class_high_pc:
10527     case dw_val_class_lbl_id:
10528       dw2_asm_output_addr (DWARF2_ADDR_SIZE, AT_lbl (a), "%s", name);
10529       break;
10530     default:
10531       gcc_unreachable ();
10532     }
10533 }
10534
10535 /* Output a type signature.  */
10536
10537 static inline void
10538 output_signature (const char *sig, const char *name)
10539 {
10540   int i;
10541
10542   for (i = 0; i < DWARF_TYPE_SIGNATURE_SIZE; i++)
10543     dw2_asm_output_data (1, sig[i], i == 0 ? "%s" : NULL, name);
10544 }
10545
10546 /* Output a discriminant value.  */
10547
10548 static inline void
10549 output_discr_value (dw_discr_value *discr_value, const char *name)
10550 {
10551   if (discr_value->pos)
10552     dw2_asm_output_data_uleb128 (discr_value->v.uval, "%s", name);
10553   else
10554     dw2_asm_output_data_sleb128 (discr_value->v.sval, "%s", name);
10555 }
10556
10557 /* Output the DIE and its attributes.  Called recursively to generate
10558    the definitions of each child DIE.  */
10559
10560 static void
10561 output_die (dw_die_ref die)
10562 {
10563   dw_attr_node *a;
10564   dw_die_ref c;
10565   unsigned long size;
10566   unsigned ix;
10567
10568   dw2_asm_output_data_uleb128 (die->die_abbrev, "(DIE (%#lx) %s)",
10569                                (unsigned long)die->die_offset,
10570                                dwarf_tag_name (die->die_tag));
10571
10572   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
10573     {
10574       const char *name = dwarf_attr_name (a->dw_attr);
10575
10576       switch (AT_class (a))
10577         {
10578         case dw_val_class_addr:
10579           output_attr_index_or_value (a);
10580           break;
10581
10582         case dw_val_class_offset:
10583           dw2_asm_output_data (DWARF_OFFSET_SIZE, a->dw_attr_val.v.val_offset,
10584                                "%s", name);
10585           break;
10586
10587         case dw_val_class_range_list:
10588           output_range_list_offset (a);
10589           break;
10590
10591         case dw_val_class_loc:
10592           size = size_of_locs (AT_loc (a));
10593
10594           /* Output the block length for this list of location operations.  */
10595           if (dwarf_version >= 4)
10596             dw2_asm_output_data_uleb128 (size, "%s", name);
10597           else
10598             dw2_asm_output_data (constant_size (size), size, "%s", name);
10599
10600           output_loc_sequence (AT_loc (a), -1);
10601           break;
10602
10603         case dw_val_class_const:
10604           /* ??? It would be slightly more efficient to use a scheme like is
10605              used for unsigned constants below, but gdb 4.x does not sign
10606              extend.  Gdb 5.x does sign extend.  */
10607           dw2_asm_output_data_sleb128 (AT_int (a), "%s", name);
10608           break;
10609
10610         case dw_val_class_unsigned_const:
10611           {
10612             int csize = constant_size (AT_unsigned (a));
10613             if (dwarf_version == 3
10614                 && a->dw_attr == DW_AT_data_member_location
10615                 && csize >= 4)
10616               dw2_asm_output_data_uleb128 (AT_unsigned (a), "%s", name);
10617             else
10618               dw2_asm_output_data (csize, AT_unsigned (a), "%s", name);
10619           }
10620           break;
10621
10622         case dw_val_class_symview:
10623           {
10624             int vsize;
10625             if (symview_upper_bound <= 0xff)
10626               vsize = 1;
10627             else if (symview_upper_bound <= 0xffff)
10628               vsize = 2;
10629             else if (symview_upper_bound <= 0xffffffff)
10630               vsize = 4;
10631             else
10632               vsize = 8;
10633             dw2_asm_output_addr (vsize, a->dw_attr_val.v.val_symbolic_view,
10634                                  "%s", name);
10635           }
10636           break;
10637
10638         case dw_val_class_const_implicit:
10639           if (flag_debug_asm)
10640             fprintf (asm_out_file, "\t\t\t%s %s ("
10641                                    HOST_WIDE_INT_PRINT_DEC ")\n",
10642                      ASM_COMMENT_START, name, AT_int (a));
10643           break;
10644
10645         case dw_val_class_unsigned_const_implicit:
10646           if (flag_debug_asm)
10647             fprintf (asm_out_file, "\t\t\t%s %s ("
10648                                    HOST_WIDE_INT_PRINT_HEX ")\n",
10649                      ASM_COMMENT_START, name, AT_unsigned (a));
10650           break;
10651
10652         case dw_val_class_const_double:
10653           {
10654             unsigned HOST_WIDE_INT first, second;
10655
10656             if (HOST_BITS_PER_WIDE_INT >= DWARF_LARGEST_DATA_FORM_BITS)
10657               dw2_asm_output_data (1,
10658                                    HOST_BITS_PER_DOUBLE_INT
10659                                    / HOST_BITS_PER_CHAR,
10660                                    NULL);
10661
10662             if (WORDS_BIG_ENDIAN)
10663               {
10664                 first = a->dw_attr_val.v.val_double.high;
10665                 second = a->dw_attr_val.v.val_double.low;
10666               }
10667             else
10668               {
10669                 first = a->dw_attr_val.v.val_double.low;
10670                 second = a->dw_attr_val.v.val_double.high;
10671               }
10672
10673             dw2_asm_output_data (HOST_BITS_PER_WIDE_INT / HOST_BITS_PER_CHAR,
10674                                  first, "%s", name);
10675             dw2_asm_output_data (HOST_BITS_PER_WIDE_INT / HOST_BITS_PER_CHAR,
10676                                  second, NULL);
10677           }
10678           break;
10679
10680         case dw_val_class_wide_int:
10681           {
10682             int i;
10683             int len = get_full_len (*a->dw_attr_val.v.val_wide);
10684             int l = HOST_BITS_PER_WIDE_INT / HOST_BITS_PER_CHAR;
10685             if (len * HOST_BITS_PER_WIDE_INT > DWARF_LARGEST_DATA_FORM_BITS)
10686               dw2_asm_output_data (1, get_full_len (*a->dw_attr_val.v.val_wide)
10687                                       * l, NULL);
10688
10689             if (WORDS_BIG_ENDIAN)
10690               for (i = len - 1; i >= 0; --i)
10691                 {
10692                   dw2_asm_output_data (l, a->dw_attr_val.v.val_wide->elt (i),
10693                                        "%s", name);
10694                   name = "";
10695                 }
10696             else
10697               for (i = 0; i < len; ++i)
10698                 {
10699                   dw2_asm_output_data (l, a->dw_attr_val.v.val_wide->elt (i),
10700                                        "%s", name);
10701                   name = "";
10702                 }
10703           }
10704           break;
10705
10706         case dw_val_class_vec:
10707           {
10708             unsigned int elt_size = a->dw_attr_val.v.val_vec.elt_size;
10709             unsigned int len = a->dw_attr_val.v.val_vec.length;
10710             unsigned int i;
10711             unsigned char *p;
10712
10713             dw2_asm_output_data (constant_size (len * elt_size),
10714                                  len * elt_size, "%s", name);
10715             if (elt_size > sizeof (HOST_WIDE_INT))
10716               {
10717                 elt_size /= 2;
10718                 len *= 2;
10719               }
10720             for (i = 0, p = (unsigned char *) a->dw_attr_val.v.val_vec.array;
10721                  i < len;
10722                  i++, p += elt_size)
10723               dw2_asm_output_data (elt_size, extract_int (p, elt_size),
10724                                    "fp or vector constant word %u", i);
10725             break;
10726           }
10727
10728         case dw_val_class_flag:
10729           if (dwarf_version >= 4)
10730             {
10731               /* Currently all add_AT_flag calls pass in 1 as last argument,
10732                  so DW_FORM_flag_present can be used.  If that ever changes,
10733                  we'll need to use DW_FORM_flag and have some optimization
10734                  in build_abbrev_table that will change those to
10735                  DW_FORM_flag_present if it is set to 1 in all DIEs using
10736                  the same abbrev entry.  */
10737               gcc_assert (AT_flag (a) == 1);
10738               if (flag_debug_asm)
10739                 fprintf (asm_out_file, "\t\t\t%s %s\n",
10740                          ASM_COMMENT_START, name);
10741               break;
10742             }
10743           dw2_asm_output_data (1, AT_flag (a), "%s", name);
10744           break;
10745
10746         case dw_val_class_loc_list:
10747           output_loc_list_offset (a);
10748           break;
10749
10750         case dw_val_class_view_list:
10751           output_view_list_offset (a);
10752           break;
10753
10754         case dw_val_class_die_ref:
10755           if (AT_ref_external (a))
10756             {
10757               if (AT_ref (a)->comdat_type_p)
10758                 {
10759                   comdat_type_node *type_node
10760                     = AT_ref (a)->die_id.die_type_node;
10761
10762                   gcc_assert (type_node);
10763                   output_signature (type_node->signature, name);
10764                 }
10765               else
10766                 {
10767                   const char *sym = AT_ref (a)->die_id.die_symbol;
10768                   int size;
10769
10770                   gcc_assert (sym);
10771                   /* In DWARF2, DW_FORM_ref_addr is sized by target address
10772                      length, whereas in DWARF3 it's always sized as an
10773                      offset.  */
10774                   if (dwarf_version == 2)
10775                     size = DWARF2_ADDR_SIZE;
10776                   else
10777                     size = DWARF_OFFSET_SIZE;
10778                   /* ???  We cannot unconditionally output die_offset if
10779                      non-zero - others might create references to those
10780                      DIEs via symbols.
10781                      And we do not clear its DIE offset after outputting it
10782                      (and the label refers to the actual DIEs, not the
10783                      DWARF CU unit header which is when using label + offset
10784                      would be the correct thing to do).
10785                      ???  This is the reason for the with_offset flag.  */
10786                   if (AT_ref (a)->with_offset)
10787                     dw2_asm_output_offset (size, sym, AT_ref (a)->die_offset,
10788                                            debug_info_section, "%s", name);
10789                   else
10790                     dw2_asm_output_offset (size, sym, debug_info_section, "%s",
10791                                            name);
10792                 }
10793             }
10794           else
10795             {
10796               gcc_assert (AT_ref (a)->die_offset);
10797               dw2_asm_output_data (DWARF_OFFSET_SIZE, AT_ref (a)->die_offset,
10798                                    "%s", name);
10799             }
10800           break;
10801
10802         case dw_val_class_fde_ref:
10803           {
10804             char l1[MAX_ARTIFICIAL_LABEL_BYTES];
10805
10806             ASM_GENERATE_INTERNAL_LABEL (l1, FDE_LABEL,
10807                                          a->dw_attr_val.v.val_fde_index * 2);
10808             dw2_asm_output_offset (DWARF_OFFSET_SIZE, l1, debug_frame_section,
10809                                    "%s", name);
10810           }
10811           break;
10812
10813         case dw_val_class_vms_delta:
10814 #ifdef ASM_OUTPUT_DWARF_VMS_DELTA
10815           dw2_asm_output_vms_delta (DWARF_OFFSET_SIZE,
10816                                     AT_vms_delta2 (a), AT_vms_delta1 (a),
10817                                     "%s", name);
10818 #else
10819           dw2_asm_output_delta (DWARF_OFFSET_SIZE,
10820                                 AT_vms_delta2 (a), AT_vms_delta1 (a),
10821                                 "%s", name);
10822 #endif
10823           break;
10824
10825         case dw_val_class_lbl_id:
10826           output_attr_index_or_value (a);
10827           break;
10828
10829         case dw_val_class_lineptr:
10830           dw2_asm_output_offset (DWARF_OFFSET_SIZE, AT_lbl (a),
10831                                  debug_line_section, "%s", name);
10832           break;
10833
10834         case dw_val_class_macptr:
10835           dw2_asm_output_offset (DWARF_OFFSET_SIZE, AT_lbl (a),
10836                                  debug_macinfo_section, "%s", name);
10837           break;
10838
10839         case dw_val_class_loclistsptr:
10840           dw2_asm_output_offset (DWARF_OFFSET_SIZE, AT_lbl (a),
10841                                  debug_loc_section, "%s", name);
10842           break;
10843
10844         case dw_val_class_str:
10845           if (a->dw_attr_val.v.val_str->form == DW_FORM_strp)
10846             dw2_asm_output_offset (DWARF_OFFSET_SIZE,
10847                                    a->dw_attr_val.v.val_str->label,
10848                                    debug_str_section,
10849                                    "%s: \"%s\"", name, AT_string (a));
10850           else if (a->dw_attr_val.v.val_str->form == DW_FORM_line_strp)
10851             dw2_asm_output_offset (DWARF_OFFSET_SIZE,
10852                                    a->dw_attr_val.v.val_str->label,
10853                                    debug_line_str_section,
10854                                    "%s: \"%s\"", name, AT_string (a));
10855           else if (a->dw_attr_val.v.val_str->form == DW_FORM_GNU_str_index)
10856             dw2_asm_output_data_uleb128 (AT_index (a),
10857                                          "%s: \"%s\"", name, AT_string (a));
10858           else
10859             dw2_asm_output_nstring (AT_string (a), -1, "%s", name);
10860           break;
10861
10862         case dw_val_class_file:
10863           {
10864             int f = maybe_emit_file (a->dw_attr_val.v.val_file);
10865
10866             dw2_asm_output_data (constant_size (f), f, "%s (%s)", name,
10867                                  a->dw_attr_val.v.val_file->filename);
10868             break;
10869           }
10870
10871         case dw_val_class_file_implicit:
10872           if (flag_debug_asm)
10873             fprintf (asm_out_file, "\t\t\t%s %s (%d, %s)\n",
10874                      ASM_COMMENT_START, name,
10875                      maybe_emit_file (a->dw_attr_val.v.val_file),
10876                      a->dw_attr_val.v.val_file->filename);
10877           break;
10878
10879         case dw_val_class_data8:
10880           {
10881             int i;
10882
10883             for (i = 0; i < 8; i++)
10884               dw2_asm_output_data (1, a->dw_attr_val.v.val_data8[i],
10885                                    i == 0 ? "%s" : NULL, name);
10886             break;
10887           }
10888
10889         case dw_val_class_high_pc:
10890           dw2_asm_output_delta (DWARF2_ADDR_SIZE, AT_lbl (a),
10891                                 get_AT_low_pc (die), "DW_AT_high_pc");
10892           break;
10893
10894         case dw_val_class_discr_value:
10895           output_discr_value (&a->dw_attr_val.v.val_discr_value, name);
10896           break;
10897
10898         case dw_val_class_discr_list:
10899           {
10900             dw_discr_list_ref list = AT_discr_list (a);
10901             const int size = size_of_discr_list (list);
10902
10903             /* This is a block, so output its length first.  */
10904             dw2_asm_output_data (constant_size (size), size,
10905                                  "%s: block size", name);
10906
10907             for (; list != NULL; list = list->dw_discr_next)
10908               {
10909                 /* One byte for the discriminant value descriptor, and then as
10910                    many LEB128 numbers as required.  */
10911                 if (list->dw_discr_range)
10912                   dw2_asm_output_data (1, DW_DSC_range,
10913                                        "%s: DW_DSC_range", name);
10914                 else
10915                   dw2_asm_output_data (1, DW_DSC_label,
10916                                        "%s: DW_DSC_label", name);
10917
10918                 output_discr_value (&list->dw_discr_lower_bound, name);
10919                 if (list->dw_discr_range)
10920                   output_discr_value (&list->dw_discr_upper_bound, name);
10921               }
10922             break;
10923           }
10924
10925         default:
10926           gcc_unreachable ();
10927         }
10928     }
10929
10930   FOR_EACH_CHILD (die, c, output_die (c));
10931
10932   /* Add null byte to terminate sibling list.  */
10933   if (die->die_child != NULL)
10934     dw2_asm_output_data (1, 0, "end of children of DIE %#lx",
10935                          (unsigned long) die->die_offset);
10936 }
10937
10938 /* Output the dwarf version number.  */
10939
10940 static void
10941 output_dwarf_version ()
10942 {
10943   /* ??? For now, if -gdwarf-6 is specified, we output version 5 with
10944      views in loclist.  That will change eventually.  */
10945   if (dwarf_version == 6)
10946     {
10947       static bool once;
10948       if (!once)
10949         {
10950           warning (0,
10951                    "-gdwarf-6 is output as version 5 with incompatibilities");
10952           once = true;
10953         }
10954       dw2_asm_output_data (2, 5, "DWARF version number");
10955     }
10956   else
10957     dw2_asm_output_data (2, dwarf_version, "DWARF version number");
10958 }
10959
10960 /* Output the compilation unit that appears at the beginning of the
10961    .debug_info section, and precedes the DIE descriptions.  */
10962
10963 static void
10964 output_compilation_unit_header (enum dwarf_unit_type ut)
10965 {
10966   if (!XCOFF_DEBUGGING_INFO)
10967     {
10968       if (DWARF_INITIAL_LENGTH_SIZE - DWARF_OFFSET_SIZE == 4)
10969         dw2_asm_output_data (4, 0xffffffff,
10970           "Initial length escape value indicating 64-bit DWARF extension");
10971       dw2_asm_output_data (DWARF_OFFSET_SIZE,
10972                            next_die_offset - DWARF_INITIAL_LENGTH_SIZE,
10973                            "Length of Compilation Unit Info");
10974     }
10975
10976   output_dwarf_version ();
10977   if (dwarf_version >= 5)
10978     {
10979       const char *name;
10980       switch (ut)
10981         {
10982         case DW_UT_compile: name = "DW_UT_compile"; break;
10983         case DW_UT_type: name = "DW_UT_type"; break;
10984         case DW_UT_split_compile: name = "DW_UT_split_compile"; break;
10985         case DW_UT_split_type: name = "DW_UT_split_type"; break;
10986         default: gcc_unreachable ();
10987         }
10988       dw2_asm_output_data (1, ut, "%s", name);
10989       dw2_asm_output_data (1, DWARF2_ADDR_SIZE, "Pointer Size (in bytes)");
10990     }
10991   dw2_asm_output_offset (DWARF_OFFSET_SIZE, abbrev_section_label,
10992                          debug_abbrev_section,
10993                          "Offset Into Abbrev. Section");
10994   if (dwarf_version < 5)
10995     dw2_asm_output_data (1, DWARF2_ADDR_SIZE, "Pointer Size (in bytes)");
10996 }
10997
10998 /* Output the compilation unit DIE and its children.  */
10999
11000 static void
11001 output_comp_unit (dw_die_ref die, int output_if_empty,
11002                   const unsigned char *dwo_id)
11003 {
11004   const char *secname, *oldsym;
11005   char *tmp;
11006
11007   /* Unless we are outputting main CU, we may throw away empty ones.  */
11008   if (!output_if_empty && die->die_child == NULL)
11009     return;
11010
11011   /* Even if there are no children of this DIE, we must output the information
11012      about the compilation unit.  Otherwise, on an empty translation unit, we
11013      will generate a present, but empty, .debug_info section.  IRIX 6.5 `nm'
11014      will then complain when examining the file.  First mark all the DIEs in
11015      this CU so we know which get local refs.  */
11016   mark_dies (die);
11017
11018   external_ref_hash_type *extern_map = optimize_external_refs (die);
11019
11020   /* For now, optimize only the main CU, in order to optimize the rest
11021      we'd need to see all of them earlier.  Leave the rest for post-linking
11022      tools like DWZ.  */
11023   if (die == comp_unit_die ())
11024     abbrev_opt_start = vec_safe_length (abbrev_die_table);
11025
11026   build_abbrev_table (die, extern_map);
11027
11028   optimize_abbrev_table ();
11029
11030   delete extern_map;
11031
11032   /* Initialize the beginning DIE offset - and calculate sizes/offsets.  */
11033   next_die_offset = (dwo_id
11034                      ? DWARF_COMPILE_UNIT_SKELETON_HEADER_SIZE
11035                      : DWARF_COMPILE_UNIT_HEADER_SIZE);
11036   calc_die_sizes (die);
11037
11038   oldsym = die->die_id.die_symbol;
11039   if (oldsym && die->comdat_type_p)
11040     {
11041       tmp = XALLOCAVEC (char, strlen (oldsym) + 24);
11042
11043       sprintf (tmp, ".gnu.linkonce.wi.%s", oldsym);
11044       secname = tmp;
11045       die->die_id.die_symbol = NULL;
11046       switch_to_section (get_section (secname, SECTION_DEBUG, NULL));
11047     }
11048   else
11049     {
11050       switch_to_section (debug_info_section);
11051       ASM_OUTPUT_LABEL (asm_out_file, debug_info_section_label);
11052       info_section_emitted = true;
11053     }
11054
11055   /* For LTO cross unit DIE refs we want a symbol on the start of the
11056      debuginfo section, not on the CU DIE.  */
11057   if ((flag_generate_lto || flag_generate_offload) && oldsym)
11058     {
11059       /* ???  No way to get visibility assembled without a decl.  */
11060       tree decl = build_decl (UNKNOWN_LOCATION, VAR_DECL,
11061                               get_identifier (oldsym), char_type_node);
11062       TREE_PUBLIC (decl) = true;
11063       TREE_STATIC (decl) = true;
11064       DECL_ARTIFICIAL (decl) = true;
11065       DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
11066       DECL_VISIBILITY_SPECIFIED (decl) = true;
11067       targetm.asm_out.assemble_visibility (decl, VISIBILITY_HIDDEN);
11068 #ifdef ASM_WEAKEN_LABEL
11069       /* We prefer a .weak because that handles duplicates from duplicate
11070          archive members in a graceful way.  */
11071       ASM_WEAKEN_LABEL (asm_out_file, oldsym);
11072 #else
11073       targetm.asm_out.globalize_label (asm_out_file, oldsym);
11074 #endif
11075       ASM_OUTPUT_LABEL (asm_out_file, oldsym);
11076     }
11077
11078   /* Output debugging information.  */
11079   output_compilation_unit_header (dwo_id
11080                                   ? DW_UT_split_compile : DW_UT_compile);
11081   if (dwarf_version >= 5)
11082     {
11083       if (dwo_id != NULL)
11084         for (int i = 0; i < 8; i++)
11085           dw2_asm_output_data (1, dwo_id[i], i == 0 ? "DWO id" : NULL);
11086     }
11087   output_die (die);
11088
11089   /* Leave the marks on the main CU, so we can check them in
11090      output_pubnames.  */
11091   if (oldsym)
11092     {
11093       unmark_dies (die);
11094       die->die_id.die_symbol = oldsym;
11095     }
11096 }
11097
11098 /* Whether to generate the DWARF accelerator tables in .debug_pubnames
11099    and .debug_pubtypes.  This is configured per-target, but can be
11100    overridden by the -gpubnames or -gno-pubnames options.  */
11101
11102 static inline bool
11103 want_pubnames (void)
11104 {
11105   if (debug_info_level <= DINFO_LEVEL_TERSE
11106       /* Names and types go to the early debug part only.  */
11107       || in_lto_p)
11108     return false;
11109   if (debug_generate_pub_sections != -1)
11110     return debug_generate_pub_sections;
11111   return targetm.want_debug_pub_sections;
11112 }
11113
11114 /* Add the DW_AT_GNU_pubnames and DW_AT_GNU_pubtypes attributes.  */
11115
11116 static void
11117 add_AT_pubnames (dw_die_ref die)
11118 {
11119   if (want_pubnames ())
11120     add_AT_flag (die, DW_AT_GNU_pubnames, 1);
11121 }
11122
11123 /* Add a string attribute value to a skeleton DIE.  */
11124
11125 static inline void
11126 add_skeleton_AT_string (dw_die_ref die, enum dwarf_attribute attr_kind,
11127                         const char *str)
11128 {
11129   dw_attr_node attr;
11130   struct indirect_string_node *node;
11131
11132   if (! skeleton_debug_str_hash)
11133     skeleton_debug_str_hash
11134       = hash_table<indirect_string_hasher>::create_ggc (10);
11135
11136   node = find_AT_string_in_table (str, skeleton_debug_str_hash);
11137   find_string_form (node);
11138   if (node->form == DW_FORM_GNU_str_index)
11139     node->form = DW_FORM_strp;
11140
11141   attr.dw_attr = attr_kind;
11142   attr.dw_attr_val.val_class = dw_val_class_str;
11143   attr.dw_attr_val.val_entry = NULL;
11144   attr.dw_attr_val.v.val_str = node;
11145   add_dwarf_attr (die, &attr);
11146 }
11147
11148 /* Helper function to generate top-level dies for skeleton debug_info and
11149    debug_types.  */
11150
11151 static void
11152 add_top_level_skeleton_die_attrs (dw_die_ref die)
11153 {
11154   const char *dwo_file_name = concat (aux_base_name, ".dwo", NULL);
11155   const char *comp_dir = comp_dir_string ();
11156
11157   add_skeleton_AT_string (die, dwarf_AT (DW_AT_dwo_name), dwo_file_name);
11158   if (comp_dir != NULL)
11159     add_skeleton_AT_string (die, DW_AT_comp_dir, comp_dir);
11160   add_AT_pubnames (die);
11161   add_AT_lineptr (die, DW_AT_GNU_addr_base, debug_addr_section_label);
11162 }
11163
11164 /* Output skeleton debug sections that point to the dwo file.  */
11165
11166 static void
11167 output_skeleton_debug_sections (dw_die_ref comp_unit,
11168                                 const unsigned char *dwo_id)
11169 {
11170   /* These attributes will be found in the full debug_info section.  */
11171   remove_AT (comp_unit, DW_AT_producer);
11172   remove_AT (comp_unit, DW_AT_language);
11173
11174   switch_to_section (debug_skeleton_info_section);
11175   ASM_OUTPUT_LABEL (asm_out_file, debug_skeleton_info_section_label);
11176
11177   /* Produce the skeleton compilation-unit header.  This one differs enough from
11178      a normal CU header that it's better not to call output_compilation_unit
11179      header.  */
11180   if (DWARF_INITIAL_LENGTH_SIZE - DWARF_OFFSET_SIZE == 4)
11181     dw2_asm_output_data (4, 0xffffffff,
11182                          "Initial length escape value indicating 64-bit "
11183                          "DWARF extension");
11184
11185   dw2_asm_output_data (DWARF_OFFSET_SIZE,
11186                        DWARF_COMPILE_UNIT_SKELETON_HEADER_SIZE
11187                        - DWARF_INITIAL_LENGTH_SIZE
11188                        + size_of_die (comp_unit),
11189                       "Length of Compilation Unit Info");
11190   output_dwarf_version ();
11191   if (dwarf_version >= 5)
11192     {
11193       dw2_asm_output_data (1, DW_UT_skeleton, "DW_UT_skeleton");
11194       dw2_asm_output_data (1, DWARF2_ADDR_SIZE, "Pointer Size (in bytes)");
11195     }
11196   dw2_asm_output_offset (DWARF_OFFSET_SIZE, debug_skeleton_abbrev_section_label,
11197                          debug_skeleton_abbrev_section,
11198                          "Offset Into Abbrev. Section");
11199   if (dwarf_version < 5)
11200     dw2_asm_output_data (1, DWARF2_ADDR_SIZE, "Pointer Size (in bytes)");
11201   else
11202     for (int i = 0; i < 8; i++)
11203       dw2_asm_output_data (1, dwo_id[i], i == 0 ? "DWO id" : NULL);
11204
11205   comp_unit->die_abbrev = SKELETON_COMP_DIE_ABBREV;
11206   output_die (comp_unit);
11207
11208   /* Build the skeleton debug_abbrev section.  */
11209   switch_to_section (debug_skeleton_abbrev_section);
11210   ASM_OUTPUT_LABEL (asm_out_file, debug_skeleton_abbrev_section_label);
11211
11212   output_die_abbrevs (SKELETON_COMP_DIE_ABBREV, comp_unit);
11213
11214   dw2_asm_output_data (1, 0, "end of skeleton .debug_abbrev");
11215 }
11216
11217 /* Output a comdat type unit DIE and its children.  */
11218
11219 static void
11220 output_comdat_type_unit (comdat_type_node *node)
11221 {
11222   const char *secname;
11223   char *tmp;
11224   int i;
11225 #if defined (OBJECT_FORMAT_ELF)
11226   tree comdat_key;
11227 #endif
11228
11229   /* First mark all the DIEs in this CU so we know which get local refs.  */
11230   mark_dies (node->root_die);
11231
11232   external_ref_hash_type *extern_map = optimize_external_refs (node->root_die);
11233
11234   build_abbrev_table (node->root_die, extern_map);
11235
11236   delete extern_map;
11237   extern_map = NULL;
11238
11239   /* Initialize the beginning DIE offset - and calculate sizes/offsets.  */
11240   next_die_offset = DWARF_COMDAT_TYPE_UNIT_HEADER_SIZE;
11241   calc_die_sizes (node->root_die);
11242
11243 #if defined (OBJECT_FORMAT_ELF)
11244   if (dwarf_version >= 5)
11245     {
11246       if (!dwarf_split_debug_info)
11247         secname = ".debug_info";
11248       else
11249         secname = ".debug_info.dwo";
11250     }
11251   else if (!dwarf_split_debug_info)
11252     secname = ".debug_types";
11253   else
11254     secname = ".debug_types.dwo";
11255
11256   tmp = XALLOCAVEC (char, 4 + DWARF_TYPE_SIGNATURE_SIZE * 2);
11257   sprintf (tmp, dwarf_version >= 5 ? "wi." : "wt.");
11258   for (i = 0; i < DWARF_TYPE_SIGNATURE_SIZE; i++)
11259     sprintf (tmp + 3 + i * 2, "%02x", node->signature[i] & 0xff);
11260   comdat_key = get_identifier (tmp);
11261   targetm.asm_out.named_section (secname,
11262                                  SECTION_DEBUG | SECTION_LINKONCE,
11263                                  comdat_key);
11264 #else
11265   tmp = XALLOCAVEC (char, 18 + DWARF_TYPE_SIGNATURE_SIZE * 2);
11266   sprintf (tmp, (dwarf_version >= 5
11267                  ? ".gnu.linkonce.wi." : ".gnu.linkonce.wt."));
11268   for (i = 0; i < DWARF_TYPE_SIGNATURE_SIZE; i++)
11269     sprintf (tmp + 17 + i * 2, "%02x", node->signature[i] & 0xff);
11270   secname = tmp;
11271   switch_to_section (get_section (secname, SECTION_DEBUG, NULL));
11272 #endif
11273
11274   /* Output debugging information.  */
11275   output_compilation_unit_header (dwarf_split_debug_info
11276                                   ? DW_UT_split_type : DW_UT_type);
11277   output_signature (node->signature, "Type Signature");
11278   dw2_asm_output_data (DWARF_OFFSET_SIZE, node->type_die->die_offset,
11279                        "Offset to Type DIE");
11280   output_die (node->root_die);
11281
11282   unmark_dies (node->root_die);
11283 }
11284
11285 /* Return the DWARF2/3 pubname associated with a decl.  */
11286
11287 static const char *
11288 dwarf2_name (tree decl, int scope)
11289 {
11290   if (DECL_NAMELESS (decl))
11291     return NULL;
11292   return lang_hooks.dwarf_name (decl, scope ? 1 : 0);
11293 }
11294
11295 /* Add a new entry to .debug_pubnames if appropriate.  */
11296
11297 static void
11298 add_pubname_string (const char *str, dw_die_ref die)
11299 {
11300   pubname_entry e;
11301
11302   e.die = die;
11303   e.name = xstrdup (str);
11304   vec_safe_push (pubname_table, e);
11305 }
11306
11307 static void
11308 add_pubname (tree decl, dw_die_ref die)
11309 {
11310   if (!want_pubnames ())
11311     return;
11312
11313   /* Don't add items to the table when we expect that the consumer will have
11314      just read the enclosing die.  For example, if the consumer is looking at a
11315      class_member, it will either be inside the class already, or will have just
11316      looked up the class to find the member.  Either way, searching the class is
11317      faster than searching the index.  */
11318   if ((TREE_PUBLIC (decl) && !class_scope_p (die->die_parent))
11319       || is_cu_die (die->die_parent) || is_namespace_die (die->die_parent))
11320     {
11321       const char *name = dwarf2_name (decl, 1);
11322
11323       if (name)
11324         add_pubname_string (name, die);
11325     }
11326 }
11327
11328 /* Add an enumerator to the pubnames section.  */
11329
11330 static void
11331 add_enumerator_pubname (const char *scope_name, dw_die_ref die)
11332 {
11333   pubname_entry e;
11334
11335   gcc_assert (scope_name);
11336   e.name = concat (scope_name, get_AT_string (die, DW_AT_name), NULL);
11337   e.die = die;
11338   vec_safe_push (pubname_table, e);
11339 }
11340
11341 /* Add a new entry to .debug_pubtypes if appropriate.  */
11342
11343 static void
11344 add_pubtype (tree decl, dw_die_ref die)
11345 {
11346   pubname_entry e;
11347
11348   if (!want_pubnames ())
11349     return;
11350
11351   if ((TREE_PUBLIC (decl)
11352        || is_cu_die (die->die_parent) || is_namespace_die (die->die_parent))
11353       && (die->die_tag == DW_TAG_typedef || COMPLETE_TYPE_P (decl)))
11354     {
11355       tree scope = NULL;
11356       const char *scope_name = "";
11357       const char *sep = is_cxx () ? "::" : ".";
11358       const char *name;
11359
11360       scope = TYPE_P (decl) ? TYPE_CONTEXT (decl) : NULL;
11361       if (scope && TREE_CODE (scope) == NAMESPACE_DECL)
11362         {
11363           scope_name = lang_hooks.dwarf_name (scope, 1);
11364           if (scope_name != NULL && scope_name[0] != '\0')
11365             scope_name = concat (scope_name, sep, NULL);
11366           else
11367             scope_name = "";
11368         }
11369
11370       if (TYPE_P (decl))
11371         name = type_tag (decl);
11372       else
11373         name = lang_hooks.dwarf_name (decl, 1);
11374
11375       /* If we don't have a name for the type, there's no point in adding
11376          it to the table.  */
11377       if (name != NULL && name[0] != '\0')
11378         {
11379           e.die = die;
11380           e.name = concat (scope_name, name, NULL);
11381           vec_safe_push (pubtype_table, e);
11382         }
11383
11384       /* Although it might be more consistent to add the pubinfo for the
11385          enumerators as their dies are created, they should only be added if the
11386          enum type meets the criteria above.  So rather than re-check the parent
11387          enum type whenever an enumerator die is created, just output them all
11388          here.  This isn't protected by the name conditional because anonymous
11389          enums don't have names.  */
11390       if (die->die_tag == DW_TAG_enumeration_type)
11391         {
11392           dw_die_ref c;
11393
11394           FOR_EACH_CHILD (die, c, add_enumerator_pubname (scope_name, c));
11395         }
11396     }
11397 }
11398
11399 /* Output a single entry in the pubnames table.  */
11400
11401 static void
11402 output_pubname (dw_offset die_offset, pubname_entry *entry)
11403 {
11404   dw_die_ref die = entry->die;
11405   int is_static = get_AT_flag (die, DW_AT_external) ? 0 : 1;
11406
11407   dw2_asm_output_data (DWARF_OFFSET_SIZE, die_offset, "DIE offset");
11408
11409   if (debug_generate_pub_sections == 2)
11410     {
11411       /* This logic follows gdb's method for determining the value of the flag
11412          byte.  */
11413       uint32_t flags = GDB_INDEX_SYMBOL_KIND_NONE;
11414       switch (die->die_tag)
11415       {
11416         case DW_TAG_typedef:
11417         case DW_TAG_base_type:
11418         case DW_TAG_subrange_type:
11419           GDB_INDEX_SYMBOL_KIND_SET_VALUE(flags, GDB_INDEX_SYMBOL_KIND_TYPE);
11420           GDB_INDEX_SYMBOL_STATIC_SET_VALUE(flags, 1);
11421           break;
11422         case DW_TAG_enumerator:
11423           GDB_INDEX_SYMBOL_KIND_SET_VALUE(flags,
11424                                           GDB_INDEX_SYMBOL_KIND_VARIABLE);
11425           if (!is_cxx ())
11426             GDB_INDEX_SYMBOL_STATIC_SET_VALUE(flags, 1);
11427           break;
11428         case DW_TAG_subprogram:
11429           GDB_INDEX_SYMBOL_KIND_SET_VALUE(flags,
11430                                           GDB_INDEX_SYMBOL_KIND_FUNCTION);
11431           if (!is_ada ())
11432             GDB_INDEX_SYMBOL_STATIC_SET_VALUE(flags, is_static);
11433           break;
11434         case DW_TAG_constant:
11435           GDB_INDEX_SYMBOL_KIND_SET_VALUE(flags,
11436                                           GDB_INDEX_SYMBOL_KIND_VARIABLE);
11437           GDB_INDEX_SYMBOL_STATIC_SET_VALUE(flags, is_static);
11438           break;
11439         case DW_TAG_variable:
11440           GDB_INDEX_SYMBOL_KIND_SET_VALUE(flags,
11441                                           GDB_INDEX_SYMBOL_KIND_VARIABLE);
11442           GDB_INDEX_SYMBOL_STATIC_SET_VALUE(flags, is_static);
11443           break;
11444         case DW_TAG_namespace:
11445         case DW_TAG_imported_declaration:
11446           GDB_INDEX_SYMBOL_KIND_SET_VALUE(flags, GDB_INDEX_SYMBOL_KIND_TYPE);
11447           break;
11448         case DW_TAG_class_type:
11449         case DW_TAG_interface_type:
11450         case DW_TAG_structure_type:
11451         case DW_TAG_union_type:
11452         case DW_TAG_enumeration_type:
11453           GDB_INDEX_SYMBOL_KIND_SET_VALUE(flags, GDB_INDEX_SYMBOL_KIND_TYPE);
11454           if (!is_cxx ())
11455             GDB_INDEX_SYMBOL_STATIC_SET_VALUE(flags, 1);
11456           break;
11457         default:
11458           /* An unusual tag.  Leave the flag-byte empty.  */
11459           break;
11460       }
11461       dw2_asm_output_data (1, flags >> GDB_INDEX_CU_BITSIZE,
11462                            "GDB-index flags");
11463     }
11464
11465   dw2_asm_output_nstring (entry->name, -1, "external name");
11466 }
11467
11468
11469 /* Output the public names table used to speed up access to externally
11470    visible names; or the public types table used to find type definitions.  */
11471
11472 static void
11473 output_pubnames (vec<pubname_entry, va_gc> *names)
11474 {
11475   unsigned i;
11476   unsigned long pubnames_length = size_of_pubnames (names);
11477   pubname_entry *pub;
11478
11479   if (!XCOFF_DEBUGGING_INFO)
11480     {
11481       if (DWARF_INITIAL_LENGTH_SIZE - DWARF_OFFSET_SIZE == 4)
11482         dw2_asm_output_data (4, 0xffffffff,
11483           "Initial length escape value indicating 64-bit DWARF extension");
11484       dw2_asm_output_data (DWARF_OFFSET_SIZE, pubnames_length,
11485                            "Pub Info Length");
11486     }
11487
11488   /* Version number for pubnames/pubtypes is independent of dwarf version.  */
11489   dw2_asm_output_data (2, 2, "DWARF pubnames/pubtypes version");
11490
11491   if (dwarf_split_debug_info)
11492     dw2_asm_output_offset (DWARF_OFFSET_SIZE, debug_skeleton_info_section_label,
11493                            debug_skeleton_info_section,
11494                            "Offset of Compilation Unit Info");
11495   else
11496     dw2_asm_output_offset (DWARF_OFFSET_SIZE, debug_info_section_label,
11497                            debug_info_section,
11498                            "Offset of Compilation Unit Info");
11499   dw2_asm_output_data (DWARF_OFFSET_SIZE, next_die_offset,
11500                        "Compilation Unit Length");
11501
11502   FOR_EACH_VEC_ELT (*names, i, pub)
11503     {
11504       if (include_pubname_in_output (names, pub))
11505         {
11506           dw_offset die_offset = pub->die->die_offset;
11507
11508           /* We shouldn't see pubnames for DIEs outside of the main CU.  */
11509           if (names == pubname_table && pub->die->die_tag != DW_TAG_enumerator)
11510             gcc_assert (pub->die->die_mark);
11511
11512           /* If we're putting types in their own .debug_types sections,
11513              the .debug_pubtypes table will still point to the compile
11514              unit (not the type unit), so we want to use the offset of
11515              the skeleton DIE (if there is one).  */
11516           if (pub->die->comdat_type_p && names == pubtype_table)
11517             {
11518               comdat_type_node *type_node = pub->die->die_id.die_type_node;
11519
11520               if (type_node != NULL)
11521                 die_offset = (type_node->skeleton_die != NULL
11522                               ? type_node->skeleton_die->die_offset
11523                               : comp_unit_die ()->die_offset);
11524             }
11525
11526           output_pubname (die_offset, pub);
11527         }
11528     }
11529
11530   dw2_asm_output_data (DWARF_OFFSET_SIZE, 0, NULL);
11531 }
11532
11533 /* Output public names and types tables if necessary.  */
11534
11535 static void
11536 output_pubtables (void)
11537 {
11538   if (!want_pubnames () || !info_section_emitted)
11539     return;
11540
11541   switch_to_section (debug_pubnames_section);
11542   output_pubnames (pubname_table);
11543   /* ??? Only defined by DWARF3, but emitted by Darwin for DWARF2.
11544      It shouldn't hurt to emit it always, since pure DWARF2 consumers
11545      simply won't look for the section.  */
11546   switch_to_section (debug_pubtypes_section);
11547   output_pubnames (pubtype_table);
11548 }
11549
11550
11551 /* Output the information that goes into the .debug_aranges table.
11552    Namely, define the beginning and ending address range of the
11553    text section generated for this compilation unit.  */
11554
11555 static void
11556 output_aranges (void)
11557 {
11558   unsigned i;
11559   unsigned long aranges_length = size_of_aranges ();
11560   
11561   if (!XCOFF_DEBUGGING_INFO)
11562     {
11563       if (DWARF_INITIAL_LENGTH_SIZE - DWARF_OFFSET_SIZE == 4)
11564         dw2_asm_output_data (4, 0xffffffff,
11565           "Initial length escape value indicating 64-bit DWARF extension");
11566       dw2_asm_output_data (DWARF_OFFSET_SIZE, aranges_length,
11567                            "Length of Address Ranges Info");
11568     }
11569
11570   /* Version number for aranges is still 2, even up to DWARF5.  */
11571   dw2_asm_output_data (2, 2, "DWARF aranges version");
11572   if (dwarf_split_debug_info)
11573     dw2_asm_output_offset (DWARF_OFFSET_SIZE, debug_skeleton_info_section_label,
11574                            debug_skeleton_info_section,
11575                            "Offset of Compilation Unit Info");
11576   else
11577     dw2_asm_output_offset (DWARF_OFFSET_SIZE, debug_info_section_label,
11578                            debug_info_section,
11579                            "Offset of Compilation Unit Info");
11580   dw2_asm_output_data (1, DWARF2_ADDR_SIZE, "Size of Address");
11581   dw2_asm_output_data (1, 0, "Size of Segment Descriptor");
11582
11583   /* We need to align to twice the pointer size here.  */
11584   if (DWARF_ARANGES_PAD_SIZE)
11585     {
11586       /* Pad using a 2 byte words so that padding is correct for any
11587          pointer size.  */
11588       dw2_asm_output_data (2, 0, "Pad to %d byte boundary",
11589                            2 * DWARF2_ADDR_SIZE);
11590       for (i = 2; i < (unsigned) DWARF_ARANGES_PAD_SIZE; i += 2)
11591         dw2_asm_output_data (2, 0, NULL);
11592     }
11593
11594   /* It is necessary not to output these entries if the sections were
11595      not used; if the sections were not used, the length will be 0 and
11596      the address may end up as 0 if the section is discarded by ld
11597      --gc-sections, leaving an invalid (0, 0) entry that can be
11598      confused with the terminator.  */
11599   if (text_section_used)
11600     {
11601       dw2_asm_output_addr (DWARF2_ADDR_SIZE, text_section_label, "Address");
11602       dw2_asm_output_delta (DWARF2_ADDR_SIZE, text_end_label,
11603                             text_section_label, "Length");
11604     }
11605   if (cold_text_section_used)
11606     {
11607       dw2_asm_output_addr (DWARF2_ADDR_SIZE, cold_text_section_label,
11608                            "Address");
11609       dw2_asm_output_delta (DWARF2_ADDR_SIZE, cold_end_label,
11610                             cold_text_section_label, "Length");
11611     }
11612
11613   if (have_multiple_function_sections)
11614     {
11615       unsigned fde_idx;
11616       dw_fde_ref fde;
11617
11618       FOR_EACH_VEC_ELT (*fde_vec, fde_idx, fde)
11619         {
11620           if (DECL_IGNORED_P (fde->decl))
11621             continue;
11622           if (!fde->in_std_section)
11623             {
11624               dw2_asm_output_addr (DWARF2_ADDR_SIZE, fde->dw_fde_begin,
11625                                    "Address");
11626               dw2_asm_output_delta (DWARF2_ADDR_SIZE, fde->dw_fde_end,
11627                                     fde->dw_fde_begin, "Length");
11628             }
11629           if (fde->dw_fde_second_begin && !fde->second_in_std_section)
11630             {
11631               dw2_asm_output_addr (DWARF2_ADDR_SIZE, fde->dw_fde_second_begin,
11632                                    "Address");
11633               dw2_asm_output_delta (DWARF2_ADDR_SIZE, fde->dw_fde_second_end,
11634                                     fde->dw_fde_second_begin, "Length");
11635             }
11636         }
11637     }
11638
11639   /* Output the terminator words.  */
11640   dw2_asm_output_data (DWARF2_ADDR_SIZE, 0, NULL);
11641   dw2_asm_output_data (DWARF2_ADDR_SIZE, 0, NULL);
11642 }
11643
11644 /* Add a new entry to .debug_ranges.  Return its index into
11645    ranges_table vector.  */
11646
11647 static unsigned int
11648 add_ranges_num (int num, bool maybe_new_sec)
11649 {
11650   dw_ranges r = { NULL, num, 0, maybe_new_sec };
11651   vec_safe_push (ranges_table, r);
11652   return vec_safe_length (ranges_table) - 1;
11653 }
11654
11655 /* Add a new entry to .debug_ranges corresponding to a block, or a
11656    range terminator if BLOCK is NULL.  MAYBE_NEW_SEC is true if
11657    this entry might be in a different section from previous range.  */
11658
11659 static unsigned int
11660 add_ranges (const_tree block, bool maybe_new_sec)
11661 {
11662   return add_ranges_num (block ? BLOCK_NUMBER (block) : 0, maybe_new_sec);
11663 }
11664
11665 /* Note that (*rnglist_table)[offset] is either a head of a rnglist
11666    chain, or middle entry of a chain that will be directly referred to.  */
11667
11668 static void
11669 note_rnglist_head (unsigned int offset)
11670 {
11671   if (dwarf_version < 5 || (*ranges_table)[offset].label)
11672     return;
11673   (*ranges_table)[offset].label = gen_internal_sym ("LLRL");
11674 }
11675
11676 /* Add a new entry to .debug_ranges corresponding to a pair of labels.
11677    When using dwarf_split_debug_info, address attributes in dies destined
11678    for the final executable should be direct references--setting the
11679    parameter force_direct ensures this behavior.  */
11680
11681 static void
11682 add_ranges_by_labels (dw_die_ref die, const char *begin, const char *end,
11683                       bool *added, bool force_direct)
11684 {
11685   unsigned int in_use = vec_safe_length (ranges_by_label);
11686   unsigned int offset;
11687   dw_ranges_by_label rbl = { begin, end };
11688   vec_safe_push (ranges_by_label, rbl);
11689   offset = add_ranges_num (-(int)in_use - 1, true);
11690   if (!*added)
11691     {
11692       add_AT_range_list (die, DW_AT_ranges, offset, force_direct);
11693       *added = true;
11694       note_rnglist_head (offset);
11695     }
11696 }
11697
11698 /* Emit .debug_ranges section.  */
11699
11700 static void
11701 output_ranges (void)
11702 {
11703   unsigned i;
11704   static const char *const start_fmt = "Offset %#x";
11705   const char *fmt = start_fmt;
11706   dw_ranges *r;
11707
11708   switch_to_section (debug_ranges_section);
11709   ASM_OUTPUT_LABEL (asm_out_file, ranges_section_label);
11710   FOR_EACH_VEC_SAFE_ELT (ranges_table, i, r)
11711     {
11712       int block_num = r->num;
11713
11714       if (block_num > 0)
11715         {
11716           char blabel[MAX_ARTIFICIAL_LABEL_BYTES];
11717           char elabel[MAX_ARTIFICIAL_LABEL_BYTES];
11718
11719           ASM_GENERATE_INTERNAL_LABEL (blabel, BLOCK_BEGIN_LABEL, block_num);
11720           ASM_GENERATE_INTERNAL_LABEL (elabel, BLOCK_END_LABEL, block_num);
11721
11722           /* If all code is in the text section, then the compilation
11723              unit base address defaults to DW_AT_low_pc, which is the
11724              base of the text section.  */
11725           if (!have_multiple_function_sections)
11726             {
11727               dw2_asm_output_delta (DWARF2_ADDR_SIZE, blabel,
11728                                     text_section_label,
11729                                     fmt, i * 2 * DWARF2_ADDR_SIZE);
11730               dw2_asm_output_delta (DWARF2_ADDR_SIZE, elabel,
11731                                     text_section_label, NULL);
11732             }
11733
11734           /* Otherwise, the compilation unit base address is zero,
11735              which allows us to use absolute addresses, and not worry
11736              about whether the target supports cross-section
11737              arithmetic.  */
11738           else
11739             {
11740               dw2_asm_output_addr (DWARF2_ADDR_SIZE, blabel,
11741                                    fmt, i * 2 * DWARF2_ADDR_SIZE);
11742               dw2_asm_output_addr (DWARF2_ADDR_SIZE, elabel, NULL);
11743             }
11744
11745           fmt = NULL;
11746         }
11747
11748       /* Negative block_num stands for an index into ranges_by_label.  */
11749       else if (block_num < 0)
11750         {
11751           int lab_idx = - block_num - 1;
11752
11753           if (!have_multiple_function_sections)
11754             {
11755               gcc_unreachable ();
11756 #if 0
11757               /* If we ever use add_ranges_by_labels () for a single
11758                  function section, all we have to do is to take out
11759                  the #if 0 above.  */
11760               dw2_asm_output_delta (DWARF2_ADDR_SIZE,
11761                                     (*ranges_by_label)[lab_idx].begin,
11762                                     text_section_label,
11763                                     fmt, i * 2 * DWARF2_ADDR_SIZE);
11764               dw2_asm_output_delta (DWARF2_ADDR_SIZE,
11765                                     (*ranges_by_label)[lab_idx].end,
11766                                     text_section_label, NULL);
11767 #endif
11768             }
11769           else
11770             {
11771               dw2_asm_output_addr (DWARF2_ADDR_SIZE,
11772                                    (*ranges_by_label)[lab_idx].begin,
11773                                    fmt, i * 2 * DWARF2_ADDR_SIZE);
11774               dw2_asm_output_addr (DWARF2_ADDR_SIZE,
11775                                    (*ranges_by_label)[lab_idx].end,
11776                                    NULL);
11777             }
11778         }
11779       else
11780         {
11781           dw2_asm_output_data (DWARF2_ADDR_SIZE, 0, NULL);
11782           dw2_asm_output_data (DWARF2_ADDR_SIZE, 0, NULL);
11783           fmt = start_fmt;
11784         }
11785     }
11786 }
11787
11788 /* Non-zero if .debug_line_str should be used for .debug_line section
11789    strings or strings that are likely shareable with those.  */
11790 #define DWARF5_USE_DEBUG_LINE_STR \
11791   (!DWARF2_INDIRECT_STRING_SUPPORT_MISSING_ON_TARGET            \
11792    && (DEBUG_STR_SECTION_FLAGS & SECTION_MERGE) != 0            \
11793    /* FIXME: there is no .debug_line_str.dwo section,           \
11794       for -gsplit-dwarf we should use DW_FORM_strx instead.  */ \
11795    && !dwarf_split_debug_info)
11796
11797 /* Assign .debug_rnglists indexes.  */
11798
11799 static void
11800 index_rnglists (void)
11801 {
11802   unsigned i;
11803   dw_ranges *r;
11804
11805   FOR_EACH_VEC_SAFE_ELT (ranges_table, i, r)
11806     if (r->label)
11807       r->idx = rnglist_idx++;
11808 }
11809
11810 /* Emit .debug_rnglists section.  */
11811
11812 static void
11813 output_rnglists (unsigned generation)
11814 {
11815   unsigned i;
11816   dw_ranges *r;
11817   char l1[MAX_ARTIFICIAL_LABEL_BYTES];
11818   char l2[MAX_ARTIFICIAL_LABEL_BYTES];
11819   char basebuf[MAX_ARTIFICIAL_LABEL_BYTES];
11820
11821   switch_to_section (debug_ranges_section);
11822   ASM_OUTPUT_LABEL (asm_out_file, ranges_section_label);
11823   /* There are up to 4 unique ranges labels per generation.
11824      See also init_sections_and_labels.  */
11825   ASM_GENERATE_INTERNAL_LABEL (l1, DEBUG_RANGES_SECTION_LABEL,
11826                                2 + generation * 4);
11827   ASM_GENERATE_INTERNAL_LABEL (l2, DEBUG_RANGES_SECTION_LABEL,
11828                                3 + generation * 4);
11829   if (DWARF_INITIAL_LENGTH_SIZE - DWARF_OFFSET_SIZE == 4)
11830     dw2_asm_output_data (4, 0xffffffff,
11831                          "Initial length escape value indicating "
11832                          "64-bit DWARF extension");
11833   dw2_asm_output_delta (DWARF_OFFSET_SIZE, l2, l1,
11834                         "Length of Range Lists");
11835   ASM_OUTPUT_LABEL (asm_out_file, l1);
11836   output_dwarf_version ();
11837   dw2_asm_output_data (1, DWARF2_ADDR_SIZE, "Address Size");
11838   dw2_asm_output_data (1, 0, "Segment Size");
11839   /* Emit the offset table only for -gsplit-dwarf.  If we don't care
11840      about relocation sizes and primarily care about the size of .debug*
11841      sections in linked shared libraries and executables, then
11842      the offset table plus corresponding DW_FORM_rnglistx uleb128 indexes
11843      into it are usually larger than just DW_FORM_sec_offset offsets
11844      into the .debug_rnglists section.  */
11845   dw2_asm_output_data (4, dwarf_split_debug_info ? rnglist_idx : 0,
11846                        "Offset Entry Count");
11847   if (dwarf_split_debug_info)
11848     {
11849       ASM_OUTPUT_LABEL (asm_out_file, ranges_base_label);
11850       FOR_EACH_VEC_SAFE_ELT (ranges_table, i, r)
11851         if (r->label)
11852           dw2_asm_output_delta (DWARF_OFFSET_SIZE, r->label,
11853                                 ranges_base_label, NULL);
11854     }
11855
11856   const char *lab = "";
11857   unsigned int len = vec_safe_length (ranges_table);
11858   const char *base = NULL;
11859   FOR_EACH_VEC_SAFE_ELT (ranges_table, i, r)
11860     {
11861       int block_num = r->num;
11862
11863       if (r->label)
11864         {
11865           ASM_OUTPUT_LABEL (asm_out_file, r->label);
11866           lab = r->label;
11867         }
11868       if (HAVE_AS_LEB128 && (r->label || r->maybe_new_sec))
11869         base = NULL;
11870       if (block_num > 0)
11871         {
11872           char blabel[MAX_ARTIFICIAL_LABEL_BYTES];
11873           char elabel[MAX_ARTIFICIAL_LABEL_BYTES];
11874
11875           ASM_GENERATE_INTERNAL_LABEL (blabel, BLOCK_BEGIN_LABEL, block_num);
11876           ASM_GENERATE_INTERNAL_LABEL (elabel, BLOCK_END_LABEL, block_num);
11877
11878           if (HAVE_AS_LEB128)
11879             {
11880               /* If all code is in the text section, then the compilation
11881                  unit base address defaults to DW_AT_low_pc, which is the
11882                  base of the text section.  */
11883               if (!have_multiple_function_sections)
11884                 {
11885                   dw2_asm_output_data (1, DW_RLE_offset_pair,
11886                                        "DW_RLE_offset_pair (%s)", lab);
11887                   dw2_asm_output_delta_uleb128 (blabel, text_section_label,
11888                                                 "Range begin address (%s)", lab);
11889                   dw2_asm_output_delta_uleb128 (elabel, text_section_label,
11890                                                 "Range end address (%s)", lab);
11891                   continue;
11892                 }
11893               if (base == NULL)
11894                 {
11895                   dw_ranges *r2 = NULL;
11896                   if (i < len - 1)
11897                     r2 = &(*ranges_table)[i + 1];
11898                   if (r2
11899                       && r2->num != 0
11900                       && r2->label == NULL
11901                       && !r2->maybe_new_sec)
11902                     {
11903                       dw2_asm_output_data (1, DW_RLE_base_address,
11904                                            "DW_RLE_base_address (%s)", lab);
11905                       dw2_asm_output_addr (DWARF2_ADDR_SIZE, blabel,
11906                                            "Base address (%s)", lab);
11907                       strcpy (basebuf, blabel);
11908                       base = basebuf;
11909                     }
11910                 }
11911               if (base)
11912                 {
11913                   dw2_asm_output_data (1, DW_RLE_offset_pair,
11914                                        "DW_RLE_offset_pair (%s)", lab);
11915                   dw2_asm_output_delta_uleb128 (blabel, base,
11916                                                 "Range begin address (%s)", lab);
11917                   dw2_asm_output_delta_uleb128 (elabel, base,
11918                                                 "Range end address (%s)", lab);
11919                   continue;
11920                 }
11921               dw2_asm_output_data (1, DW_RLE_start_length,
11922                                    "DW_RLE_start_length (%s)", lab);
11923               dw2_asm_output_addr (DWARF2_ADDR_SIZE, blabel,
11924                                    "Range begin address (%s)", lab);
11925               dw2_asm_output_delta_uleb128 (elabel, blabel,
11926                                             "Range length (%s)", lab);
11927             }
11928           else
11929             {
11930               dw2_asm_output_data (1, DW_RLE_start_end,
11931                                    "DW_RLE_start_end (%s)", lab);
11932               dw2_asm_output_addr (DWARF2_ADDR_SIZE, blabel,
11933                                    "Range begin address (%s)", lab);
11934               dw2_asm_output_addr (DWARF2_ADDR_SIZE, elabel,
11935                                    "Range end address (%s)", lab);
11936             }
11937         }
11938
11939       /* Negative block_num stands for an index into ranges_by_label.  */
11940       else if (block_num < 0)
11941         {
11942           int lab_idx = - block_num - 1;
11943           const char *blabel = (*ranges_by_label)[lab_idx].begin;
11944           const char *elabel = (*ranges_by_label)[lab_idx].end;
11945
11946           if (!have_multiple_function_sections)
11947             gcc_unreachable ();
11948           if (HAVE_AS_LEB128)
11949             {
11950               dw2_asm_output_data (1, DW_RLE_start_length,
11951                                    "DW_RLE_start_length (%s)", lab);
11952               dw2_asm_output_addr (DWARF2_ADDR_SIZE, blabel,
11953                                    "Range begin address (%s)", lab);
11954               dw2_asm_output_delta_uleb128 (elabel, blabel,
11955                                             "Range length (%s)", lab);
11956             }
11957           else
11958             {
11959               dw2_asm_output_data (1, DW_RLE_start_end,
11960                                    "DW_RLE_start_end (%s)", lab);
11961               dw2_asm_output_addr (DWARF2_ADDR_SIZE, blabel,
11962                                    "Range begin address (%s)", lab);
11963               dw2_asm_output_addr (DWARF2_ADDR_SIZE, elabel,
11964                                    "Range end address (%s)", lab);
11965             }
11966         }
11967       else
11968         dw2_asm_output_data (1, DW_RLE_end_of_list,
11969                              "DW_RLE_end_of_list (%s)", lab);
11970     }
11971   ASM_OUTPUT_LABEL (asm_out_file, l2);
11972 }
11973
11974 /* Data structure containing information about input files.  */
11975 struct file_info
11976 {
11977   const char *path;     /* Complete file name.  */
11978   const char *fname;    /* File name part.  */
11979   int length;           /* Length of entire string.  */
11980   struct dwarf_file_data * file_idx;    /* Index in input file table.  */
11981   int dir_idx;          /* Index in directory table.  */
11982 };
11983
11984 /* Data structure containing information about directories with source
11985    files.  */
11986 struct dir_info
11987 {
11988   const char *path;     /* Path including directory name.  */
11989   int length;           /* Path length.  */
11990   int prefix;           /* Index of directory entry which is a prefix.  */
11991   int count;            /* Number of files in this directory.  */
11992   int dir_idx;          /* Index of directory used as base.  */
11993 };
11994
11995 /* Callback function for file_info comparison.  We sort by looking at
11996    the directories in the path.  */
11997
11998 static int
11999 file_info_cmp (const void *p1, const void *p2)
12000 {
12001   const struct file_info *const s1 = (const struct file_info *) p1;
12002   const struct file_info *const s2 = (const struct file_info *) p2;
12003   const unsigned char *cp1;
12004   const unsigned char *cp2;
12005
12006   /* Take care of file names without directories.  We need to make sure that
12007      we return consistent values to qsort since some will get confused if
12008      we return the same value when identical operands are passed in opposite
12009      orders.  So if neither has a directory, return 0 and otherwise return
12010      1 or -1 depending on which one has the directory.  */
12011   if ((s1->path == s1->fname || s2->path == s2->fname))
12012     return (s2->path == s2->fname) - (s1->path == s1->fname);
12013
12014   cp1 = (const unsigned char *) s1->path;
12015   cp2 = (const unsigned char *) s2->path;
12016
12017   while (1)
12018     {
12019       ++cp1;
12020       ++cp2;
12021       /* Reached the end of the first path?  If so, handle like above.  */
12022       if ((cp1 == (const unsigned char *) s1->fname)
12023           || (cp2 == (const unsigned char *) s2->fname))
12024         return ((cp2 == (const unsigned char *) s2->fname)
12025                 - (cp1 == (const unsigned char *) s1->fname));
12026
12027       /* Character of current path component the same?  */
12028       else if (*cp1 != *cp2)
12029         return *cp1 - *cp2;
12030     }
12031 }
12032
12033 struct file_name_acquire_data
12034 {
12035   struct file_info *files;
12036   int used_files;
12037   int max_files;
12038 };
12039
12040 /* Traversal function for the hash table.  */
12041
12042 int
12043 file_name_acquire (dwarf_file_data **slot, file_name_acquire_data *fnad)
12044 {
12045   struct dwarf_file_data *d = *slot;
12046   struct file_info *fi;
12047   const char *f;
12048
12049   gcc_assert (fnad->max_files >= d->emitted_number);
12050
12051   if (! d->emitted_number)
12052     return 1;
12053
12054   gcc_assert (fnad->max_files != fnad->used_files);
12055
12056   fi = fnad->files + fnad->used_files++;
12057
12058   /* Skip all leading "./".  */
12059   f = d->filename;
12060   while (f[0] == '.' && IS_DIR_SEPARATOR (f[1]))
12061     f += 2;
12062
12063   /* Create a new array entry.  */
12064   fi->path = f;
12065   fi->length = strlen (f);
12066   fi->file_idx = d;
12067
12068   /* Search for the file name part.  */
12069   f = strrchr (f, DIR_SEPARATOR);
12070 #if defined (DIR_SEPARATOR_2)
12071   {
12072     char *g = strrchr (fi->path, DIR_SEPARATOR_2);
12073
12074     if (g != NULL)
12075       {
12076         if (f == NULL || f < g)
12077           f = g;
12078       }
12079   }
12080 #endif
12081
12082   fi->fname = f == NULL ? fi->path : f + 1;
12083   return 1;
12084 }
12085
12086 /* Helper function for output_file_names.  Emit a FORM encoded
12087    string STR, with assembly comment start ENTRY_KIND and
12088    index IDX */
12089
12090 static void
12091 output_line_string (enum dwarf_form form, const char *str,
12092                     const char *entry_kind, unsigned int idx)
12093 {
12094   switch (form)
12095     {
12096     case DW_FORM_string:
12097       dw2_asm_output_nstring (str, -1, "%s: %#x", entry_kind, idx);
12098       break;
12099     case DW_FORM_line_strp:
12100       if (!debug_line_str_hash)
12101         debug_line_str_hash
12102           = hash_table<indirect_string_hasher>::create_ggc (10);
12103
12104       struct indirect_string_node *node;
12105       node = find_AT_string_in_table (str, debug_line_str_hash);
12106       set_indirect_string (node);
12107       node->form = form;
12108       dw2_asm_output_offset (DWARF_OFFSET_SIZE, node->label,
12109                              debug_line_str_section, "%s: %#x: \"%s\"",
12110                              entry_kind, 0, node->str);
12111       break;
12112     default:
12113       gcc_unreachable ();
12114     }
12115 }
12116
12117 /* Output the directory table and the file name table.  We try to minimize
12118    the total amount of memory needed.  A heuristic is used to avoid large
12119    slowdowns with many input files.  */
12120
12121 static void
12122 output_file_names (void)
12123 {
12124   struct file_name_acquire_data fnad;
12125   int numfiles;
12126   struct file_info *files;
12127   struct dir_info *dirs;
12128   int *saved;
12129   int *savehere;
12130   int *backmap;
12131   int ndirs;
12132   int idx_offset;
12133   int i;
12134
12135   if (!last_emitted_file)
12136     {
12137       if (dwarf_version >= 5)
12138         {
12139           dw2_asm_output_data (1, 0, "Directory entry format count");
12140           dw2_asm_output_data_uleb128 (0, "Directories count");
12141           dw2_asm_output_data (1, 0, "File name entry format count");
12142           dw2_asm_output_data_uleb128 (0, "File names count");
12143         }
12144       else
12145         {
12146           dw2_asm_output_data (1, 0, "End directory table");
12147           dw2_asm_output_data (1, 0, "End file name table");
12148         }
12149       return;
12150     }
12151
12152   numfiles = last_emitted_file->emitted_number;
12153
12154   /* Allocate the various arrays we need.  */
12155   files = XALLOCAVEC (struct file_info, numfiles);
12156   dirs = XALLOCAVEC (struct dir_info, numfiles);
12157
12158   fnad.files = files;
12159   fnad.used_files = 0;
12160   fnad.max_files = numfiles;
12161   file_table->traverse<file_name_acquire_data *, file_name_acquire> (&fnad);
12162   gcc_assert (fnad.used_files == fnad.max_files);
12163
12164   qsort (files, numfiles, sizeof (files[0]), file_info_cmp);
12165
12166   /* Find all the different directories used.  */
12167   dirs[0].path = files[0].path;
12168   dirs[0].length = files[0].fname - files[0].path;
12169   dirs[0].prefix = -1;
12170   dirs[0].count = 1;
12171   dirs[0].dir_idx = 0;
12172   files[0].dir_idx = 0;
12173   ndirs = 1;
12174
12175   for (i = 1; i < numfiles; i++)
12176     if (files[i].fname - files[i].path == dirs[ndirs - 1].length
12177         && memcmp (dirs[ndirs - 1].path, files[i].path,
12178                    dirs[ndirs - 1].length) == 0)
12179       {
12180         /* Same directory as last entry.  */
12181         files[i].dir_idx = ndirs - 1;
12182         ++dirs[ndirs - 1].count;
12183       }
12184     else
12185       {
12186         int j;
12187
12188         /* This is a new directory.  */
12189         dirs[ndirs].path = files[i].path;
12190         dirs[ndirs].length = files[i].fname - files[i].path;
12191         dirs[ndirs].count = 1;
12192         dirs[ndirs].dir_idx = ndirs;
12193         files[i].dir_idx = ndirs;
12194
12195         /* Search for a prefix.  */
12196         dirs[ndirs].prefix = -1;
12197         for (j = 0; j < ndirs; j++)
12198           if (dirs[j].length < dirs[ndirs].length
12199               && dirs[j].length > 1
12200               && (dirs[ndirs].prefix == -1
12201                   || dirs[j].length > dirs[dirs[ndirs].prefix].length)
12202               && memcmp (dirs[j].path, dirs[ndirs].path, dirs[j].length) == 0)
12203             dirs[ndirs].prefix = j;
12204
12205         ++ndirs;
12206       }
12207
12208   /* Now to the actual work.  We have to find a subset of the directories which
12209      allow expressing the file name using references to the directory table
12210      with the least amount of characters.  We do not do an exhaustive search
12211      where we would have to check out every combination of every single
12212      possible prefix.  Instead we use a heuristic which provides nearly optimal
12213      results in most cases and never is much off.  */
12214   saved = XALLOCAVEC (int, ndirs);
12215   savehere = XALLOCAVEC (int, ndirs);
12216
12217   memset (saved, '\0', ndirs * sizeof (saved[0]));
12218   for (i = 0; i < ndirs; i++)
12219     {
12220       int j;
12221       int total;
12222
12223       /* We can always save some space for the current directory.  But this
12224          does not mean it will be enough to justify adding the directory.  */
12225       savehere[i] = dirs[i].length;
12226       total = (savehere[i] - saved[i]) * dirs[i].count;
12227
12228       for (j = i + 1; j < ndirs; j++)
12229         {
12230           savehere[j] = 0;
12231           if (saved[j] < dirs[i].length)
12232             {
12233               /* Determine whether the dirs[i] path is a prefix of the
12234                  dirs[j] path.  */
12235               int k;
12236
12237               k = dirs[j].prefix;
12238               while (k != -1 && k != (int) i)
12239                 k = dirs[k].prefix;
12240
12241               if (k == (int) i)
12242                 {
12243                   /* Yes it is.  We can possibly save some memory by
12244                      writing the filenames in dirs[j] relative to
12245                      dirs[i].  */
12246                   savehere[j] = dirs[i].length;
12247                   total += (savehere[j] - saved[j]) * dirs[j].count;
12248                 }
12249             }
12250         }
12251
12252       /* Check whether we can save enough to justify adding the dirs[i]
12253          directory.  */
12254       if (total > dirs[i].length + 1)
12255         {
12256           /* It's worthwhile adding.  */
12257           for (j = i; j < ndirs; j++)
12258             if (savehere[j] > 0)
12259               {
12260                 /* Remember how much we saved for this directory so far.  */
12261                 saved[j] = savehere[j];
12262
12263                 /* Remember the prefix directory.  */
12264                 dirs[j].dir_idx = i;
12265               }
12266         }
12267     }
12268
12269   /* Emit the directory name table.  */
12270   idx_offset = dirs[0].length > 0 ? 1 : 0;
12271   enum dwarf_form str_form = DW_FORM_string;
12272   enum dwarf_form idx_form = DW_FORM_udata;
12273   if (dwarf_version >= 5)
12274     {
12275       const char *comp_dir = comp_dir_string ();
12276       if (comp_dir == NULL)
12277         comp_dir = "";
12278       dw2_asm_output_data (1, 1, "Directory entry format count");
12279       if (DWARF5_USE_DEBUG_LINE_STR)
12280         str_form = DW_FORM_line_strp;
12281       dw2_asm_output_data_uleb128 (DW_LNCT_path, "DW_LNCT_path");
12282       dw2_asm_output_data_uleb128 (str_form, "%s",
12283                                    get_DW_FORM_name (str_form));
12284       dw2_asm_output_data_uleb128 (ndirs + idx_offset, "Directories count");
12285       if (str_form == DW_FORM_string)
12286         {
12287           dw2_asm_output_nstring (comp_dir, -1, "Directory Entry: %#x", 0);
12288           for (i = 1 - idx_offset; i < ndirs; i++)
12289             dw2_asm_output_nstring (dirs[i].path,
12290                                     dirs[i].length
12291                                     - !DWARF2_DIR_SHOULD_END_WITH_SEPARATOR,
12292                                     "Directory Entry: %#x", i + idx_offset);
12293         }
12294       else
12295         {
12296           output_line_string (str_form, comp_dir, "Directory Entry", 0);
12297           for (i = 1 - idx_offset; i < ndirs; i++)
12298             {
12299               const char *str
12300                 = ggc_alloc_string (dirs[i].path,
12301                                     dirs[i].length
12302                                     - !DWARF2_DIR_SHOULD_END_WITH_SEPARATOR);
12303               output_line_string (str_form, str, "Directory Entry",
12304                                   (unsigned) i + idx_offset);
12305             }
12306         }
12307     }
12308   else
12309     {
12310       for (i = 1 - idx_offset; i < ndirs; i++)
12311         dw2_asm_output_nstring (dirs[i].path,
12312                                 dirs[i].length
12313                                 - !DWARF2_DIR_SHOULD_END_WITH_SEPARATOR,
12314                                 "Directory Entry: %#x", i + idx_offset);
12315
12316       dw2_asm_output_data (1, 0, "End directory table");
12317     }
12318
12319   /* We have to emit them in the order of emitted_number since that's
12320      used in the debug info generation.  To do this efficiently we
12321      generate a back-mapping of the indices first.  */
12322   backmap = XALLOCAVEC (int, numfiles);
12323   for (i = 0; i < numfiles; i++)
12324     backmap[files[i].file_idx->emitted_number - 1] = i;
12325
12326   if (dwarf_version >= 5)
12327     {
12328       const char *filename0 = get_AT_string (comp_unit_die (), DW_AT_name);
12329       if (filename0 == NULL)
12330         filename0 = "";
12331       /* DW_LNCT_directory_index can use DW_FORM_udata, DW_FORM_data1 and
12332          DW_FORM_data2.  Choose one based on the number of directories
12333          and how much space would they occupy in each encoding.
12334          If we have at most 256 directories, all indexes fit into
12335          a single byte, so DW_FORM_data1 is most compact (if there
12336          are at most 128 directories, DW_FORM_udata would be as
12337          compact as that, but not shorter and slower to decode).  */
12338       if (ndirs + idx_offset <= 256)
12339         idx_form = DW_FORM_data1;
12340       /* If there are more than 65536 directories, we have to use
12341          DW_FORM_udata, DW_FORM_data2 can't refer to them.
12342          Otherwise, compute what space would occupy if all the indexes
12343          used DW_FORM_udata - sum - and compare that to how large would
12344          be DW_FORM_data2 encoding, and pick the more efficient one.  */
12345       else if (ndirs + idx_offset <= 65536)
12346         {
12347           unsigned HOST_WIDE_INT sum = 1;
12348           for (i = 0; i < numfiles; i++)
12349             {
12350               int file_idx = backmap[i];
12351               int dir_idx = dirs[files[file_idx].dir_idx].dir_idx;
12352               sum += size_of_uleb128 (dir_idx);
12353             }
12354           if (sum >= HOST_WIDE_INT_UC (2) * (numfiles + 1))
12355             idx_form = DW_FORM_data2;
12356         }
12357 #ifdef VMS_DEBUGGING_INFO
12358       dw2_asm_output_data (1, 4, "File name entry format count");
12359 #else
12360       dw2_asm_output_data (1, 2, "File name entry format count");
12361 #endif
12362       dw2_asm_output_data_uleb128 (DW_LNCT_path, "DW_LNCT_path");
12363       dw2_asm_output_data_uleb128 (str_form, "%s",
12364                                    get_DW_FORM_name (str_form));
12365       dw2_asm_output_data_uleb128 (DW_LNCT_directory_index,
12366                                    "DW_LNCT_directory_index");
12367       dw2_asm_output_data_uleb128 (idx_form, "%s",
12368                                    get_DW_FORM_name (idx_form));
12369 #ifdef VMS_DEBUGGING_INFO
12370       dw2_asm_output_data_uleb128 (DW_LNCT_timestamp, "DW_LNCT_timestamp");
12371       dw2_asm_output_data_uleb128 (DW_FORM_udata, "DW_FORM_udata");
12372       dw2_asm_output_data_uleb128 (DW_LNCT_size, "DW_LNCT_size");
12373       dw2_asm_output_data_uleb128 (DW_FORM_udata, "DW_FORM_udata");
12374 #endif
12375       dw2_asm_output_data_uleb128 (numfiles + 1, "File names count");
12376
12377       output_line_string (str_form, filename0, "File Entry", 0);
12378
12379       /* Include directory index.  */
12380       if (idx_form != DW_FORM_udata)
12381         dw2_asm_output_data (idx_form == DW_FORM_data1 ? 1 : 2,
12382                              0, NULL);
12383       else
12384         dw2_asm_output_data_uleb128 (0, NULL);
12385
12386 #ifdef VMS_DEBUGGING_INFO
12387       dw2_asm_output_data_uleb128 (0, NULL);
12388       dw2_asm_output_data_uleb128 (0, NULL);
12389 #endif
12390     }
12391
12392   /* Now write all the file names.  */
12393   for (i = 0; i < numfiles; i++)
12394     {
12395       int file_idx = backmap[i];
12396       int dir_idx = dirs[files[file_idx].dir_idx].dir_idx;
12397
12398 #ifdef VMS_DEBUGGING_INFO
12399 #define MAX_VMS_VERSION_LEN 6 /* ";32768" */
12400
12401       /* Setting these fields can lead to debugger miscomparisons,
12402          but VMS Debug requires them to be set correctly.  */
12403
12404       int ver;
12405       long long cdt;
12406       long siz;
12407       int maxfilelen = (strlen (files[file_idx].path)
12408                         + dirs[dir_idx].length
12409                         + MAX_VMS_VERSION_LEN + 1);
12410       char *filebuf = XALLOCAVEC (char, maxfilelen);
12411
12412       vms_file_stats_name (files[file_idx].path, 0, 0, 0, &ver);
12413       snprintf (filebuf, maxfilelen, "%s;%d",
12414                 files[file_idx].path + dirs[dir_idx].length, ver);
12415
12416       output_line_string (str_form, filebuf, "File Entry", (unsigned) i + 1);
12417
12418       /* Include directory index.  */
12419       if (dwarf_version >= 5 && idx_form != DW_FORM_udata)
12420         dw2_asm_output_data (idx_form == DW_FORM_data1 ? 1 : 2,
12421                              dir_idx + idx_offset, NULL);
12422       else
12423         dw2_asm_output_data_uleb128 (dir_idx + idx_offset, NULL);
12424
12425       /* Modification time.  */
12426       dw2_asm_output_data_uleb128 ((vms_file_stats_name (files[file_idx].path,
12427                                                          &cdt, 0, 0, 0) == 0)
12428                                    ? cdt : 0, NULL);
12429
12430       /* File length in bytes.  */
12431       dw2_asm_output_data_uleb128 ((vms_file_stats_name (files[file_idx].path,
12432                                                          0, &siz, 0, 0) == 0)
12433                                    ? siz : 0, NULL);
12434 #else
12435       output_line_string (str_form,
12436                           files[file_idx].path + dirs[dir_idx].length,
12437                           "File Entry", (unsigned) i + 1);
12438
12439       /* Include directory index.  */
12440       if (dwarf_version >= 5 && idx_form != DW_FORM_udata)
12441         dw2_asm_output_data (idx_form == DW_FORM_data1 ? 1 : 2,
12442                              dir_idx + idx_offset, NULL);
12443       else
12444         dw2_asm_output_data_uleb128 (dir_idx + idx_offset, NULL);
12445
12446       if (dwarf_version >= 5)
12447         continue;
12448
12449       /* Modification time.  */
12450       dw2_asm_output_data_uleb128 (0, NULL);
12451
12452       /* File length in bytes.  */
12453       dw2_asm_output_data_uleb128 (0, NULL);
12454 #endif /* VMS_DEBUGGING_INFO */
12455     }
12456
12457   if (dwarf_version < 5)
12458     dw2_asm_output_data (1, 0, "End file name table");
12459 }
12460
12461
12462 /* Output one line number table into the .debug_line section.  */
12463
12464 static void
12465 output_one_line_info_table (dw_line_info_table *table)
12466 {
12467   char line_label[MAX_ARTIFICIAL_LABEL_BYTES];
12468   unsigned int current_line = 1;
12469   bool current_is_stmt = DWARF_LINE_DEFAULT_IS_STMT_START;
12470   dw_line_info_entry *ent, *prev_addr;
12471   size_t i;
12472   unsigned int view;
12473
12474   view = 0;
12475
12476   FOR_EACH_VEC_SAFE_ELT (table->entries, i, ent)
12477     {
12478       switch (ent->opcode)
12479         {
12480         case LI_set_address:
12481           /* ??? Unfortunately, we have little choice here currently, and
12482              must always use the most general form.  GCC does not know the
12483              address delta itself, so we can't use DW_LNS_advance_pc.  Many
12484              ports do have length attributes which will give an upper bound
12485              on the address range.  We could perhaps use length attributes
12486              to determine when it is safe to use DW_LNS_fixed_advance_pc.  */
12487           ASM_GENERATE_INTERNAL_LABEL (line_label, LINE_CODE_LABEL, ent->val);
12488
12489           view = 0;
12490
12491           /* This can handle any delta.  This takes
12492              4+DWARF2_ADDR_SIZE bytes.  */
12493           dw2_asm_output_data (1, 0, "set address %s%s", line_label,
12494                                debug_variable_location_views
12495                                ? ", reset view to 0" : "");
12496           dw2_asm_output_data_uleb128 (1 + DWARF2_ADDR_SIZE, NULL);
12497           dw2_asm_output_data (1, DW_LNE_set_address, NULL);
12498           dw2_asm_output_addr (DWARF2_ADDR_SIZE, line_label, NULL);
12499
12500           prev_addr = ent;
12501           break;
12502
12503         case LI_adv_address:
12504           {
12505             ASM_GENERATE_INTERNAL_LABEL (line_label, LINE_CODE_LABEL, ent->val);
12506             char prev_label[MAX_ARTIFICIAL_LABEL_BYTES];
12507             ASM_GENERATE_INTERNAL_LABEL (prev_label, LINE_CODE_LABEL, prev_addr->val);
12508
12509             view++;
12510
12511             dw2_asm_output_data (1, DW_LNS_fixed_advance_pc, "fixed advance PC, increment view to %i", view);
12512             dw2_asm_output_delta (2, line_label, prev_label,
12513                                   "from %s to %s", prev_label, line_label);
12514
12515             prev_addr = ent;
12516             break;
12517           }
12518
12519         case LI_set_line:
12520           if (ent->val == current_line)
12521             {
12522               /* We still need to start a new row, so output a copy insn.  */
12523               dw2_asm_output_data (1, DW_LNS_copy,
12524                                    "copy line %u", current_line);
12525             }
12526           else
12527             {
12528               int line_offset = ent->val - current_line;
12529               int line_delta = line_offset - DWARF_LINE_BASE;
12530
12531               current_line = ent->val;
12532               if (line_delta >= 0 && line_delta < (DWARF_LINE_RANGE - 1))
12533                 {
12534                   /* This can handle deltas from -10 to 234, using the current
12535                      definitions of DWARF_LINE_BASE and DWARF_LINE_RANGE.
12536                      This takes 1 byte.  */
12537                   dw2_asm_output_data (1, DWARF_LINE_OPCODE_BASE + line_delta,
12538                                        "line %u", current_line);
12539                 }
12540               else
12541                 {
12542                   /* This can handle any delta.  This takes at least 4 bytes,
12543                      depending on the value being encoded.  */
12544                   dw2_asm_output_data (1, DW_LNS_advance_line,
12545                                        "advance to line %u", current_line);
12546                   dw2_asm_output_data_sleb128 (line_offset, NULL);
12547                   dw2_asm_output_data (1, DW_LNS_copy, NULL);
12548                 }
12549             }
12550           break;
12551
12552         case LI_set_file:
12553           dw2_asm_output_data (1, DW_LNS_set_file, "set file %u", ent->val);
12554           dw2_asm_output_data_uleb128 (ent->val, "%u", ent->val);
12555           break;
12556
12557         case LI_set_column:
12558           dw2_asm_output_data (1, DW_LNS_set_column, "column %u", ent->val);
12559           dw2_asm_output_data_uleb128 (ent->val, "%u", ent->val);
12560           break;
12561
12562         case LI_negate_stmt:
12563           current_is_stmt = !current_is_stmt;
12564           dw2_asm_output_data (1, DW_LNS_negate_stmt,
12565                                "is_stmt %d", current_is_stmt);
12566           break;
12567
12568         case LI_set_prologue_end:
12569           dw2_asm_output_data (1, DW_LNS_set_prologue_end,
12570                                "set prologue end");
12571           break;
12572           
12573         case LI_set_epilogue_begin:
12574           dw2_asm_output_data (1, DW_LNS_set_epilogue_begin,
12575                                "set epilogue begin");
12576           break;
12577
12578         case LI_set_discriminator:
12579           dw2_asm_output_data (1, 0, "discriminator %u", ent->val);
12580           dw2_asm_output_data_uleb128 (1 + size_of_uleb128 (ent->val), NULL);
12581           dw2_asm_output_data (1, DW_LNE_set_discriminator, NULL);
12582           dw2_asm_output_data_uleb128 (ent->val, NULL);
12583           break;
12584         }
12585     }
12586
12587   /* Emit debug info for the address of the end of the table.  */
12588   dw2_asm_output_data (1, 0, "set address %s", table->end_label);
12589   dw2_asm_output_data_uleb128 (1 + DWARF2_ADDR_SIZE, NULL);
12590   dw2_asm_output_data (1, DW_LNE_set_address, NULL);
12591   dw2_asm_output_addr (DWARF2_ADDR_SIZE, table->end_label, NULL);
12592
12593   dw2_asm_output_data (1, 0, "end sequence");
12594   dw2_asm_output_data_uleb128 (1, NULL);
12595   dw2_asm_output_data (1, DW_LNE_end_sequence, NULL);
12596 }
12597
12598 /* Output the source line number correspondence information.  This
12599    information goes into the .debug_line section.  */
12600
12601 static void
12602 output_line_info (bool prologue_only)
12603 {
12604   static unsigned int generation;
12605   char l1[MAX_ARTIFICIAL_LABEL_BYTES], l2[MAX_ARTIFICIAL_LABEL_BYTES];
12606   char p1[MAX_ARTIFICIAL_LABEL_BYTES], p2[MAX_ARTIFICIAL_LABEL_BYTES];
12607   bool saw_one = false;
12608   int opc;
12609
12610   ASM_GENERATE_INTERNAL_LABEL (l1, LINE_NUMBER_BEGIN_LABEL, generation);
12611   ASM_GENERATE_INTERNAL_LABEL (l2, LINE_NUMBER_END_LABEL, generation);
12612   ASM_GENERATE_INTERNAL_LABEL (p1, LN_PROLOG_AS_LABEL, generation);
12613   ASM_GENERATE_INTERNAL_LABEL (p2, LN_PROLOG_END_LABEL, generation++);
12614
12615   if (!XCOFF_DEBUGGING_INFO)
12616     {
12617       if (DWARF_INITIAL_LENGTH_SIZE - DWARF_OFFSET_SIZE == 4)
12618         dw2_asm_output_data (4, 0xffffffff,
12619           "Initial length escape value indicating 64-bit DWARF extension");
12620       dw2_asm_output_delta (DWARF_OFFSET_SIZE, l2, l1,
12621                             "Length of Source Line Info");
12622     }
12623
12624   ASM_OUTPUT_LABEL (asm_out_file, l1);
12625
12626   output_dwarf_version ();
12627   if (dwarf_version >= 5)
12628     {
12629       dw2_asm_output_data (1, DWARF2_ADDR_SIZE, "Address Size");
12630       dw2_asm_output_data (1, 0, "Segment Size");
12631     }
12632   dw2_asm_output_delta (DWARF_OFFSET_SIZE, p2, p1, "Prolog Length");
12633   ASM_OUTPUT_LABEL (asm_out_file, p1);
12634
12635   /* Define the architecture-dependent minimum instruction length (in bytes).
12636      In this implementation of DWARF, this field is used for information
12637      purposes only.  Since GCC generates assembly language, we have no
12638      a priori knowledge of how many instruction bytes are generated for each
12639      source line, and therefore can use only the DW_LNE_set_address and
12640      DW_LNS_fixed_advance_pc line information commands.  Accordingly, we fix
12641      this as '1', which is "correct enough" for all architectures,
12642      and don't let the target override.  */
12643   dw2_asm_output_data (1, 1, "Minimum Instruction Length");
12644
12645   if (dwarf_version >= 4)
12646     dw2_asm_output_data (1, DWARF_LINE_DEFAULT_MAX_OPS_PER_INSN,
12647                          "Maximum Operations Per Instruction");
12648   dw2_asm_output_data (1, DWARF_LINE_DEFAULT_IS_STMT_START,
12649                        "Default is_stmt_start flag");
12650   dw2_asm_output_data (1, DWARF_LINE_BASE,
12651                        "Line Base Value (Special Opcodes)");
12652   dw2_asm_output_data (1, DWARF_LINE_RANGE,
12653                        "Line Range Value (Special Opcodes)");
12654   dw2_asm_output_data (1, DWARF_LINE_OPCODE_BASE,
12655                        "Special Opcode Base");
12656
12657   for (opc = 1; opc < DWARF_LINE_OPCODE_BASE; opc++)
12658     {
12659       int n_op_args;
12660       switch (opc)
12661         {
12662         case DW_LNS_advance_pc:
12663         case DW_LNS_advance_line:
12664         case DW_LNS_set_file:
12665         case DW_LNS_set_column:
12666         case DW_LNS_fixed_advance_pc:
12667         case DW_LNS_set_isa:
12668           n_op_args = 1;
12669           break;
12670         default:
12671           n_op_args = 0;
12672           break;
12673         }
12674
12675       dw2_asm_output_data (1, n_op_args, "opcode: %#x has %d args",
12676                            opc, n_op_args);
12677     }
12678
12679   /* Write out the information about the files we use.  */
12680   output_file_names ();
12681   ASM_OUTPUT_LABEL (asm_out_file, p2);
12682   if (prologue_only)
12683     {
12684       /* Output the marker for the end of the line number info.  */
12685       ASM_OUTPUT_LABEL (asm_out_file, l2);
12686       return;
12687     }
12688
12689   if (separate_line_info)
12690     {
12691       dw_line_info_table *table;
12692       size_t i;
12693
12694       FOR_EACH_VEC_ELT (*separate_line_info, i, table)
12695         if (table->in_use)
12696           {
12697             output_one_line_info_table (table);
12698             saw_one = true;
12699           }
12700     }
12701   if (cold_text_section_line_info && cold_text_section_line_info->in_use)
12702     {
12703       output_one_line_info_table (cold_text_section_line_info);
12704       saw_one = true;
12705     }
12706
12707   /* ??? Some Darwin linkers crash on a .debug_line section with no
12708      sequences.  Further, merely a DW_LNE_end_sequence entry is not
12709      sufficient -- the address column must also be initialized.
12710      Make sure to output at least one set_address/end_sequence pair,
12711      choosing .text since that section is always present.  */
12712   if (text_section_line_info->in_use || !saw_one)
12713     output_one_line_info_table (text_section_line_info);
12714
12715   /* Output the marker for the end of the line number info.  */
12716   ASM_OUTPUT_LABEL (asm_out_file, l2);
12717 }
12718 \f
12719 /* Return true if DW_AT_endianity should be emitted according to REVERSE.  */
12720
12721 static inline bool
12722 need_endianity_attribute_p (bool reverse)
12723 {
12724   return reverse && (dwarf_version >= 3 || !dwarf_strict);
12725 }
12726
12727 /* Given a pointer to a tree node for some base type, return a pointer to
12728    a DIE that describes the given type.  REVERSE is true if the type is
12729    to be interpreted in the reverse storage order wrt the target order.
12730
12731    This routine must only be called for GCC type nodes that correspond to
12732    Dwarf base (fundamental) types.  */
12733
12734 static dw_die_ref
12735 base_type_die (tree type, bool reverse)
12736 {
12737   dw_die_ref base_type_result;
12738   enum dwarf_type encoding;
12739   bool fpt_used = false;
12740   struct fixed_point_type_info fpt_info;
12741   tree type_bias = NULL_TREE;
12742
12743   /* If this is a subtype that should not be emitted as a subrange type,
12744      use the base type.  See subrange_type_for_debug_p.  */
12745   if (TREE_CODE (type) == INTEGER_TYPE && TREE_TYPE (type) != NULL_TREE)
12746     type = TREE_TYPE (type);
12747
12748   switch (TREE_CODE (type))
12749     {
12750     case INTEGER_TYPE:
12751       if ((dwarf_version >= 4 || !dwarf_strict)
12752           && TYPE_NAME (type)
12753           && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
12754           && DECL_IS_BUILTIN (TYPE_NAME (type))
12755           && DECL_NAME (TYPE_NAME (type)))
12756         {
12757           const char *name = IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (type)));
12758           if (strcmp (name, "char16_t") == 0
12759               || strcmp (name, "char32_t") == 0)
12760             {
12761               encoding = DW_ATE_UTF;
12762               break;
12763             }
12764         }
12765       if ((dwarf_version >= 3 || !dwarf_strict)
12766           && lang_hooks.types.get_fixed_point_type_info)
12767         {
12768           memset (&fpt_info, 0, sizeof (fpt_info));
12769           if (lang_hooks.types.get_fixed_point_type_info (type, &fpt_info))
12770             {
12771               fpt_used = true;
12772               encoding = ((TYPE_UNSIGNED (type))
12773                           ? DW_ATE_unsigned_fixed
12774                           : DW_ATE_signed_fixed);
12775               break;
12776             }
12777         }
12778       if (TYPE_STRING_FLAG (type))
12779         {
12780           if (TYPE_UNSIGNED (type))
12781             encoding = DW_ATE_unsigned_char;
12782           else
12783             encoding = DW_ATE_signed_char;
12784         }
12785       else if (TYPE_UNSIGNED (type))
12786         encoding = DW_ATE_unsigned;
12787       else
12788         encoding = DW_ATE_signed;
12789
12790       if (!dwarf_strict
12791           && lang_hooks.types.get_type_bias)
12792         type_bias = lang_hooks.types.get_type_bias (type);
12793       break;
12794
12795     case REAL_TYPE:
12796       if (DECIMAL_FLOAT_MODE_P (TYPE_MODE (type)))
12797         {
12798           if (dwarf_version >= 3 || !dwarf_strict)
12799             encoding = DW_ATE_decimal_float;
12800           else
12801             encoding = DW_ATE_lo_user;
12802         }
12803       else
12804         encoding = DW_ATE_float;
12805       break;
12806
12807     case FIXED_POINT_TYPE:
12808       if (!(dwarf_version >= 3 || !dwarf_strict))
12809         encoding = DW_ATE_lo_user;
12810       else if (TYPE_UNSIGNED (type))
12811         encoding = DW_ATE_unsigned_fixed;
12812       else
12813         encoding = DW_ATE_signed_fixed;
12814       break;
12815
12816       /* Dwarf2 doesn't know anything about complex ints, so use
12817          a user defined type for it.  */
12818     case COMPLEX_TYPE:
12819       if (TREE_CODE (TREE_TYPE (type)) == REAL_TYPE)
12820         encoding = DW_ATE_complex_float;
12821       else
12822         encoding = DW_ATE_lo_user;
12823       break;
12824
12825     case BOOLEAN_TYPE:
12826       /* GNU FORTRAN/Ada/C++ BOOLEAN type.  */
12827       encoding = DW_ATE_boolean;
12828       break;
12829
12830     default:
12831       /* No other TREE_CODEs are Dwarf fundamental types.  */
12832       gcc_unreachable ();
12833     }
12834
12835   base_type_result = new_die_raw (DW_TAG_base_type);
12836
12837   add_AT_unsigned (base_type_result, DW_AT_byte_size,
12838                    int_size_in_bytes (type));
12839   add_AT_unsigned (base_type_result, DW_AT_encoding, encoding);
12840
12841   if (need_endianity_attribute_p (reverse))
12842     add_AT_unsigned (base_type_result, DW_AT_endianity,
12843                      BYTES_BIG_ENDIAN ? DW_END_little : DW_END_big);
12844
12845   add_alignment_attribute (base_type_result, type);
12846
12847   if (fpt_used)
12848     {
12849       switch (fpt_info.scale_factor_kind)
12850         {
12851         case fixed_point_scale_factor_binary:
12852           add_AT_int (base_type_result, DW_AT_binary_scale,
12853                       fpt_info.scale_factor.binary);
12854           break;
12855
12856         case fixed_point_scale_factor_decimal:
12857           add_AT_int (base_type_result, DW_AT_decimal_scale,
12858                       fpt_info.scale_factor.decimal);
12859           break;
12860
12861         case fixed_point_scale_factor_arbitrary:
12862           /* Arbitrary scale factors cannot be described in standard DWARF,
12863              yet.  */
12864           if (!dwarf_strict)
12865             {
12866               /* Describe the scale factor as a rational constant.  */
12867               const dw_die_ref scale_factor
12868                 = new_die (DW_TAG_constant, comp_unit_die (), type);
12869
12870               add_AT_unsigned (scale_factor, DW_AT_GNU_numerator,
12871                                fpt_info.scale_factor.arbitrary.numerator);
12872               add_AT_int (scale_factor, DW_AT_GNU_denominator,
12873                           fpt_info.scale_factor.arbitrary.denominator);
12874
12875               add_AT_die_ref (base_type_result, DW_AT_small, scale_factor);
12876             }
12877           break;
12878
12879         default:
12880           gcc_unreachable ();
12881         }
12882     }
12883
12884   if (type_bias)
12885     add_scalar_info (base_type_result, DW_AT_GNU_bias, type_bias,
12886                      dw_scalar_form_constant
12887                      | dw_scalar_form_exprloc
12888                      | dw_scalar_form_reference,
12889                      NULL);
12890
12891   return base_type_result;
12892 }
12893
12894 /* A C++ function with deduced return type can have a TEMPLATE_TYPE_PARM
12895    named 'auto' in its type: return true for it, false otherwise.  */
12896
12897 static inline bool
12898 is_cxx_auto (tree type)
12899 {
12900   if (is_cxx ())
12901     {
12902       tree name = TYPE_IDENTIFIER (type);
12903       if (name == get_identifier ("auto")
12904           || name == get_identifier ("decltype(auto)"))
12905         return true;
12906     }
12907   return false;
12908 }
12909
12910 /* Given a pointer to an arbitrary ..._TYPE tree node, return nonzero if the
12911    given input type is a Dwarf "fundamental" type.  Otherwise return null.  */
12912
12913 static inline int
12914 is_base_type (tree type)
12915 {
12916   switch (TREE_CODE (type))
12917     {
12918     case INTEGER_TYPE:
12919     case REAL_TYPE:
12920     case FIXED_POINT_TYPE:
12921     case COMPLEX_TYPE:
12922     case BOOLEAN_TYPE:
12923     case POINTER_BOUNDS_TYPE:
12924       return 1;
12925
12926     case VOID_TYPE:
12927     case ARRAY_TYPE:
12928     case RECORD_TYPE:
12929     case UNION_TYPE:
12930     case QUAL_UNION_TYPE:
12931     case ENUMERAL_TYPE:
12932     case FUNCTION_TYPE:
12933     case METHOD_TYPE:
12934     case POINTER_TYPE:
12935     case REFERENCE_TYPE:
12936     case NULLPTR_TYPE:
12937     case OFFSET_TYPE:
12938     case LANG_TYPE:
12939     case VECTOR_TYPE:
12940       return 0;
12941
12942     default:
12943       if (is_cxx_auto (type))
12944         return 0;
12945       gcc_unreachable ();
12946     }
12947
12948   return 0;
12949 }
12950
12951 /* Given a pointer to a tree node, assumed to be some kind of a ..._TYPE
12952    node, return the size in bits for the type if it is a constant, or else
12953    return the alignment for the type if the type's size is not constant, or
12954    else return BITS_PER_WORD if the type actually turns out to be an
12955    ERROR_MARK node.  */
12956
12957 static inline unsigned HOST_WIDE_INT
12958 simple_type_size_in_bits (const_tree type)
12959 {
12960   if (TREE_CODE (type) == ERROR_MARK)
12961     return BITS_PER_WORD;
12962   else if (TYPE_SIZE (type) == NULL_TREE)
12963     return 0;
12964   else if (tree_fits_uhwi_p (TYPE_SIZE (type)))
12965     return tree_to_uhwi (TYPE_SIZE (type));
12966   else
12967     return TYPE_ALIGN (type);
12968 }
12969
12970 /* Similarly, but return an offset_int instead of UHWI.  */
12971
12972 static inline offset_int
12973 offset_int_type_size_in_bits (const_tree type)
12974 {
12975   if (TREE_CODE (type) == ERROR_MARK)
12976     return BITS_PER_WORD;
12977   else if (TYPE_SIZE (type) == NULL_TREE)
12978     return 0;
12979   else if (TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST)
12980     return wi::to_offset (TYPE_SIZE (type));
12981   else
12982     return TYPE_ALIGN (type);
12983 }
12984
12985 /*  Given a pointer to a tree node for a subrange type, return a pointer
12986     to a DIE that describes the given type.  */
12987
12988 static dw_die_ref
12989 subrange_type_die (tree type, tree low, tree high, tree bias,
12990                    dw_die_ref context_die)
12991 {
12992   dw_die_ref subrange_die;
12993   const HOST_WIDE_INT size_in_bytes = int_size_in_bytes (type);
12994
12995   if (context_die == NULL)
12996     context_die = comp_unit_die ();
12997
12998   subrange_die = new_die (DW_TAG_subrange_type, context_die, type);
12999
13000   if (int_size_in_bytes (TREE_TYPE (type)) != size_in_bytes)
13001     {
13002       /* The size of the subrange type and its base type do not match,
13003          so we need to generate a size attribute for the subrange type.  */
13004       add_AT_unsigned (subrange_die, DW_AT_byte_size, size_in_bytes);
13005     }
13006
13007   add_alignment_attribute (subrange_die, type);
13008
13009   if (low)
13010     add_bound_info (subrange_die, DW_AT_lower_bound, low, NULL);
13011   if (high)
13012     add_bound_info (subrange_die, DW_AT_upper_bound, high, NULL);
13013   if (bias && !dwarf_strict)
13014     add_scalar_info (subrange_die, DW_AT_GNU_bias, bias,
13015                      dw_scalar_form_constant
13016                      | dw_scalar_form_exprloc
13017                      | dw_scalar_form_reference,
13018                      NULL);
13019
13020   return subrange_die;
13021 }
13022
13023 /* Returns the (const and/or volatile) cv_qualifiers associated with
13024    the decl node.  This will normally be augmented with the
13025    cv_qualifiers of the underlying type in add_type_attribute.  */
13026
13027 static int
13028 decl_quals (const_tree decl)
13029 {
13030   return ((TREE_READONLY (decl)
13031            /* The C++ front-end correctly marks reference-typed
13032               variables as readonly, but from a language (and debug
13033               info) standpoint they are not const-qualified.  */
13034            && TREE_CODE (TREE_TYPE (decl)) != REFERENCE_TYPE
13035            ? TYPE_QUAL_CONST : TYPE_UNQUALIFIED)
13036           | (TREE_THIS_VOLATILE (decl)
13037              ? TYPE_QUAL_VOLATILE : TYPE_UNQUALIFIED));
13038 }
13039
13040 /* Determine the TYPE whose qualifiers match the largest strict subset
13041    of the given TYPE_QUALS, and return its qualifiers.  Ignore all
13042    qualifiers outside QUAL_MASK.  */
13043
13044 static int
13045 get_nearest_type_subqualifiers (tree type, int type_quals, int qual_mask)
13046 {
13047   tree t;
13048   int best_rank = 0, best_qual = 0, max_rank;
13049
13050   type_quals &= qual_mask;
13051   max_rank = popcount_hwi (type_quals) - 1;
13052
13053   for (t = TYPE_MAIN_VARIANT (type); t && best_rank < max_rank;
13054        t = TYPE_NEXT_VARIANT (t))
13055     {
13056       int q = TYPE_QUALS (t) & qual_mask;
13057
13058       if ((q & type_quals) == q && q != type_quals
13059           && check_base_type (t, type))
13060         {
13061           int rank = popcount_hwi (q);
13062
13063           if (rank > best_rank)
13064             {
13065               best_rank = rank;
13066               best_qual = q;
13067             }
13068         }
13069     }
13070
13071   return best_qual;
13072 }
13073
13074 struct dwarf_qual_info_t { int q; enum dwarf_tag t; };
13075 static const dwarf_qual_info_t dwarf_qual_info[] =
13076 {
13077   { TYPE_QUAL_CONST, DW_TAG_const_type },
13078   { TYPE_QUAL_VOLATILE, DW_TAG_volatile_type },
13079   { TYPE_QUAL_RESTRICT, DW_TAG_restrict_type },
13080   { TYPE_QUAL_ATOMIC, DW_TAG_atomic_type }
13081 };
13082 static const unsigned int dwarf_qual_info_size
13083   = sizeof (dwarf_qual_info) / sizeof (dwarf_qual_info[0]);
13084
13085 /* If DIE is a qualified DIE of some base DIE with the same parent,
13086    return the base DIE, otherwise return NULL.  Set MASK to the
13087    qualifiers added compared to the returned DIE.  */
13088
13089 static dw_die_ref
13090 qualified_die_p (dw_die_ref die, int *mask, unsigned int depth)
13091 {
13092   unsigned int i;
13093   for (i = 0; i < dwarf_qual_info_size; i++)
13094     if (die->die_tag == dwarf_qual_info[i].t)
13095       break;
13096   if (i == dwarf_qual_info_size)
13097     return NULL;
13098   if (vec_safe_length (die->die_attr) != 1)
13099     return NULL;
13100   dw_die_ref type = get_AT_ref (die, DW_AT_type);
13101   if (type == NULL || type->die_parent != die->die_parent)
13102     return NULL;
13103   *mask |= dwarf_qual_info[i].q;
13104   if (depth)
13105     {
13106       dw_die_ref ret = qualified_die_p (type, mask, depth - 1);
13107       if (ret)
13108         return ret;
13109     }
13110   return type;
13111 }
13112
13113 /* Given a pointer to an arbitrary ..._TYPE tree node, return a debugging
13114    entry that chains the modifiers specified by CV_QUALS in front of the
13115    given type.  REVERSE is true if the type is to be interpreted in the
13116    reverse storage order wrt the target order.  */
13117
13118 static dw_die_ref
13119 modified_type_die (tree type, int cv_quals, bool reverse,
13120                    dw_die_ref context_die)
13121 {
13122   enum tree_code code = TREE_CODE (type);
13123   dw_die_ref mod_type_die;
13124   dw_die_ref sub_die = NULL;
13125   tree item_type = NULL;
13126   tree qualified_type;
13127   tree name, low, high;
13128   dw_die_ref mod_scope;
13129   /* Only these cv-qualifiers are currently handled.  */
13130   const int cv_qual_mask = (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE
13131                             | TYPE_QUAL_RESTRICT | TYPE_QUAL_ATOMIC | 
13132                             ENCODE_QUAL_ADDR_SPACE(~0U));
13133   const bool reverse_base_type
13134     = need_endianity_attribute_p (reverse) && is_base_type (type);
13135
13136   if (code == ERROR_MARK)
13137     return NULL;
13138
13139   if (lang_hooks.types.get_debug_type)
13140     {
13141       tree debug_type = lang_hooks.types.get_debug_type (type);
13142
13143       if (debug_type != NULL_TREE && debug_type != type)
13144         return modified_type_die (debug_type, cv_quals, reverse, context_die);
13145     }
13146
13147   cv_quals &= cv_qual_mask;
13148
13149   /* Don't emit DW_TAG_restrict_type for DWARFv2, since it is a type
13150      tag modifier (and not an attribute) old consumers won't be able
13151      to handle it.  */
13152   if (dwarf_version < 3)
13153     cv_quals &= ~TYPE_QUAL_RESTRICT;
13154
13155   /* Likewise for DW_TAG_atomic_type for DWARFv5.  */
13156   if (dwarf_version < 5)
13157     cv_quals &= ~TYPE_QUAL_ATOMIC;
13158
13159   /* See if we already have the appropriately qualified variant of
13160      this type.  */
13161   qualified_type = get_qualified_type (type, cv_quals);
13162
13163   if (qualified_type == sizetype)
13164     {
13165       /* Try not to expose the internal sizetype type's name.  */
13166       if (TYPE_NAME (qualified_type)
13167           && TREE_CODE (TYPE_NAME (qualified_type)) == TYPE_DECL)
13168         {
13169           tree t = TREE_TYPE (TYPE_NAME (qualified_type));
13170
13171           gcc_checking_assert (TREE_CODE (t) == INTEGER_TYPE
13172                                && (TYPE_PRECISION (t)
13173                                    == TYPE_PRECISION (qualified_type))
13174                                && (TYPE_UNSIGNED (t)
13175                                    == TYPE_UNSIGNED (qualified_type)));
13176           qualified_type = t;
13177         }
13178       else if (qualified_type == sizetype
13179                && TREE_CODE (sizetype) == TREE_CODE (size_type_node)
13180                && TYPE_PRECISION (sizetype) == TYPE_PRECISION (size_type_node)
13181                && TYPE_UNSIGNED (sizetype) == TYPE_UNSIGNED (size_type_node))
13182         qualified_type = size_type_node;
13183       if (type == sizetype)
13184         type = qualified_type;
13185     }
13186
13187   /* If we do, then we can just use its DIE, if it exists.  */
13188   if (qualified_type)
13189     {
13190       mod_type_die = lookup_type_die (qualified_type);
13191
13192       /* DW_AT_endianity doesn't come from a qualifier on the type, so it is
13193          dealt with specially: the DIE with the attribute, if it exists, is
13194          placed immediately after the regular DIE for the same base type.  */
13195       if (mod_type_die
13196           && (!reverse_base_type
13197               || ((mod_type_die = mod_type_die->die_sib) != NULL
13198                   && get_AT_unsigned (mod_type_die, DW_AT_endianity))))
13199         return mod_type_die;
13200     }
13201
13202   name = qualified_type ? TYPE_NAME (qualified_type) : NULL;
13203
13204   /* Handle C typedef types.  */
13205   if (name
13206       && TREE_CODE (name) == TYPE_DECL
13207       && DECL_ORIGINAL_TYPE (name)
13208       && !DECL_ARTIFICIAL (name))
13209     {
13210       tree dtype = TREE_TYPE (name);
13211
13212       /* Skip the typedef for base types with DW_AT_endianity, no big deal.  */
13213       if (qualified_type == dtype && !reverse_base_type)
13214         {
13215           tree origin = decl_ultimate_origin (name);
13216
13217           /* Typedef variants that have an abstract origin don't get their own
13218              type DIE (see gen_typedef_die), so fall back on the ultimate
13219              abstract origin instead.  */
13220           if (origin != NULL && origin != name)
13221             return modified_type_die (TREE_TYPE (origin), cv_quals, reverse,
13222                                       context_die);
13223
13224           /* For a named type, use the typedef.  */
13225           gen_type_die (qualified_type, context_die);
13226           return lookup_type_die (qualified_type);
13227         }
13228       else
13229         {
13230           int dquals = TYPE_QUALS_NO_ADDR_SPACE (dtype);
13231           dquals &= cv_qual_mask;
13232           if ((dquals & ~cv_quals) != TYPE_UNQUALIFIED
13233               || (cv_quals == dquals && DECL_ORIGINAL_TYPE (name) != type))
13234             /* cv-unqualified version of named type.  Just use
13235                the unnamed type to which it refers.  */
13236             return modified_type_die (DECL_ORIGINAL_TYPE (name), cv_quals,
13237                                       reverse, context_die);
13238           /* Else cv-qualified version of named type; fall through.  */
13239         }
13240     }
13241
13242   mod_scope = scope_die_for (type, context_die);
13243
13244   if (cv_quals)
13245     {
13246       int sub_quals = 0, first_quals = 0;
13247       unsigned i;
13248       dw_die_ref first = NULL, last = NULL;
13249
13250       /* Determine a lesser qualified type that most closely matches
13251          this one.  Then generate DW_TAG_* entries for the remaining
13252          qualifiers.  */
13253       sub_quals = get_nearest_type_subqualifiers (type, cv_quals,
13254                                                   cv_qual_mask);
13255       if (sub_quals && use_debug_types)
13256         {
13257           bool needed = false;
13258           /* If emitting type units, make sure the order of qualifiers
13259              is canonical.  Thus, start from unqualified type if
13260              an earlier qualifier is missing in sub_quals, but some later
13261              one is present there.  */
13262           for (i = 0; i < dwarf_qual_info_size; i++)
13263             if (dwarf_qual_info[i].q & cv_quals & ~sub_quals)
13264               needed = true;
13265             else if (needed && (dwarf_qual_info[i].q & cv_quals))
13266               {
13267                 sub_quals = 0;
13268                 break;
13269               }
13270         }
13271       mod_type_die = modified_type_die (type, sub_quals, reverse, context_die);
13272       if (mod_scope && mod_type_die && mod_type_die->die_parent == mod_scope)
13273         {
13274           /* As not all intermediate qualified DIEs have corresponding
13275              tree types, ensure that qualified DIEs in the same scope
13276              as their DW_AT_type are emitted after their DW_AT_type,
13277              only with other qualified DIEs for the same type possibly
13278              in between them.  Determine the range of such qualified
13279              DIEs now (first being the base type, last being corresponding
13280              last qualified DIE for it).  */
13281           unsigned int count = 0;
13282           first = qualified_die_p (mod_type_die, &first_quals,
13283                                    dwarf_qual_info_size);
13284           if (first == NULL)
13285             first = mod_type_die;
13286           gcc_assert ((first_quals & ~sub_quals) == 0);
13287           for (count = 0, last = first;
13288                count < (1U << dwarf_qual_info_size);
13289                count++, last = last->die_sib)
13290             {
13291               int quals = 0;
13292               if (last == mod_scope->die_child)
13293                 break;
13294               if (qualified_die_p (last->die_sib, &quals, dwarf_qual_info_size)
13295                   != first)
13296                 break;
13297             }
13298         }
13299
13300       for (i = 0; i < dwarf_qual_info_size; i++)
13301         if (dwarf_qual_info[i].q & cv_quals & ~sub_quals)
13302           {
13303             dw_die_ref d;
13304             if (first && first != last)
13305               {
13306                 for (d = first->die_sib; ; d = d->die_sib)
13307                   {
13308                     int quals = 0;
13309                     qualified_die_p (d, &quals, dwarf_qual_info_size);
13310                     if (quals == (first_quals | dwarf_qual_info[i].q))
13311                       break;
13312                     if (d == last)
13313                       {
13314                         d = NULL;
13315                         break;
13316                       }
13317                   }
13318                 if (d)
13319                   {
13320                     mod_type_die = d;
13321                     continue;
13322                   }
13323               }
13324             if (first)
13325               {
13326                 d = new_die_raw (dwarf_qual_info[i].t);
13327                 add_child_die_after (mod_scope, d, last);
13328                 last = d;
13329               }
13330             else
13331               d = new_die (dwarf_qual_info[i].t, mod_scope, type);
13332             if (mod_type_die)
13333               add_AT_die_ref (d, DW_AT_type, mod_type_die);
13334             mod_type_die = d;
13335             first_quals |= dwarf_qual_info[i].q;
13336           }
13337     }
13338   else if (code == POINTER_TYPE || code == REFERENCE_TYPE)
13339     {
13340       dwarf_tag tag = DW_TAG_pointer_type;
13341       if (code == REFERENCE_TYPE)
13342         {
13343           if (TYPE_REF_IS_RVALUE (type) && dwarf_version >= 4)
13344             tag = DW_TAG_rvalue_reference_type;
13345           else
13346             tag = DW_TAG_reference_type;
13347         }
13348       mod_type_die = new_die (tag, mod_scope, type);
13349
13350       add_AT_unsigned (mod_type_die, DW_AT_byte_size,
13351                        simple_type_size_in_bits (type) / BITS_PER_UNIT);
13352       add_alignment_attribute (mod_type_die, type);
13353       item_type = TREE_TYPE (type);
13354
13355       addr_space_t as = TYPE_ADDR_SPACE (item_type);
13356       if (!ADDR_SPACE_GENERIC_P (as))
13357         {
13358           int action = targetm.addr_space.debug (as);
13359           if (action >= 0)
13360             {
13361               /* Positive values indicate an address_class.  */
13362               add_AT_unsigned (mod_type_die, DW_AT_address_class, action);
13363             }
13364           else
13365             {
13366               /* Negative values indicate an (inverted) segment base reg.  */
13367               dw_loc_descr_ref d
13368                 = one_reg_loc_descriptor (~action, VAR_INIT_STATUS_INITIALIZED);
13369               add_AT_loc (mod_type_die, DW_AT_segment, d);
13370             }
13371         }
13372     }
13373   else if (code == INTEGER_TYPE
13374            && TREE_TYPE (type) != NULL_TREE
13375            && subrange_type_for_debug_p (type, &low, &high))
13376     {
13377       tree bias = NULL_TREE;
13378       if (lang_hooks.types.get_type_bias)
13379         bias = lang_hooks.types.get_type_bias (type);
13380       mod_type_die = subrange_type_die (type, low, high, bias, context_die);
13381       item_type = TREE_TYPE (type);
13382     }
13383   else if (is_base_type (type))
13384     {
13385       mod_type_die = base_type_die (type, reverse);
13386
13387       /* The DIE with DW_AT_endianity is placed right after the naked DIE.  */
13388       if (reverse_base_type)
13389         {
13390           dw_die_ref after_die
13391             = modified_type_die (type, cv_quals, false, context_die);
13392           add_child_die_after (comp_unit_die (), mod_type_die, after_die);
13393         }
13394       else
13395         add_child_die (comp_unit_die (), mod_type_die);
13396
13397       add_pubtype (type, mod_type_die);
13398     }
13399   else
13400     {
13401       gen_type_die (type, context_die);
13402
13403       /* We have to get the type_main_variant here (and pass that to the
13404          `lookup_type_die' routine) because the ..._TYPE node we have
13405          might simply be a *copy* of some original type node (where the
13406          copy was created to help us keep track of typedef names) and
13407          that copy might have a different TYPE_UID from the original
13408          ..._TYPE node.  */
13409       if (TREE_CODE (type) == FUNCTION_TYPE
13410           || TREE_CODE (type) == METHOD_TYPE)
13411         {
13412           /* For function/method types, can't just use type_main_variant here,
13413              because that can have different ref-qualifiers for C++,
13414              but try to canonicalize.  */
13415           tree main = TYPE_MAIN_VARIANT (type);
13416           for (tree t = main; t; t = TYPE_NEXT_VARIANT (t))
13417             if (TYPE_QUALS_NO_ADDR_SPACE (t) == 0
13418                 && check_base_type (t, main)
13419                 && check_lang_type (t, type))
13420               return lookup_type_die (t);
13421           return lookup_type_die (type);
13422         }
13423       else if (TREE_CODE (type) != VECTOR_TYPE
13424                && TREE_CODE (type) != ARRAY_TYPE)
13425         return lookup_type_die (type_main_variant (type));
13426       else
13427         /* Vectors have the debugging information in the type,
13428            not the main variant.  */
13429         return lookup_type_die (type);
13430     }
13431
13432   /* Builtin types don't have a DECL_ORIGINAL_TYPE.  For those,
13433      don't output a DW_TAG_typedef, since there isn't one in the
13434      user's program; just attach a DW_AT_name to the type.
13435      Don't attach a DW_AT_name to DW_TAG_const_type or DW_TAG_volatile_type
13436      if the base type already has the same name.  */
13437   if (name
13438       && ((TREE_CODE (name) != TYPE_DECL
13439            && (qualified_type == TYPE_MAIN_VARIANT (type)
13440                || (cv_quals == TYPE_UNQUALIFIED)))
13441           || (TREE_CODE (name) == TYPE_DECL
13442               && TREE_TYPE (name) == qualified_type
13443               && DECL_NAME (name))))
13444     {
13445       if (TREE_CODE (name) == TYPE_DECL)
13446         /* Could just call add_name_and_src_coords_attributes here,
13447            but since this is a builtin type it doesn't have any
13448            useful source coordinates anyway.  */
13449         name = DECL_NAME (name);
13450       add_name_attribute (mod_type_die, IDENTIFIER_POINTER (name));
13451     }
13452   /* This probably indicates a bug.  */
13453   else if (mod_type_die && mod_type_die->die_tag == DW_TAG_base_type)
13454     {
13455       name = TYPE_IDENTIFIER (type);
13456       add_name_attribute (mod_type_die,
13457                           name ? IDENTIFIER_POINTER (name) : "__unknown__");
13458     }
13459
13460   if (qualified_type && !reverse_base_type)
13461     equate_type_number_to_die (qualified_type, mod_type_die);
13462
13463   if (item_type)
13464     /* We must do this after the equate_type_number_to_die call, in case
13465        this is a recursive type.  This ensures that the modified_type_die
13466        recursion will terminate even if the type is recursive.  Recursive
13467        types are possible in Ada.  */
13468     sub_die = modified_type_die (item_type,
13469                                  TYPE_QUALS_NO_ADDR_SPACE (item_type),
13470                                  reverse,
13471                                  context_die);
13472
13473   if (sub_die != NULL)
13474     add_AT_die_ref (mod_type_die, DW_AT_type, sub_die);
13475
13476   add_gnat_descriptive_type_attribute (mod_type_die, type, context_die);
13477   if (TYPE_ARTIFICIAL (type))
13478     add_AT_flag (mod_type_die, DW_AT_artificial, 1);
13479
13480   return mod_type_die;
13481 }
13482
13483 /* Generate DIEs for the generic parameters of T.
13484    T must be either a generic type or a generic function.
13485    See http://gcc.gnu.org/wiki/TemplateParmsDwarf for more.  */
13486
13487 static void
13488 gen_generic_params_dies (tree t)
13489 {
13490   tree parms, args;
13491   int parms_num, i;
13492   dw_die_ref die = NULL;
13493   int non_default;
13494
13495   if (!t || (TYPE_P (t) && !COMPLETE_TYPE_P (t)))
13496     return;
13497
13498   if (TYPE_P (t))
13499     die = lookup_type_die (t);
13500   else if (DECL_P (t))
13501     die = lookup_decl_die (t);
13502
13503   gcc_assert (die);
13504
13505   parms = lang_hooks.get_innermost_generic_parms (t);
13506   if (!parms)
13507     /* T has no generic parameter. It means T is neither a generic type
13508        or function. End of story.  */
13509     return;
13510
13511   parms_num = TREE_VEC_LENGTH (parms);
13512   args = lang_hooks.get_innermost_generic_args (t);
13513   if (TREE_CHAIN (args) && TREE_CODE (TREE_CHAIN (args)) == INTEGER_CST)
13514     non_default = int_cst_value (TREE_CHAIN (args));
13515   else
13516     non_default = TREE_VEC_LENGTH (args);
13517   for (i = 0; i < parms_num; i++)
13518     {
13519       tree parm, arg, arg_pack_elems;
13520       dw_die_ref parm_die;
13521
13522       parm = TREE_VEC_ELT (parms, i);
13523       arg = TREE_VEC_ELT (args, i);
13524       arg_pack_elems = lang_hooks.types.get_argument_pack_elems (arg);
13525       gcc_assert (parm && TREE_VALUE (parm) && arg);
13526
13527       if (parm && TREE_VALUE (parm) && arg)
13528         {
13529           /* If PARM represents a template parameter pack,
13530              emit a DW_TAG_GNU_template_parameter_pack DIE, followed
13531              by DW_TAG_template_*_parameter DIEs for the argument
13532              pack elements of ARG. Note that ARG would then be
13533              an argument pack.  */
13534           if (arg_pack_elems)
13535             parm_die = template_parameter_pack_die (TREE_VALUE (parm),
13536                                                     arg_pack_elems,
13537                                                     die);
13538           else
13539             parm_die = generic_parameter_die (TREE_VALUE (parm), arg,
13540                                               true /* emit name */, die);
13541           if (i >= non_default)
13542             add_AT_flag (parm_die, DW_AT_default_value, 1);
13543         }
13544     }
13545 }
13546
13547 /* Create and return a DIE for PARM which should be
13548    the representation of a generic type parameter.
13549    For instance, in the C++ front end, PARM would be a template parameter.
13550    ARG is the argument to PARM.
13551    EMIT_NAME_P if tree, the DIE will have DW_AT_name attribute set to the
13552    name of the PARM.
13553    PARENT_DIE is the parent DIE which the new created DIE should be added to,
13554    as a child node.  */
13555
13556 static dw_die_ref
13557 generic_parameter_die (tree parm, tree arg,
13558                        bool emit_name_p,
13559                        dw_die_ref parent_die)
13560 {
13561   dw_die_ref tmpl_die = NULL;
13562   const char *name = NULL;
13563
13564   if (!parm || !DECL_NAME (parm) || !arg)
13565     return NULL;
13566
13567   /* We support non-type generic parameters and arguments,
13568      type generic parameters and arguments, as well as
13569      generic generic parameters (a.k.a. template template parameters in C++)
13570      and arguments.  */
13571   if (TREE_CODE (parm) == PARM_DECL)
13572     /* PARM is a nontype generic parameter  */
13573     tmpl_die = new_die (DW_TAG_template_value_param, parent_die, parm);
13574   else if (TREE_CODE (parm) == TYPE_DECL)
13575     /* PARM is a type generic parameter.  */
13576     tmpl_die = new_die (DW_TAG_template_type_param, parent_die, parm);
13577   else if (lang_hooks.decls.generic_generic_parameter_decl_p (parm))
13578     /* PARM is a generic generic parameter.
13579        Its DIE is a GNU extension. It shall have a
13580        DW_AT_name attribute to represent the name of the template template
13581        parameter, and a DW_AT_GNU_template_name attribute to represent the
13582        name of the template template argument.  */
13583     tmpl_die = new_die (DW_TAG_GNU_template_template_param,
13584                         parent_die, parm);
13585   else
13586     gcc_unreachable ();
13587
13588   if (tmpl_die)
13589     {
13590       tree tmpl_type;
13591
13592       /* If PARM is a generic parameter pack, it means we are
13593          emitting debug info for a template argument pack element.
13594          In other terms, ARG is a template argument pack element.
13595          In that case, we don't emit any DW_AT_name attribute for
13596          the die.  */
13597       if (emit_name_p)
13598         {
13599           name = IDENTIFIER_POINTER (DECL_NAME (parm));
13600           gcc_assert (name);
13601           add_AT_string (tmpl_die, DW_AT_name, name);
13602         }
13603
13604       if (!lang_hooks.decls.generic_generic_parameter_decl_p (parm))
13605         {
13606           /* DWARF3, 5.6.8 says if PARM is a non-type generic parameter
13607              TMPL_DIE should have a child DW_AT_type attribute that is set
13608              to the type of the argument to PARM, which is ARG.
13609              If PARM is a type generic parameter, TMPL_DIE should have a
13610              child DW_AT_type that is set to ARG.  */
13611           tmpl_type = TYPE_P (arg) ? arg : TREE_TYPE (arg);
13612           add_type_attribute (tmpl_die, tmpl_type,
13613                               (TREE_THIS_VOLATILE (tmpl_type)
13614                                ? TYPE_QUAL_VOLATILE : TYPE_UNQUALIFIED),
13615                               false, parent_die);
13616         }
13617       else
13618         {
13619           /* So TMPL_DIE is a DIE representing a
13620              a generic generic template parameter, a.k.a template template
13621              parameter in C++ and arg is a template.  */
13622
13623           /* The DW_AT_GNU_template_name attribute of the DIE must be set
13624              to the name of the argument.  */
13625           name = dwarf2_name (TYPE_P (arg) ? TYPE_NAME (arg) : arg, 1);
13626           if (name)
13627             add_AT_string (tmpl_die, DW_AT_GNU_template_name, name);
13628         }
13629
13630       if (TREE_CODE (parm) == PARM_DECL)
13631         /* So PARM is a non-type generic parameter.
13632            DWARF3 5.6.8 says we must set a DW_AT_const_value child
13633            attribute of TMPL_DIE which value represents the value
13634            of ARG.
13635            We must be careful here:
13636            The value of ARG might reference some function decls.
13637            We might currently be emitting debug info for a generic
13638            type and types are emitted before function decls, we don't
13639            know if the function decls referenced by ARG will actually be
13640            emitted after cgraph computations.
13641            So must defer the generation of the DW_AT_const_value to
13642            after cgraph is ready.  */
13643         append_entry_to_tmpl_value_parm_die_table (tmpl_die, arg);
13644     }
13645
13646   return tmpl_die;
13647 }
13648
13649 /* Generate and return a  DW_TAG_GNU_template_parameter_pack DIE representing.
13650    PARM_PACK must be a template parameter pack. The returned DIE
13651    will be child DIE of PARENT_DIE.  */
13652
13653 static dw_die_ref
13654 template_parameter_pack_die (tree parm_pack,
13655                              tree parm_pack_args,
13656                              dw_die_ref parent_die)
13657 {
13658   dw_die_ref die;
13659   int j;
13660
13661   gcc_assert (parent_die && parm_pack);
13662
13663   die = new_die (DW_TAG_GNU_template_parameter_pack, parent_die, parm_pack);
13664   add_name_and_src_coords_attributes (die, parm_pack);
13665   for (j = 0; j < TREE_VEC_LENGTH (parm_pack_args); j++)
13666     generic_parameter_die (parm_pack,
13667                            TREE_VEC_ELT (parm_pack_args, j),
13668                            false /* Don't emit DW_AT_name */,
13669                            die);
13670   return die;
13671 }
13672
13673 /* Given a pointer to an arbitrary ..._TYPE tree node, return true if it is
13674    an enumerated type.  */
13675
13676 static inline int
13677 type_is_enum (const_tree type)
13678 {
13679   return TREE_CODE (type) == ENUMERAL_TYPE;
13680 }
13681
13682 /* Return the DBX register number described by a given RTL node.  */
13683
13684 static unsigned int
13685 dbx_reg_number (const_rtx rtl)
13686 {
13687   unsigned regno = REGNO (rtl);
13688
13689   gcc_assert (regno < FIRST_PSEUDO_REGISTER);
13690
13691 #ifdef LEAF_REG_REMAP
13692   if (crtl->uses_only_leaf_regs)
13693     {
13694       int leaf_reg = LEAF_REG_REMAP (regno);
13695       if (leaf_reg != -1)
13696         regno = (unsigned) leaf_reg;
13697     }
13698 #endif
13699
13700   regno = DBX_REGISTER_NUMBER (regno);
13701   gcc_assert (regno != INVALID_REGNUM);
13702   return regno;
13703 }
13704
13705 /* Optionally add a DW_OP_piece term to a location description expression.
13706    DW_OP_piece is only added if the location description expression already
13707    doesn't end with DW_OP_piece.  */
13708
13709 static void
13710 add_loc_descr_op_piece (dw_loc_descr_ref *list_head, int size)
13711 {
13712   dw_loc_descr_ref loc;
13713
13714   if (*list_head != NULL)
13715     {
13716       /* Find the end of the chain.  */
13717       for (loc = *list_head; loc->dw_loc_next != NULL; loc = loc->dw_loc_next)
13718         ;
13719
13720       if (loc->dw_loc_opc != DW_OP_piece)
13721         loc->dw_loc_next = new_loc_descr (DW_OP_piece, size, 0);
13722     }
13723 }
13724
13725 /* Return a location descriptor that designates a machine register or
13726    zero if there is none.  */
13727
13728 static dw_loc_descr_ref
13729 reg_loc_descriptor (rtx rtl, enum var_init_status initialized)
13730 {
13731   rtx regs;
13732
13733   if (REGNO (rtl) >= FIRST_PSEUDO_REGISTER)
13734     return 0;
13735
13736   /* We only use "frame base" when we're sure we're talking about the
13737      post-prologue local stack frame.  We do this by *not* running
13738      register elimination until this point, and recognizing the special
13739      argument pointer and soft frame pointer rtx's.
13740      Use DW_OP_fbreg offset DW_OP_stack_value in this case.  */
13741   if ((rtl == arg_pointer_rtx || rtl == frame_pointer_rtx)
13742       && eliminate_regs (rtl, VOIDmode, NULL_RTX) != rtl)
13743     {
13744       dw_loc_descr_ref result = NULL;
13745
13746       if (dwarf_version >= 4 || !dwarf_strict)
13747         {
13748           result = mem_loc_descriptor (rtl, GET_MODE (rtl), VOIDmode,
13749                                        initialized);
13750           if (result)
13751             add_loc_descr (&result,
13752                            new_loc_descr (DW_OP_stack_value, 0, 0));
13753         }
13754       return result;
13755     }
13756
13757   regs = targetm.dwarf_register_span (rtl);
13758
13759   if (REG_NREGS (rtl) > 1 || regs)
13760     return multiple_reg_loc_descriptor (rtl, regs, initialized);
13761   else
13762     {
13763       unsigned int dbx_regnum = dbx_reg_number (rtl);
13764       if (dbx_regnum == IGNORED_DWARF_REGNUM)
13765         return 0;
13766       return one_reg_loc_descriptor (dbx_regnum, initialized);
13767     }
13768 }
13769
13770 /* Return a location descriptor that designates a machine register for
13771    a given hard register number.  */
13772
13773 static dw_loc_descr_ref
13774 one_reg_loc_descriptor (unsigned int regno, enum var_init_status initialized)
13775 {
13776   dw_loc_descr_ref reg_loc_descr;
13777
13778   if (regno <= 31)
13779     reg_loc_descr
13780       = new_loc_descr ((enum dwarf_location_atom) (DW_OP_reg0 + regno), 0, 0);
13781   else
13782     reg_loc_descr = new_loc_descr (DW_OP_regx, regno, 0);
13783
13784   if (initialized == VAR_INIT_STATUS_UNINITIALIZED)
13785     add_loc_descr (&reg_loc_descr, new_loc_descr (DW_OP_GNU_uninit, 0, 0));
13786
13787   return reg_loc_descr;
13788 }
13789
13790 /* Given an RTL of a register, return a location descriptor that
13791    designates a value that spans more than one register.  */
13792
13793 static dw_loc_descr_ref
13794 multiple_reg_loc_descriptor (rtx rtl, rtx regs,
13795                              enum var_init_status initialized)
13796 {
13797   int size, i;
13798   dw_loc_descr_ref loc_result = NULL;
13799
13800   /* Simple, contiguous registers.  */
13801   if (regs == NULL_RTX)
13802     {
13803       unsigned reg = REGNO (rtl);
13804       int nregs;
13805
13806 #ifdef LEAF_REG_REMAP
13807       if (crtl->uses_only_leaf_regs)
13808         {
13809           int leaf_reg = LEAF_REG_REMAP (reg);
13810           if (leaf_reg != -1)
13811             reg = (unsigned) leaf_reg;
13812         }
13813 #endif
13814
13815       gcc_assert ((unsigned) DBX_REGISTER_NUMBER (reg) == dbx_reg_number (rtl));
13816       nregs = REG_NREGS (rtl);
13817
13818       /* At present we only track constant-sized pieces.  */
13819       if (!GET_MODE_SIZE (GET_MODE (rtl)).is_constant (&size))
13820         return NULL;
13821       size /= nregs;
13822
13823       loc_result = NULL;
13824       while (nregs--)
13825         {
13826           dw_loc_descr_ref t;
13827
13828           t = one_reg_loc_descriptor (DBX_REGISTER_NUMBER (reg),
13829                                       VAR_INIT_STATUS_INITIALIZED);
13830           add_loc_descr (&loc_result, t);
13831           add_loc_descr_op_piece (&loc_result, size);
13832           ++reg;
13833         }
13834       return loc_result;
13835     }
13836
13837   /* Now onto stupid register sets in non contiguous locations.  */
13838
13839   gcc_assert (GET_CODE (regs) == PARALLEL);
13840
13841   /* At present we only track constant-sized pieces.  */
13842   if (!GET_MODE_SIZE (GET_MODE (XVECEXP (regs, 0, 0))).is_constant (&size))
13843     return NULL;
13844   loc_result = NULL;
13845
13846   for (i = 0; i < XVECLEN (regs, 0); ++i)
13847     {
13848       dw_loc_descr_ref t;
13849
13850       t = one_reg_loc_descriptor (dbx_reg_number (XVECEXP (regs, 0, i)),
13851                                   VAR_INIT_STATUS_INITIALIZED);
13852       add_loc_descr (&loc_result, t);
13853       add_loc_descr_op_piece (&loc_result, size);
13854     }
13855
13856   if (loc_result && initialized == VAR_INIT_STATUS_UNINITIALIZED)
13857     add_loc_descr (&loc_result, new_loc_descr (DW_OP_GNU_uninit, 0, 0));
13858   return loc_result;
13859 }
13860
13861 static unsigned long size_of_int_loc_descriptor (HOST_WIDE_INT);
13862
13863 /* Return a location descriptor that designates a constant i,
13864    as a compound operation from constant (i >> shift), constant shift
13865    and DW_OP_shl.  */
13866
13867 static dw_loc_descr_ref
13868 int_shift_loc_descriptor (HOST_WIDE_INT i, int shift)
13869 {
13870   dw_loc_descr_ref ret = int_loc_descriptor (i >> shift);
13871   add_loc_descr (&ret, int_loc_descriptor (shift));
13872   add_loc_descr (&ret, new_loc_descr (DW_OP_shl, 0, 0));
13873   return ret;
13874 }
13875
13876 /* Return a location descriptor that designates constant POLY_I.  */
13877
13878 static dw_loc_descr_ref
13879 int_loc_descriptor (poly_int64 poly_i)
13880 {
13881   enum dwarf_location_atom op;
13882
13883   HOST_WIDE_INT i;
13884   if (!poly_i.is_constant (&i))
13885     {
13886       /* Create location descriptions for the non-constant part and
13887          add any constant offset at the end.  */
13888       dw_loc_descr_ref ret = NULL;
13889       HOST_WIDE_INT constant = poly_i.coeffs[0];
13890       for (unsigned int j = 1; j < NUM_POLY_INT_COEFFS; ++j)
13891         {
13892           HOST_WIDE_INT coeff = poly_i.coeffs[j];
13893           if (coeff != 0)
13894             {
13895               dw_loc_descr_ref start = ret;
13896               unsigned int factor;
13897               int bias;
13898               unsigned int regno = targetm.dwarf_poly_indeterminate_value
13899                 (j, &factor, &bias);
13900
13901               /* Add COEFF * ((REGNO / FACTOR) - BIAS) to the value:
13902                  add COEFF * (REGNO / FACTOR) now and subtract
13903                  COEFF * BIAS from the final constant part.  */
13904               constant -= coeff * bias;
13905               add_loc_descr (&ret, new_reg_loc_descr (regno, 0));
13906               if (coeff % factor == 0)
13907                 coeff /= factor;
13908               else
13909                 {
13910                   int amount = exact_log2 (factor);
13911                   gcc_assert (amount >= 0);
13912                   add_loc_descr (&ret, int_loc_descriptor (amount));
13913                   add_loc_descr (&ret, new_loc_descr (DW_OP_shr, 0, 0));
13914                 }
13915               if (coeff != 1)
13916                 {
13917                   add_loc_descr (&ret, int_loc_descriptor (coeff));
13918                   add_loc_descr (&ret, new_loc_descr (DW_OP_mul, 0, 0));
13919                 }
13920               if (start)
13921                 add_loc_descr (&ret, new_loc_descr (DW_OP_plus, 0, 0));
13922             }
13923         }
13924       loc_descr_plus_const (&ret, constant);
13925       return ret;
13926     }
13927
13928   /* Pick the smallest representation of a constant, rather than just
13929      defaulting to the LEB encoding.  */
13930   if (i >= 0)
13931     {
13932       int clz = clz_hwi (i);
13933       int ctz = ctz_hwi (i);
13934       if (i <= 31)
13935         op = (enum dwarf_location_atom) (DW_OP_lit0 + i);
13936       else if (i <= 0xff)
13937         op = DW_OP_const1u;
13938       else if (i <= 0xffff)
13939         op = DW_OP_const2u;
13940       else if (clz + ctz >= HOST_BITS_PER_WIDE_INT - 5
13941                && clz + 5 + 255 >= HOST_BITS_PER_WIDE_INT)
13942         /* DW_OP_litX DW_OP_litY DW_OP_shl takes just 3 bytes and
13943            DW_OP_litX DW_OP_const1u Y DW_OP_shl takes just 4 bytes,
13944            while DW_OP_const4u is 5 bytes.  */
13945         return int_shift_loc_descriptor (i, HOST_BITS_PER_WIDE_INT - clz - 5);
13946       else if (clz + ctz >= HOST_BITS_PER_WIDE_INT - 8
13947                && clz + 8 + 31 >= HOST_BITS_PER_WIDE_INT)
13948         /* DW_OP_const1u X DW_OP_litY DW_OP_shl takes just 4 bytes,
13949            while DW_OP_const4u is 5 bytes.  */
13950         return int_shift_loc_descriptor (i, HOST_BITS_PER_WIDE_INT - clz - 8);
13951
13952       else if (DWARF2_ADDR_SIZE == 4 && i > 0x7fffffff
13953                && size_of_int_loc_descriptor ((HOST_WIDE_INT) (int32_t) i)
13954                   <= 4)
13955         {
13956           /* As i >= 2**31, the double cast above will yield a negative number.
13957              Since wrapping is defined in DWARF expressions we can output big
13958              positive integers as small negative ones, regardless of the size
13959              of host wide ints.
13960
13961              Here, since the evaluator will handle 32-bit values and since i >=
13962              2**31, we know it's going to be interpreted as a negative literal:
13963              store it this way if we can do better than 5 bytes this way.  */
13964           return int_loc_descriptor ((HOST_WIDE_INT) (int32_t) i);
13965         }
13966       else if (HOST_BITS_PER_WIDE_INT == 32 || i <= 0xffffffff)
13967         op = DW_OP_const4u;
13968
13969       /* Past this point, i >= 0x100000000 and thus DW_OP_constu will take at
13970          least 6 bytes: see if we can do better before falling back to it.  */
13971       else if (clz + ctz >= HOST_BITS_PER_WIDE_INT - 8
13972                && clz + 8 + 255 >= HOST_BITS_PER_WIDE_INT)
13973         /* DW_OP_const1u X DW_OP_const1u Y DW_OP_shl takes just 5 bytes.  */
13974         return int_shift_loc_descriptor (i, HOST_BITS_PER_WIDE_INT - clz - 8);
13975       else if (clz + ctz >= HOST_BITS_PER_WIDE_INT - 16
13976                && clz + 16 + (size_of_uleb128 (i) > 5 ? 255 : 31)
13977                   >= HOST_BITS_PER_WIDE_INT)
13978         /* DW_OP_const2u X DW_OP_litY DW_OP_shl takes just 5 bytes,
13979            DW_OP_const2u X DW_OP_const1u Y DW_OP_shl takes 6 bytes.  */
13980         return int_shift_loc_descriptor (i, HOST_BITS_PER_WIDE_INT - clz - 16);
13981       else if (clz + ctz >= HOST_BITS_PER_WIDE_INT - 32
13982                && clz + 32 + 31 >= HOST_BITS_PER_WIDE_INT
13983                && size_of_uleb128 (i) > 6)
13984         /* DW_OP_const4u X DW_OP_litY DW_OP_shl takes just 7 bytes.  */
13985         return int_shift_loc_descriptor (i, HOST_BITS_PER_WIDE_INT - clz - 32);
13986       else
13987         op = DW_OP_constu;
13988     }
13989   else
13990     {
13991       if (i >= -0x80)
13992         op = DW_OP_const1s;
13993       else if (i >= -0x8000)
13994         op = DW_OP_const2s;
13995       else if (HOST_BITS_PER_WIDE_INT == 32 || i >= -0x80000000)
13996         {
13997           if (size_of_int_loc_descriptor (i) < 5)
13998             {
13999               dw_loc_descr_ref ret = int_loc_descriptor (-i);
14000               add_loc_descr (&ret, new_loc_descr (DW_OP_neg, 0, 0));
14001               return ret;
14002             }
14003           op = DW_OP_const4s;
14004         }
14005       else
14006         {
14007           if (size_of_int_loc_descriptor (i)
14008               < (unsigned long) 1 + size_of_sleb128 (i))
14009             {
14010               dw_loc_descr_ref ret = int_loc_descriptor (-i);
14011               add_loc_descr (&ret, new_loc_descr (DW_OP_neg, 0, 0));
14012               return ret;
14013             }
14014           op = DW_OP_consts;
14015         }
14016     }
14017
14018   return new_loc_descr (op, i, 0);
14019 }
14020
14021 /* Likewise, for unsigned constants.  */
14022
14023 static dw_loc_descr_ref
14024 uint_loc_descriptor (unsigned HOST_WIDE_INT i)
14025 {
14026   const unsigned HOST_WIDE_INT max_int = INTTYPE_MAXIMUM (HOST_WIDE_INT);
14027   const unsigned HOST_WIDE_INT max_uint
14028     = INTTYPE_MAXIMUM (unsigned HOST_WIDE_INT);
14029
14030   /* If possible, use the clever signed constants handling.  */
14031   if (i <= max_int)
14032     return int_loc_descriptor ((HOST_WIDE_INT) i);
14033
14034   /* Here, we are left with positive numbers that cannot be represented as
14035      HOST_WIDE_INT, i.e.:
14036          max (HOST_WIDE_INT) < i <= max (unsigned HOST_WIDE_INT)
14037
14038      Using DW_OP_const4/8/./u operation to encode them consumes a lot of bytes
14039      whereas may be better to output a negative integer: thanks to integer
14040      wrapping, we know that:
14041          x = x - 2 ** DWARF2_ADDR_SIZE
14042            = x - 2 * (max (HOST_WIDE_INT) + 1)
14043      So numbers close to max (unsigned HOST_WIDE_INT) could be represented as
14044      small negative integers.  Let's try that in cases it will clearly improve
14045      the encoding: there is no gain turning DW_OP_const4u into
14046      DW_OP_const4s.  */
14047   if (DWARF2_ADDR_SIZE * 8 == HOST_BITS_PER_WIDE_INT
14048       && ((DWARF2_ADDR_SIZE == 4 && i > max_uint - 0x8000)
14049           || (DWARF2_ADDR_SIZE == 8 && i > max_uint - 0x80000000)))
14050     {
14051       const unsigned HOST_WIDE_INT first_shift = i - max_int - 1;
14052
14053       /* Now, -1 <  first_shift <= max (HOST_WIDE_INT)
14054          i.e.  0 <= first_shift <= max (HOST_WIDE_INT).  */
14055       const HOST_WIDE_INT second_shift
14056         = (HOST_WIDE_INT) first_shift - (HOST_WIDE_INT) max_int - 1;
14057
14058       /* So we finally have:
14059               -max (HOST_WIDE_INT) - 1 <= second_shift <= -1.
14060          i.e.  min (HOST_WIDE_INT)     <= second_shift <  0.  */
14061       return int_loc_descriptor (second_shift);
14062     }
14063
14064   /* Last chance: fallback to a simple constant operation.  */
14065   return new_loc_descr
14066      ((HOST_BITS_PER_WIDE_INT == 32 || i <= 0xffffffff)
14067       ? DW_OP_const4u
14068       : DW_OP_const8u,
14069       i, 0);
14070 }
14071
14072 /* Generate and return a location description that computes the unsigned
14073    comparison of the two stack top entries (a OP b where b is the top-most
14074    entry and a is the second one).  The KIND of comparison can be LT_EXPR,
14075    LE_EXPR, GT_EXPR or GE_EXPR.  */
14076
14077 static dw_loc_descr_ref
14078 uint_comparison_loc_list (enum tree_code kind)
14079 {
14080   enum dwarf_location_atom op, flip_op;
14081   dw_loc_descr_ref ret, bra_node, jmp_node, tmp;
14082
14083   switch (kind)
14084     {
14085     case LT_EXPR:
14086       op = DW_OP_lt;
14087       break;
14088     case LE_EXPR:
14089       op = DW_OP_le;
14090       break;
14091     case GT_EXPR:
14092       op = DW_OP_gt;
14093       break;
14094     case GE_EXPR:
14095       op = DW_OP_ge;
14096       break;
14097     default:
14098       gcc_unreachable ();
14099     }
14100
14101   bra_node = new_loc_descr (DW_OP_bra, 0, 0);
14102   jmp_node = new_loc_descr (DW_OP_skip, 0, 0);
14103
14104   /* Until DWARFv4, operations all work on signed integers.  It is nevertheless
14105      possible to perform unsigned comparisons: we just have to distinguish
14106      three cases:
14107
14108        1. when a and b have the same sign (as signed integers); then we should
14109           return: a OP(signed) b;
14110
14111        2. when a is a negative signed integer while b is a positive one, then a
14112           is a greater unsigned integer than b; likewise when a and b's roles
14113           are flipped.
14114
14115      So first, compare the sign of the two operands.  */
14116   ret = new_loc_descr (DW_OP_over, 0, 0);
14117   add_loc_descr (&ret, new_loc_descr (DW_OP_over, 0, 0));
14118   add_loc_descr (&ret, new_loc_descr (DW_OP_xor, 0, 0));
14119   /* If they have different signs (i.e. they have different sign bits), then
14120      the stack top value has now the sign bit set and thus it's smaller than
14121      zero.  */
14122   add_loc_descr (&ret, new_loc_descr (DW_OP_lit0, 0, 0));
14123   add_loc_descr (&ret, new_loc_descr (DW_OP_lt, 0, 0));
14124   add_loc_descr (&ret, bra_node);
14125
14126   /* We are in case 1.  At this point, we know both operands have the same
14127      sign, to it's safe to use the built-in signed comparison.  */
14128   add_loc_descr (&ret, new_loc_descr (op, 0, 0));
14129   add_loc_descr (&ret, jmp_node);
14130
14131   /* We are in case 2.  Here, we know both operands do not have the same sign,
14132      so we have to flip the signed comparison.  */
14133   flip_op = (kind == LT_EXPR || kind == LE_EXPR) ? DW_OP_gt : DW_OP_lt;
14134   tmp = new_loc_descr (flip_op, 0, 0);
14135   bra_node->dw_loc_oprnd1.val_class = dw_val_class_loc;
14136   bra_node->dw_loc_oprnd1.v.val_loc = tmp;
14137   add_loc_descr (&ret, tmp);
14138
14139   /* This dummy operation is necessary to make the two branches join.  */
14140   tmp = new_loc_descr (DW_OP_nop, 0, 0);
14141   jmp_node->dw_loc_oprnd1.val_class = dw_val_class_loc;
14142   jmp_node->dw_loc_oprnd1.v.val_loc = tmp;
14143   add_loc_descr (&ret, tmp);
14144
14145   return ret;
14146 }
14147
14148 /* Likewise, but takes the location description lists (might be destructive on
14149    them).  Return NULL if either is NULL or if concatenation fails.  */
14150
14151 static dw_loc_list_ref
14152 loc_list_from_uint_comparison (dw_loc_list_ref left, dw_loc_list_ref right,
14153                                enum tree_code kind)
14154 {
14155   if (left == NULL || right == NULL)
14156     return NULL;
14157
14158   add_loc_list (&left, right);
14159   if (left == NULL)
14160     return NULL;
14161
14162   add_loc_descr_to_each (left, uint_comparison_loc_list (kind));
14163   return left;
14164 }
14165
14166 /* Return size_of_locs (int_shift_loc_descriptor (i, shift))
14167    without actually allocating it.  */
14168
14169 static unsigned long
14170 size_of_int_shift_loc_descriptor (HOST_WIDE_INT i, int shift)
14171 {
14172   return size_of_int_loc_descriptor (i >> shift)
14173          + size_of_int_loc_descriptor (shift)
14174          + 1;
14175 }
14176
14177 /* Return size_of_locs (int_loc_descriptor (i)) without
14178    actually allocating it.  */
14179
14180 static unsigned long
14181 size_of_int_loc_descriptor (HOST_WIDE_INT i)
14182 {
14183   unsigned long s;
14184
14185   if (i >= 0)
14186     {
14187       int clz, ctz;
14188       if (i <= 31)
14189         return 1;
14190       else if (i <= 0xff)
14191         return 2;
14192       else if (i <= 0xffff)
14193         return 3;
14194       clz = clz_hwi (i);
14195       ctz = ctz_hwi (i);
14196       if (clz + ctz >= HOST_BITS_PER_WIDE_INT - 5
14197           && clz + 5 + 255 >= HOST_BITS_PER_WIDE_INT)
14198         return size_of_int_shift_loc_descriptor (i, HOST_BITS_PER_WIDE_INT
14199                                                     - clz - 5);
14200       else if (clz + ctz >= HOST_BITS_PER_WIDE_INT - 8
14201                && clz + 8 + 31 >= HOST_BITS_PER_WIDE_INT)
14202         return size_of_int_shift_loc_descriptor (i, HOST_BITS_PER_WIDE_INT
14203                                                     - clz - 8);
14204       else if (DWARF2_ADDR_SIZE == 4 && i > 0x7fffffff
14205                && size_of_int_loc_descriptor ((HOST_WIDE_INT) (int32_t) i)
14206                   <= 4)
14207         return size_of_int_loc_descriptor ((HOST_WIDE_INT) (int32_t) i);
14208       else if (HOST_BITS_PER_WIDE_INT == 32 || i <= 0xffffffff)
14209         return 5;
14210       s = size_of_uleb128 ((unsigned HOST_WIDE_INT) i);
14211       if (clz + ctz >= HOST_BITS_PER_WIDE_INT - 8
14212           && clz + 8 + 255 >= HOST_BITS_PER_WIDE_INT)
14213         return size_of_int_shift_loc_descriptor (i, HOST_BITS_PER_WIDE_INT
14214                                                     - clz - 8);
14215       else if (clz + ctz >= HOST_BITS_PER_WIDE_INT - 16
14216                && clz + 16 + (s > 5 ? 255 : 31) >= HOST_BITS_PER_WIDE_INT)
14217         return size_of_int_shift_loc_descriptor (i, HOST_BITS_PER_WIDE_INT
14218                                                     - clz - 16);
14219       else if (clz + ctz >= HOST_BITS_PER_WIDE_INT - 32
14220                && clz + 32 + 31 >= HOST_BITS_PER_WIDE_INT
14221                && s > 6)
14222         return size_of_int_shift_loc_descriptor (i, HOST_BITS_PER_WIDE_INT
14223                                                     - clz - 32);
14224       else
14225         return 1 + s;
14226     }
14227   else
14228     {
14229       if (i >= -0x80)
14230         return 2;
14231       else if (i >= -0x8000)
14232         return 3;
14233       else if (HOST_BITS_PER_WIDE_INT == 32 || i >= -0x80000000)
14234         {
14235           if (-(unsigned HOST_WIDE_INT) i != (unsigned HOST_WIDE_INT) i)
14236             {
14237               s = size_of_int_loc_descriptor (-i) + 1;
14238               if (s < 5)
14239                 return s;
14240             }
14241           return 5;
14242         }
14243       else
14244         {
14245           unsigned long r = 1 + size_of_sleb128 (i);
14246           if (-(unsigned HOST_WIDE_INT) i != (unsigned HOST_WIDE_INT) i)
14247             {
14248               s = size_of_int_loc_descriptor (-i) + 1;
14249               if (s < r)
14250                 return s;
14251             }
14252           return r;
14253         }
14254     }
14255 }
14256
14257 /* Return loc description representing "address" of integer value.
14258    This can appear only as toplevel expression.  */
14259
14260 static dw_loc_descr_ref
14261 address_of_int_loc_descriptor (int size, HOST_WIDE_INT i)
14262 {
14263   int litsize;
14264   dw_loc_descr_ref loc_result = NULL;
14265
14266   if (!(dwarf_version >= 4 || !dwarf_strict))
14267     return NULL;
14268
14269   litsize = size_of_int_loc_descriptor (i);
14270   /* Determine if DW_OP_stack_value or DW_OP_implicit_value
14271      is more compact.  For DW_OP_stack_value we need:
14272      litsize + 1 (DW_OP_stack_value)
14273      and for DW_OP_implicit_value:
14274      1 (DW_OP_implicit_value) + 1 (length) + size.  */
14275   if ((int) DWARF2_ADDR_SIZE >= size && litsize + 1 <= 1 + 1 + size)
14276     {
14277       loc_result = int_loc_descriptor (i);
14278       add_loc_descr (&loc_result,
14279                      new_loc_descr (DW_OP_stack_value, 0, 0));
14280       return loc_result;
14281     }
14282
14283   loc_result = new_loc_descr (DW_OP_implicit_value,
14284                               size, 0);
14285   loc_result->dw_loc_oprnd2.val_class = dw_val_class_const;
14286   loc_result->dw_loc_oprnd2.v.val_int = i;
14287   return loc_result;
14288 }
14289
14290 /* Return a location descriptor that designates a base+offset location.  */
14291
14292 static dw_loc_descr_ref
14293 based_loc_descr (rtx reg, poly_int64 offset,
14294                  enum var_init_status initialized)
14295 {
14296   unsigned int regno;
14297   dw_loc_descr_ref result;
14298   dw_fde_ref fde = cfun->fde;
14299
14300   /* We only use "frame base" when we're sure we're talking about the
14301      post-prologue local stack frame.  We do this by *not* running
14302      register elimination until this point, and recognizing the special
14303      argument pointer and soft frame pointer rtx's.  */
14304   if (reg == arg_pointer_rtx || reg == frame_pointer_rtx)
14305     {
14306       rtx elim = (ira_use_lra_p
14307                   ? lra_eliminate_regs (reg, VOIDmode, NULL_RTX)
14308                   : eliminate_regs (reg, VOIDmode, NULL_RTX));
14309
14310       if (elim != reg)
14311         {
14312           elim = strip_offset_and_add (elim, &offset);
14313           gcc_assert ((SUPPORTS_STACK_ALIGNMENT
14314                        && (elim == hard_frame_pointer_rtx
14315                            || elim == stack_pointer_rtx))
14316                       || elim == (frame_pointer_needed
14317                                   ? hard_frame_pointer_rtx
14318                                   : stack_pointer_rtx));
14319
14320           /* If drap register is used to align stack, use frame
14321              pointer + offset to access stack variables.  If stack
14322              is aligned without drap, use stack pointer + offset to
14323              access stack variables.  */
14324           if (crtl->stack_realign_tried
14325               && reg == frame_pointer_rtx)
14326             {
14327               int base_reg
14328                 = DWARF_FRAME_REGNUM ((fde && fde->drap_reg != INVALID_REGNUM)
14329                                       ? HARD_FRAME_POINTER_REGNUM
14330                                       : REGNO (elim));
14331               return new_reg_loc_descr (base_reg, offset);
14332             }
14333
14334           gcc_assert (frame_pointer_fb_offset_valid);
14335           offset += frame_pointer_fb_offset;
14336           HOST_WIDE_INT const_offset;
14337           if (offset.is_constant (&const_offset))
14338             return new_loc_descr (DW_OP_fbreg, const_offset, 0);
14339           else
14340             {
14341               dw_loc_descr_ref ret = new_loc_descr (DW_OP_fbreg, 0, 0);
14342               loc_descr_plus_const (&ret, offset);
14343               return ret;
14344             }
14345         }
14346     }
14347
14348   regno = REGNO (reg);
14349 #ifdef LEAF_REG_REMAP
14350   if (crtl->uses_only_leaf_regs)
14351     {
14352       int leaf_reg = LEAF_REG_REMAP (regno);
14353       if (leaf_reg != -1)
14354         regno = (unsigned) leaf_reg;
14355     }
14356 #endif
14357   regno = DWARF_FRAME_REGNUM (regno);
14358
14359   HOST_WIDE_INT const_offset;
14360   if (!optimize && fde
14361       && (fde->drap_reg == regno || fde->vdrap_reg == regno)
14362       && offset.is_constant (&const_offset))
14363     {
14364       /* Use cfa+offset to represent the location of arguments passed
14365          on the stack when drap is used to align stack.
14366          Only do this when not optimizing, for optimized code var-tracking
14367          is supposed to track where the arguments live and the register
14368          used as vdrap or drap in some spot might be used for something
14369          else in other part of the routine.  */
14370       return new_loc_descr (DW_OP_fbreg, const_offset, 0);
14371     }
14372
14373   result = new_reg_loc_descr (regno, offset);
14374
14375   if (initialized == VAR_INIT_STATUS_UNINITIALIZED)
14376     add_loc_descr (&result, new_loc_descr (DW_OP_GNU_uninit, 0, 0));
14377
14378   return result;
14379 }
14380
14381 /* Return true if this RTL expression describes a base+offset calculation.  */
14382
14383 static inline int
14384 is_based_loc (const_rtx rtl)
14385 {
14386   return (GET_CODE (rtl) == PLUS
14387           && ((REG_P (XEXP (rtl, 0))
14388                && REGNO (XEXP (rtl, 0)) < FIRST_PSEUDO_REGISTER
14389                && CONST_INT_P (XEXP (rtl, 1)))));
14390 }
14391
14392 /* Try to handle TLS MEMs, for which mem_loc_descriptor on XEXP (mem, 0)
14393    failed.  */
14394
14395 static dw_loc_descr_ref
14396 tls_mem_loc_descriptor (rtx mem)
14397 {
14398   tree base;
14399   dw_loc_descr_ref loc_result;
14400
14401   if (MEM_EXPR (mem) == NULL_TREE || !MEM_OFFSET_KNOWN_P (mem))
14402     return NULL;
14403
14404   base = get_base_address (MEM_EXPR (mem));
14405   if (base == NULL
14406       || !VAR_P (base)
14407       || !DECL_THREAD_LOCAL_P (base))
14408     return NULL;
14409
14410   loc_result = loc_descriptor_from_tree (MEM_EXPR (mem), 1, NULL);
14411   if (loc_result == NULL)
14412     return NULL;
14413
14414   if (maybe_ne (MEM_OFFSET (mem), 0))
14415     loc_descr_plus_const (&loc_result, MEM_OFFSET (mem));
14416
14417   return loc_result;
14418 }
14419
14420 /* Output debug info about reason why we failed to expand expression as dwarf
14421    expression.  */
14422
14423 static void
14424 expansion_failed (tree expr, rtx rtl, char const *reason)
14425 {
14426   if (dump_file && (dump_flags & TDF_DETAILS))
14427     {
14428       fprintf (dump_file, "Failed to expand as dwarf: ");
14429       if (expr)
14430         print_generic_expr (dump_file, expr, dump_flags);
14431       if (rtl)
14432         {
14433           fprintf (dump_file, "\n");
14434           print_rtl (dump_file, rtl);
14435         }
14436       fprintf (dump_file, "\nReason: %s\n", reason);
14437     }
14438 }
14439
14440 /* True if handling a former CONST by mem_loc_descriptor piecewise.  */
14441
14442 static bool in_const_p;
14443
14444 /* Helper function for const_ok_for_output.  */
14445
14446 static bool
14447 const_ok_for_output_1 (rtx rtl)
14448 {
14449   if (targetm.const_not_ok_for_debug_p (rtl))
14450     {
14451       if (GET_CODE (rtl) != UNSPEC)
14452         {
14453           expansion_failed (NULL_TREE, rtl,
14454                             "Expression rejected for debug by the backend.\n");
14455           return false;
14456         }
14457
14458       /* If delegitimize_address couldn't do anything with the UNSPEC, and
14459          the target hook doesn't explicitly allow it in debug info, assume
14460          we can't express it in the debug info.  */
14461       /* Don't complain about TLS UNSPECs, those are just too hard to
14462          delegitimize.  Note this could be a non-decl SYMBOL_REF such as
14463          one in a constant pool entry, so testing SYMBOL_REF_TLS_MODEL
14464          rather than DECL_THREAD_LOCAL_P is not just an optimization.  */
14465       if (flag_checking
14466           && !in_const_p
14467           && (XVECLEN (rtl, 0) == 0
14468               || GET_CODE (XVECEXP (rtl, 0, 0)) != SYMBOL_REF
14469               || SYMBOL_REF_TLS_MODEL (XVECEXP (rtl, 0, 0)) == TLS_MODEL_NONE))
14470         inform (current_function_decl
14471                 ? DECL_SOURCE_LOCATION (current_function_decl)
14472                 : UNKNOWN_LOCATION,
14473 #if NUM_UNSPEC_VALUES > 0
14474                 "non-delegitimized UNSPEC %s (%d) found in variable location",
14475                 ((XINT (rtl, 1) >= 0 && XINT (rtl, 1) < NUM_UNSPEC_VALUES)
14476                  ? unspec_strings[XINT (rtl, 1)] : "unknown"),
14477                 XINT (rtl, 1));
14478 #else
14479                 "non-delegitimized UNSPEC %d found in variable location",
14480                 XINT (rtl, 1));
14481 #endif
14482       expansion_failed (NULL_TREE, rtl,
14483                         "UNSPEC hasn't been delegitimized.\n");
14484       return false;
14485     }
14486
14487   if (CONST_POLY_INT_P (rtl))
14488     return false;
14489
14490   /* FIXME: Refer to PR60655. It is possible for simplification
14491      of rtl expressions in var tracking to produce such expressions.
14492      We should really identify / validate expressions
14493      enclosed in CONST that can be handled by assemblers on various
14494      targets and only handle legitimate cases here.  */
14495   switch (GET_CODE (rtl))
14496     {
14497     case SYMBOL_REF:
14498       break;
14499     case NOT:
14500     case NEG:
14501       return false;
14502     case PLUS:
14503       {
14504         /* Make sure SYMBOL_REFs/UNSPECs are at most in one of the
14505            operands.  */
14506         subrtx_var_iterator::array_type array;
14507         bool first = false;
14508         FOR_EACH_SUBRTX_VAR (iter, array, XEXP (rtl, 0), ALL)
14509           if (SYMBOL_REF_P (*iter)
14510               || LABEL_P (*iter)
14511               || GET_CODE (*iter) == UNSPEC)
14512             {
14513               first = true;
14514               break;
14515             }
14516         if (!first)
14517           return true;
14518         FOR_EACH_SUBRTX_VAR (iter, array, XEXP (rtl, 1), ALL)
14519           if (SYMBOL_REF_P (*iter)
14520               || LABEL_P (*iter)
14521               || GET_CODE (*iter) == UNSPEC)
14522             return false;
14523         return true;
14524       }
14525     case MINUS:
14526       {
14527         /* Disallow negation of SYMBOL_REFs or UNSPECs when they
14528            appear in the second operand of MINUS.  */
14529         subrtx_var_iterator::array_type array;
14530         FOR_EACH_SUBRTX_VAR (iter, array, XEXP (rtl, 1), ALL)
14531           if (SYMBOL_REF_P (*iter)
14532               || LABEL_P (*iter)
14533               || GET_CODE (*iter) == UNSPEC)
14534             return false;
14535         return true;
14536       }
14537     default:
14538       return true;
14539     }
14540
14541   if (CONSTANT_POOL_ADDRESS_P (rtl))
14542     {
14543       bool marked;
14544       get_pool_constant_mark (rtl, &marked);
14545       /* If all references to this pool constant were optimized away,
14546          it was not output and thus we can't represent it.  */
14547       if (!marked)
14548         {
14549           expansion_failed (NULL_TREE, rtl,
14550                             "Constant was removed from constant pool.\n");
14551           return false;
14552         }
14553     }
14554
14555   if (SYMBOL_REF_TLS_MODEL (rtl) != TLS_MODEL_NONE)
14556     return false;
14557
14558   /* Avoid references to external symbols in debug info, on several targets
14559      the linker might even refuse to link when linking a shared library,
14560      and in many other cases the relocations for .debug_info/.debug_loc are
14561      dropped, so the address becomes zero anyway.  Hidden symbols, guaranteed
14562      to be defined within the same shared library or executable are fine.  */
14563   if (SYMBOL_REF_EXTERNAL_P (rtl))
14564     {
14565       tree decl = SYMBOL_REF_DECL (rtl);
14566
14567       if (decl == NULL || !targetm.binds_local_p (decl))
14568         {
14569           expansion_failed (NULL_TREE, rtl,
14570                             "Symbol not defined in current TU.\n");
14571           return false;
14572         }
14573     }
14574
14575   return true;
14576 }
14577
14578 /* Return true if constant RTL can be emitted in DW_OP_addr or
14579    DW_AT_const_value.  TLS SYMBOL_REFs, external SYMBOL_REFs or
14580    non-marked constant pool SYMBOL_REFs can't be referenced in it.  */
14581
14582 static bool
14583 const_ok_for_output (rtx rtl)
14584 {
14585   if (GET_CODE (rtl) == SYMBOL_REF)
14586     return const_ok_for_output_1 (rtl);
14587
14588   if (GET_CODE (rtl) == CONST)
14589     {
14590       subrtx_var_iterator::array_type array;
14591       FOR_EACH_SUBRTX_VAR (iter, array, XEXP (rtl, 0), ALL)
14592         if (!const_ok_for_output_1 (*iter))
14593           return false;
14594       return true;
14595     }
14596
14597   return true;
14598 }
14599
14600 /* Return a reference to DW_TAG_base_type corresponding to MODE and UNSIGNEDP
14601    if possible, NULL otherwise.  */
14602
14603 static dw_die_ref
14604 base_type_for_mode (machine_mode mode, bool unsignedp)
14605 {
14606   dw_die_ref type_die;
14607   tree type = lang_hooks.types.type_for_mode (mode, unsignedp);
14608
14609   if (type == NULL)
14610     return NULL;
14611   switch (TREE_CODE (type))
14612     {
14613     case INTEGER_TYPE:
14614     case REAL_TYPE:
14615       break;
14616     default:
14617       return NULL;
14618     }
14619   type_die = lookup_type_die (type);
14620   if (!type_die)
14621     type_die = modified_type_die (type, TYPE_UNQUALIFIED, false,
14622                                   comp_unit_die ());
14623   if (type_die == NULL || type_die->die_tag != DW_TAG_base_type)
14624     return NULL;
14625   return type_die;
14626 }
14627
14628 /* For OP descriptor assumed to be in unsigned MODE, convert it to a unsigned
14629    type matching MODE, or, if MODE is narrower than or as wide as
14630    DWARF2_ADDR_SIZE, untyped.  Return NULL if the conversion is not
14631    possible.  */
14632
14633 static dw_loc_descr_ref
14634 convert_descriptor_to_mode (scalar_int_mode mode, dw_loc_descr_ref op)
14635 {
14636   machine_mode outer_mode = mode;
14637   dw_die_ref type_die;
14638   dw_loc_descr_ref cvt;
14639
14640   if (GET_MODE_SIZE (mode) <= DWARF2_ADDR_SIZE)
14641     {
14642       add_loc_descr (&op, new_loc_descr (dwarf_OP (DW_OP_convert), 0, 0));
14643       return op;
14644     }
14645   type_die = base_type_for_mode (outer_mode, 1);
14646   if (type_die == NULL)
14647     return NULL;
14648   cvt = new_loc_descr (dwarf_OP (DW_OP_convert), 0, 0);
14649   cvt->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
14650   cvt->dw_loc_oprnd1.v.val_die_ref.die = type_die;
14651   cvt->dw_loc_oprnd1.v.val_die_ref.external = 0;
14652   add_loc_descr (&op, cvt);
14653   return op;
14654 }
14655
14656 /* Return location descriptor for comparison OP with operands OP0 and OP1.  */
14657
14658 static dw_loc_descr_ref
14659 compare_loc_descriptor (enum dwarf_location_atom op, dw_loc_descr_ref op0,
14660                         dw_loc_descr_ref op1)
14661 {
14662   dw_loc_descr_ref ret = op0;
14663   add_loc_descr (&ret, op1);
14664   add_loc_descr (&ret, new_loc_descr (op, 0, 0));
14665   if (STORE_FLAG_VALUE != 1)
14666     {
14667       add_loc_descr (&ret, int_loc_descriptor (STORE_FLAG_VALUE));
14668       add_loc_descr (&ret, new_loc_descr (DW_OP_mul, 0, 0));
14669     }
14670   return ret;
14671 }
14672
14673 /* Subroutine of scompare_loc_descriptor for the case in which we're
14674    comparing two scalar integer operands OP0 and OP1 that have mode OP_MODE,
14675    and in which OP_MODE is bigger than DWARF2_ADDR_SIZE.  */
14676
14677 static dw_loc_descr_ref
14678 scompare_loc_descriptor_wide (enum dwarf_location_atom op,
14679                               scalar_int_mode op_mode,
14680                               dw_loc_descr_ref op0, dw_loc_descr_ref op1)
14681 {
14682   dw_die_ref type_die = base_type_for_mode (op_mode, 0);
14683   dw_loc_descr_ref cvt;
14684
14685   if (type_die == NULL)
14686     return NULL;
14687   cvt = new_loc_descr (dwarf_OP (DW_OP_convert), 0, 0);
14688   cvt->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
14689   cvt->dw_loc_oprnd1.v.val_die_ref.die = type_die;
14690   cvt->dw_loc_oprnd1.v.val_die_ref.external = 0;
14691   add_loc_descr (&op0, cvt);
14692   cvt = new_loc_descr (dwarf_OP (DW_OP_convert), 0, 0);
14693   cvt->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
14694   cvt->dw_loc_oprnd1.v.val_die_ref.die = type_die;
14695   cvt->dw_loc_oprnd1.v.val_die_ref.external = 0;
14696   add_loc_descr (&op1, cvt);
14697   return compare_loc_descriptor (op, op0, op1);
14698 }
14699
14700 /* Subroutine of scompare_loc_descriptor for the case in which we're
14701    comparing two scalar integer operands OP0 and OP1 that have mode OP_MODE,
14702    and in which OP_MODE is smaller than DWARF2_ADDR_SIZE.  */
14703
14704 static dw_loc_descr_ref
14705 scompare_loc_descriptor_narrow (enum dwarf_location_atom op, rtx rtl,
14706                                 scalar_int_mode op_mode,
14707                                 dw_loc_descr_ref op0, dw_loc_descr_ref op1)
14708 {
14709   int shift = (DWARF2_ADDR_SIZE - GET_MODE_SIZE (op_mode)) * BITS_PER_UNIT;
14710   /* For eq/ne, if the operands are known to be zero-extended,
14711      there is no need to do the fancy shifting up.  */
14712   if (op == DW_OP_eq || op == DW_OP_ne)
14713     {
14714       dw_loc_descr_ref last0, last1;
14715       for (last0 = op0; last0->dw_loc_next != NULL; last0 = last0->dw_loc_next)
14716         ;
14717       for (last1 = op1; last1->dw_loc_next != NULL; last1 = last1->dw_loc_next)
14718         ;
14719       /* deref_size zero extends, and for constants we can check
14720          whether they are zero extended or not.  */
14721       if (((last0->dw_loc_opc == DW_OP_deref_size
14722             && last0->dw_loc_oprnd1.v.val_int <= GET_MODE_SIZE (op_mode))
14723            || (CONST_INT_P (XEXP (rtl, 0))
14724                && (unsigned HOST_WIDE_INT) INTVAL (XEXP (rtl, 0))
14725                   == (INTVAL (XEXP (rtl, 0)) & GET_MODE_MASK (op_mode))))
14726           && ((last1->dw_loc_opc == DW_OP_deref_size
14727                && last1->dw_loc_oprnd1.v.val_int <= GET_MODE_SIZE (op_mode))
14728               || (CONST_INT_P (XEXP (rtl, 1))
14729                   && (unsigned HOST_WIDE_INT) INTVAL (XEXP (rtl, 1))
14730                      == (INTVAL (XEXP (rtl, 1)) & GET_MODE_MASK (op_mode)))))
14731         return compare_loc_descriptor (op, op0, op1);
14732
14733       /* EQ/NE comparison against constant in narrower type than
14734          DWARF2_ADDR_SIZE can be performed either as
14735          DW_OP_const1u <shift> DW_OP_shl DW_OP_const* <cst << shift>
14736          DW_OP_{eq,ne}
14737          or
14738          DW_OP_const*u <mode_mask> DW_OP_and DW_OP_const* <cst & mode_mask>
14739          DW_OP_{eq,ne}.  Pick whatever is shorter.  */
14740       if (CONST_INT_P (XEXP (rtl, 1))
14741           && GET_MODE_BITSIZE (op_mode) < HOST_BITS_PER_WIDE_INT
14742           && (size_of_int_loc_descriptor (shift) + 1
14743               + size_of_int_loc_descriptor (UINTVAL (XEXP (rtl, 1)) << shift)
14744               >= size_of_int_loc_descriptor (GET_MODE_MASK (op_mode)) + 1
14745                  + size_of_int_loc_descriptor (INTVAL (XEXP (rtl, 1))
14746                                                & GET_MODE_MASK (op_mode))))
14747         {
14748           add_loc_descr (&op0, int_loc_descriptor (GET_MODE_MASK (op_mode)));
14749           add_loc_descr (&op0, new_loc_descr (DW_OP_and, 0, 0));
14750           op1 = int_loc_descriptor (INTVAL (XEXP (rtl, 1))
14751                                     & GET_MODE_MASK (op_mode));
14752           return compare_loc_descriptor (op, op0, op1);
14753         }
14754     }
14755   add_loc_descr (&op0, int_loc_descriptor (shift));
14756   add_loc_descr (&op0, new_loc_descr (DW_OP_shl, 0, 0));
14757   if (CONST_INT_P (XEXP (rtl, 1)))
14758     op1 = int_loc_descriptor (UINTVAL (XEXP (rtl, 1)) << shift);
14759   else
14760     {
14761       add_loc_descr (&op1, int_loc_descriptor (shift));
14762       add_loc_descr (&op1, new_loc_descr (DW_OP_shl, 0, 0));
14763     }
14764   return compare_loc_descriptor (op, op0, op1);
14765 }
14766
14767 /* Return location descriptor for unsigned comparison OP RTL.  */
14768
14769 static dw_loc_descr_ref
14770 scompare_loc_descriptor (enum dwarf_location_atom op, rtx rtl,
14771                          machine_mode mem_mode)
14772 {
14773   machine_mode op_mode = GET_MODE (XEXP (rtl, 0));
14774   dw_loc_descr_ref op0, op1;
14775
14776   if (op_mode == VOIDmode)
14777     op_mode = GET_MODE (XEXP (rtl, 1));
14778   if (op_mode == VOIDmode)
14779     return NULL;
14780
14781   scalar_int_mode int_op_mode;
14782   if (dwarf_strict
14783       && dwarf_version < 5
14784       && (!is_a <scalar_int_mode> (op_mode, &int_op_mode)
14785           || GET_MODE_SIZE (int_op_mode) > DWARF2_ADDR_SIZE))
14786     return NULL;
14787
14788   op0 = mem_loc_descriptor (XEXP (rtl, 0), op_mode, mem_mode,
14789                             VAR_INIT_STATUS_INITIALIZED);
14790   op1 = mem_loc_descriptor (XEXP (rtl, 1), op_mode, mem_mode,
14791                             VAR_INIT_STATUS_INITIALIZED);
14792
14793   if (op0 == NULL || op1 == NULL)
14794     return NULL;
14795
14796   if (is_a <scalar_int_mode> (op_mode, &int_op_mode))
14797     {
14798       if (GET_MODE_SIZE (int_op_mode) < DWARF2_ADDR_SIZE)
14799         return scompare_loc_descriptor_narrow (op, rtl, int_op_mode, op0, op1);
14800
14801       if (GET_MODE_SIZE (int_op_mode) > DWARF2_ADDR_SIZE)
14802         return scompare_loc_descriptor_wide (op, int_op_mode, op0, op1);
14803     }
14804   return compare_loc_descriptor (op, op0, op1);
14805 }
14806
14807 /* Return location descriptor for unsigned comparison OP RTL.  */
14808
14809 static dw_loc_descr_ref
14810 ucompare_loc_descriptor (enum dwarf_location_atom op, rtx rtl,
14811                          machine_mode mem_mode)
14812 {
14813   dw_loc_descr_ref op0, op1;
14814
14815   machine_mode test_op_mode = GET_MODE (XEXP (rtl, 0));
14816   if (test_op_mode == VOIDmode)
14817     test_op_mode = GET_MODE (XEXP (rtl, 1));
14818
14819   scalar_int_mode op_mode;
14820   if (!is_a <scalar_int_mode> (test_op_mode, &op_mode))
14821     return NULL;
14822
14823   if (dwarf_strict
14824       && dwarf_version < 5
14825       && GET_MODE_SIZE (op_mode) > DWARF2_ADDR_SIZE)
14826     return NULL;
14827
14828   op0 = mem_loc_descriptor (XEXP (rtl, 0), op_mode, mem_mode,
14829                             VAR_INIT_STATUS_INITIALIZED);
14830   op1 = mem_loc_descriptor (XEXP (rtl, 1), op_mode, mem_mode,
14831                             VAR_INIT_STATUS_INITIALIZED);
14832
14833   if (op0 == NULL || op1 == NULL)
14834     return NULL;
14835
14836   if (GET_MODE_SIZE (op_mode) < DWARF2_ADDR_SIZE)
14837     {
14838       HOST_WIDE_INT mask = GET_MODE_MASK (op_mode);
14839       dw_loc_descr_ref last0, last1;
14840       for (last0 = op0; last0->dw_loc_next != NULL; last0 = last0->dw_loc_next)
14841         ;
14842       for (last1 = op1; last1->dw_loc_next != NULL; last1 = last1->dw_loc_next)
14843         ;
14844       if (CONST_INT_P (XEXP (rtl, 0)))
14845         op0 = int_loc_descriptor (INTVAL (XEXP (rtl, 0)) & mask);
14846       /* deref_size zero extends, so no need to mask it again.  */
14847       else if (last0->dw_loc_opc != DW_OP_deref_size
14848                || last0->dw_loc_oprnd1.v.val_int > GET_MODE_SIZE (op_mode))
14849         {
14850           add_loc_descr (&op0, int_loc_descriptor (mask));
14851           add_loc_descr (&op0, new_loc_descr (DW_OP_and, 0, 0));
14852         }
14853       if (CONST_INT_P (XEXP (rtl, 1)))
14854         op1 = int_loc_descriptor (INTVAL (XEXP (rtl, 1)) & mask);
14855       /* deref_size zero extends, so no need to mask it again.  */
14856       else if (last1->dw_loc_opc != DW_OP_deref_size
14857                || last1->dw_loc_oprnd1.v.val_int > GET_MODE_SIZE (op_mode))
14858         {
14859           add_loc_descr (&op1, int_loc_descriptor (mask));
14860           add_loc_descr (&op1, new_loc_descr (DW_OP_and, 0, 0));
14861         }
14862     }
14863   else if (GET_MODE_SIZE (op_mode) == DWARF2_ADDR_SIZE)
14864     {
14865       HOST_WIDE_INT bias = 1;
14866       bias <<= (DWARF2_ADDR_SIZE * BITS_PER_UNIT - 1);
14867       add_loc_descr (&op0, new_loc_descr (DW_OP_plus_uconst, bias, 0));
14868       if (CONST_INT_P (XEXP (rtl, 1)))
14869         op1 = int_loc_descriptor ((unsigned HOST_WIDE_INT) bias
14870                                   + INTVAL (XEXP (rtl, 1)));
14871       else
14872         add_loc_descr (&op1, new_loc_descr (DW_OP_plus_uconst,
14873                                             bias, 0));
14874     }
14875   return compare_loc_descriptor (op, op0, op1);
14876 }
14877
14878 /* Return location descriptor for {U,S}{MIN,MAX}.  */
14879
14880 static dw_loc_descr_ref
14881 minmax_loc_descriptor (rtx rtl, machine_mode mode,
14882                        machine_mode mem_mode)
14883 {
14884   enum dwarf_location_atom op;
14885   dw_loc_descr_ref op0, op1, ret;
14886   dw_loc_descr_ref bra_node, drop_node;
14887
14888   scalar_int_mode int_mode;
14889   if (dwarf_strict
14890       && dwarf_version < 5
14891       && (!is_a <scalar_int_mode> (mode, &int_mode)
14892           || GET_MODE_SIZE (int_mode) > DWARF2_ADDR_SIZE))
14893     return NULL;
14894
14895   op0 = mem_loc_descriptor (XEXP (rtl, 0), mode, mem_mode,
14896                             VAR_INIT_STATUS_INITIALIZED);
14897   op1 = mem_loc_descriptor (XEXP (rtl, 1), mode, mem_mode,
14898                             VAR_INIT_STATUS_INITIALIZED);
14899
14900   if (op0 == NULL || op1 == NULL)
14901     return NULL;
14902
14903   add_loc_descr (&op0, new_loc_descr (DW_OP_dup, 0, 0));
14904   add_loc_descr (&op1, new_loc_descr (DW_OP_swap, 0, 0));
14905   add_loc_descr (&op1, new_loc_descr (DW_OP_over, 0, 0));
14906   if (GET_CODE (rtl) == UMIN || GET_CODE (rtl) == UMAX)
14907     {
14908       /* Checked by the caller.  */
14909       int_mode = as_a <scalar_int_mode> (mode);
14910       if (GET_MODE_SIZE (int_mode) < DWARF2_ADDR_SIZE)
14911         {
14912           HOST_WIDE_INT mask = GET_MODE_MASK (int_mode);
14913           add_loc_descr (&op0, int_loc_descriptor (mask));
14914           add_loc_descr (&op0, new_loc_descr (DW_OP_and, 0, 0));
14915           add_loc_descr (&op1, int_loc_descriptor (mask));
14916           add_loc_descr (&op1, new_loc_descr (DW_OP_and, 0, 0));
14917         }
14918       else if (GET_MODE_SIZE (int_mode) == DWARF2_ADDR_SIZE)
14919         {
14920           HOST_WIDE_INT bias = 1;
14921           bias <<= (DWARF2_ADDR_SIZE * BITS_PER_UNIT - 1);
14922           add_loc_descr (&op0, new_loc_descr (DW_OP_plus_uconst, bias, 0));
14923           add_loc_descr (&op1, new_loc_descr (DW_OP_plus_uconst, bias, 0));
14924         }
14925     }
14926   else if (is_a <scalar_int_mode> (mode, &int_mode)
14927            && GET_MODE_SIZE (int_mode) < DWARF2_ADDR_SIZE)
14928     {
14929       int shift = (DWARF2_ADDR_SIZE - GET_MODE_SIZE (int_mode)) * BITS_PER_UNIT;
14930       add_loc_descr (&op0, int_loc_descriptor (shift));
14931       add_loc_descr (&op0, new_loc_descr (DW_OP_shl, 0, 0));
14932       add_loc_descr (&op1, int_loc_descriptor (shift));
14933       add_loc_descr (&op1, new_loc_descr (DW_OP_shl, 0, 0));
14934     }
14935   else if (is_a <scalar_int_mode> (mode, &int_mode)
14936            && GET_MODE_SIZE (int_mode) > DWARF2_ADDR_SIZE)
14937     {
14938       dw_die_ref type_die = base_type_for_mode (int_mode, 0);
14939       dw_loc_descr_ref cvt;
14940       if (type_die == NULL)
14941         return NULL;
14942       cvt = new_loc_descr (dwarf_OP (DW_OP_convert), 0, 0);
14943       cvt->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
14944       cvt->dw_loc_oprnd1.v.val_die_ref.die = type_die;
14945       cvt->dw_loc_oprnd1.v.val_die_ref.external = 0;
14946       add_loc_descr (&op0, cvt);
14947       cvt = new_loc_descr (dwarf_OP (DW_OP_convert), 0, 0);
14948       cvt->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
14949       cvt->dw_loc_oprnd1.v.val_die_ref.die = type_die;
14950       cvt->dw_loc_oprnd1.v.val_die_ref.external = 0;
14951       add_loc_descr (&op1, cvt);
14952     }
14953
14954   if (GET_CODE (rtl) == SMIN || GET_CODE (rtl) == UMIN)
14955     op = DW_OP_lt;
14956   else
14957     op = DW_OP_gt;
14958   ret = op0;
14959   add_loc_descr (&ret, op1);
14960   add_loc_descr (&ret, new_loc_descr (op, 0, 0));
14961   bra_node = new_loc_descr (DW_OP_bra, 0, 0);
14962   add_loc_descr (&ret, bra_node);
14963   add_loc_descr (&ret, new_loc_descr (DW_OP_swap, 0, 0));
14964   drop_node = new_loc_descr (DW_OP_drop, 0, 0);
14965   add_loc_descr (&ret, drop_node);
14966   bra_node->dw_loc_oprnd1.val_class = dw_val_class_loc;
14967   bra_node->dw_loc_oprnd1.v.val_loc = drop_node;
14968   if ((GET_CODE (rtl) == SMIN || GET_CODE (rtl) == SMAX)
14969       && is_a <scalar_int_mode> (mode, &int_mode)
14970       && GET_MODE_SIZE (int_mode) > DWARF2_ADDR_SIZE)
14971     ret = convert_descriptor_to_mode (int_mode, ret);
14972   return ret;
14973 }
14974
14975 /* Helper function for mem_loc_descriptor.  Perform OP binary op,
14976    but after converting arguments to type_die, afterwards
14977    convert back to unsigned.  */
14978
14979 static dw_loc_descr_ref
14980 typed_binop (enum dwarf_location_atom op, rtx rtl, dw_die_ref type_die,
14981              scalar_int_mode mode, machine_mode mem_mode)
14982 {
14983   dw_loc_descr_ref cvt, op0, op1;
14984
14985   if (type_die == NULL)
14986     return NULL;
14987   op0 = mem_loc_descriptor (XEXP (rtl, 0), mode, mem_mode,
14988                             VAR_INIT_STATUS_INITIALIZED);
14989   op1 = mem_loc_descriptor (XEXP (rtl, 1), mode, mem_mode,
14990                             VAR_INIT_STATUS_INITIALIZED);
14991   if (op0 == NULL || op1 == NULL)
14992     return NULL;
14993   cvt = new_loc_descr (dwarf_OP (DW_OP_convert), 0, 0);
14994   cvt->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
14995   cvt->dw_loc_oprnd1.v.val_die_ref.die = type_die;
14996   cvt->dw_loc_oprnd1.v.val_die_ref.external = 0;
14997   add_loc_descr (&op0, cvt);
14998   cvt = new_loc_descr (dwarf_OP (DW_OP_convert), 0, 0);
14999   cvt->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
15000   cvt->dw_loc_oprnd1.v.val_die_ref.die = type_die;
15001   cvt->dw_loc_oprnd1.v.val_die_ref.external = 0;
15002   add_loc_descr (&op1, cvt);
15003   add_loc_descr (&op0, op1);
15004   add_loc_descr (&op0, new_loc_descr (op, 0, 0));
15005   return convert_descriptor_to_mode (mode, op0);
15006 }
15007
15008 /* CLZ (where constV is CLZ_DEFINED_VALUE_AT_ZERO computed value,
15009    const0 is DW_OP_lit0 or corresponding typed constant,
15010    const1 is DW_OP_lit1 or corresponding typed constant
15011    and constMSB is constant with just the MSB bit set
15012    for the mode):
15013        DW_OP_dup DW_OP_bra <L1> DW_OP_drop constV DW_OP_skip <L4>
15014    L1: const0 DW_OP_swap
15015    L2: DW_OP_dup constMSB DW_OP_and DW_OP_bra <L3> const1 DW_OP_shl
15016        DW_OP_swap DW_OP_plus_uconst <1> DW_OP_swap DW_OP_skip <L2>
15017    L3: DW_OP_drop
15018    L4: DW_OP_nop
15019
15020    CTZ is similar:
15021        DW_OP_dup DW_OP_bra <L1> DW_OP_drop constV DW_OP_skip <L4>
15022    L1: const0 DW_OP_swap
15023    L2: DW_OP_dup const1 DW_OP_and DW_OP_bra <L3> const1 DW_OP_shr
15024        DW_OP_swap DW_OP_plus_uconst <1> DW_OP_swap DW_OP_skip <L2>
15025    L3: DW_OP_drop
15026    L4: DW_OP_nop
15027
15028    FFS is similar:
15029        DW_OP_dup DW_OP_bra <L1> DW_OP_drop const0 DW_OP_skip <L4>
15030    L1: const1 DW_OP_swap
15031    L2: DW_OP_dup const1 DW_OP_and DW_OP_bra <L3> const1 DW_OP_shr
15032        DW_OP_swap DW_OP_plus_uconst <1> DW_OP_swap DW_OP_skip <L2>
15033    L3: DW_OP_drop
15034    L4: DW_OP_nop  */
15035
15036 static dw_loc_descr_ref
15037 clz_loc_descriptor (rtx rtl, scalar_int_mode mode,
15038                     machine_mode mem_mode)
15039 {
15040   dw_loc_descr_ref op0, ret, tmp;
15041   HOST_WIDE_INT valv;
15042   dw_loc_descr_ref l1jump, l1label;
15043   dw_loc_descr_ref l2jump, l2label;
15044   dw_loc_descr_ref l3jump, l3label;
15045   dw_loc_descr_ref l4jump, l4label;
15046   rtx msb;
15047
15048   if (GET_MODE (XEXP (rtl, 0)) != mode)
15049     return NULL;
15050
15051   op0 = mem_loc_descriptor (XEXP (rtl, 0), mode, mem_mode,
15052                             VAR_INIT_STATUS_INITIALIZED);
15053   if (op0 == NULL)
15054     return NULL;
15055   ret = op0;
15056   if (GET_CODE (rtl) == CLZ)
15057     {
15058       if (!CLZ_DEFINED_VALUE_AT_ZERO (mode, valv))
15059         valv = GET_MODE_BITSIZE (mode);
15060     }
15061   else if (GET_CODE (rtl) == FFS)
15062     valv = 0;
15063   else if (!CTZ_DEFINED_VALUE_AT_ZERO (mode, valv))
15064     valv = GET_MODE_BITSIZE (mode);
15065   add_loc_descr (&ret, new_loc_descr (DW_OP_dup, 0, 0));
15066   l1jump = new_loc_descr (DW_OP_bra, 0, 0);
15067   add_loc_descr (&ret, l1jump);
15068   add_loc_descr (&ret, new_loc_descr (DW_OP_drop, 0, 0));
15069   tmp = mem_loc_descriptor (GEN_INT (valv), mode, mem_mode,
15070                             VAR_INIT_STATUS_INITIALIZED);
15071   if (tmp == NULL)
15072     return NULL;
15073   add_loc_descr (&ret, tmp);
15074   l4jump = new_loc_descr (DW_OP_skip, 0, 0);
15075   add_loc_descr (&ret, l4jump);
15076   l1label = mem_loc_descriptor (GET_CODE (rtl) == FFS
15077                                 ? const1_rtx : const0_rtx,
15078                                 mode, mem_mode,
15079                                 VAR_INIT_STATUS_INITIALIZED);
15080   if (l1label == NULL)
15081     return NULL;
15082   add_loc_descr (&ret, l1label);
15083   add_loc_descr (&ret, new_loc_descr (DW_OP_swap, 0, 0));
15084   l2label = new_loc_descr (DW_OP_dup, 0, 0);
15085   add_loc_descr (&ret, l2label);
15086   if (GET_CODE (rtl) != CLZ)
15087     msb = const1_rtx;
15088   else if (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT)
15089     msb = GEN_INT (HOST_WIDE_INT_1U
15090                    << (GET_MODE_BITSIZE (mode) - 1));
15091   else
15092     msb = immed_wide_int_const
15093       (wi::set_bit_in_zero (GET_MODE_PRECISION (mode) - 1,
15094                             GET_MODE_PRECISION (mode)), mode);
15095   if (GET_CODE (msb) == CONST_INT && INTVAL (msb) < 0)
15096     tmp = new_loc_descr (HOST_BITS_PER_WIDE_INT == 32
15097                          ? DW_OP_const4u : HOST_BITS_PER_WIDE_INT == 64
15098                          ? DW_OP_const8u : DW_OP_constu, INTVAL (msb), 0);
15099   else
15100     tmp = mem_loc_descriptor (msb, mode, mem_mode,
15101                               VAR_INIT_STATUS_INITIALIZED);
15102   if (tmp == NULL)
15103     return NULL;
15104   add_loc_descr (&ret, tmp);
15105   add_loc_descr (&ret, new_loc_descr (DW_OP_and, 0, 0));
15106   l3jump = new_loc_descr (DW_OP_bra, 0, 0);
15107   add_loc_descr (&ret, l3jump);
15108   tmp = mem_loc_descriptor (const1_rtx, mode, mem_mode,
15109                             VAR_INIT_STATUS_INITIALIZED);
15110   if (tmp == NULL)
15111     return NULL;
15112   add_loc_descr (&ret, tmp);
15113   add_loc_descr (&ret, new_loc_descr (GET_CODE (rtl) == CLZ
15114                                       ? DW_OP_shl : DW_OP_shr, 0, 0));
15115   add_loc_descr (&ret, new_loc_descr (DW_OP_swap, 0, 0));
15116   add_loc_descr (&ret, new_loc_descr (DW_OP_plus_uconst, 1, 0));
15117   add_loc_descr (&ret, new_loc_descr (DW_OP_swap, 0, 0));
15118   l2jump = new_loc_descr (DW_OP_skip, 0, 0);
15119   add_loc_descr (&ret, l2jump);
15120   l3label = new_loc_descr (DW_OP_drop, 0, 0);
15121   add_loc_descr (&ret, l3label);
15122   l4label = new_loc_descr (DW_OP_nop, 0, 0);
15123   add_loc_descr (&ret, l4label);
15124   l1jump->dw_loc_oprnd1.val_class = dw_val_class_loc;
15125   l1jump->dw_loc_oprnd1.v.val_loc = l1label;
15126   l2jump->dw_loc_oprnd1.val_class = dw_val_class_loc;
15127   l2jump->dw_loc_oprnd1.v.val_loc = l2label;
15128   l3jump->dw_loc_oprnd1.val_class = dw_val_class_loc;
15129   l3jump->dw_loc_oprnd1.v.val_loc = l3label;
15130   l4jump->dw_loc_oprnd1.val_class = dw_val_class_loc;
15131   l4jump->dw_loc_oprnd1.v.val_loc = l4label;
15132   return ret;
15133 }
15134
15135 /* POPCOUNT (const0 is DW_OP_lit0 or corresponding typed constant,
15136    const1 is DW_OP_lit1 or corresponding typed constant):
15137        const0 DW_OP_swap
15138    L1: DW_OP_dup DW_OP_bra <L2> DW_OP_dup DW_OP_rot const1 DW_OP_and
15139        DW_OP_plus DW_OP_swap const1 DW_OP_shr DW_OP_skip <L1>
15140    L2: DW_OP_drop
15141
15142    PARITY is similar:
15143    L1: DW_OP_dup DW_OP_bra <L2> DW_OP_dup DW_OP_rot const1 DW_OP_and
15144        DW_OP_xor DW_OP_swap const1 DW_OP_shr DW_OP_skip <L1>
15145    L2: DW_OP_drop  */
15146
15147 static dw_loc_descr_ref
15148 popcount_loc_descriptor (rtx rtl, scalar_int_mode mode,
15149                          machine_mode mem_mode)
15150 {
15151   dw_loc_descr_ref op0, ret, tmp;
15152   dw_loc_descr_ref l1jump, l1label;
15153   dw_loc_descr_ref l2jump, l2label;
15154
15155   if (GET_MODE (XEXP (rtl, 0)) != mode)
15156     return NULL;
15157
15158   op0 = mem_loc_descriptor (XEXP (rtl, 0), mode, mem_mode,
15159                             VAR_INIT_STATUS_INITIALIZED);
15160   if (op0 == NULL)
15161     return NULL;
15162   ret = op0;
15163   tmp = mem_loc_descriptor (const0_rtx, mode, mem_mode,
15164                             VAR_INIT_STATUS_INITIALIZED);
15165   if (tmp == NULL)
15166     return NULL;
15167   add_loc_descr (&ret, tmp);
15168   add_loc_descr (&ret, new_loc_descr (DW_OP_swap, 0, 0));
15169   l1label = new_loc_descr (DW_OP_dup, 0, 0);
15170   add_loc_descr (&ret, l1label);
15171   l2jump = new_loc_descr (DW_OP_bra, 0, 0);
15172   add_loc_descr (&ret, l2jump);
15173   add_loc_descr (&ret, new_loc_descr (DW_OP_dup, 0, 0));
15174   add_loc_descr (&ret, new_loc_descr (DW_OP_rot, 0, 0));
15175   tmp = mem_loc_descriptor (const1_rtx, mode, mem_mode,
15176                             VAR_INIT_STATUS_INITIALIZED);
15177   if (tmp == NULL)
15178     return NULL;
15179   add_loc_descr (&ret, tmp);
15180   add_loc_descr (&ret, new_loc_descr (DW_OP_and, 0, 0));
15181   add_loc_descr (&ret, new_loc_descr (GET_CODE (rtl) == POPCOUNT
15182                                       ? DW_OP_plus : DW_OP_xor, 0, 0));
15183   add_loc_descr (&ret, new_loc_descr (DW_OP_swap, 0, 0));
15184   tmp = mem_loc_descriptor (const1_rtx, mode, mem_mode,
15185                             VAR_INIT_STATUS_INITIALIZED);
15186   add_loc_descr (&ret, tmp);
15187   add_loc_descr (&ret, new_loc_descr (DW_OP_shr, 0, 0));
15188   l1jump = new_loc_descr (DW_OP_skip, 0, 0);
15189   add_loc_descr (&ret, l1jump);
15190   l2label = new_loc_descr (DW_OP_drop, 0, 0);
15191   add_loc_descr (&ret, l2label);
15192   l1jump->dw_loc_oprnd1.val_class = dw_val_class_loc;
15193   l1jump->dw_loc_oprnd1.v.val_loc = l1label;
15194   l2jump->dw_loc_oprnd1.val_class = dw_val_class_loc;
15195   l2jump->dw_loc_oprnd1.v.val_loc = l2label;
15196   return ret;
15197 }
15198
15199 /* BSWAP (constS is initial shift count, either 56 or 24):
15200        constS const0
15201    L1: DW_OP_pick <2> constS DW_OP_pick <3> DW_OP_minus DW_OP_shr
15202        const255 DW_OP_and DW_OP_pick <2> DW_OP_shl DW_OP_or
15203        DW_OP_swap DW_OP_dup const0 DW_OP_eq DW_OP_bra <L2> const8
15204        DW_OP_minus DW_OP_swap DW_OP_skip <L1>
15205    L2: DW_OP_drop DW_OP_swap DW_OP_drop  */
15206
15207 static dw_loc_descr_ref
15208 bswap_loc_descriptor (rtx rtl, scalar_int_mode mode,
15209                       machine_mode mem_mode)
15210 {
15211   dw_loc_descr_ref op0, ret, tmp;
15212   dw_loc_descr_ref l1jump, l1label;
15213   dw_loc_descr_ref l2jump, l2label;
15214
15215   if (BITS_PER_UNIT != 8
15216       || (GET_MODE_BITSIZE (mode) != 32
15217           && GET_MODE_BITSIZE (mode) != 64))
15218     return NULL;
15219
15220   op0 = mem_loc_descriptor (XEXP (rtl, 0), mode, mem_mode,
15221                             VAR_INIT_STATUS_INITIALIZED);
15222   if (op0 == NULL)
15223     return NULL;
15224
15225   ret = op0;
15226   tmp = mem_loc_descriptor (GEN_INT (GET_MODE_BITSIZE (mode) - 8),
15227                             mode, mem_mode,
15228                             VAR_INIT_STATUS_INITIALIZED);
15229   if (tmp == NULL)
15230     return NULL;
15231   add_loc_descr (&ret, tmp);
15232   tmp = mem_loc_descriptor (const0_rtx, mode, mem_mode,
15233                             VAR_INIT_STATUS_INITIALIZED);
15234   if (tmp == NULL)
15235     return NULL;
15236   add_loc_descr (&ret, tmp);
15237   l1label = new_loc_descr (DW_OP_pick, 2, 0);
15238   add_loc_descr (&ret, l1label);
15239   tmp = mem_loc_descriptor (GEN_INT (GET_MODE_BITSIZE (mode) - 8),
15240                             mode, mem_mode,
15241                             VAR_INIT_STATUS_INITIALIZED);
15242   add_loc_descr (&ret, tmp);
15243   add_loc_descr (&ret, new_loc_descr (DW_OP_pick, 3, 0));
15244   add_loc_descr (&ret, new_loc_descr (DW_OP_minus, 0, 0));
15245   add_loc_descr (&ret, new_loc_descr (DW_OP_shr, 0, 0));
15246   tmp = mem_loc_descriptor (GEN_INT (255), mode, mem_mode,
15247                             VAR_INIT_STATUS_INITIALIZED);
15248   if (tmp == NULL)
15249     return NULL;
15250   add_loc_descr (&ret, tmp);
15251   add_loc_descr (&ret, new_loc_descr (DW_OP_and, 0, 0));
15252   add_loc_descr (&ret, new_loc_descr (DW_OP_pick, 2, 0));
15253   add_loc_descr (&ret, new_loc_descr (DW_OP_shl, 0, 0));
15254   add_loc_descr (&ret, new_loc_descr (DW_OP_or, 0, 0));
15255   add_loc_descr (&ret, new_loc_descr (DW_OP_swap, 0, 0));
15256   add_loc_descr (&ret, new_loc_descr (DW_OP_dup, 0, 0));
15257   tmp = mem_loc_descriptor (const0_rtx, mode, mem_mode,
15258                             VAR_INIT_STATUS_INITIALIZED);
15259   add_loc_descr (&ret, tmp);
15260   add_loc_descr (&ret, new_loc_descr (DW_OP_eq, 0, 0));
15261   l2jump = new_loc_descr (DW_OP_bra, 0, 0);
15262   add_loc_descr (&ret, l2jump);
15263   tmp = mem_loc_descriptor (GEN_INT (8), mode, mem_mode,
15264                             VAR_INIT_STATUS_INITIALIZED);
15265   add_loc_descr (&ret, tmp);
15266   add_loc_descr (&ret, new_loc_descr (DW_OP_minus, 0, 0));
15267   add_loc_descr (&ret, new_loc_descr (DW_OP_swap, 0, 0));
15268   l1jump = new_loc_descr (DW_OP_skip, 0, 0);
15269   add_loc_descr (&ret, l1jump);
15270   l2label = new_loc_descr (DW_OP_drop, 0, 0);
15271   add_loc_descr (&ret, l2label);
15272   add_loc_descr (&ret, new_loc_descr (DW_OP_swap, 0, 0));
15273   add_loc_descr (&ret, new_loc_descr (DW_OP_drop, 0, 0));
15274   l1jump->dw_loc_oprnd1.val_class = dw_val_class_loc;
15275   l1jump->dw_loc_oprnd1.v.val_loc = l1label;
15276   l2jump->dw_loc_oprnd1.val_class = dw_val_class_loc;
15277   l2jump->dw_loc_oprnd1.v.val_loc = l2label;
15278   return ret;
15279 }
15280
15281 /* ROTATE (constMASK is mode mask, BITSIZE is bitsize of mode):
15282    DW_OP_over DW_OP_over DW_OP_shl [ constMASK DW_OP_and ] DW_OP_rot
15283    [ DW_OP_swap constMASK DW_OP_and DW_OP_swap ] DW_OP_neg
15284    DW_OP_plus_uconst <BITSIZE> DW_OP_shr DW_OP_or
15285
15286    ROTATERT is similar:
15287    DW_OP_over DW_OP_over DW_OP_neg DW_OP_plus_uconst <BITSIZE>
15288    DW_OP_shl [ constMASK DW_OP_and ] DW_OP_rot
15289    [ DW_OP_swap constMASK DW_OP_and DW_OP_swap ] DW_OP_shr DW_OP_or  */
15290
15291 static dw_loc_descr_ref
15292 rotate_loc_descriptor (rtx rtl, scalar_int_mode mode,
15293                        machine_mode mem_mode)
15294 {
15295   rtx rtlop1 = XEXP (rtl, 1);
15296   dw_loc_descr_ref op0, op1, ret, mask[2] = { NULL, NULL };
15297   int i;
15298
15299   if (is_narrower_int_mode (GET_MODE (rtlop1), mode))
15300     rtlop1 = gen_rtx_ZERO_EXTEND (mode, rtlop1);
15301   op0 = mem_loc_descriptor (XEXP (rtl, 0), mode, mem_mode,
15302                             VAR_INIT_STATUS_INITIALIZED);
15303   op1 = mem_loc_descriptor (rtlop1, mode, mem_mode,
15304                             VAR_INIT_STATUS_INITIALIZED);
15305   if (op0 == NULL || op1 == NULL)
15306     return NULL;
15307   if (GET_MODE_SIZE (mode) < DWARF2_ADDR_SIZE)
15308     for (i = 0; i < 2; i++)
15309       {
15310         if (GET_MODE_BITSIZE (mode) < HOST_BITS_PER_WIDE_INT)
15311           mask[i] = mem_loc_descriptor (GEN_INT (GET_MODE_MASK (mode)),
15312                                         mode, mem_mode,
15313                                         VAR_INIT_STATUS_INITIALIZED);
15314         else if (GET_MODE_BITSIZE (mode) == HOST_BITS_PER_WIDE_INT)
15315           mask[i] = new_loc_descr (HOST_BITS_PER_WIDE_INT == 32
15316                                    ? DW_OP_const4u
15317                                    : HOST_BITS_PER_WIDE_INT == 64
15318                                    ? DW_OP_const8u : DW_OP_constu,
15319                                    GET_MODE_MASK (mode), 0);
15320         else
15321           mask[i] = NULL;
15322         if (mask[i] == NULL)
15323           return NULL;
15324         add_loc_descr (&mask[i], new_loc_descr (DW_OP_and, 0, 0));
15325       }
15326   ret = op0;
15327   add_loc_descr (&ret, op1);
15328   add_loc_descr (&ret, new_loc_descr (DW_OP_over, 0, 0));
15329   add_loc_descr (&ret, new_loc_descr (DW_OP_over, 0, 0));
15330   if (GET_CODE (rtl) == ROTATERT)
15331     {
15332       add_loc_descr (&ret, new_loc_descr (DW_OP_neg, 0, 0));
15333       add_loc_descr (&ret, new_loc_descr (DW_OP_plus_uconst,
15334                                           GET_MODE_BITSIZE (mode), 0));
15335     }
15336   add_loc_descr (&ret, new_loc_descr (DW_OP_shl, 0, 0));
15337   if (mask[0] != NULL)
15338     add_loc_descr (&ret, mask[0]);
15339   add_loc_descr (&ret, new_loc_descr (DW_OP_rot, 0, 0));
15340   if (mask[1] != NULL)
15341     {
15342       add_loc_descr (&ret, new_loc_descr (DW_OP_swap, 0, 0));
15343       add_loc_descr (&ret, mask[1]);
15344       add_loc_descr (&ret, new_loc_descr (DW_OP_swap, 0, 0));
15345     }
15346   if (GET_CODE (rtl) == ROTATE)
15347     {
15348       add_loc_descr (&ret, new_loc_descr (DW_OP_neg, 0, 0));
15349       add_loc_descr (&ret, new_loc_descr (DW_OP_plus_uconst,
15350                                           GET_MODE_BITSIZE (mode), 0));
15351     }
15352   add_loc_descr (&ret, new_loc_descr (DW_OP_shr, 0, 0));
15353   add_loc_descr (&ret, new_loc_descr (DW_OP_or, 0, 0));
15354   return ret;
15355 }
15356
15357 /* Helper function for mem_loc_descriptor.  Return DW_OP_GNU_parameter_ref
15358    for DEBUG_PARAMETER_REF RTL.  */
15359
15360 static dw_loc_descr_ref
15361 parameter_ref_descriptor (rtx rtl)
15362 {
15363   dw_loc_descr_ref ret;
15364   dw_die_ref ref;
15365
15366   if (dwarf_strict)
15367     return NULL;
15368   gcc_assert (TREE_CODE (DEBUG_PARAMETER_REF_DECL (rtl)) == PARM_DECL);
15369   /* With LTO during LTRANS we get the late DIE that refers to the early
15370      DIE, thus we add another indirection here.  This seems to confuse
15371      gdb enough to make gcc.dg/guality/pr68860-1.c FAIL with LTO.  */
15372   ref = lookup_decl_die (DEBUG_PARAMETER_REF_DECL (rtl));
15373   ret = new_loc_descr (DW_OP_GNU_parameter_ref, 0, 0);
15374   if (ref)
15375     {
15376       ret->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
15377       ret->dw_loc_oprnd1.v.val_die_ref.die = ref;
15378       ret->dw_loc_oprnd1.v.val_die_ref.external = 0;
15379     }
15380   else
15381     {
15382       ret->dw_loc_oprnd1.val_class = dw_val_class_decl_ref;
15383       ret->dw_loc_oprnd1.v.val_decl_ref = DEBUG_PARAMETER_REF_DECL (rtl);
15384     }
15385   return ret;
15386 }
15387
15388 /* The following routine converts the RTL for a variable or parameter
15389    (resident in memory) into an equivalent Dwarf representation of a
15390    mechanism for getting the address of that same variable onto the top of a
15391    hypothetical "address evaluation" stack.
15392
15393    When creating memory location descriptors, we are effectively transforming
15394    the RTL for a memory-resident object into its Dwarf postfix expression
15395    equivalent.  This routine recursively descends an RTL tree, turning
15396    it into Dwarf postfix code as it goes.
15397
15398    MODE is the mode that should be assumed for the rtl if it is VOIDmode.
15399
15400    MEM_MODE is the mode of the memory reference, needed to handle some
15401    autoincrement addressing modes.
15402
15403    Return 0 if we can't represent the location.  */
15404
15405 dw_loc_descr_ref
15406 mem_loc_descriptor (rtx rtl, machine_mode mode,
15407                     machine_mode mem_mode,
15408                     enum var_init_status initialized)
15409 {
15410   dw_loc_descr_ref mem_loc_result = NULL;
15411   enum dwarf_location_atom op;
15412   dw_loc_descr_ref op0, op1;
15413   rtx inner = NULL_RTX;
15414   poly_int64 offset;
15415
15416   if (mode == VOIDmode)
15417     mode = GET_MODE (rtl);
15418
15419   /* Note that for a dynamically sized array, the location we will generate a
15420      description of here will be the lowest numbered location which is
15421      actually within the array.  That's *not* necessarily the same as the
15422      zeroth element of the array.  */
15423
15424   rtl = targetm.delegitimize_address (rtl);
15425
15426   if (mode != GET_MODE (rtl) && GET_MODE (rtl) != VOIDmode)
15427     return NULL;
15428
15429   scalar_int_mode int_mode, inner_mode, op1_mode;
15430   switch (GET_CODE (rtl))
15431     {
15432     case POST_INC:
15433     case POST_DEC:
15434     case POST_MODIFY:
15435       return mem_loc_descriptor (XEXP (rtl, 0), mode, mem_mode, initialized);
15436
15437     case SUBREG:
15438       /* The case of a subreg may arise when we have a local (register)
15439          variable or a formal (register) parameter which doesn't quite fill
15440          up an entire register.  For now, just assume that it is
15441          legitimate to make the Dwarf info refer to the whole register which
15442          contains the given subreg.  */
15443       if (!subreg_lowpart_p (rtl))
15444         break;
15445       inner = SUBREG_REG (rtl);
15446       /* FALLTHRU */
15447     case TRUNCATE:
15448       if (inner == NULL_RTX)
15449         inner = XEXP (rtl, 0);
15450       if (is_a <scalar_int_mode> (mode, &int_mode)
15451           && is_a <scalar_int_mode> (GET_MODE (inner), &inner_mode)
15452           && (GET_MODE_SIZE (int_mode) <= DWARF2_ADDR_SIZE
15453 #ifdef POINTERS_EXTEND_UNSIGNED
15454               || (int_mode == Pmode && mem_mode != VOIDmode)
15455 #endif
15456              )
15457           && GET_MODE_SIZE (inner_mode) <= DWARF2_ADDR_SIZE)
15458         {
15459           mem_loc_result = mem_loc_descriptor (inner,
15460                                                inner_mode,
15461                                                mem_mode, initialized);
15462           break;
15463         }
15464       if (dwarf_strict && dwarf_version < 5)
15465         break;
15466       if (is_a <scalar_int_mode> (mode, &int_mode)
15467           && is_a <scalar_int_mode> (GET_MODE (inner), &inner_mode)
15468           ? GET_MODE_SIZE (int_mode) <= GET_MODE_SIZE (inner_mode)
15469           : known_eq (GET_MODE_SIZE (mode), GET_MODE_SIZE (GET_MODE (inner))))
15470         {
15471           dw_die_ref type_die;
15472           dw_loc_descr_ref cvt;
15473
15474           mem_loc_result = mem_loc_descriptor (inner,
15475                                                GET_MODE (inner),
15476                                                mem_mode, initialized);
15477           if (mem_loc_result == NULL)
15478             break;
15479           type_die = base_type_for_mode (mode, SCALAR_INT_MODE_P (mode));
15480           if (type_die == NULL)
15481             {
15482               mem_loc_result = NULL;
15483               break;
15484             }
15485           if (maybe_ne (GET_MODE_SIZE (mode), GET_MODE_SIZE (GET_MODE (inner))))
15486             cvt = new_loc_descr (dwarf_OP (DW_OP_convert), 0, 0);
15487           else
15488             cvt = new_loc_descr (dwarf_OP (DW_OP_reinterpret), 0, 0);
15489           cvt->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
15490           cvt->dw_loc_oprnd1.v.val_die_ref.die = type_die;
15491           cvt->dw_loc_oprnd1.v.val_die_ref.external = 0;
15492           add_loc_descr (&mem_loc_result, cvt);
15493           if (is_a <scalar_int_mode> (mode, &int_mode)
15494               && GET_MODE_SIZE (int_mode) <= DWARF2_ADDR_SIZE)
15495             {
15496               /* Convert it to untyped afterwards.  */
15497               cvt = new_loc_descr (dwarf_OP (DW_OP_convert), 0, 0);
15498               add_loc_descr (&mem_loc_result, cvt);
15499             }
15500         }
15501       break;
15502
15503     case REG:
15504       if (!is_a <scalar_int_mode> (mode, &int_mode)
15505           || (GET_MODE_SIZE (int_mode) > DWARF2_ADDR_SIZE
15506               && rtl != arg_pointer_rtx
15507               && rtl != frame_pointer_rtx
15508 #ifdef POINTERS_EXTEND_UNSIGNED
15509               && (int_mode != Pmode || mem_mode == VOIDmode)
15510 #endif
15511               ))
15512         {
15513           dw_die_ref type_die;
15514           unsigned int dbx_regnum;
15515
15516           if (dwarf_strict && dwarf_version < 5)
15517             break;
15518           if (REGNO (rtl) > FIRST_PSEUDO_REGISTER)
15519             break;
15520           type_die = base_type_for_mode (mode, SCALAR_INT_MODE_P (mode));
15521           if (type_die == NULL)
15522             break;
15523
15524           dbx_regnum = dbx_reg_number (rtl);
15525           if (dbx_regnum == IGNORED_DWARF_REGNUM)
15526             break;
15527           mem_loc_result = new_loc_descr (dwarf_OP (DW_OP_regval_type),
15528                                           dbx_regnum, 0);
15529           mem_loc_result->dw_loc_oprnd2.val_class = dw_val_class_die_ref;
15530           mem_loc_result->dw_loc_oprnd2.v.val_die_ref.die = type_die;
15531           mem_loc_result->dw_loc_oprnd2.v.val_die_ref.external = 0;
15532           break;
15533         }
15534       /* Whenever a register number forms a part of the description of the
15535          method for calculating the (dynamic) address of a memory resident
15536          object, DWARF rules require the register number be referred to as
15537          a "base register".  This distinction is not based in any way upon
15538          what category of register the hardware believes the given register
15539          belongs to.  This is strictly DWARF terminology we're dealing with
15540          here. Note that in cases where the location of a memory-resident
15541          data object could be expressed as: OP_ADD (OP_BASEREG (basereg),
15542          OP_CONST (0)) the actual DWARF location descriptor that we generate
15543          may just be OP_BASEREG (basereg).  This may look deceptively like
15544          the object in question was allocated to a register (rather than in
15545          memory) so DWARF consumers need to be aware of the subtle
15546          distinction between OP_REG and OP_BASEREG.  */
15547       if (REGNO (rtl) < FIRST_PSEUDO_REGISTER)
15548         mem_loc_result = based_loc_descr (rtl, 0, VAR_INIT_STATUS_INITIALIZED);
15549       else if (stack_realign_drap
15550                && crtl->drap_reg
15551                && crtl->args.internal_arg_pointer == rtl
15552                && REGNO (crtl->drap_reg) < FIRST_PSEUDO_REGISTER)
15553         {
15554           /* If RTL is internal_arg_pointer, which has been optimized
15555              out, use DRAP instead.  */
15556           mem_loc_result = based_loc_descr (crtl->drap_reg, 0,
15557                                             VAR_INIT_STATUS_INITIALIZED);
15558         }
15559       break;
15560
15561     case SIGN_EXTEND:
15562     case ZERO_EXTEND:
15563       if (!is_a <scalar_int_mode> (mode, &int_mode)
15564           || !is_a <scalar_int_mode> (GET_MODE (XEXP (rtl, 0)), &inner_mode))
15565         break;
15566       op0 = mem_loc_descriptor (XEXP (rtl, 0), inner_mode,
15567                                 mem_mode, VAR_INIT_STATUS_INITIALIZED);
15568       if (op0 == 0)
15569         break;
15570       else if (GET_CODE (rtl) == ZERO_EXTEND
15571                && GET_MODE_SIZE (int_mode) <= DWARF2_ADDR_SIZE
15572                && GET_MODE_BITSIZE (inner_mode) < HOST_BITS_PER_WIDE_INT
15573                /* If DW_OP_const{1,2,4}u won't be used, it is shorter
15574                   to expand zero extend as two shifts instead of
15575                   masking.  */
15576                && GET_MODE_SIZE (inner_mode) <= 4)
15577         {
15578           mem_loc_result = op0;
15579           add_loc_descr (&mem_loc_result,
15580                          int_loc_descriptor (GET_MODE_MASK (inner_mode)));
15581           add_loc_descr (&mem_loc_result, new_loc_descr (DW_OP_and, 0, 0));
15582         }
15583       else if (GET_MODE_SIZE (int_mode) <= DWARF2_ADDR_SIZE)
15584         {
15585           int shift = DWARF2_ADDR_SIZE - GET_MODE_SIZE (inner_mode);
15586           shift *= BITS_PER_UNIT;
15587           if (GET_CODE (rtl) == SIGN_EXTEND)
15588             op = DW_OP_shra;
15589           else
15590             op = DW_OP_shr;
15591           mem_loc_result = op0;
15592           add_loc_descr (&mem_loc_result, int_loc_descriptor (shift));
15593           add_loc_descr (&mem_loc_result, new_loc_descr (DW_OP_shl, 0, 0));
15594           add_loc_descr (&mem_loc_result, int_loc_descriptor (shift));
15595           add_loc_descr (&mem_loc_result, new_loc_descr (op, 0, 0));
15596         }
15597       else if (!dwarf_strict || dwarf_version >= 5)
15598         {
15599           dw_die_ref type_die1, type_die2;
15600           dw_loc_descr_ref cvt;
15601
15602           type_die1 = base_type_for_mode (inner_mode,
15603                                           GET_CODE (rtl) == ZERO_EXTEND);
15604           if (type_die1 == NULL)
15605             break;
15606           type_die2 = base_type_for_mode (int_mode, 1);
15607           if (type_die2 == NULL)
15608             break;
15609           mem_loc_result = op0;
15610           cvt = new_loc_descr (dwarf_OP (DW_OP_convert), 0, 0);
15611           cvt->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
15612           cvt->dw_loc_oprnd1.v.val_die_ref.die = type_die1;
15613           cvt->dw_loc_oprnd1.v.val_die_ref.external = 0;
15614           add_loc_descr (&mem_loc_result, cvt);
15615           cvt = new_loc_descr (dwarf_OP (DW_OP_convert), 0, 0);
15616           cvt->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
15617           cvt->dw_loc_oprnd1.v.val_die_ref.die = type_die2;
15618           cvt->dw_loc_oprnd1.v.val_die_ref.external = 0;
15619           add_loc_descr (&mem_loc_result, cvt);
15620         }
15621       break;
15622
15623     case MEM:
15624       {
15625         rtx new_rtl = avoid_constant_pool_reference (rtl);
15626         if (new_rtl != rtl)
15627           {
15628             mem_loc_result = mem_loc_descriptor (new_rtl, mode, mem_mode,
15629                                                  initialized);
15630             if (mem_loc_result != NULL)
15631               return mem_loc_result;
15632           }
15633       }
15634       mem_loc_result = mem_loc_descriptor (XEXP (rtl, 0),
15635                                            get_address_mode (rtl), mode,
15636                                            VAR_INIT_STATUS_INITIALIZED);
15637       if (mem_loc_result == NULL)
15638         mem_loc_result = tls_mem_loc_descriptor (rtl);
15639       if (mem_loc_result != NULL)
15640         {
15641           if (!is_a <scalar_int_mode> (mode, &int_mode)
15642               || GET_MODE_SIZE (int_mode) > DWARF2_ADDR_SIZE)
15643             {
15644               dw_die_ref type_die;
15645               dw_loc_descr_ref deref;
15646               HOST_WIDE_INT size;
15647
15648               if (dwarf_strict && dwarf_version < 5)
15649                 return NULL;
15650               if (!GET_MODE_SIZE (mode).is_constant (&size))
15651                 return NULL;
15652               type_die
15653                 = base_type_for_mode (mode, SCALAR_INT_MODE_P (mode));
15654               if (type_die == NULL)
15655                 return NULL;
15656               deref = new_loc_descr (dwarf_OP (DW_OP_deref_type), size, 0);
15657               deref->dw_loc_oprnd2.val_class = dw_val_class_die_ref;
15658               deref->dw_loc_oprnd2.v.val_die_ref.die = type_die;
15659               deref->dw_loc_oprnd2.v.val_die_ref.external = 0;
15660               add_loc_descr (&mem_loc_result, deref);
15661             }
15662           else if (GET_MODE_SIZE (int_mode) == DWARF2_ADDR_SIZE)
15663             add_loc_descr (&mem_loc_result, new_loc_descr (DW_OP_deref, 0, 0));
15664           else
15665             add_loc_descr (&mem_loc_result,
15666                            new_loc_descr (DW_OP_deref_size,
15667                                           GET_MODE_SIZE (int_mode), 0));
15668         }
15669       break;
15670
15671     case LO_SUM:
15672       return mem_loc_descriptor (XEXP (rtl, 1), mode, mem_mode, initialized);
15673
15674     case LABEL_REF:
15675       /* Some ports can transform a symbol ref into a label ref, because
15676          the symbol ref is too far away and has to be dumped into a constant
15677          pool.  */
15678     case CONST:
15679     case SYMBOL_REF:
15680     case UNSPEC:
15681       if (!is_a <scalar_int_mode> (mode, &int_mode)
15682           || (GET_MODE_SIZE (int_mode) > DWARF2_ADDR_SIZE
15683 #ifdef POINTERS_EXTEND_UNSIGNED
15684               && (int_mode != Pmode || mem_mode == VOIDmode)
15685 #endif
15686               ))
15687         break;
15688
15689       if (GET_CODE (rtl) == UNSPEC)
15690         {
15691           /* If delegitimize_address couldn't do anything with the UNSPEC, we
15692              can't express it in the debug info.  This can happen e.g. with some
15693              TLS UNSPECs.  Allow UNSPECs formerly from CONST that the backend
15694              approves.  */
15695           bool not_ok = false;
15696
15697           if (!in_const_p)
15698             break;
15699
15700           subrtx_var_iterator::array_type array;
15701           FOR_EACH_SUBRTX_VAR (iter, array, rtl, ALL)
15702             if (*iter != rtl && !CONSTANT_P (*iter))
15703               {
15704                 not_ok = true;
15705                 break;
15706               }
15707
15708           if (not_ok)
15709             break;
15710
15711           FOR_EACH_SUBRTX_VAR (iter, array, rtl, ALL)
15712             if (!const_ok_for_output_1 (*iter))
15713               {
15714                 not_ok = true;
15715                 break;
15716               }
15717
15718           if (not_ok)
15719             break;
15720
15721           rtl = gen_rtx_CONST (GET_MODE (rtl), rtl);
15722           goto symref;
15723         }
15724
15725       if (GET_CODE (rtl) == SYMBOL_REF
15726           && SYMBOL_REF_TLS_MODEL (rtl) != TLS_MODEL_NONE)
15727         {
15728           dw_loc_descr_ref temp;
15729
15730           /* If this is not defined, we have no way to emit the data.  */
15731           if (!targetm.have_tls || !targetm.asm_out.output_dwarf_dtprel)
15732             break;
15733
15734           temp = new_addr_loc_descr (rtl, dtprel_true);
15735
15736           /* We check for DWARF 5 here because gdb did not implement
15737              DW_OP_form_tls_address until after 7.12.  */
15738           mem_loc_result = new_loc_descr ((dwarf_version >= 5
15739                                            ? DW_OP_form_tls_address
15740                                            : DW_OP_GNU_push_tls_address),
15741                                           0, 0);
15742           add_loc_descr (&mem_loc_result, temp);
15743
15744           break;
15745         }
15746
15747       if (!const_ok_for_output (rtl))
15748         {
15749           if (GET_CODE (rtl) == CONST)
15750             switch (GET_CODE (XEXP (rtl, 0)))
15751               {
15752               case NOT:
15753                 op = DW_OP_not;
15754                 goto try_const_unop;
15755               case NEG:
15756                 op = DW_OP_neg;
15757                 goto try_const_unop;
15758               try_const_unop:
15759                 rtx arg;
15760                 arg = XEXP (XEXP (rtl, 0), 0);
15761                 if (!CONSTANT_P (arg))
15762                   arg = gen_rtx_CONST (int_mode, arg);
15763                 op0 = mem_loc_descriptor (arg, int_mode, mem_mode,
15764                                           initialized);
15765                 if (op0)
15766                   {
15767                     mem_loc_result = op0;
15768                     add_loc_descr (&mem_loc_result, new_loc_descr (op, 0, 0));
15769                   }
15770                 break;
15771               default:
15772                 {
15773                   bool save_in_const_p = in_const_p;
15774                   in_const_p = true;
15775                   mem_loc_result = mem_loc_descriptor (XEXP (rtl, 0), int_mode,
15776                                                        mem_mode, initialized);
15777                   in_const_p = save_in_const_p;
15778                 }
15779                 break;
15780               }
15781           break;
15782         }
15783
15784     symref:
15785       mem_loc_result = new_addr_loc_descr (rtl, dtprel_false);
15786       vec_safe_push (used_rtx_array, rtl);
15787       break;
15788
15789     case CONCAT:
15790     case CONCATN:
15791     case VAR_LOCATION:
15792     case DEBUG_IMPLICIT_PTR:
15793       expansion_failed (NULL_TREE, rtl,
15794                         "CONCAT/CONCATN/VAR_LOCATION is handled only by loc_descriptor");
15795       return 0;
15796
15797     case ENTRY_VALUE:
15798       if (dwarf_strict && dwarf_version < 5)
15799         return NULL;
15800       if (REG_P (ENTRY_VALUE_EXP (rtl)))
15801         {
15802           if (!is_a <scalar_int_mode> (mode, &int_mode)
15803               || GET_MODE_SIZE (int_mode) > DWARF2_ADDR_SIZE)
15804             op0 = mem_loc_descriptor (ENTRY_VALUE_EXP (rtl), mode,
15805                                       VOIDmode, VAR_INIT_STATUS_INITIALIZED);
15806           else
15807             {
15808               unsigned int dbx_regnum = dbx_reg_number (ENTRY_VALUE_EXP (rtl));
15809               if (dbx_regnum == IGNORED_DWARF_REGNUM)
15810                 return NULL;
15811               op0 = one_reg_loc_descriptor (dbx_regnum,
15812                                             VAR_INIT_STATUS_INITIALIZED);
15813             }
15814         }
15815       else if (MEM_P (ENTRY_VALUE_EXP (rtl))
15816                && REG_P (XEXP (ENTRY_VALUE_EXP (rtl), 0)))
15817         {
15818           op0 = mem_loc_descriptor (ENTRY_VALUE_EXP (rtl), mode,
15819                                     VOIDmode, VAR_INIT_STATUS_INITIALIZED);
15820           if (op0 && op0->dw_loc_opc == DW_OP_fbreg)
15821             return NULL;
15822         }
15823       else
15824         gcc_unreachable ();
15825       if (op0 == NULL)
15826         return NULL;
15827       mem_loc_result = new_loc_descr (dwarf_OP (DW_OP_entry_value), 0, 0);
15828       mem_loc_result->dw_loc_oprnd1.val_class = dw_val_class_loc;
15829       mem_loc_result->dw_loc_oprnd1.v.val_loc = op0;
15830       break;
15831
15832     case DEBUG_PARAMETER_REF:
15833       mem_loc_result = parameter_ref_descriptor (rtl);
15834       break;
15835
15836     case PRE_MODIFY:
15837       /* Extract the PLUS expression nested inside and fall into
15838          PLUS code below.  */
15839       rtl = XEXP (rtl, 1);
15840       goto plus;
15841
15842     case PRE_INC:
15843     case PRE_DEC:
15844       /* Turn these into a PLUS expression and fall into the PLUS code
15845          below.  */
15846       rtl = gen_rtx_PLUS (mode, XEXP (rtl, 0),
15847                           gen_int_mode (GET_CODE (rtl) == PRE_INC
15848                                         ? GET_MODE_UNIT_SIZE (mem_mode)
15849                                         : -GET_MODE_UNIT_SIZE (mem_mode),
15850                                         mode));
15851
15852       /* fall through */
15853
15854     case PLUS:
15855     plus:
15856       if (is_based_loc (rtl)
15857           && is_a <scalar_int_mode> (mode, &int_mode)
15858           && (GET_MODE_SIZE (int_mode) <= DWARF2_ADDR_SIZE
15859               || XEXP (rtl, 0) == arg_pointer_rtx
15860               || XEXP (rtl, 0) == frame_pointer_rtx))
15861         mem_loc_result = based_loc_descr (XEXP (rtl, 0),
15862                                           INTVAL (XEXP (rtl, 1)),
15863                                           VAR_INIT_STATUS_INITIALIZED);
15864       else
15865         {
15866           mem_loc_result = mem_loc_descriptor (XEXP (rtl, 0), mode, mem_mode,
15867                                                VAR_INIT_STATUS_INITIALIZED);
15868           if (mem_loc_result == 0)
15869             break;
15870
15871           if (CONST_INT_P (XEXP (rtl, 1))
15872               && (GET_MODE_SIZE (as_a <scalar_int_mode> (mode))
15873                   <= DWARF2_ADDR_SIZE))
15874             loc_descr_plus_const (&mem_loc_result, INTVAL (XEXP (rtl, 1)));
15875           else
15876             {
15877               op1 = mem_loc_descriptor (XEXP (rtl, 1), mode, mem_mode,
15878                                         VAR_INIT_STATUS_INITIALIZED);
15879               if (op1 == 0)
15880                 return NULL;
15881               add_loc_descr (&mem_loc_result, op1);
15882               add_loc_descr (&mem_loc_result,
15883                              new_loc_descr (DW_OP_plus, 0, 0));
15884             }
15885         }
15886       break;
15887
15888     /* If a pseudo-reg is optimized away, it is possible for it to
15889        be replaced with a MEM containing a multiply or shift.  */
15890     case MINUS:
15891       op = DW_OP_minus;
15892       goto do_binop;
15893
15894     case MULT:
15895       op = DW_OP_mul;
15896       goto do_binop;
15897
15898     case DIV:
15899       if ((!dwarf_strict || dwarf_version >= 5)
15900           && is_a <scalar_int_mode> (mode, &int_mode)
15901           && GET_MODE_SIZE (int_mode) > DWARF2_ADDR_SIZE)
15902         {
15903           mem_loc_result = typed_binop (DW_OP_div, rtl,
15904                                         base_type_for_mode (mode, 0),
15905                                         int_mode, mem_mode);
15906           break;
15907         }
15908       op = DW_OP_div;
15909       goto do_binop;
15910
15911     case UMOD:
15912       op = DW_OP_mod;
15913       goto do_binop;
15914
15915     case ASHIFT:
15916       op = DW_OP_shl;
15917       goto do_shift;
15918
15919     case ASHIFTRT:
15920       op = DW_OP_shra;
15921       goto do_shift;
15922
15923     case LSHIFTRT:
15924       op = DW_OP_shr;
15925       goto do_shift;
15926
15927     do_shift:
15928       if (!is_a <scalar_int_mode> (mode, &int_mode))
15929         break;
15930       op0 = mem_loc_descriptor (XEXP (rtl, 0), int_mode, mem_mode,
15931                                 VAR_INIT_STATUS_INITIALIZED);
15932       {
15933         rtx rtlop1 = XEXP (rtl, 1);
15934         if (is_a <scalar_int_mode> (GET_MODE (rtlop1), &op1_mode)
15935             && GET_MODE_BITSIZE (op1_mode) < GET_MODE_BITSIZE (int_mode))
15936           rtlop1 = gen_rtx_ZERO_EXTEND (int_mode, rtlop1);
15937         op1 = mem_loc_descriptor (rtlop1, int_mode, mem_mode,
15938                                   VAR_INIT_STATUS_INITIALIZED);
15939       }
15940
15941       if (op0 == 0 || op1 == 0)
15942         break;
15943
15944       mem_loc_result = op0;
15945       add_loc_descr (&mem_loc_result, op1);
15946       add_loc_descr (&mem_loc_result, new_loc_descr (op, 0, 0));
15947       break;
15948
15949     case AND:
15950       op = DW_OP_and;
15951       goto do_binop;
15952
15953     case IOR:
15954       op = DW_OP_or;
15955       goto do_binop;
15956
15957     case XOR:
15958       op = DW_OP_xor;
15959       goto do_binop;
15960
15961     do_binop:
15962       op0 = mem_loc_descriptor (XEXP (rtl, 0), mode, mem_mode,
15963                                 VAR_INIT_STATUS_INITIALIZED);
15964       op1 = mem_loc_descriptor (XEXP (rtl, 1), mode, mem_mode,
15965                                 VAR_INIT_STATUS_INITIALIZED);
15966
15967       if (op0 == 0 || op1 == 0)
15968         break;
15969
15970       mem_loc_result = op0;
15971       add_loc_descr (&mem_loc_result, op1);
15972       add_loc_descr (&mem_loc_result, new_loc_descr (op, 0, 0));
15973       break;
15974
15975     case MOD:
15976       if ((!dwarf_strict || dwarf_version >= 5)
15977           && is_a <scalar_int_mode> (mode, &int_mode)
15978           && GET_MODE_SIZE (int_mode) > DWARF2_ADDR_SIZE)
15979         {
15980           mem_loc_result = typed_binop (DW_OP_mod, rtl,
15981                                         base_type_for_mode (mode, 0),
15982                                         int_mode, mem_mode);
15983           break;
15984         }
15985
15986       op0 = mem_loc_descriptor (XEXP (rtl, 0), mode, mem_mode,
15987                                 VAR_INIT_STATUS_INITIALIZED);
15988       op1 = mem_loc_descriptor (XEXP (rtl, 1), mode, mem_mode,
15989                                 VAR_INIT_STATUS_INITIALIZED);
15990
15991       if (op0 == 0 || op1 == 0)
15992         break;
15993
15994       mem_loc_result = op0;
15995       add_loc_descr (&mem_loc_result, op1);
15996       add_loc_descr (&mem_loc_result, new_loc_descr (DW_OP_over, 0, 0));
15997       add_loc_descr (&mem_loc_result, new_loc_descr (DW_OP_over, 0, 0));
15998       add_loc_descr (&mem_loc_result, new_loc_descr (DW_OP_div, 0, 0));
15999       add_loc_descr (&mem_loc_result, new_loc_descr (DW_OP_mul, 0, 0));
16000       add_loc_descr (&mem_loc_result, new_loc_descr (DW_OP_minus, 0, 0));
16001       break;
16002
16003     case UDIV:
16004       if ((!dwarf_strict || dwarf_version >= 5)
16005           && is_a <scalar_int_mode> (mode, &int_mode))
16006         {
16007           if (GET_MODE_SIZE (int_mode) > DWARF2_ADDR_SIZE)
16008             {
16009               op = DW_OP_div;
16010               goto do_binop;
16011             }
16012           mem_loc_result = typed_binop (DW_OP_div, rtl,
16013                                         base_type_for_mode (int_mode, 1),
16014                                         int_mode, mem_mode);
16015         }
16016       break;
16017
16018     case NOT:
16019       op = DW_OP_not;
16020       goto do_unop;
16021
16022     case ABS:
16023       op = DW_OP_abs;
16024       goto do_unop;
16025
16026     case NEG:
16027       op = DW_OP_neg;
16028       goto do_unop;
16029
16030     do_unop:
16031       op0 = mem_loc_descriptor (XEXP (rtl, 0), mode, mem_mode,
16032                                 VAR_INIT_STATUS_INITIALIZED);
16033
16034       if (op0 == 0)
16035         break;
16036
16037       mem_loc_result = op0;
16038       add_loc_descr (&mem_loc_result, new_loc_descr (op, 0, 0));
16039       break;
16040
16041     case CONST_INT:
16042       if (!is_a <scalar_int_mode> (mode, &int_mode)
16043           || GET_MODE_SIZE (int_mode) <= DWARF2_ADDR_SIZE
16044 #ifdef POINTERS_EXTEND_UNSIGNED
16045           || (int_mode == Pmode
16046               && mem_mode != VOIDmode
16047               && trunc_int_for_mode (INTVAL (rtl), ptr_mode) == INTVAL (rtl))
16048 #endif
16049           )
16050         {
16051           mem_loc_result = int_loc_descriptor (INTVAL (rtl));
16052           break;
16053         }
16054       if ((!dwarf_strict || dwarf_version >= 5)
16055           && (GET_MODE_BITSIZE (int_mode) == HOST_BITS_PER_WIDE_INT
16056               || GET_MODE_BITSIZE (int_mode) == HOST_BITS_PER_DOUBLE_INT))
16057         {
16058           dw_die_ref type_die = base_type_for_mode (int_mode, 1);
16059           scalar_int_mode amode;
16060           if (type_die == NULL)
16061             return NULL;
16062           if (INTVAL (rtl) >= 0
16063               && (int_mode_for_size (DWARF2_ADDR_SIZE * BITS_PER_UNIT, 0)
16064                   .exists (&amode))
16065               && trunc_int_for_mode (INTVAL (rtl), amode) == INTVAL (rtl)
16066               /* const DW_OP_convert <XXX> vs.
16067                  DW_OP_const_type <XXX, 1, const>.  */
16068               && size_of_int_loc_descriptor (INTVAL (rtl)) + 1 + 1
16069                  < (unsigned long) 1 + 1 + 1 + GET_MODE_SIZE (int_mode))
16070             {
16071               mem_loc_result = int_loc_descriptor (INTVAL (rtl));
16072               op0 = new_loc_descr (dwarf_OP (DW_OP_convert), 0, 0);
16073               op0->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
16074               op0->dw_loc_oprnd1.v.val_die_ref.die = type_die;
16075               op0->dw_loc_oprnd1.v.val_die_ref.external = 0;
16076               add_loc_descr (&mem_loc_result, op0);
16077               return mem_loc_result;
16078             }
16079           mem_loc_result = new_loc_descr (dwarf_OP (DW_OP_const_type), 0,
16080                                           INTVAL (rtl));
16081           mem_loc_result->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
16082           mem_loc_result->dw_loc_oprnd1.v.val_die_ref.die = type_die;
16083           mem_loc_result->dw_loc_oprnd1.v.val_die_ref.external = 0;
16084           if (GET_MODE_BITSIZE (int_mode) == HOST_BITS_PER_WIDE_INT)
16085             mem_loc_result->dw_loc_oprnd2.val_class = dw_val_class_const;
16086           else
16087             {
16088               mem_loc_result->dw_loc_oprnd2.val_class
16089                 = dw_val_class_const_double;
16090               mem_loc_result->dw_loc_oprnd2.v.val_double
16091                 = double_int::from_shwi (INTVAL (rtl));
16092             }
16093         }
16094       break;
16095
16096     case CONST_DOUBLE:
16097       if (!dwarf_strict || dwarf_version >= 5)
16098         {
16099           dw_die_ref type_die;
16100
16101           /* Note that if TARGET_SUPPORTS_WIDE_INT == 0, a
16102              CONST_DOUBLE rtx could represent either a large integer
16103              or a floating-point constant.  If TARGET_SUPPORTS_WIDE_INT != 0,
16104              the value is always a floating point constant.
16105
16106              When it is an integer, a CONST_DOUBLE is used whenever
16107              the constant requires 2 HWIs to be adequately represented.
16108              We output CONST_DOUBLEs as blocks.  */
16109           if (mode == VOIDmode
16110               || (GET_MODE (rtl) == VOIDmode
16111                   && maybe_ne (GET_MODE_BITSIZE (mode),
16112                                HOST_BITS_PER_DOUBLE_INT)))
16113             break;
16114           type_die = base_type_for_mode (mode, SCALAR_INT_MODE_P (mode));
16115           if (type_die == NULL)
16116             return NULL;
16117           mem_loc_result = new_loc_descr (dwarf_OP (DW_OP_const_type), 0, 0);
16118           mem_loc_result->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
16119           mem_loc_result->dw_loc_oprnd1.v.val_die_ref.die = type_die;
16120           mem_loc_result->dw_loc_oprnd1.v.val_die_ref.external = 0;
16121 #if TARGET_SUPPORTS_WIDE_INT == 0
16122           if (!SCALAR_FLOAT_MODE_P (mode))
16123             {
16124               mem_loc_result->dw_loc_oprnd2.val_class
16125                 = dw_val_class_const_double;
16126               mem_loc_result->dw_loc_oprnd2.v.val_double
16127                 = rtx_to_double_int (rtl);
16128             }
16129           else
16130 #endif
16131             {
16132               scalar_float_mode float_mode = as_a <scalar_float_mode> (mode);
16133               unsigned int length = GET_MODE_SIZE (float_mode);
16134               unsigned char *array = ggc_vec_alloc<unsigned char> (length);
16135
16136               insert_float (rtl, array);
16137               mem_loc_result->dw_loc_oprnd2.val_class = dw_val_class_vec;
16138               mem_loc_result->dw_loc_oprnd2.v.val_vec.length = length / 4;
16139               mem_loc_result->dw_loc_oprnd2.v.val_vec.elt_size = 4;
16140               mem_loc_result->dw_loc_oprnd2.v.val_vec.array = array;
16141             }
16142         }
16143       break;
16144
16145     case CONST_WIDE_INT:
16146       if (!dwarf_strict || dwarf_version >= 5)
16147         {
16148           dw_die_ref type_die;
16149
16150           type_die = base_type_for_mode (mode, SCALAR_INT_MODE_P (mode));
16151           if (type_die == NULL)
16152             return NULL;
16153           mem_loc_result = new_loc_descr (dwarf_OP (DW_OP_const_type), 0, 0);
16154           mem_loc_result->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
16155           mem_loc_result->dw_loc_oprnd1.v.val_die_ref.die = type_die;
16156           mem_loc_result->dw_loc_oprnd1.v.val_die_ref.external = 0;
16157           mem_loc_result->dw_loc_oprnd2.val_class
16158             = dw_val_class_wide_int;
16159           mem_loc_result->dw_loc_oprnd2.v.val_wide = ggc_alloc<wide_int> ();
16160           *mem_loc_result->dw_loc_oprnd2.v.val_wide = rtx_mode_t (rtl, mode);
16161         }
16162       break;
16163
16164     case CONST_POLY_INT:
16165       mem_loc_result = int_loc_descriptor (rtx_to_poly_int64 (rtl));
16166       break;
16167
16168     case EQ:
16169       mem_loc_result = scompare_loc_descriptor (DW_OP_eq, rtl, mem_mode);
16170       break;
16171
16172     case GE:
16173       mem_loc_result = scompare_loc_descriptor (DW_OP_ge, rtl, mem_mode);
16174       break;
16175
16176     case GT:
16177       mem_loc_result = scompare_loc_descriptor (DW_OP_gt, rtl, mem_mode);
16178       break;
16179
16180     case LE:
16181       mem_loc_result = scompare_loc_descriptor (DW_OP_le, rtl, mem_mode);
16182       break;
16183
16184     case LT:
16185       mem_loc_result = scompare_loc_descriptor (DW_OP_lt, rtl, mem_mode);
16186       break;
16187
16188     case NE:
16189       mem_loc_result = scompare_loc_descriptor (DW_OP_ne, rtl, mem_mode);
16190       break;
16191
16192     case GEU:
16193       mem_loc_result = ucompare_loc_descriptor (DW_OP_ge, rtl, mem_mode);
16194       break;
16195
16196     case GTU:
16197       mem_loc_result = ucompare_loc_descriptor (DW_OP_gt, rtl, mem_mode);
16198       break;
16199
16200     case LEU:
16201       mem_loc_result = ucompare_loc_descriptor (DW_OP_le, rtl, mem_mode);
16202       break;
16203
16204     case LTU:
16205       mem_loc_result = ucompare_loc_descriptor (DW_OP_lt, rtl, mem_mode);
16206       break;
16207
16208     case UMIN:
16209     case UMAX:
16210       if (!SCALAR_INT_MODE_P (mode))
16211         break;
16212       /* FALLTHRU */
16213     case SMIN:
16214     case SMAX:
16215       mem_loc_result = minmax_loc_descriptor (rtl, mode, mem_mode);
16216       break;
16217
16218     case ZERO_EXTRACT:
16219     case SIGN_EXTRACT:
16220       if (CONST_INT_P (XEXP (rtl, 1))
16221           && CONST_INT_P (XEXP (rtl, 2))
16222           && is_a <scalar_int_mode> (mode, &int_mode)
16223           && is_a <scalar_int_mode> (GET_MODE (XEXP (rtl, 0)), &inner_mode)
16224           && GET_MODE_SIZE (int_mode) <= DWARF2_ADDR_SIZE
16225           && GET_MODE_SIZE (inner_mode) <= DWARF2_ADDR_SIZE
16226           && ((unsigned) INTVAL (XEXP (rtl, 1))
16227               + (unsigned) INTVAL (XEXP (rtl, 2))
16228               <= GET_MODE_BITSIZE (int_mode)))
16229         {
16230           int shift, size;
16231           op0 = mem_loc_descriptor (XEXP (rtl, 0), inner_mode,
16232                                     mem_mode, VAR_INIT_STATUS_INITIALIZED);
16233           if (op0 == 0)
16234             break;
16235           if (GET_CODE (rtl) == SIGN_EXTRACT)
16236             op = DW_OP_shra;
16237           else
16238             op = DW_OP_shr;
16239           mem_loc_result = op0;
16240           size = INTVAL (XEXP (rtl, 1));
16241           shift = INTVAL (XEXP (rtl, 2));
16242           if (BITS_BIG_ENDIAN)
16243             shift = GET_MODE_BITSIZE (inner_mode) - shift - size;
16244           if (shift + size != (int) DWARF2_ADDR_SIZE)
16245             {
16246               add_loc_descr (&mem_loc_result,
16247                              int_loc_descriptor (DWARF2_ADDR_SIZE
16248                                                  - shift - size));
16249               add_loc_descr (&mem_loc_result, new_loc_descr (DW_OP_shl, 0, 0));
16250             }
16251           if (size != (int) DWARF2_ADDR_SIZE)
16252             {
16253               add_loc_descr (&mem_loc_result,
16254                              int_loc_descriptor (DWARF2_ADDR_SIZE - size));
16255               add_loc_descr (&mem_loc_result, new_loc_descr (op, 0, 0));
16256             }
16257         }
16258       break;
16259
16260     case IF_THEN_ELSE:
16261       {
16262         dw_loc_descr_ref op2, bra_node, drop_node;
16263         op0 = mem_loc_descriptor (XEXP (rtl, 0),
16264                                   GET_MODE (XEXP (rtl, 0)) == VOIDmode
16265                                   ? word_mode : GET_MODE (XEXP (rtl, 0)),
16266                                   mem_mode, VAR_INIT_STATUS_INITIALIZED);
16267         op1 = mem_loc_descriptor (XEXP (rtl, 1), mode, mem_mode,
16268                                   VAR_INIT_STATUS_INITIALIZED);
16269         op2 = mem_loc_descriptor (XEXP (rtl, 2), mode, mem_mode,
16270                                   VAR_INIT_STATUS_INITIALIZED);
16271         if (op0 == NULL || op1 == NULL || op2 == NULL)
16272           break;
16273
16274         mem_loc_result = op1;
16275         add_loc_descr (&mem_loc_result, op2);
16276         add_loc_descr (&mem_loc_result, op0);
16277         bra_node = new_loc_descr (DW_OP_bra, 0, 0);
16278         add_loc_descr (&mem_loc_result, bra_node);
16279         add_loc_descr (&mem_loc_result, new_loc_descr (DW_OP_swap, 0, 0));
16280         drop_node = new_loc_descr (DW_OP_drop, 0, 0);
16281         add_loc_descr (&mem_loc_result, drop_node);
16282         bra_node->dw_loc_oprnd1.val_class = dw_val_class_loc;
16283         bra_node->dw_loc_oprnd1.v.val_loc = drop_node;
16284       }
16285       break;
16286
16287     case FLOAT_EXTEND:
16288     case FLOAT_TRUNCATE:
16289     case FLOAT:
16290     case UNSIGNED_FLOAT:
16291     case FIX:
16292     case UNSIGNED_FIX:
16293       if (!dwarf_strict || dwarf_version >= 5)
16294         {
16295           dw_die_ref type_die;
16296           dw_loc_descr_ref cvt;
16297
16298           op0 = mem_loc_descriptor (XEXP (rtl, 0), GET_MODE (XEXP (rtl, 0)),
16299                                     mem_mode, VAR_INIT_STATUS_INITIALIZED);
16300           if (op0 == NULL)
16301             break;
16302           if (is_a <scalar_int_mode> (GET_MODE (XEXP (rtl, 0)), &int_mode)
16303               && (GET_CODE (rtl) == FLOAT
16304                   || GET_MODE_SIZE (int_mode) <= DWARF2_ADDR_SIZE))
16305             {
16306               type_die = base_type_for_mode (int_mode,
16307                                              GET_CODE (rtl) == UNSIGNED_FLOAT);
16308               if (type_die == NULL)
16309                 break;
16310               cvt = new_loc_descr (dwarf_OP (DW_OP_convert), 0, 0);
16311               cvt->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
16312               cvt->dw_loc_oprnd1.v.val_die_ref.die = type_die;
16313               cvt->dw_loc_oprnd1.v.val_die_ref.external = 0;
16314               add_loc_descr (&op0, cvt);
16315             }
16316           type_die = base_type_for_mode (mode, GET_CODE (rtl) == UNSIGNED_FIX);
16317           if (type_die == NULL)
16318             break;
16319           cvt = new_loc_descr (dwarf_OP (DW_OP_convert), 0, 0);
16320           cvt->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
16321           cvt->dw_loc_oprnd1.v.val_die_ref.die = type_die;
16322           cvt->dw_loc_oprnd1.v.val_die_ref.external = 0;
16323           add_loc_descr (&op0, cvt);
16324           if (is_a <scalar_int_mode> (mode, &int_mode)
16325               && (GET_CODE (rtl) == FIX
16326                   || GET_MODE_SIZE (int_mode) < DWARF2_ADDR_SIZE))
16327             {
16328               op0 = convert_descriptor_to_mode (int_mode, op0);
16329               if (op0 == NULL)
16330                 break;
16331             }
16332           mem_loc_result = op0;
16333         }
16334       break;
16335
16336     case CLZ:
16337     case CTZ:
16338     case FFS:
16339       if (is_a <scalar_int_mode> (mode, &int_mode))
16340         mem_loc_result = clz_loc_descriptor (rtl, int_mode, mem_mode);
16341       break;
16342
16343     case POPCOUNT:
16344     case PARITY:
16345       if (is_a <scalar_int_mode> (mode, &int_mode))
16346         mem_loc_result = popcount_loc_descriptor (rtl, int_mode, mem_mode);
16347       break;
16348
16349     case BSWAP:
16350       if (is_a <scalar_int_mode> (mode, &int_mode))
16351         mem_loc_result = bswap_loc_descriptor (rtl, int_mode, mem_mode);
16352       break;
16353
16354     case ROTATE:
16355     case ROTATERT:
16356       if (is_a <scalar_int_mode> (mode, &int_mode))
16357         mem_loc_result = rotate_loc_descriptor (rtl, int_mode, mem_mode);
16358       break;
16359
16360     case COMPARE:
16361       /* In theory, we could implement the above.  */
16362       /* DWARF cannot represent the unsigned compare operations
16363          natively.  */
16364     case SS_MULT:
16365     case US_MULT:
16366     case SS_DIV:
16367     case US_DIV:
16368     case SS_PLUS:
16369     case US_PLUS:
16370     case SS_MINUS:
16371     case US_MINUS:
16372     case SS_NEG:
16373     case US_NEG:
16374     case SS_ABS:
16375     case SS_ASHIFT:
16376     case US_ASHIFT:
16377     case SS_TRUNCATE:
16378     case US_TRUNCATE:
16379     case UNORDERED:
16380     case ORDERED:
16381     case UNEQ:
16382     case UNGE:
16383     case UNGT:
16384     case UNLE:
16385     case UNLT:
16386     case LTGT:
16387     case FRACT_CONVERT:
16388     case UNSIGNED_FRACT_CONVERT:
16389     case SAT_FRACT:
16390     case UNSIGNED_SAT_FRACT:
16391     case SQRT:
16392     case ASM_OPERANDS:
16393     case VEC_MERGE:
16394     case VEC_SELECT:
16395     case VEC_CONCAT:
16396     case VEC_DUPLICATE:
16397     case VEC_SERIES:
16398     case HIGH:
16399     case FMA:
16400     case STRICT_LOW_PART:
16401     case CONST_VECTOR:
16402     case CONST_FIXED:
16403     case CLRSB:
16404     case CLOBBER:
16405       break;
16406
16407     case CONST_STRING:
16408       resolve_one_addr (&rtl);
16409       goto symref;
16410
16411     /* RTL sequences inside PARALLEL record a series of DWARF operations for
16412        the expression.  An UNSPEC rtx represents a raw DWARF operation,
16413        new_loc_descr is called for it to build the operation directly.
16414        Otherwise mem_loc_descriptor is called recursively.  */
16415     case PARALLEL:
16416       {
16417         int index = 0;
16418         dw_loc_descr_ref exp_result = NULL;
16419
16420         for (; index < XVECLEN (rtl, 0); index++)
16421           {
16422             rtx elem = XVECEXP (rtl, 0, index);
16423             if (GET_CODE (elem) == UNSPEC)
16424               {
16425                 /* Each DWARF operation UNSPEC contain two operands, if
16426                    one operand is not used for the operation, const0_rtx is
16427                    passed.  */
16428                 gcc_assert (XVECLEN (elem, 0) == 2);
16429
16430                 HOST_WIDE_INT dw_op = XINT (elem, 1);
16431                 HOST_WIDE_INT oprnd1 = INTVAL (XVECEXP (elem, 0, 0));
16432                 HOST_WIDE_INT oprnd2 = INTVAL (XVECEXP (elem, 0, 1));
16433                 exp_result
16434                   = new_loc_descr ((enum dwarf_location_atom) dw_op, oprnd1,
16435                                    oprnd2);
16436               }
16437             else
16438               exp_result
16439                 = mem_loc_descriptor (elem, mode, mem_mode,
16440                                       VAR_INIT_STATUS_INITIALIZED);
16441
16442             if (!mem_loc_result)
16443               mem_loc_result = exp_result;
16444             else
16445               add_loc_descr (&mem_loc_result, exp_result);
16446           }
16447
16448         break;
16449       }
16450
16451     default:
16452       if (flag_checking)
16453         {
16454           print_rtl (stderr, rtl);
16455           gcc_unreachable ();
16456         }
16457       break;
16458     }
16459
16460   if (mem_loc_result && initialized == VAR_INIT_STATUS_UNINITIALIZED)
16461     add_loc_descr (&mem_loc_result, new_loc_descr (DW_OP_GNU_uninit, 0, 0));
16462
16463   return mem_loc_result;
16464 }
16465
16466 /* Return a descriptor that describes the concatenation of two locations.
16467    This is typically a complex variable.  */
16468
16469 static dw_loc_descr_ref
16470 concat_loc_descriptor (rtx x0, rtx x1, enum var_init_status initialized)
16471 {
16472   /* At present we only track constant-sized pieces.  */
16473   unsigned int size0, size1;
16474   if (!GET_MODE_SIZE (GET_MODE (x0)).is_constant (&size0)
16475       || !GET_MODE_SIZE (GET_MODE (x1)).is_constant (&size1))
16476     return 0;
16477
16478   dw_loc_descr_ref cc_loc_result = NULL;
16479   dw_loc_descr_ref x0_ref
16480     = loc_descriptor (x0, VOIDmode, VAR_INIT_STATUS_INITIALIZED);
16481   dw_loc_descr_ref x1_ref
16482     = loc_descriptor (x1, VOIDmode, VAR_INIT_STATUS_INITIALIZED);
16483
16484   if (x0_ref == 0 || x1_ref == 0)
16485     return 0;
16486
16487   cc_loc_result = x0_ref;
16488   add_loc_descr_op_piece (&cc_loc_result, size0);
16489
16490   add_loc_descr (&cc_loc_result, x1_ref);
16491   add_loc_descr_op_piece (&cc_loc_result, size1);
16492
16493   if (initialized == VAR_INIT_STATUS_UNINITIALIZED)
16494     add_loc_descr (&cc_loc_result, new_loc_descr (DW_OP_GNU_uninit, 0, 0));
16495
16496   return cc_loc_result;
16497 }
16498
16499 /* Return a descriptor that describes the concatenation of N
16500    locations.  */
16501
16502 static dw_loc_descr_ref
16503 concatn_loc_descriptor (rtx concatn, enum var_init_status initialized)
16504 {
16505   unsigned int i;
16506   dw_loc_descr_ref cc_loc_result = NULL;
16507   unsigned int n = XVECLEN (concatn, 0);
16508   unsigned int size;
16509
16510   for (i = 0; i < n; ++i)
16511     {
16512       dw_loc_descr_ref ref;
16513       rtx x = XVECEXP (concatn, 0, i);
16514
16515       /* At present we only track constant-sized pieces.  */
16516       if (!GET_MODE_SIZE (GET_MODE (x)).is_constant (&size))
16517         return NULL;
16518
16519       ref = loc_descriptor (x, VOIDmode, VAR_INIT_STATUS_INITIALIZED);
16520       if (ref == NULL)
16521         return NULL;
16522
16523       add_loc_descr (&cc_loc_result, ref);
16524       add_loc_descr_op_piece (&cc_loc_result, size);
16525     }
16526
16527   if (cc_loc_result && initialized == VAR_INIT_STATUS_UNINITIALIZED)
16528     add_loc_descr (&cc_loc_result, new_loc_descr (DW_OP_GNU_uninit, 0, 0));
16529
16530   return cc_loc_result;
16531 }
16532
16533 /* Helper function for loc_descriptor.  Return DW_OP_implicit_pointer
16534    for DEBUG_IMPLICIT_PTR RTL.  */
16535
16536 static dw_loc_descr_ref
16537 implicit_ptr_descriptor (rtx rtl, HOST_WIDE_INT offset)
16538 {
16539   dw_loc_descr_ref ret;
16540   dw_die_ref ref;
16541
16542   if (dwarf_strict && dwarf_version < 5)
16543     return NULL;
16544   gcc_assert (TREE_CODE (DEBUG_IMPLICIT_PTR_DECL (rtl)) == VAR_DECL
16545               || TREE_CODE (DEBUG_IMPLICIT_PTR_DECL (rtl)) == PARM_DECL
16546               || TREE_CODE (DEBUG_IMPLICIT_PTR_DECL (rtl)) == RESULT_DECL);
16547   ref = lookup_decl_die (DEBUG_IMPLICIT_PTR_DECL (rtl));
16548   ret = new_loc_descr (dwarf_OP (DW_OP_implicit_pointer), 0, offset);
16549   ret->dw_loc_oprnd2.val_class = dw_val_class_const;
16550   if (ref)
16551     {
16552       ret->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
16553       ret->dw_loc_oprnd1.v.val_die_ref.die = ref;
16554       ret->dw_loc_oprnd1.v.val_die_ref.external = 0;
16555     }
16556   else
16557     {
16558       ret->dw_loc_oprnd1.val_class = dw_val_class_decl_ref;
16559       ret->dw_loc_oprnd1.v.val_decl_ref = DEBUG_IMPLICIT_PTR_DECL (rtl);
16560     }
16561   return ret;
16562 }
16563
16564 /* Output a proper Dwarf location descriptor for a variable or parameter
16565    which is either allocated in a register or in a memory location.  For a
16566    register, we just generate an OP_REG and the register number.  For a
16567    memory location we provide a Dwarf postfix expression describing how to
16568    generate the (dynamic) address of the object onto the address stack.
16569
16570    MODE is mode of the decl if this loc_descriptor is going to be used in
16571    .debug_loc section where DW_OP_stack_value and DW_OP_implicit_value are
16572    allowed, VOIDmode otherwise.
16573
16574    If we don't know how to describe it, return 0.  */
16575
16576 static dw_loc_descr_ref
16577 loc_descriptor (rtx rtl, machine_mode mode,
16578                 enum var_init_status initialized)
16579 {
16580   dw_loc_descr_ref loc_result = NULL;
16581   scalar_int_mode int_mode;
16582
16583   switch (GET_CODE (rtl))
16584     {
16585     case SUBREG:
16586       /* The case of a subreg may arise when we have a local (register)
16587          variable or a formal (register) parameter which doesn't quite fill
16588          up an entire register.  For now, just assume that it is
16589          legitimate to make the Dwarf info refer to the whole register which
16590          contains the given subreg.  */
16591       if (REG_P (SUBREG_REG (rtl)) && subreg_lowpart_p (rtl))
16592         loc_result = loc_descriptor (SUBREG_REG (rtl),
16593                                      GET_MODE (SUBREG_REG (rtl)), initialized);
16594       else
16595         goto do_default;
16596       break;
16597
16598     case REG:
16599       loc_result = reg_loc_descriptor (rtl, initialized);
16600       break;
16601
16602     case MEM:
16603       loc_result = mem_loc_descriptor (XEXP (rtl, 0), get_address_mode (rtl),
16604                                        GET_MODE (rtl), initialized);
16605       if (loc_result == NULL)
16606         loc_result = tls_mem_loc_descriptor (rtl);
16607       if (loc_result == NULL)
16608         {
16609           rtx new_rtl = avoid_constant_pool_reference (rtl);
16610           if (new_rtl != rtl)
16611             loc_result = loc_descriptor (new_rtl, mode, initialized);
16612         }
16613       break;
16614
16615     case CONCAT:
16616       loc_result = concat_loc_descriptor (XEXP (rtl, 0), XEXP (rtl, 1),
16617                                           initialized);
16618       break;
16619
16620     case CONCATN:
16621       loc_result = concatn_loc_descriptor (rtl, initialized);
16622       break;
16623
16624     case VAR_LOCATION:
16625       /* Single part.  */
16626       if (GET_CODE (PAT_VAR_LOCATION_LOC (rtl)) != PARALLEL)
16627         {
16628           rtx loc = PAT_VAR_LOCATION_LOC (rtl);
16629           if (GET_CODE (loc) == EXPR_LIST)
16630             loc = XEXP (loc, 0);
16631           loc_result = loc_descriptor (loc, mode, initialized);
16632           break;
16633         }
16634
16635       rtl = XEXP (rtl, 1);
16636       /* FALLTHRU */
16637
16638     case PARALLEL:
16639       {
16640         rtvec par_elems = XVEC (rtl, 0);
16641         int num_elem = GET_NUM_ELEM (par_elems);
16642         machine_mode mode;
16643         int i, size;
16644
16645         /* Create the first one, so we have something to add to.  */
16646         loc_result = loc_descriptor (XEXP (RTVEC_ELT (par_elems, 0), 0),
16647                                      VOIDmode, initialized);
16648         if (loc_result == NULL)
16649           return NULL;
16650         mode = GET_MODE (XEXP (RTVEC_ELT (par_elems, 0), 0));
16651         /* At present we only track constant-sized pieces.  */
16652         if (!GET_MODE_SIZE (mode).is_constant (&size))
16653           return NULL;
16654         add_loc_descr_op_piece (&loc_result, size);
16655         for (i = 1; i < num_elem; i++)
16656           {
16657             dw_loc_descr_ref temp;
16658
16659             temp = loc_descriptor (XEXP (RTVEC_ELT (par_elems, i), 0),
16660                                    VOIDmode, initialized);
16661             if (temp == NULL)
16662               return NULL;
16663             add_loc_descr (&loc_result, temp);
16664             mode = GET_MODE (XEXP (RTVEC_ELT (par_elems, i), 0));
16665             /* At present we only track constant-sized pieces.  */
16666             if (!GET_MODE_SIZE (mode).is_constant (&size))
16667               return NULL;
16668             add_loc_descr_op_piece (&loc_result, size);
16669           }
16670       }
16671       break;
16672
16673     case CONST_INT:
16674       if (mode != VOIDmode && mode != BLKmode)
16675         {
16676           int_mode = as_a <scalar_int_mode> (mode);
16677           loc_result = address_of_int_loc_descriptor (GET_MODE_SIZE (int_mode),
16678                                                       INTVAL (rtl));
16679         }
16680       break;
16681
16682     case CONST_DOUBLE:
16683       if (mode == VOIDmode)
16684         mode = GET_MODE (rtl);
16685
16686       if (mode != VOIDmode && (dwarf_version >= 4 || !dwarf_strict))
16687         {
16688           gcc_assert (mode == GET_MODE (rtl) || VOIDmode == GET_MODE (rtl));
16689
16690           /* Note that a CONST_DOUBLE rtx could represent either an integer
16691              or a floating-point constant.  A CONST_DOUBLE is used whenever
16692              the constant requires more than one word in order to be
16693              adequately represented.  We output CONST_DOUBLEs as blocks.  */
16694           scalar_mode smode = as_a <scalar_mode> (mode);
16695           loc_result = new_loc_descr (DW_OP_implicit_value,
16696                                       GET_MODE_SIZE (smode), 0);
16697 #if TARGET_SUPPORTS_WIDE_INT == 0
16698           if (!SCALAR_FLOAT_MODE_P (smode))
16699             {
16700               loc_result->dw_loc_oprnd2.val_class = dw_val_class_const_double;
16701               loc_result->dw_loc_oprnd2.v.val_double
16702                 = rtx_to_double_int (rtl);
16703             }
16704           else
16705 #endif
16706             {
16707               unsigned int length = GET_MODE_SIZE (smode);
16708               unsigned char *array = ggc_vec_alloc<unsigned char> (length);
16709
16710               insert_float (rtl, array);
16711               loc_result->dw_loc_oprnd2.val_class = dw_val_class_vec;
16712               loc_result->dw_loc_oprnd2.v.val_vec.length = length / 4;
16713               loc_result->dw_loc_oprnd2.v.val_vec.elt_size = 4;
16714               loc_result->dw_loc_oprnd2.v.val_vec.array = array;
16715             }
16716         }
16717       break;
16718
16719     case CONST_WIDE_INT:
16720       if (mode == VOIDmode)
16721         mode = GET_MODE (rtl);
16722
16723       if (mode != VOIDmode && (dwarf_version >= 4 || !dwarf_strict))
16724         {
16725           int_mode = as_a <scalar_int_mode> (mode);
16726           loc_result = new_loc_descr (DW_OP_implicit_value,
16727                                       GET_MODE_SIZE (int_mode), 0);
16728           loc_result->dw_loc_oprnd2.val_class = dw_val_class_wide_int;
16729           loc_result->dw_loc_oprnd2.v.val_wide = ggc_alloc<wide_int> ();
16730           *loc_result->dw_loc_oprnd2.v.val_wide = rtx_mode_t (rtl, int_mode);
16731         }
16732       break;
16733
16734     case CONST_VECTOR:
16735       if (mode == VOIDmode)
16736         mode = GET_MODE (rtl);
16737
16738       if (mode != VOIDmode && (dwarf_version >= 4 || !dwarf_strict))
16739         {
16740           unsigned int length;
16741           if (!CONST_VECTOR_NUNITS (rtl).is_constant (&length))
16742             return NULL;
16743
16744           unsigned int elt_size = GET_MODE_UNIT_SIZE (GET_MODE (rtl));
16745           unsigned char *array
16746             = ggc_vec_alloc<unsigned char> (length * elt_size);
16747           unsigned int i;
16748           unsigned char *p;
16749           machine_mode imode = GET_MODE_INNER (mode);
16750
16751           gcc_assert (mode == GET_MODE (rtl) || VOIDmode == GET_MODE (rtl));
16752           switch (GET_MODE_CLASS (mode))
16753             {
16754             case MODE_VECTOR_INT:
16755               for (i = 0, p = array; i < length; i++, p += elt_size)
16756                 {
16757                   rtx elt = CONST_VECTOR_ELT (rtl, i);
16758                   insert_wide_int (rtx_mode_t (elt, imode), p, elt_size);
16759                 }
16760               break;
16761
16762             case MODE_VECTOR_FLOAT:
16763               for (i = 0, p = array; i < length; i++, p += elt_size)
16764                 {
16765                   rtx elt = CONST_VECTOR_ELT (rtl, i);
16766                   insert_float (elt, p);
16767                 }
16768               break;
16769
16770             default:
16771               gcc_unreachable ();
16772             }
16773
16774           loc_result = new_loc_descr (DW_OP_implicit_value,
16775                                       length * elt_size, 0);
16776           loc_result->dw_loc_oprnd2.val_class = dw_val_class_vec;
16777           loc_result->dw_loc_oprnd2.v.val_vec.length = length;
16778           loc_result->dw_loc_oprnd2.v.val_vec.elt_size = elt_size;
16779           loc_result->dw_loc_oprnd2.v.val_vec.array = array;
16780         }
16781       break;
16782
16783     case CONST:
16784       if (mode == VOIDmode
16785           || CONST_SCALAR_INT_P (XEXP (rtl, 0))
16786           || CONST_DOUBLE_AS_FLOAT_P (XEXP (rtl, 0))
16787           || GET_CODE (XEXP (rtl, 0)) == CONST_VECTOR)
16788         {
16789           loc_result = loc_descriptor (XEXP (rtl, 0), mode, initialized);
16790           break;
16791         }
16792       /* FALLTHROUGH */
16793     case SYMBOL_REF:
16794       if (!const_ok_for_output (rtl))
16795         break;
16796       /* FALLTHROUGH */
16797     case LABEL_REF:
16798       if (is_a <scalar_int_mode> (mode, &int_mode)
16799           && GET_MODE_SIZE (int_mode) == DWARF2_ADDR_SIZE
16800           && (dwarf_version >= 4 || !dwarf_strict))
16801         {
16802          loc_result = new_addr_loc_descr (rtl, dtprel_false);
16803           add_loc_descr (&loc_result, new_loc_descr (DW_OP_stack_value, 0, 0));
16804           vec_safe_push (used_rtx_array, rtl);
16805         }
16806       break;
16807
16808     case DEBUG_IMPLICIT_PTR:
16809       loc_result = implicit_ptr_descriptor (rtl, 0);
16810       break;
16811
16812     case PLUS:
16813       if (GET_CODE (XEXP (rtl, 0)) == DEBUG_IMPLICIT_PTR
16814           && CONST_INT_P (XEXP (rtl, 1)))
16815         {
16816           loc_result
16817             = implicit_ptr_descriptor (XEXP (rtl, 0), INTVAL (XEXP (rtl, 1)));
16818           break;
16819         }
16820       /* FALLTHRU */
16821     do_default:
16822     default:
16823       if ((is_a <scalar_int_mode> (mode, &int_mode)
16824            && GET_MODE (rtl) == int_mode
16825            && GET_MODE_SIZE (int_mode) <= DWARF2_ADDR_SIZE
16826            && dwarf_version >= 4)
16827           || (!dwarf_strict && mode != VOIDmode && mode != BLKmode))
16828         {
16829           /* Value expression.  */
16830           loc_result = mem_loc_descriptor (rtl, mode, VOIDmode, initialized);
16831           if (loc_result)
16832             add_loc_descr (&loc_result,
16833                            new_loc_descr (DW_OP_stack_value, 0, 0));
16834         }
16835       break;
16836     }
16837
16838   return loc_result;
16839 }
16840
16841 /* We need to figure out what section we should use as the base for the
16842    address ranges where a given location is valid.
16843    1. If this particular DECL has a section associated with it, use that.
16844    2. If this function has a section associated with it, use that.
16845    3. Otherwise, use the text section.
16846    XXX: If you split a variable across multiple sections, we won't notice.  */
16847
16848 static const char *
16849 secname_for_decl (const_tree decl)
16850 {
16851   const char *secname;
16852
16853   if (VAR_OR_FUNCTION_DECL_P (decl)
16854       && (DECL_EXTERNAL (decl) || TREE_PUBLIC (decl) || TREE_STATIC (decl))
16855       && DECL_SECTION_NAME (decl))
16856     secname = DECL_SECTION_NAME (decl);
16857   else if (current_function_decl && DECL_SECTION_NAME (current_function_decl))
16858     {
16859       if (in_cold_section_p)
16860         {
16861           section *sec = current_function_section ();
16862           if (sec->common.flags & SECTION_NAMED)
16863             return sec->named.name;
16864         }
16865       secname = DECL_SECTION_NAME (current_function_decl);
16866     }
16867   else if (cfun && in_cold_section_p)
16868     secname = crtl->subsections.cold_section_label;
16869   else
16870     secname = text_section_label;
16871
16872   return secname;
16873 }
16874
16875 /* Return true when DECL_BY_REFERENCE is defined and set for DECL.  */
16876
16877 static bool
16878 decl_by_reference_p (tree decl)
16879 {
16880   return ((TREE_CODE (decl) == PARM_DECL || TREE_CODE (decl) == RESULT_DECL
16881            || VAR_P (decl))
16882           && DECL_BY_REFERENCE (decl));
16883 }
16884
16885 /* Helper function for dw_loc_list.  Compute proper Dwarf location descriptor
16886    for VARLOC.  */
16887
16888 static dw_loc_descr_ref
16889 dw_loc_list_1 (tree loc, rtx varloc, int want_address,
16890                enum var_init_status initialized)
16891 {
16892   int have_address = 0;
16893   dw_loc_descr_ref descr;
16894   machine_mode mode;
16895
16896   if (want_address != 2)
16897     {
16898       gcc_assert (GET_CODE (varloc) == VAR_LOCATION);
16899       /* Single part.  */
16900       if (GET_CODE (PAT_VAR_LOCATION_LOC (varloc)) != PARALLEL)
16901         {
16902           varloc = PAT_VAR_LOCATION_LOC (varloc);
16903           if (GET_CODE (varloc) == EXPR_LIST)
16904             varloc = XEXP (varloc, 0);
16905           mode = GET_MODE (varloc);
16906           if (MEM_P (varloc))
16907             {
16908               rtx addr = XEXP (varloc, 0);
16909               descr = mem_loc_descriptor (addr, get_address_mode (varloc),
16910                                           mode, initialized);
16911               if (descr)
16912                 have_address = 1;
16913               else
16914                 {
16915                   rtx x = avoid_constant_pool_reference (varloc);
16916                   if (x != varloc)
16917                     descr = mem_loc_descriptor (x, mode, VOIDmode,
16918                                                 initialized);
16919                 }
16920             }
16921           else
16922             descr = mem_loc_descriptor (varloc, mode, VOIDmode, initialized);
16923         }
16924       else
16925         return 0;
16926     }
16927   else
16928     {
16929       if (GET_CODE (varloc) == VAR_LOCATION)
16930         mode = DECL_MODE (PAT_VAR_LOCATION_DECL (varloc));
16931       else
16932         mode = DECL_MODE (loc);
16933       descr = loc_descriptor (varloc, mode, initialized);
16934       have_address = 1;
16935     }
16936
16937   if (!descr)
16938     return 0;
16939
16940   if (want_address == 2 && !have_address
16941       && (dwarf_version >= 4 || !dwarf_strict))
16942     {
16943       if (int_size_in_bytes (TREE_TYPE (loc)) > DWARF2_ADDR_SIZE)
16944         {
16945           expansion_failed (loc, NULL_RTX,
16946                             "DWARF address size mismatch");
16947           return 0;
16948         }
16949       add_loc_descr (&descr, new_loc_descr (DW_OP_stack_value, 0, 0));
16950       have_address = 1;
16951     }
16952   /* Show if we can't fill the request for an address.  */
16953   if (want_address && !have_address)
16954     {
16955       expansion_failed (loc, NULL_RTX,
16956                         "Want address and only have value");
16957       return 0;
16958     }
16959
16960   /* If we've got an address and don't want one, dereference.  */
16961   if (!want_address && have_address)
16962     {
16963       HOST_WIDE_INT size = int_size_in_bytes (TREE_TYPE (loc));
16964       enum dwarf_location_atom op;
16965
16966       if (size > DWARF2_ADDR_SIZE || size == -1)
16967         {
16968           expansion_failed (loc, NULL_RTX,
16969                             "DWARF address size mismatch");
16970           return 0;
16971         }
16972       else if (size == DWARF2_ADDR_SIZE)
16973         op = DW_OP_deref;
16974       else
16975         op = DW_OP_deref_size;
16976
16977       add_loc_descr (&descr, new_loc_descr (op, size, 0));
16978     }
16979
16980   return descr;
16981 }
16982
16983 /* Create a DW_OP_piece or DW_OP_bit_piece for bitsize, or return NULL
16984    if it is not possible.  */
16985
16986 static dw_loc_descr_ref
16987 new_loc_descr_op_bit_piece (HOST_WIDE_INT bitsize, HOST_WIDE_INT offset)
16988 {
16989   if ((bitsize % BITS_PER_UNIT) == 0 && offset == 0)
16990     return new_loc_descr (DW_OP_piece, bitsize / BITS_PER_UNIT, 0);
16991   else if (dwarf_version >= 3 || !dwarf_strict)
16992     return new_loc_descr (DW_OP_bit_piece, bitsize, offset);
16993   else
16994     return NULL;
16995 }
16996
16997 /* Helper function for dw_loc_list.  Compute proper Dwarf location descriptor
16998    for VAR_LOC_NOTE for variable DECL that has been optimized by SRA.  */
16999
17000 static dw_loc_descr_ref
17001 dw_sra_loc_expr (tree decl, rtx loc)
17002 {
17003   rtx p;
17004   unsigned HOST_WIDE_INT padsize = 0;
17005   dw_loc_descr_ref descr, *descr_tail;
17006   unsigned HOST_WIDE_INT decl_size;
17007   rtx varloc;
17008   enum var_init_status initialized;
17009
17010   if (DECL_SIZE (decl) == NULL
17011       || !tree_fits_uhwi_p (DECL_SIZE (decl)))
17012     return NULL;
17013
17014   decl_size = tree_to_uhwi (DECL_SIZE (decl));
17015   descr = NULL;
17016   descr_tail = &descr;
17017
17018   for (p = loc; p; p = XEXP (p, 1))
17019     {
17020       unsigned HOST_WIDE_INT bitsize = decl_piece_bitsize (p);
17021       rtx loc_note = *decl_piece_varloc_ptr (p);
17022       dw_loc_descr_ref cur_descr;
17023       dw_loc_descr_ref *tail, last = NULL;
17024       unsigned HOST_WIDE_INT opsize = 0;
17025
17026       if (loc_note == NULL_RTX
17027           || NOTE_VAR_LOCATION_LOC (loc_note) == NULL_RTX)
17028         {
17029           padsize += bitsize;
17030           continue;
17031         }
17032       initialized = NOTE_VAR_LOCATION_STATUS (loc_note);
17033       varloc = NOTE_VAR_LOCATION (loc_note);
17034       cur_descr = dw_loc_list_1 (decl, varloc, 2, initialized);
17035       if (cur_descr == NULL)
17036         {
17037           padsize += bitsize;
17038           continue;
17039         }
17040
17041       /* Check that cur_descr either doesn't use
17042          DW_OP_*piece operations, or their sum is equal
17043          to bitsize.  Otherwise we can't embed it.  */
17044       for (tail = &cur_descr; *tail != NULL;
17045            tail = &(*tail)->dw_loc_next)
17046         if ((*tail)->dw_loc_opc == DW_OP_piece)
17047           {
17048             opsize += (*tail)->dw_loc_oprnd1.v.val_unsigned
17049                       * BITS_PER_UNIT;
17050             last = *tail;
17051           }
17052         else if ((*tail)->dw_loc_opc == DW_OP_bit_piece)
17053           {
17054             opsize += (*tail)->dw_loc_oprnd1.v.val_unsigned;
17055             last = *tail;
17056           }
17057
17058       if (last != NULL && opsize != bitsize)
17059         {
17060           padsize += bitsize;
17061           /* Discard the current piece of the descriptor and release any
17062              addr_table entries it uses.  */
17063           remove_loc_list_addr_table_entries (cur_descr);
17064           continue;
17065         }
17066
17067       /* If there is a hole, add DW_OP_*piece after empty DWARF
17068          expression, which means that those bits are optimized out.  */
17069       if (padsize)
17070         {
17071           if (padsize > decl_size)
17072             {
17073               remove_loc_list_addr_table_entries (cur_descr);
17074               goto discard_descr;
17075             }
17076           decl_size -= padsize;
17077           *descr_tail = new_loc_descr_op_bit_piece (padsize, 0);
17078           if (*descr_tail == NULL)
17079             {
17080               remove_loc_list_addr_table_entries (cur_descr);
17081               goto discard_descr;
17082             }
17083           descr_tail = &(*descr_tail)->dw_loc_next;
17084           padsize = 0;
17085         }
17086       *descr_tail = cur_descr;
17087       descr_tail = tail;
17088       if (bitsize > decl_size)
17089         goto discard_descr;
17090       decl_size -= bitsize;
17091       if (last == NULL)
17092         {
17093           HOST_WIDE_INT offset = 0;
17094           if (GET_CODE (varloc) == VAR_LOCATION
17095               && GET_CODE (PAT_VAR_LOCATION_LOC (varloc)) != PARALLEL)
17096             {
17097               varloc = PAT_VAR_LOCATION_LOC (varloc);
17098               if (GET_CODE (varloc) == EXPR_LIST)
17099                 varloc = XEXP (varloc, 0);
17100             }
17101           do 
17102             {
17103               if (GET_CODE (varloc) == CONST
17104                   || GET_CODE (varloc) == SIGN_EXTEND
17105                   || GET_CODE (varloc) == ZERO_EXTEND)
17106                 varloc = XEXP (varloc, 0);
17107               else if (GET_CODE (varloc) == SUBREG)
17108                 varloc = SUBREG_REG (varloc);
17109               else
17110                 break;
17111             }
17112           while (1);
17113           /* DW_OP_bit_size offset should be zero for register
17114              or implicit location descriptions and empty location
17115              descriptions, but for memory addresses needs big endian
17116              adjustment.  */
17117           if (MEM_P (varloc))
17118             {
17119               unsigned HOST_WIDE_INT memsize;
17120               if (!poly_uint64 (MEM_SIZE (varloc)).is_constant (&memsize))
17121                 goto discard_descr;
17122               memsize *= BITS_PER_UNIT;
17123               if (memsize != bitsize)
17124                 {
17125                   if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN
17126                       && (memsize > BITS_PER_WORD || bitsize > BITS_PER_WORD))
17127                     goto discard_descr;
17128                   if (memsize < bitsize)
17129                     goto discard_descr;
17130                   if (BITS_BIG_ENDIAN)
17131                     offset = memsize - bitsize;
17132                 }
17133             }
17134
17135           *descr_tail = new_loc_descr_op_bit_piece (bitsize, offset);
17136           if (*descr_tail == NULL)
17137             goto discard_descr;
17138           descr_tail = &(*descr_tail)->dw_loc_next;
17139         }
17140     }
17141
17142   /* If there were any non-empty expressions, add padding till the end of
17143      the decl.  */
17144   if (descr != NULL && decl_size != 0)
17145     {
17146       *descr_tail = new_loc_descr_op_bit_piece (decl_size, 0);
17147       if (*descr_tail == NULL)
17148         goto discard_descr;
17149     }
17150   return descr;
17151
17152 discard_descr:
17153   /* Discard the descriptor and release any addr_table entries it uses.  */
17154   remove_loc_list_addr_table_entries (descr);
17155   return NULL;
17156 }
17157
17158 /* Return the dwarf representation of the location list LOC_LIST of
17159    DECL.  WANT_ADDRESS has the same meaning as in loc_list_from_tree
17160    function.  */
17161
17162 static dw_loc_list_ref
17163 dw_loc_list (var_loc_list *loc_list, tree decl, int want_address)
17164 {
17165   const char *endname, *secname;
17166   var_loc_view endview;
17167   rtx varloc;
17168   enum var_init_status initialized;
17169   struct var_loc_node *node;
17170   dw_loc_descr_ref descr;
17171   char label_id[MAX_ARTIFICIAL_LABEL_BYTES];
17172   dw_loc_list_ref list = NULL;
17173   dw_loc_list_ref *listp = &list;
17174
17175   /* Now that we know what section we are using for a base,
17176      actually construct the list of locations.
17177      The first location information is what is passed to the
17178      function that creates the location list, and the remaining
17179      locations just get added on to that list.
17180      Note that we only know the start address for a location
17181      (IE location changes), so to build the range, we use
17182      the range [current location start, next location start].
17183      This means we have to special case the last node, and generate
17184      a range of [last location start, end of function label].  */
17185
17186   if (cfun && crtl->has_bb_partition)
17187     {
17188       bool save_in_cold_section_p = in_cold_section_p;
17189       in_cold_section_p = first_function_block_is_cold;
17190       if (loc_list->last_before_switch == NULL)
17191         in_cold_section_p = !in_cold_section_p;
17192       secname = secname_for_decl (decl);
17193       in_cold_section_p = save_in_cold_section_p;
17194     }
17195   else
17196     secname = secname_for_decl (decl);
17197
17198   for (node = loc_list->first; node; node = node->next)
17199     {
17200       bool range_across_switch = false;
17201       if (GET_CODE (node->loc) == EXPR_LIST
17202           || NOTE_VAR_LOCATION_LOC (node->loc) != NULL_RTX)
17203         {
17204           if (GET_CODE (node->loc) == EXPR_LIST)
17205             {
17206               descr = NULL;
17207               /* This requires DW_OP_{,bit_}piece, which is not usable
17208                  inside DWARF expressions.  */
17209               if (want_address == 2)
17210                 descr = dw_sra_loc_expr (decl, node->loc);
17211             }
17212           else
17213             {
17214               initialized = NOTE_VAR_LOCATION_STATUS (node->loc);
17215               varloc = NOTE_VAR_LOCATION (node->loc);
17216               descr = dw_loc_list_1 (decl, varloc, want_address, initialized);
17217             }
17218           if (descr)
17219             {
17220               /* If section switch happens in between node->label
17221                  and node->next->label (or end of function) and
17222                  we can't emit it as a single entry list,
17223                  emit two ranges, first one ending at the end
17224                  of first partition and second one starting at the
17225                  beginning of second partition.  */
17226               if (node == loc_list->last_before_switch
17227                   && (node != loc_list->first || loc_list->first->next
17228                       /* If we are to emit a view number, we will emit
17229                          a loclist rather than a single location
17230                          expression for the entire function (see
17231                          loc_list_has_views), so we have to split the
17232                          range that straddles across partitions.  */
17233                       || !ZERO_VIEW_P (node->view))
17234                   && current_function_decl)
17235                 {
17236                   endname = cfun->fde->dw_fde_end;
17237                   endview = 0;
17238                   range_across_switch = true;
17239                 }
17240               /* The variable has a location between NODE->LABEL and
17241                  NODE->NEXT->LABEL.  */
17242               else if (node->next)
17243                 endname = node->next->label, endview = node->next->view;
17244               /* If the variable has a location at the last label
17245                  it keeps its location until the end of function.  */
17246               else if (!current_function_decl)
17247                 endname = text_end_label, endview = 0;
17248               else
17249                 {
17250                   ASM_GENERATE_INTERNAL_LABEL (label_id, FUNC_END_LABEL,
17251                                                current_function_funcdef_no);
17252                   endname = ggc_strdup (label_id);
17253                   endview = 0;
17254                 }
17255
17256               *listp = new_loc_list (descr, node->label, node->view,
17257                                      endname, endview, secname);
17258               if (TREE_CODE (decl) == PARM_DECL
17259                   && node == loc_list->first
17260                   && NOTE_P (node->loc)
17261                   && strcmp (node->label, endname) == 0)
17262                 (*listp)->force = true;
17263               listp = &(*listp)->dw_loc_next;
17264             }
17265         }
17266
17267       if (cfun
17268           && crtl->has_bb_partition
17269           && node == loc_list->last_before_switch)
17270         {
17271           bool save_in_cold_section_p = in_cold_section_p;
17272           in_cold_section_p = !first_function_block_is_cold;
17273           secname = secname_for_decl (decl);
17274           in_cold_section_p = save_in_cold_section_p;
17275         }
17276
17277       if (range_across_switch)
17278         {
17279           if (GET_CODE (node->loc) == EXPR_LIST)
17280             descr = dw_sra_loc_expr (decl, node->loc);
17281           else
17282             {
17283               initialized = NOTE_VAR_LOCATION_STATUS (node->loc);
17284               varloc = NOTE_VAR_LOCATION (node->loc);
17285               descr = dw_loc_list_1 (decl, varloc, want_address,
17286                                      initialized);
17287             }
17288           gcc_assert (descr);
17289           /* The variable has a location between NODE->LABEL and
17290              NODE->NEXT->LABEL.  */
17291           if (node->next)
17292             endname = node->next->label, endview = node->next->view;
17293           else
17294             endname = cfun->fde->dw_fde_second_end, endview = 0;
17295           *listp = new_loc_list (descr, cfun->fde->dw_fde_second_begin, 0,
17296                                  endname, endview, secname);
17297           listp = &(*listp)->dw_loc_next;
17298         }
17299     }
17300
17301   /* Try to avoid the overhead of a location list emitting a location
17302      expression instead, but only if we didn't have more than one
17303      location entry in the first place.  If some entries were not
17304      representable, we don't want to pretend a single entry that was
17305      applies to the entire scope in which the variable is
17306      available.  */
17307   if (list && loc_list->first->next)
17308     gen_llsym (list);
17309   else
17310     maybe_gen_llsym (list);
17311
17312   return list;
17313 }
17314
17315 /* Return if the loc_list has only single element and thus can be represented
17316    as location description.   */
17317
17318 static bool
17319 single_element_loc_list_p (dw_loc_list_ref list)
17320 {
17321   gcc_assert (!list->dw_loc_next || list->ll_symbol);
17322   return !list->ll_symbol;
17323 }
17324
17325 /* Duplicate a single element of location list.  */
17326
17327 static inline dw_loc_descr_ref
17328 copy_loc_descr (dw_loc_descr_ref ref)
17329 {
17330   dw_loc_descr_ref copy = ggc_alloc<dw_loc_descr_node> ();
17331   memcpy (copy, ref, sizeof (dw_loc_descr_node));
17332   return copy;
17333 }
17334
17335 /* To each location in list LIST append loc descr REF.  */
17336
17337 static void
17338 add_loc_descr_to_each (dw_loc_list_ref list, dw_loc_descr_ref ref)
17339 {
17340   dw_loc_descr_ref copy;
17341   add_loc_descr (&list->expr, ref);
17342   list = list->dw_loc_next;
17343   while (list)
17344     {
17345       copy = copy_loc_descr (ref);
17346       add_loc_descr (&list->expr, copy);
17347       while (copy->dw_loc_next)
17348         copy = copy->dw_loc_next = copy_loc_descr (copy->dw_loc_next);
17349       list = list->dw_loc_next;
17350     }
17351 }
17352
17353 /* To each location in list LIST prepend loc descr REF.  */
17354
17355 static void
17356 prepend_loc_descr_to_each (dw_loc_list_ref list, dw_loc_descr_ref ref)
17357 {
17358   dw_loc_descr_ref copy;
17359   dw_loc_descr_ref ref_end = list->expr;
17360   add_loc_descr (&ref, list->expr);
17361   list->expr = ref;
17362   list = list->dw_loc_next;
17363   while (list)
17364     {
17365       dw_loc_descr_ref end = list->expr;
17366       list->expr = copy = copy_loc_descr (ref);
17367       while (copy->dw_loc_next != ref_end)
17368         copy = copy->dw_loc_next = copy_loc_descr (copy->dw_loc_next);
17369       copy->dw_loc_next = end;
17370       list = list->dw_loc_next;
17371     }
17372 }
17373
17374 /* Given two lists RET and LIST
17375    produce location list that is result of adding expression in LIST
17376    to expression in RET on each position in program.
17377    Might be destructive on both RET and LIST.
17378
17379    TODO: We handle only simple cases of RET or LIST having at most one
17380    element.  General case would involve sorting the lists in program order
17381    and merging them that will need some additional work.
17382    Adding that will improve quality of debug info especially for SRA-ed
17383    structures.  */
17384
17385 static void
17386 add_loc_list (dw_loc_list_ref *ret, dw_loc_list_ref list)
17387 {
17388   if (!list)
17389     return;
17390   if (!*ret)
17391     {
17392       *ret = list;
17393       return;
17394     }
17395   if (!list->dw_loc_next)
17396     {
17397       add_loc_descr_to_each (*ret, list->expr);
17398       return;
17399     }
17400   if (!(*ret)->dw_loc_next)
17401     {
17402       prepend_loc_descr_to_each (list, (*ret)->expr);
17403       *ret = list;
17404       return;
17405     }
17406   expansion_failed (NULL_TREE, NULL_RTX,
17407                     "Don't know how to merge two non-trivial"
17408                     " location lists.\n");
17409   *ret = NULL;
17410   return;
17411 }
17412
17413 /* LOC is constant expression.  Try a luck, look it up in constant
17414    pool and return its loc_descr of its address.  */
17415
17416 static dw_loc_descr_ref
17417 cst_pool_loc_descr (tree loc)
17418 {
17419   /* Get an RTL for this, if something has been emitted.  */
17420   rtx rtl = lookup_constant_def (loc);
17421
17422   if (!rtl || !MEM_P (rtl))
17423     {
17424       gcc_assert (!rtl);
17425       return 0;
17426     }
17427   gcc_assert (GET_CODE (XEXP (rtl, 0)) == SYMBOL_REF);
17428
17429   /* TODO: We might get more coverage if we was actually delaying expansion
17430      of all expressions till end of compilation when constant pools are fully
17431      populated.  */
17432   if (!TREE_ASM_WRITTEN (SYMBOL_REF_DECL (XEXP (rtl, 0))))
17433     {
17434       expansion_failed (loc, NULL_RTX,
17435                         "CST value in contant pool but not marked.");
17436       return 0;
17437     }
17438   return mem_loc_descriptor (XEXP (rtl, 0), get_address_mode (rtl),
17439                              GET_MODE (rtl), VAR_INIT_STATUS_INITIALIZED);
17440 }
17441
17442 /* Return dw_loc_list representing address of addr_expr LOC
17443    by looking for inner INDIRECT_REF expression and turning
17444    it into simple arithmetics.
17445
17446    See loc_list_from_tree for the meaning of CONTEXT.  */
17447
17448 static dw_loc_list_ref
17449 loc_list_for_address_of_addr_expr_of_indirect_ref (tree loc, bool toplev,
17450                                                    loc_descr_context *context)
17451 {
17452   tree obj, offset;
17453   poly_int64 bitsize, bitpos, bytepos;
17454   machine_mode mode;
17455   int unsignedp, reversep, volatilep = 0;
17456   dw_loc_list_ref list_ret = NULL, list_ret1 = NULL;
17457
17458   obj = get_inner_reference (TREE_OPERAND (loc, 0),
17459                              &bitsize, &bitpos, &offset, &mode,
17460                              &unsignedp, &reversep, &volatilep);
17461   STRIP_NOPS (obj);
17462   if (!multiple_p (bitpos, BITS_PER_UNIT, &bytepos))
17463     {
17464       expansion_failed (loc, NULL_RTX, "bitfield access");
17465       return 0;
17466     }
17467   if (!INDIRECT_REF_P (obj))
17468     {
17469       expansion_failed (obj,
17470                         NULL_RTX, "no indirect ref in inner refrence");
17471       return 0;
17472     }
17473   if (!offset && known_eq (bitpos, 0))
17474     list_ret = loc_list_from_tree (TREE_OPERAND (obj, 0), toplev ? 2 : 1,
17475                                    context);
17476   else if (toplev
17477            && int_size_in_bytes (TREE_TYPE (loc)) <= DWARF2_ADDR_SIZE
17478            && (dwarf_version >= 4 || !dwarf_strict))
17479     {
17480       list_ret = loc_list_from_tree (TREE_OPERAND (obj, 0), 0, context);
17481       if (!list_ret)
17482         return 0;
17483       if (offset)
17484         {
17485           /* Variable offset.  */
17486           list_ret1 = loc_list_from_tree (offset, 0, context);
17487           if (list_ret1 == 0)
17488             return 0;
17489           add_loc_list (&list_ret, list_ret1);
17490           if (!list_ret)
17491             return 0;
17492           add_loc_descr_to_each (list_ret,
17493                                  new_loc_descr (DW_OP_plus, 0, 0));
17494         }
17495       HOST_WIDE_INT value;
17496       if (bytepos.is_constant (&value) && value > 0)
17497         add_loc_descr_to_each (list_ret,
17498                                new_loc_descr (DW_OP_plus_uconst, value, 0));
17499       else if (maybe_ne (bytepos, 0))
17500         loc_list_plus_const (list_ret, bytepos);
17501       add_loc_descr_to_each (list_ret,
17502                              new_loc_descr (DW_OP_stack_value, 0, 0));
17503     }
17504   return list_ret;
17505 }
17506
17507 /* Set LOC to the next operation that is not a DW_OP_nop operation. In the case
17508    all operations from LOC are nops, move to the last one.  Insert in NOPS all
17509    operations that are skipped.  */
17510
17511 static void
17512 loc_descr_to_next_no_nop (dw_loc_descr_ref &loc,
17513                           hash_set<dw_loc_descr_ref> &nops)
17514 {
17515   while (loc->dw_loc_next != NULL && loc->dw_loc_opc == DW_OP_nop)
17516     {
17517       nops.add (loc);
17518       loc = loc->dw_loc_next;
17519     }
17520 }
17521
17522 /* Helper for loc_descr_without_nops: free the location description operation
17523    P.  */
17524
17525 bool
17526 free_loc_descr (const dw_loc_descr_ref &loc, void *data ATTRIBUTE_UNUSED)
17527 {
17528   ggc_free (loc);
17529   return true;
17530 }
17531
17532 /* Remove all DW_OP_nop operations from LOC except, if it exists, the one that
17533    finishes LOC.  */
17534
17535 static void
17536 loc_descr_without_nops (dw_loc_descr_ref &loc)
17537 {
17538   if (loc->dw_loc_opc == DW_OP_nop && loc->dw_loc_next == NULL)
17539     return;
17540
17541   /* Set of all DW_OP_nop operations we remove.  */
17542   hash_set<dw_loc_descr_ref> nops;
17543
17544   /* First, strip all prefix NOP operations in order to keep the head of the
17545      operations list.  */
17546   loc_descr_to_next_no_nop (loc, nops);
17547
17548   for (dw_loc_descr_ref cur = loc; cur != NULL;)
17549     {
17550       /* For control flow operations: strip "prefix" nops in destination
17551          labels.  */
17552       if (cur->dw_loc_oprnd1.val_class == dw_val_class_loc)
17553         loc_descr_to_next_no_nop (cur->dw_loc_oprnd1.v.val_loc, nops);
17554       if (cur->dw_loc_oprnd2.val_class == dw_val_class_loc)
17555         loc_descr_to_next_no_nop (cur->dw_loc_oprnd2.v.val_loc, nops);
17556
17557       /* Do the same for the operations that follow, then move to the next
17558          iteration.  */
17559       if (cur->dw_loc_next != NULL)
17560         loc_descr_to_next_no_nop (cur->dw_loc_next, nops);
17561       cur = cur->dw_loc_next;
17562     }
17563
17564   nops.traverse<void *, free_loc_descr> (NULL);
17565 }
17566
17567
17568 struct dwarf_procedure_info;
17569
17570 /* Helper structure for location descriptions generation.  */
17571 struct loc_descr_context
17572 {
17573   /* The type that is implicitly referenced by DW_OP_push_object_address, or
17574      NULL_TREE if DW_OP_push_object_address in invalid for this location
17575      description.  This is used when processing PLACEHOLDER_EXPR nodes.  */
17576   tree context_type;
17577   /* The ..._DECL node that should be translated as a
17578      DW_OP_push_object_address operation.  */
17579   tree base_decl;
17580   /* Information about the DWARF procedure we are currently generating. NULL if
17581      we are not generating a DWARF procedure.  */
17582   struct dwarf_procedure_info *dpi;
17583   /* True if integral PLACEHOLDER_EXPR stands for the first argument passed
17584      by consumer.  Used for DW_TAG_generic_subrange attributes.  */
17585   bool placeholder_arg;
17586   /* True if PLACEHOLDER_EXPR has been seen.  */
17587   bool placeholder_seen;
17588 };
17589
17590 /* DWARF procedures generation
17591
17592    DWARF expressions (aka. location descriptions) are used to encode variable
17593    things such as sizes or offsets.  Such computations can have redundant parts
17594    that can be factorized in order to reduce the size of the output debug
17595    information.  This is the whole point of DWARF procedures.
17596
17597    Thanks to stor-layout.c, size and offset expressions in GENERIC trees are
17598    already factorized into functions ("size functions") in order to handle very
17599    big and complex types.  Such functions are quite simple: they have integral
17600    arguments, they return an integral result and their body contains only a
17601    return statement with arithmetic expressions.  This is the only kind of
17602    function we are interested in translating into DWARF procedures, here.
17603
17604    DWARF expressions and DWARF procedure are executed using a stack, so we have
17605    to define some calling convention for them to interact.  Let's say that:
17606
17607    - Before calling a DWARF procedure, DWARF expressions must push on the stack
17608      all arguments in reverse order (right-to-left) so that when the DWARF
17609      procedure execution starts, the first argument is the top of the stack.
17610
17611    - Then, when returning, the DWARF procedure must have consumed all arguments
17612      on the stack, must have pushed the result and touched nothing else.
17613
17614    - Each integral argument and the result are integral types can be hold in a
17615      single stack slot.
17616
17617    - We call "frame offset" the number of stack slots that are "under DWARF
17618      procedure control": it includes the arguments slots, the temporaries and
17619      the result slot. Thus, it is equal to the number of arguments when the
17620      procedure execution starts and must be equal to one (the result) when it
17621      returns.  */
17622
17623 /* Helper structure used when generating operations for a DWARF procedure.  */
17624 struct dwarf_procedure_info
17625 {
17626   /* The FUNCTION_DECL node corresponding to the DWARF procedure that is
17627      currently translated.  */
17628   tree fndecl;
17629   /* The number of arguments FNDECL takes.  */
17630   unsigned args_count;
17631 };
17632
17633 /* Return a pointer to a newly created DIE node for a DWARF procedure.  Add
17634    LOCATION as its DW_AT_location attribute.  If FNDECL is not NULL_TREE,
17635    equate it to this DIE.  */
17636
17637 static dw_die_ref
17638 new_dwarf_proc_die (dw_loc_descr_ref location, tree fndecl,
17639                     dw_die_ref parent_die)
17640 {
17641   dw_die_ref dwarf_proc_die;
17642
17643   if ((dwarf_version < 3 && dwarf_strict)
17644       || location == NULL)
17645     return NULL;
17646
17647   dwarf_proc_die = new_die (DW_TAG_dwarf_procedure, parent_die, fndecl);
17648   if (fndecl)
17649     equate_decl_number_to_die (fndecl, dwarf_proc_die);
17650   add_AT_loc (dwarf_proc_die, DW_AT_location, location);
17651   return dwarf_proc_die;
17652 }
17653
17654 /* Return whether TYPE is a supported type as a DWARF procedure argument
17655    type or return type (we handle only scalar types and pointer types that
17656    aren't wider than the DWARF expression evaluation stack.  */
17657
17658 static bool
17659 is_handled_procedure_type (tree type)
17660 {
17661   return ((INTEGRAL_TYPE_P (type)
17662            || TREE_CODE (type) == OFFSET_TYPE
17663            || TREE_CODE (type) == POINTER_TYPE)
17664           && int_size_in_bytes (type) <= DWARF2_ADDR_SIZE);
17665 }
17666
17667 /* Helper for resolve_args_picking: do the same but stop when coming across
17668    visited nodes.  For each node we visit, register in FRAME_OFFSETS the frame
17669    offset *before* evaluating the corresponding operation.  */
17670
17671 static bool
17672 resolve_args_picking_1 (dw_loc_descr_ref loc, unsigned initial_frame_offset,
17673                         struct dwarf_procedure_info *dpi,
17674                         hash_map<dw_loc_descr_ref, unsigned> &frame_offsets)
17675 {
17676   /* The "frame_offset" identifier is already used to name a macro... */
17677   unsigned frame_offset_ = initial_frame_offset;
17678   dw_loc_descr_ref l;
17679
17680   for (l = loc; l != NULL;)
17681     {
17682       bool existed;
17683       unsigned &l_frame_offset = frame_offsets.get_or_insert (l, &existed);
17684
17685       /* If we already met this node, there is nothing to compute anymore.  */
17686       if (existed)
17687         {
17688           /* Make sure that the stack size is consistent wherever the execution
17689              flow comes from.  */
17690           gcc_assert ((unsigned) l_frame_offset == frame_offset_);
17691           break;
17692         }
17693       l_frame_offset = frame_offset_;
17694
17695       /* If needed, relocate the picking offset with respect to the frame
17696          offset. */
17697       if (l->frame_offset_rel)
17698         {
17699           unsigned HOST_WIDE_INT off;
17700           switch (l->dw_loc_opc)
17701             {
17702             case DW_OP_pick:
17703               off = l->dw_loc_oprnd1.v.val_unsigned;
17704               break;
17705             case DW_OP_dup:
17706               off = 0;
17707               break;
17708             case DW_OP_over:
17709               off = 1;
17710               break;
17711             default:
17712               gcc_unreachable ();
17713             }
17714           /* frame_offset_ is the size of the current stack frame, including
17715              incoming arguments. Besides, the arguments are pushed
17716              right-to-left.  Thus, in order to access the Nth argument from
17717              this operation node, the picking has to skip temporaries *plus*
17718              one stack slot per argument (0 for the first one, 1 for the second
17719              one, etc.).
17720
17721              The targetted argument number (N) is already set as the operand,
17722              and the number of temporaries can be computed with:
17723                frame_offsets_ - dpi->args_count */
17724           off += frame_offset_ - dpi->args_count;
17725
17726           /* DW_OP_pick handles only offsets from 0 to 255 (inclusive)...  */
17727           if (off > 255)
17728             return false;
17729
17730           if (off == 0)
17731             {
17732               l->dw_loc_opc = DW_OP_dup;
17733               l->dw_loc_oprnd1.v.val_unsigned = 0;
17734             }
17735           else if (off == 1)
17736             {
17737               l->dw_loc_opc = DW_OP_over;
17738               l->dw_loc_oprnd1.v.val_unsigned = 0;
17739             }
17740           else
17741             {
17742               l->dw_loc_opc = DW_OP_pick;
17743               l->dw_loc_oprnd1.v.val_unsigned = off;
17744             }
17745         }
17746
17747       /* Update frame_offset according to the effect the current operation has
17748          on the stack.  */
17749       switch (l->dw_loc_opc)
17750         {
17751         case DW_OP_deref:
17752         case DW_OP_swap:
17753         case DW_OP_rot:
17754         case DW_OP_abs:
17755         case DW_OP_neg:
17756         case DW_OP_not:
17757         case DW_OP_plus_uconst:
17758         case DW_OP_skip:
17759         case DW_OP_reg0:
17760         case DW_OP_reg1:
17761         case DW_OP_reg2:
17762         case DW_OP_reg3:
17763         case DW_OP_reg4:
17764         case DW_OP_reg5:
17765         case DW_OP_reg6:
17766         case DW_OP_reg7:
17767         case DW_OP_reg8:
17768         case DW_OP_reg9:
17769         case DW_OP_reg10:
17770         case DW_OP_reg11:
17771         case DW_OP_reg12:
17772         case DW_OP_reg13:
17773         case DW_OP_reg14:
17774         case DW_OP_reg15:
17775         case DW_OP_reg16:
17776         case DW_OP_reg17:
17777         case DW_OP_reg18:
17778         case DW_OP_reg19:
17779         case DW_OP_reg20:
17780         case DW_OP_reg21:
17781         case DW_OP_reg22:
17782         case DW_OP_reg23:
17783         case DW_OP_reg24:
17784         case DW_OP_reg25:
17785         case DW_OP_reg26:
17786         case DW_OP_reg27:
17787         case DW_OP_reg28:
17788         case DW_OP_reg29:
17789         case DW_OP_reg30:
17790         case DW_OP_reg31:
17791         case DW_OP_bregx:
17792         case DW_OP_piece:
17793         case DW_OP_deref_size:
17794         case DW_OP_nop:
17795         case DW_OP_bit_piece:
17796         case DW_OP_implicit_value:
17797         case DW_OP_stack_value:
17798           break;
17799
17800         case DW_OP_addr:
17801         case DW_OP_const1u:
17802         case DW_OP_const1s:
17803         case DW_OP_const2u:
17804         case DW_OP_const2s:
17805         case DW_OP_const4u:
17806         case DW_OP_const4s:
17807         case DW_OP_const8u:
17808         case DW_OP_const8s:
17809         case DW_OP_constu:
17810         case DW_OP_consts:
17811         case DW_OP_dup:
17812         case DW_OP_over:
17813         case DW_OP_pick:
17814         case DW_OP_lit0:
17815         case DW_OP_lit1:
17816         case DW_OP_lit2:
17817         case DW_OP_lit3:
17818         case DW_OP_lit4:
17819         case DW_OP_lit5:
17820         case DW_OP_lit6:
17821         case DW_OP_lit7:
17822         case DW_OP_lit8:
17823         case DW_OP_lit9:
17824         case DW_OP_lit10:
17825         case DW_OP_lit11:
17826         case DW_OP_lit12:
17827         case DW_OP_lit13:
17828         case DW_OP_lit14:
17829         case DW_OP_lit15:
17830         case DW_OP_lit16:
17831         case DW_OP_lit17:
17832         case DW_OP_lit18:
17833         case DW_OP_lit19:
17834         case DW_OP_lit20:
17835         case DW_OP_lit21:
17836         case DW_OP_lit22:
17837         case DW_OP_lit23:
17838         case DW_OP_lit24:
17839         case DW_OP_lit25:
17840         case DW_OP_lit26:
17841         case DW_OP_lit27:
17842         case DW_OP_lit28:
17843         case DW_OP_lit29:
17844         case DW_OP_lit30:
17845         case DW_OP_lit31:
17846         case DW_OP_breg0:
17847         case DW_OP_breg1:
17848         case DW_OP_breg2:
17849         case DW_OP_breg3:
17850         case DW_OP_breg4:
17851         case DW_OP_breg5:
17852         case DW_OP_breg6:
17853         case DW_OP_breg7:
17854         case DW_OP_breg8:
17855         case DW_OP_breg9:
17856         case DW_OP_breg10:
17857         case DW_OP_breg11:
17858         case DW_OP_breg12:
17859         case DW_OP_breg13:
17860         case DW_OP_breg14:
17861         case DW_OP_breg15:
17862         case DW_OP_breg16:
17863         case DW_OP_breg17:
17864         case DW_OP_breg18:
17865         case DW_OP_breg19:
17866         case DW_OP_breg20:
17867         case DW_OP_breg21:
17868         case DW_OP_breg22:
17869         case DW_OP_breg23:
17870         case DW_OP_breg24:
17871         case DW_OP_breg25:
17872         case DW_OP_breg26:
17873         case DW_OP_breg27:
17874         case DW_OP_breg28:
17875         case DW_OP_breg29:
17876         case DW_OP_breg30:
17877         case DW_OP_breg31:
17878         case DW_OP_fbreg:
17879         case DW_OP_push_object_address:
17880         case DW_OP_call_frame_cfa:
17881         case DW_OP_GNU_variable_value:
17882           ++frame_offset_;
17883           break;
17884
17885         case DW_OP_drop:
17886         case DW_OP_xderef:
17887         case DW_OP_and:
17888         case DW_OP_div:
17889         case DW_OP_minus:
17890         case DW_OP_mod:
17891         case DW_OP_mul:
17892         case DW_OP_or:
17893         case DW_OP_plus:
17894         case DW_OP_shl:
17895         case DW_OP_shr:
17896         case DW_OP_shra:
17897         case DW_OP_xor:
17898         case DW_OP_bra:
17899         case DW_OP_eq:
17900         case DW_OP_ge:
17901         case DW_OP_gt:
17902         case DW_OP_le:
17903         case DW_OP_lt:
17904         case DW_OP_ne:
17905         case DW_OP_regx:
17906         case DW_OP_xderef_size:
17907           --frame_offset_;
17908           break;
17909
17910         case DW_OP_call2:
17911         case DW_OP_call4:
17912         case DW_OP_call_ref:
17913           {
17914             dw_die_ref dwarf_proc = l->dw_loc_oprnd1.v.val_die_ref.die;
17915             int *stack_usage = dwarf_proc_stack_usage_map->get (dwarf_proc);
17916
17917             if (stack_usage == NULL)
17918               return false;
17919             frame_offset_ += *stack_usage;
17920             break;
17921           }
17922
17923         case DW_OP_implicit_pointer:
17924         case DW_OP_entry_value:
17925         case DW_OP_const_type:
17926         case DW_OP_regval_type:
17927         case DW_OP_deref_type:
17928         case DW_OP_convert:
17929         case DW_OP_reinterpret:
17930         case DW_OP_form_tls_address:
17931         case DW_OP_GNU_push_tls_address:
17932         case DW_OP_GNU_uninit:
17933         case DW_OP_GNU_encoded_addr:
17934         case DW_OP_GNU_implicit_pointer:
17935         case DW_OP_GNU_entry_value:
17936         case DW_OP_GNU_const_type:
17937         case DW_OP_GNU_regval_type:
17938         case DW_OP_GNU_deref_type:
17939         case DW_OP_GNU_convert:
17940         case DW_OP_GNU_reinterpret:
17941         case DW_OP_GNU_parameter_ref:
17942           /* loc_list_from_tree will probably not output these operations for
17943              size functions, so assume they will not appear here.  */
17944           /* Fall through...  */
17945
17946         default:
17947           gcc_unreachable ();
17948         }
17949
17950       /* Now, follow the control flow (except subroutine calls).  */
17951       switch (l->dw_loc_opc)
17952         {
17953         case DW_OP_bra:
17954           if (!resolve_args_picking_1 (l->dw_loc_next, frame_offset_, dpi,
17955                                        frame_offsets))
17956             return false;
17957           /* Fall through. */
17958
17959         case DW_OP_skip:
17960           l = l->dw_loc_oprnd1.v.val_loc;
17961           break;
17962
17963         case DW_OP_stack_value:
17964           return true;
17965
17966         default:
17967           l = l->dw_loc_next;
17968           break;
17969         }
17970     }
17971
17972   return true;
17973 }
17974
17975 /* Make a DFS over operations reachable through LOC (i.e. follow branch
17976    operations) in order to resolve the operand of DW_OP_pick operations that
17977    target DWARF procedure arguments (DPI).  INITIAL_FRAME_OFFSET is the frame
17978    offset *before* LOC is executed.  Return if all relocations were
17979    successful.  */
17980
17981 static bool
17982 resolve_args_picking (dw_loc_descr_ref loc, unsigned initial_frame_offset,
17983                       struct dwarf_procedure_info *dpi)
17984 {
17985   /* Associate to all visited operations the frame offset *before* evaluating
17986      this operation.  */
17987   hash_map<dw_loc_descr_ref, unsigned> frame_offsets;
17988
17989   return resolve_args_picking_1 (loc, initial_frame_offset, dpi,
17990                                  frame_offsets);
17991 }
17992
17993 /* Try to generate a DWARF procedure that computes the same result as FNDECL.
17994    Return NULL if it is not possible.  */
17995
17996 static dw_die_ref
17997 function_to_dwarf_procedure (tree fndecl)
17998 {
17999   struct loc_descr_context ctx;
18000   struct dwarf_procedure_info dpi;
18001   dw_die_ref dwarf_proc_die;
18002   tree tree_body = DECL_SAVED_TREE (fndecl);
18003   dw_loc_descr_ref loc_body, epilogue;
18004
18005   tree cursor;
18006   unsigned i;
18007
18008   /* Do not generate multiple DWARF procedures for the same function
18009      declaration.  */
18010   dwarf_proc_die = lookup_decl_die (fndecl);
18011   if (dwarf_proc_die != NULL)
18012     return dwarf_proc_die;
18013
18014   /* DWARF procedures are available starting with the DWARFv3 standard.  */
18015   if (dwarf_version < 3 && dwarf_strict)
18016     return NULL;
18017
18018   /* We handle only functions for which we still have a body, that return a
18019      supported type and that takes arguments with supported types.  Note that
18020      there is no point translating functions that return nothing.  */
18021   if (tree_body == NULL_TREE
18022       || DECL_RESULT (fndecl) == NULL_TREE
18023       || !is_handled_procedure_type (TREE_TYPE (DECL_RESULT (fndecl))))
18024     return NULL;
18025
18026   for (cursor = DECL_ARGUMENTS (fndecl);
18027        cursor != NULL_TREE;
18028        cursor = TREE_CHAIN (cursor))
18029     if (!is_handled_procedure_type (TREE_TYPE (cursor)))
18030       return NULL;
18031
18032   /* Match only "expr" in: RETURN_EXPR (MODIFY_EXPR (RESULT_DECL, expr)).  */
18033   if (TREE_CODE (tree_body) != RETURN_EXPR)
18034     return NULL;
18035   tree_body = TREE_OPERAND (tree_body, 0);
18036   if (TREE_CODE (tree_body) != MODIFY_EXPR
18037       || TREE_OPERAND (tree_body, 0) != DECL_RESULT (fndecl))
18038     return NULL;
18039   tree_body = TREE_OPERAND (tree_body, 1);
18040
18041   /* Try to translate the body expression itself.  Note that this will probably
18042      cause an infinite recursion if its call graph has a cycle.  This is very
18043      unlikely for size functions, however, so don't bother with such things at
18044      the moment.  */
18045   ctx.context_type = NULL_TREE;
18046   ctx.base_decl = NULL_TREE;
18047   ctx.dpi = &dpi;
18048   ctx.placeholder_arg = false;
18049   ctx.placeholder_seen = false;
18050   dpi.fndecl = fndecl;
18051   dpi.args_count = list_length (DECL_ARGUMENTS (fndecl));
18052   loc_body = loc_descriptor_from_tree (tree_body, 0, &ctx);
18053   if (!loc_body)
18054     return NULL;
18055
18056   /* After evaluating all operands in "loc_body", we should still have on the
18057      stack all arguments plus the desired function result (top of the stack).
18058      Generate code in order to keep only the result in our stack frame.  */
18059   epilogue = NULL;
18060   for (i = 0; i < dpi.args_count; ++i)
18061     {
18062       dw_loc_descr_ref op_couple = new_loc_descr (DW_OP_swap, 0, 0);
18063       op_couple->dw_loc_next = new_loc_descr (DW_OP_drop, 0, 0);
18064       op_couple->dw_loc_next->dw_loc_next = epilogue;
18065       epilogue = op_couple;
18066     }
18067   add_loc_descr (&loc_body, epilogue);
18068   if (!resolve_args_picking (loc_body, dpi.args_count, &dpi))
18069     return NULL;
18070
18071   /* Trailing nops from loc_descriptor_from_tree (if any) cannot be removed
18072      because they are considered useful.  Now there is an epilogue, they are
18073      not anymore, so give it another try.   */
18074   loc_descr_without_nops (loc_body);
18075
18076   /* fndecl may be used both as a regular DW_TAG_subprogram DIE and as
18077      a DW_TAG_dwarf_procedure, so we may have a conflict, here.  It's unlikely,
18078      though, given that size functions do not come from source, so they should
18079      not have a dedicated DW_TAG_subprogram DIE.  */
18080   dwarf_proc_die
18081     = new_dwarf_proc_die (loc_body, fndecl,
18082                           get_context_die (DECL_CONTEXT (fndecl)));
18083
18084   /* The called DWARF procedure consumes one stack slot per argument and
18085      returns one stack slot.  */
18086   dwarf_proc_stack_usage_map->put (dwarf_proc_die, 1 - dpi.args_count);
18087
18088   return dwarf_proc_die;
18089 }
18090
18091
18092 /* Generate Dwarf location list representing LOC.
18093    If WANT_ADDRESS is false, expression computing LOC will be computed
18094    If WANT_ADDRESS is 1, expression computing address of LOC will be returned
18095    if WANT_ADDRESS is 2, expression computing address useable in location
18096      will be returned (i.e. DW_OP_reg can be used
18097      to refer to register values).
18098
18099    CONTEXT provides information to customize the location descriptions
18100    generation.  Its context_type field specifies what type is implicitly
18101    referenced by DW_OP_push_object_address.  If it is NULL_TREE, this operation
18102    will not be generated.
18103
18104    Its DPI field determines whether we are generating a DWARF expression for a
18105    DWARF procedure, so PARM_DECL references are processed specifically.
18106
18107    If CONTEXT is NULL, the behavior is the same as if context_type, base_decl
18108    and dpi fields were null.  */
18109
18110 static dw_loc_list_ref
18111 loc_list_from_tree_1 (tree loc, int want_address,
18112                       struct loc_descr_context *context)
18113 {
18114   dw_loc_descr_ref ret = NULL, ret1 = NULL;
18115   dw_loc_list_ref list_ret = NULL, list_ret1 = NULL;
18116   int have_address = 0;
18117   enum dwarf_location_atom op;
18118
18119   /* ??? Most of the time we do not take proper care for sign/zero
18120      extending the values properly.  Hopefully this won't be a real
18121      problem...  */
18122
18123   if (context != NULL
18124       && context->base_decl == loc
18125       && want_address == 0)
18126     {
18127       if (dwarf_version >= 3 || !dwarf_strict)
18128         return new_loc_list (new_loc_descr (DW_OP_push_object_address, 0, 0),
18129                              NULL, 0, NULL, 0, NULL);
18130       else
18131         return NULL;
18132     }
18133
18134   switch (TREE_CODE (loc))
18135     {
18136     case ERROR_MARK:
18137       expansion_failed (loc, NULL_RTX, "ERROR_MARK");
18138       return 0;
18139
18140     case PLACEHOLDER_EXPR:
18141       /* This case involves extracting fields from an object to determine the
18142          position of other fields. It is supposed to appear only as the first
18143          operand of COMPONENT_REF nodes and to reference precisely the type
18144          that the context allows.  */
18145       if (context != NULL
18146           && TREE_TYPE (loc) == context->context_type
18147           && want_address >= 1)
18148         {
18149           if (dwarf_version >= 3 || !dwarf_strict)
18150             {
18151               ret = new_loc_descr (DW_OP_push_object_address, 0, 0);
18152               have_address = 1;
18153               break;
18154             }
18155           else
18156             return NULL;
18157         }
18158       /* For DW_TAG_generic_subrange attributes, PLACEHOLDER_EXPR stands for
18159          the single argument passed by consumer.  */
18160       else if (context != NULL
18161                && context->placeholder_arg
18162                && INTEGRAL_TYPE_P (TREE_TYPE (loc))
18163                && want_address == 0)
18164         {
18165           ret = new_loc_descr (DW_OP_pick, 0, 0);
18166           ret->frame_offset_rel = 1;
18167           context->placeholder_seen = true;
18168           break;
18169         }
18170       else
18171         expansion_failed (loc, NULL_RTX,
18172                           "PLACEHOLDER_EXPR for an unexpected type");
18173       break;
18174
18175     case CALL_EXPR:
18176         {
18177           const int nargs = call_expr_nargs (loc);
18178           tree callee = get_callee_fndecl (loc);
18179           int i;
18180           dw_die_ref dwarf_proc;
18181
18182           if (callee == NULL_TREE)
18183             goto call_expansion_failed;
18184
18185           /* We handle only functions that return an integer.  */
18186           if (!is_handled_procedure_type (TREE_TYPE (TREE_TYPE (callee))))
18187             goto call_expansion_failed;
18188
18189           dwarf_proc = function_to_dwarf_procedure (callee);
18190           if (dwarf_proc == NULL)
18191             goto call_expansion_failed;
18192
18193           /* Evaluate arguments right-to-left so that the first argument will
18194              be the top-most one on the stack.  */
18195           for (i = nargs - 1; i >= 0; --i)
18196             {
18197               dw_loc_descr_ref loc_descr
18198                 = loc_descriptor_from_tree (CALL_EXPR_ARG (loc, i), 0,
18199                                             context);
18200
18201               if (loc_descr == NULL)
18202                 goto call_expansion_failed;
18203
18204               add_loc_descr (&ret, loc_descr);
18205             }
18206
18207           ret1 = new_loc_descr (DW_OP_call4, 0, 0);
18208           ret1->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
18209           ret1->dw_loc_oprnd1.v.val_die_ref.die = dwarf_proc;
18210           ret1->dw_loc_oprnd1.v.val_die_ref.external = 0;
18211           add_loc_descr (&ret, ret1);
18212           break;
18213
18214         call_expansion_failed:
18215           expansion_failed (loc, NULL_RTX, "CALL_EXPR");
18216           /* There are no opcodes for these operations.  */
18217           return 0;
18218         }
18219
18220     case PREINCREMENT_EXPR:
18221     case PREDECREMENT_EXPR:
18222     case POSTINCREMENT_EXPR:
18223     case POSTDECREMENT_EXPR:
18224       expansion_failed (loc, NULL_RTX, "PRE/POST INDCREMENT/DECREMENT");
18225       /* There are no opcodes for these operations.  */
18226       return 0;
18227
18228     case ADDR_EXPR:
18229       /* If we already want an address, see if there is INDIRECT_REF inside
18230          e.g. for &this->field.  */
18231       if (want_address)
18232         {
18233           list_ret = loc_list_for_address_of_addr_expr_of_indirect_ref
18234                        (loc, want_address == 2, context);
18235           if (list_ret)
18236             have_address = 1;
18237           else if (decl_address_ip_invariant_p (TREE_OPERAND (loc, 0))
18238                    && (ret = cst_pool_loc_descr (loc)))
18239             have_address = 1;
18240         }
18241         /* Otherwise, process the argument and look for the address.  */
18242       if (!list_ret && !ret)
18243         list_ret = loc_list_from_tree_1 (TREE_OPERAND (loc, 0), 1, context);
18244       else
18245         {
18246           if (want_address)
18247             expansion_failed (loc, NULL_RTX, "need address of ADDR_EXPR");
18248           return NULL;
18249         }
18250       break;
18251
18252     case VAR_DECL:
18253       if (DECL_THREAD_LOCAL_P (loc))
18254         {
18255           rtx rtl;
18256          enum dwarf_location_atom tls_op;
18257          enum dtprel_bool dtprel = dtprel_false;
18258
18259           if (targetm.have_tls)
18260             {
18261               /* If this is not defined, we have no way to emit the
18262                  data.  */
18263               if (!targetm.asm_out.output_dwarf_dtprel)
18264                 return 0;
18265
18266                /* The way DW_OP_GNU_push_tls_address is specified, we
18267                   can only look up addresses of objects in the current
18268                   module.  We used DW_OP_addr as first op, but that's
18269                   wrong, because DW_OP_addr is relocated by the debug
18270                   info consumer, while DW_OP_GNU_push_tls_address
18271                   operand shouldn't be.  */
18272               if (DECL_EXTERNAL (loc) && !targetm.binds_local_p (loc))
18273                 return 0;
18274               dtprel = dtprel_true;
18275               /* We check for DWARF 5 here because gdb did not implement
18276                  DW_OP_form_tls_address until after 7.12.  */
18277               tls_op = (dwarf_version >= 5 ? DW_OP_form_tls_address
18278                         : DW_OP_GNU_push_tls_address);
18279             }
18280           else
18281             {
18282               if (!targetm.emutls.debug_form_tls_address
18283                   || !(dwarf_version >= 3 || !dwarf_strict))
18284                 return 0;
18285               /* We stuffed the control variable into the DECL_VALUE_EXPR
18286                  to signal (via DECL_HAS_VALUE_EXPR_P) that the decl should
18287                  no longer appear in gimple code.  We used the control
18288                  variable in specific so that we could pick it up here.  */
18289               loc = DECL_VALUE_EXPR (loc);
18290               tls_op = DW_OP_form_tls_address;
18291             }
18292
18293           rtl = rtl_for_decl_location (loc);
18294           if (rtl == NULL_RTX)
18295             return 0;
18296
18297           if (!MEM_P (rtl))
18298             return 0;
18299           rtl = XEXP (rtl, 0);
18300           if (! CONSTANT_P (rtl))
18301             return 0;
18302
18303           ret = new_addr_loc_descr (rtl, dtprel);
18304           ret1 = new_loc_descr (tls_op, 0, 0);
18305           add_loc_descr (&ret, ret1);
18306
18307           have_address = 1;
18308           break;
18309         }
18310       /* FALLTHRU */
18311
18312     case PARM_DECL:
18313       if (context != NULL && context->dpi != NULL
18314           && DECL_CONTEXT (loc) == context->dpi->fndecl)
18315         {
18316           /* We are generating code for a DWARF procedure and we want to access
18317              one of its arguments: find the appropriate argument offset and let
18318              the resolve_args_picking pass compute the offset that complies
18319              with the stack frame size.  */
18320           unsigned i = 0;
18321           tree cursor;
18322
18323           for (cursor = DECL_ARGUMENTS (context->dpi->fndecl);
18324                cursor != NULL_TREE && cursor != loc;
18325                cursor = TREE_CHAIN (cursor), ++i)
18326             ;
18327           /* If we are translating a DWARF procedure, all referenced parameters
18328              must belong to the current function.  */
18329           gcc_assert (cursor != NULL_TREE);
18330
18331           ret = new_loc_descr (DW_OP_pick, i, 0);
18332           ret->frame_offset_rel = 1;
18333           break;
18334         }
18335       /* FALLTHRU */
18336
18337     case RESULT_DECL:
18338       if (DECL_HAS_VALUE_EXPR_P (loc))
18339         return loc_list_from_tree_1 (DECL_VALUE_EXPR (loc),
18340                                      want_address, context);
18341       /* FALLTHRU */
18342
18343     case FUNCTION_DECL:
18344       {
18345         rtx rtl;
18346         var_loc_list *loc_list = lookup_decl_loc (loc);
18347
18348         if (loc_list && loc_list->first)
18349           {
18350             list_ret = dw_loc_list (loc_list, loc, want_address);
18351             have_address = want_address != 0;
18352             break;
18353           }
18354         rtl = rtl_for_decl_location (loc);
18355         if (rtl == NULL_RTX)
18356           {
18357             if (TREE_CODE (loc) != FUNCTION_DECL
18358                 && early_dwarf
18359                 && current_function_decl
18360                 && want_address != 1
18361                 && ! DECL_IGNORED_P (loc)
18362                 && (INTEGRAL_TYPE_P (TREE_TYPE (loc))
18363                     || POINTER_TYPE_P (TREE_TYPE (loc)))
18364                 && DECL_CONTEXT (loc) == current_function_decl
18365                 && (GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (TREE_TYPE (loc)))
18366                     <= DWARF2_ADDR_SIZE))
18367               {
18368                 dw_die_ref ref = lookup_decl_die (loc);
18369                 ret = new_loc_descr (DW_OP_GNU_variable_value, 0, 0);
18370                 if (ref)
18371                   {
18372                     ret->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
18373                     ret->dw_loc_oprnd1.v.val_die_ref.die = ref;
18374                     ret->dw_loc_oprnd1.v.val_die_ref.external = 0;
18375                   }
18376                 else
18377                   {
18378                     ret->dw_loc_oprnd1.val_class = dw_val_class_decl_ref;
18379                     ret->dw_loc_oprnd1.v.val_decl_ref = loc;
18380                   }
18381                 break;
18382               }
18383             expansion_failed (loc, NULL_RTX, "DECL has no RTL");
18384             return 0;
18385           }
18386         else if (CONST_INT_P (rtl))
18387           {
18388             HOST_WIDE_INT val = INTVAL (rtl);
18389             if (TYPE_UNSIGNED (TREE_TYPE (loc)))
18390               val &= GET_MODE_MASK (DECL_MODE (loc));
18391             ret = int_loc_descriptor (val);
18392           }
18393         else if (GET_CODE (rtl) == CONST_STRING)
18394           {
18395             expansion_failed (loc, NULL_RTX, "CONST_STRING");
18396             return 0;
18397           }
18398         else if (CONSTANT_P (rtl) && const_ok_for_output (rtl))
18399           ret = new_addr_loc_descr (rtl, dtprel_false);
18400         else
18401           {
18402             machine_mode mode, mem_mode;
18403
18404             /* Certain constructs can only be represented at top-level.  */
18405             if (want_address == 2)
18406               {
18407                 ret = loc_descriptor (rtl, VOIDmode,
18408                                       VAR_INIT_STATUS_INITIALIZED);
18409                 have_address = 1;
18410               }
18411             else
18412               {
18413                 mode = GET_MODE (rtl);
18414                 mem_mode = VOIDmode;
18415                 if (MEM_P (rtl))
18416                   {
18417                     mem_mode = mode;
18418                     mode = get_address_mode (rtl);
18419                     rtl = XEXP (rtl, 0);
18420                     have_address = 1;
18421                   }
18422                 ret = mem_loc_descriptor (rtl, mode, mem_mode,
18423                                           VAR_INIT_STATUS_INITIALIZED);
18424               }
18425             if (!ret)
18426               expansion_failed (loc, rtl,
18427                                 "failed to produce loc descriptor for rtl");
18428           }
18429       }
18430       break;
18431
18432     case MEM_REF:
18433       if (!integer_zerop (TREE_OPERAND (loc, 1)))
18434         {
18435           have_address = 1;
18436           goto do_plus;
18437         }
18438       /* Fallthru.  */
18439     case INDIRECT_REF:
18440       list_ret = loc_list_from_tree_1 (TREE_OPERAND (loc, 0), 0, context);
18441       have_address = 1;
18442       break;
18443
18444     case TARGET_MEM_REF:
18445     case SSA_NAME:
18446     case DEBUG_EXPR_DECL:
18447       return NULL;
18448
18449     case COMPOUND_EXPR:
18450       return loc_list_from_tree_1 (TREE_OPERAND (loc, 1), want_address,
18451                                    context);
18452
18453     CASE_CONVERT:
18454     case VIEW_CONVERT_EXPR:
18455     case SAVE_EXPR:
18456     case MODIFY_EXPR:
18457     case NON_LVALUE_EXPR:
18458       return loc_list_from_tree_1 (TREE_OPERAND (loc, 0), want_address,
18459                                    context);
18460
18461     case COMPONENT_REF:
18462     case BIT_FIELD_REF:
18463     case ARRAY_REF:
18464     case ARRAY_RANGE_REF:
18465     case REALPART_EXPR:
18466     case IMAGPART_EXPR:
18467       {
18468         tree obj, offset;
18469         poly_int64 bitsize, bitpos, bytepos;
18470         machine_mode mode;
18471         int unsignedp, reversep, volatilep = 0;
18472
18473         obj = get_inner_reference (loc, &bitsize, &bitpos, &offset, &mode,
18474                                    &unsignedp, &reversep, &volatilep);
18475
18476         gcc_assert (obj != loc);
18477
18478         list_ret = loc_list_from_tree_1 (obj,
18479                                          want_address == 2
18480                                          && known_eq (bitpos, 0)
18481                                          && !offset ? 2 : 1,
18482                                          context);
18483         /* TODO: We can extract value of the small expression via shifting even
18484            for nonzero bitpos.  */
18485         if (list_ret == 0)
18486           return 0;
18487         if (!multiple_p (bitpos, BITS_PER_UNIT, &bytepos)
18488             || !multiple_p (bitsize, BITS_PER_UNIT))
18489           {
18490             expansion_failed (loc, NULL_RTX,
18491                               "bitfield access");
18492             return 0;
18493           }
18494
18495         if (offset != NULL_TREE)
18496           {
18497             /* Variable offset.  */
18498             list_ret1 = loc_list_from_tree_1 (offset, 0, context);
18499             if (list_ret1 == 0)
18500               return 0;
18501             add_loc_list (&list_ret, list_ret1);
18502             if (!list_ret)
18503               return 0;
18504             add_loc_descr_to_each (list_ret, new_loc_descr (DW_OP_plus, 0, 0));
18505           }
18506
18507         HOST_WIDE_INT value;
18508         if (bytepos.is_constant (&value) && value > 0)
18509           add_loc_descr_to_each (list_ret, new_loc_descr (DW_OP_plus_uconst,
18510                                                           value, 0));
18511         else if (maybe_ne (bytepos, 0))
18512           loc_list_plus_const (list_ret, bytepos);
18513
18514         have_address = 1;
18515         break;
18516       }
18517
18518     case INTEGER_CST:
18519       if ((want_address || !tree_fits_shwi_p (loc))
18520           && (ret = cst_pool_loc_descr (loc)))
18521         have_address = 1;
18522       else if (want_address == 2
18523                && tree_fits_shwi_p (loc)
18524                && (ret = address_of_int_loc_descriptor
18525                            (int_size_in_bytes (TREE_TYPE (loc)),
18526                             tree_to_shwi (loc))))
18527         have_address = 1;
18528       else if (tree_fits_shwi_p (loc))
18529         ret = int_loc_descriptor (tree_to_shwi (loc));
18530       else if (tree_fits_uhwi_p (loc))
18531         ret = uint_loc_descriptor (tree_to_uhwi (loc));
18532       else
18533         {
18534           expansion_failed (loc, NULL_RTX,
18535                             "Integer operand is not host integer");
18536           return 0;
18537         }
18538       break;
18539
18540     case CONSTRUCTOR:
18541     case REAL_CST:
18542     case STRING_CST:
18543     case COMPLEX_CST:
18544       if ((ret = cst_pool_loc_descr (loc)))
18545         have_address = 1;
18546       else if (TREE_CODE (loc) == CONSTRUCTOR)
18547         {
18548           tree type = TREE_TYPE (loc);
18549           unsigned HOST_WIDE_INT size = int_size_in_bytes (type);
18550           unsigned HOST_WIDE_INT offset = 0;
18551           unsigned HOST_WIDE_INT cnt;
18552           constructor_elt *ce;
18553
18554           if (TREE_CODE (type) == RECORD_TYPE)
18555             {
18556               /* This is very limited, but it's enough to output
18557                  pointers to member functions, as long as the
18558                  referenced function is defined in the current
18559                  translation unit.  */
18560               FOR_EACH_VEC_SAFE_ELT (CONSTRUCTOR_ELTS (loc), cnt, ce)
18561                 {
18562                   tree val = ce->value;
18563
18564                   tree field = ce->index;
18565
18566                   if (val)
18567                     STRIP_NOPS (val);
18568
18569                   if (!field || DECL_BIT_FIELD (field))
18570                     {
18571                       expansion_failed (loc, NULL_RTX,
18572                                         "bitfield in record type constructor");
18573                       size = offset = (unsigned HOST_WIDE_INT)-1;
18574                       ret = NULL;
18575                       break;
18576                     }
18577
18578                   HOST_WIDE_INT fieldsize = tree_to_shwi (DECL_SIZE_UNIT (field));
18579                   unsigned HOST_WIDE_INT pos = int_byte_position (field);
18580                   gcc_assert (pos + fieldsize <= size);
18581                   if (pos < offset)
18582                     {
18583                       expansion_failed (loc, NULL_RTX,
18584                                         "out-of-order fields in record constructor");
18585                       size = offset = (unsigned HOST_WIDE_INT)-1;
18586                       ret = NULL;
18587                       break;
18588                     }
18589                   if (pos > offset)
18590                     {
18591                       ret1 = new_loc_descr (DW_OP_piece, pos - offset, 0);
18592                       add_loc_descr (&ret, ret1);
18593                       offset = pos;
18594                     }
18595                   if (val && fieldsize != 0)
18596                     {
18597                       ret1 = loc_descriptor_from_tree (val, want_address, context);
18598                       if (!ret1)
18599                         {
18600                           expansion_failed (loc, NULL_RTX,
18601                                             "unsupported expression in field");
18602                           size = offset = (unsigned HOST_WIDE_INT)-1;
18603                           ret = NULL;
18604                           break;
18605                         }
18606                       add_loc_descr (&ret, ret1);
18607                     }
18608                   if (fieldsize)
18609                     {
18610                       ret1 = new_loc_descr (DW_OP_piece, fieldsize, 0);
18611                       add_loc_descr (&ret, ret1);
18612                       offset = pos + fieldsize;
18613                     }
18614                 }
18615
18616               if (offset != size)
18617                 {
18618                   ret1 = new_loc_descr (DW_OP_piece, size - offset, 0);
18619                   add_loc_descr (&ret, ret1);
18620                   offset = size;
18621                 }
18622
18623               have_address = !!want_address;
18624             }
18625           else
18626             expansion_failed (loc, NULL_RTX,
18627                               "constructor of non-record type");
18628         }
18629       else
18630       /* We can construct small constants here using int_loc_descriptor.  */
18631         expansion_failed (loc, NULL_RTX,
18632                           "constructor or constant not in constant pool");
18633       break;
18634
18635     case TRUTH_AND_EXPR:
18636     case TRUTH_ANDIF_EXPR:
18637     case BIT_AND_EXPR:
18638       op = DW_OP_and;
18639       goto do_binop;
18640
18641     case TRUTH_XOR_EXPR:
18642     case BIT_XOR_EXPR:
18643       op = DW_OP_xor;
18644       goto do_binop;
18645
18646     case TRUTH_OR_EXPR:
18647     case TRUTH_ORIF_EXPR:
18648     case BIT_IOR_EXPR:
18649       op = DW_OP_or;
18650       goto do_binop;
18651
18652     case FLOOR_DIV_EXPR:
18653     case CEIL_DIV_EXPR:
18654     case ROUND_DIV_EXPR:
18655     case TRUNC_DIV_EXPR:
18656     case EXACT_DIV_EXPR:
18657       if (TYPE_UNSIGNED (TREE_TYPE (loc)))
18658         return 0;
18659       op = DW_OP_div;
18660       goto do_binop;
18661
18662     case MINUS_EXPR:
18663       op = DW_OP_minus;
18664       goto do_binop;
18665
18666     case FLOOR_MOD_EXPR:
18667     case CEIL_MOD_EXPR:
18668     case ROUND_MOD_EXPR:
18669     case TRUNC_MOD_EXPR:
18670       if (TYPE_UNSIGNED (TREE_TYPE (loc)))
18671         {
18672           op = DW_OP_mod;
18673           goto do_binop;
18674         }
18675       list_ret = loc_list_from_tree_1 (TREE_OPERAND (loc, 0), 0, context);
18676       list_ret1 = loc_list_from_tree_1 (TREE_OPERAND (loc, 1), 0, context);
18677       if (list_ret == 0 || list_ret1 == 0)
18678         return 0;
18679
18680       add_loc_list (&list_ret, list_ret1);
18681       if (list_ret == 0)
18682         return 0;
18683       add_loc_descr_to_each (list_ret, new_loc_descr (DW_OP_over, 0, 0));
18684       add_loc_descr_to_each (list_ret, new_loc_descr (DW_OP_over, 0, 0));
18685       add_loc_descr_to_each (list_ret, new_loc_descr (DW_OP_div, 0, 0));
18686       add_loc_descr_to_each (list_ret, new_loc_descr (DW_OP_mul, 0, 0));
18687       add_loc_descr_to_each (list_ret, new_loc_descr (DW_OP_minus, 0, 0));
18688       break;
18689
18690     case MULT_EXPR:
18691       op = DW_OP_mul;
18692       goto do_binop;
18693
18694     case LSHIFT_EXPR:
18695       op = DW_OP_shl;
18696       goto do_binop;
18697
18698     case RSHIFT_EXPR:
18699       op = (TYPE_UNSIGNED (TREE_TYPE (loc)) ? DW_OP_shr : DW_OP_shra);
18700       goto do_binop;
18701
18702     case POINTER_PLUS_EXPR:
18703     case PLUS_EXPR:
18704     do_plus:
18705       if (tree_fits_shwi_p (TREE_OPERAND (loc, 1)))
18706         {
18707           /* Big unsigned numbers can fit in HOST_WIDE_INT but it may be
18708              smarter to encode their opposite.  The DW_OP_plus_uconst operation
18709              takes 1 + X bytes, X being the size of the ULEB128 addend.  On the
18710              other hand, a "<push literal>; DW_OP_minus" pattern takes 1 + Y
18711              bytes, Y being the size of the operation that pushes the opposite
18712              of the addend.  So let's choose the smallest representation.  */
18713           const tree tree_addend = TREE_OPERAND (loc, 1);
18714           offset_int wi_addend;
18715           HOST_WIDE_INT shwi_addend;
18716           dw_loc_descr_ref loc_naddend;
18717
18718           list_ret = loc_list_from_tree_1 (TREE_OPERAND (loc, 0), 0, context);
18719           if (list_ret == 0)
18720             return 0;
18721
18722           /* Try to get the literal to push.  It is the opposite of the addend,
18723              so as we rely on wrapping during DWARF evaluation, first decode
18724              the literal as a "DWARF-sized" signed number.  */
18725           wi_addend = wi::to_offset (tree_addend);
18726           wi_addend = wi::sext (wi_addend, DWARF2_ADDR_SIZE * 8);
18727           shwi_addend = wi_addend.to_shwi ();
18728           loc_naddend = (shwi_addend != INTTYPE_MINIMUM (HOST_WIDE_INT))
18729                         ? int_loc_descriptor (-shwi_addend)
18730                         : NULL;
18731
18732           if (loc_naddend != NULL
18733               && ((unsigned) size_of_uleb128 (shwi_addend)
18734                   > size_of_loc_descr (loc_naddend)))
18735             {
18736               add_loc_descr_to_each (list_ret, loc_naddend);
18737               add_loc_descr_to_each (list_ret,
18738                                      new_loc_descr (DW_OP_minus, 0, 0));
18739             }
18740           else
18741             {
18742               for (dw_loc_descr_ref loc_cur = loc_naddend; loc_cur != NULL; )
18743                 {
18744                   loc_naddend = loc_cur;
18745                   loc_cur = loc_cur->dw_loc_next;
18746                   ggc_free (loc_naddend);
18747                 }
18748               loc_list_plus_const (list_ret, wi_addend.to_shwi ());
18749             }
18750           break;
18751         }
18752
18753       op = DW_OP_plus;
18754       goto do_binop;
18755
18756     case LE_EXPR:
18757       op = DW_OP_le;
18758       goto do_comp_binop;
18759
18760     case GE_EXPR:
18761       op = DW_OP_ge;
18762       goto do_comp_binop;
18763
18764     case LT_EXPR:
18765       op = DW_OP_lt;
18766       goto do_comp_binop;
18767
18768     case GT_EXPR:
18769       op = DW_OP_gt;
18770       goto do_comp_binop;
18771
18772     do_comp_binop:
18773       if (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (loc, 0))))
18774         {
18775           list_ret = loc_list_from_tree (TREE_OPERAND (loc, 0), 0, context);
18776           list_ret1 = loc_list_from_tree (TREE_OPERAND (loc, 1), 0, context);
18777           list_ret = loc_list_from_uint_comparison (list_ret, list_ret1,
18778                                                     TREE_CODE (loc));
18779           break;
18780         }
18781       else
18782         goto do_binop;
18783
18784     case EQ_EXPR:
18785       op = DW_OP_eq;
18786       goto do_binop;
18787
18788     case NE_EXPR:
18789       op = DW_OP_ne;
18790       goto do_binop;
18791
18792     do_binop:
18793       list_ret = loc_list_from_tree_1 (TREE_OPERAND (loc, 0), 0, context);
18794       list_ret1 = loc_list_from_tree_1 (TREE_OPERAND (loc, 1), 0, context);
18795       if (list_ret == 0 || list_ret1 == 0)
18796         return 0;
18797
18798       add_loc_list (&list_ret, list_ret1);
18799       if (list_ret == 0)
18800         return 0;
18801       add_loc_descr_to_each (list_ret, new_loc_descr (op, 0, 0));
18802       break;
18803
18804     case TRUTH_NOT_EXPR:
18805     case BIT_NOT_EXPR:
18806       op = DW_OP_not;
18807       goto do_unop;
18808
18809     case ABS_EXPR:
18810       op = DW_OP_abs;
18811       goto do_unop;
18812
18813     case NEGATE_EXPR:
18814       op = DW_OP_neg;
18815       goto do_unop;
18816
18817     do_unop:
18818       list_ret = loc_list_from_tree_1 (TREE_OPERAND (loc, 0), 0, context);
18819       if (list_ret == 0)
18820         return 0;
18821
18822       add_loc_descr_to_each (list_ret, new_loc_descr (op, 0, 0));
18823       break;
18824
18825     case MIN_EXPR:
18826     case MAX_EXPR:
18827       {
18828         const enum tree_code code =
18829           TREE_CODE (loc) == MIN_EXPR ? GT_EXPR : LT_EXPR;
18830
18831         loc = build3 (COND_EXPR, TREE_TYPE (loc),
18832                       build2 (code, integer_type_node,
18833                               TREE_OPERAND (loc, 0), TREE_OPERAND (loc, 1)),
18834                       TREE_OPERAND (loc, 1), TREE_OPERAND (loc, 0));
18835       }
18836
18837       /* fall through */
18838
18839     case COND_EXPR:
18840       {
18841         dw_loc_descr_ref lhs
18842           = loc_descriptor_from_tree (TREE_OPERAND (loc, 1), 0, context);
18843         dw_loc_list_ref rhs
18844           = loc_list_from_tree_1 (TREE_OPERAND (loc, 2), 0, context);
18845         dw_loc_descr_ref bra_node, jump_node, tmp;
18846
18847         list_ret = loc_list_from_tree_1 (TREE_OPERAND (loc, 0), 0, context);
18848         if (list_ret == 0 || lhs == 0 || rhs == 0)
18849           return 0;
18850
18851         bra_node = new_loc_descr (DW_OP_bra, 0, 0);
18852         add_loc_descr_to_each (list_ret, bra_node);
18853
18854         add_loc_list (&list_ret, rhs);
18855         jump_node = new_loc_descr (DW_OP_skip, 0, 0);
18856         add_loc_descr_to_each (list_ret, jump_node);
18857
18858         add_loc_descr_to_each (list_ret, lhs);
18859         bra_node->dw_loc_oprnd1.val_class = dw_val_class_loc;
18860         bra_node->dw_loc_oprnd1.v.val_loc = lhs;
18861
18862         /* ??? Need a node to point the skip at.  Use a nop.  */
18863         tmp = new_loc_descr (DW_OP_nop, 0, 0);
18864         add_loc_descr_to_each (list_ret, tmp);
18865         jump_node->dw_loc_oprnd1.val_class = dw_val_class_loc;
18866         jump_node->dw_loc_oprnd1.v.val_loc = tmp;
18867       }
18868       break;
18869
18870     case FIX_TRUNC_EXPR:
18871       return 0;
18872
18873     default:
18874       /* Leave front-end specific codes as simply unknown.  This comes
18875          up, for instance, with the C STMT_EXPR.  */
18876       if ((unsigned int) TREE_CODE (loc)
18877           >= (unsigned int) LAST_AND_UNUSED_TREE_CODE)
18878         {
18879           expansion_failed (loc, NULL_RTX,
18880                             "language specific tree node");
18881           return 0;
18882         }
18883
18884       /* Otherwise this is a generic code; we should just lists all of
18885          these explicitly.  We forgot one.  */
18886       if (flag_checking)
18887         gcc_unreachable ();
18888
18889       /* In a release build, we want to degrade gracefully: better to
18890          generate incomplete debugging information than to crash.  */
18891       return NULL;
18892     }
18893
18894   if (!ret && !list_ret)
18895     return 0;
18896
18897   if (want_address == 2 && !have_address
18898       && (dwarf_version >= 4 || !dwarf_strict))
18899     {
18900       if (int_size_in_bytes (TREE_TYPE (loc)) > DWARF2_ADDR_SIZE)
18901         {
18902           expansion_failed (loc, NULL_RTX,
18903                             "DWARF address size mismatch");
18904           return 0;
18905         }
18906       if (ret)
18907         add_loc_descr (&ret, new_loc_descr (DW_OP_stack_value, 0, 0));
18908       else
18909         add_loc_descr_to_each (list_ret,
18910                                new_loc_descr (DW_OP_stack_value, 0, 0));
18911       have_address = 1;
18912     }
18913   /* Show if we can't fill the request for an address.  */
18914   if (want_address && !have_address)
18915     {
18916       expansion_failed (loc, NULL_RTX,
18917                         "Want address and only have value");
18918       return 0;
18919     }
18920
18921   gcc_assert (!ret || !list_ret);
18922
18923   /* If we've got an address and don't want one, dereference.  */
18924   if (!want_address && have_address)
18925     {
18926       HOST_WIDE_INT size = int_size_in_bytes (TREE_TYPE (loc));
18927
18928       if (size > DWARF2_ADDR_SIZE || size == -1)
18929         {
18930           expansion_failed (loc, NULL_RTX,
18931                             "DWARF address size mismatch");
18932           return 0;
18933         }
18934       else if (size == DWARF2_ADDR_SIZE)
18935         op = DW_OP_deref;
18936       else
18937         op = DW_OP_deref_size;
18938
18939       if (ret)
18940         add_loc_descr (&ret, new_loc_descr (op, size, 0));
18941       else
18942         add_loc_descr_to_each (list_ret, new_loc_descr (op, size, 0));
18943     }
18944   if (ret)
18945     list_ret = new_loc_list (ret, NULL, 0, NULL, 0, NULL);
18946
18947   return list_ret;
18948 }
18949
18950 /* Likewise, but strip useless DW_OP_nop operations in the resulting
18951    expressions.  */
18952
18953 static dw_loc_list_ref
18954 loc_list_from_tree (tree loc, int want_address,
18955                     struct loc_descr_context *context)
18956 {
18957   dw_loc_list_ref result = loc_list_from_tree_1 (loc, want_address, context);
18958
18959   for (dw_loc_list_ref loc_cur = result;
18960        loc_cur != NULL; loc_cur = loc_cur->dw_loc_next)
18961     loc_descr_without_nops (loc_cur->expr);
18962   return result;
18963 }
18964
18965 /* Same as above but return only single location expression.  */
18966 static dw_loc_descr_ref
18967 loc_descriptor_from_tree (tree loc, int want_address,
18968                           struct loc_descr_context *context)
18969 {
18970   dw_loc_list_ref ret = loc_list_from_tree (loc, want_address, context);
18971   if (!ret)
18972     return NULL;
18973   if (ret->dw_loc_next)
18974     {
18975       expansion_failed (loc, NULL_RTX,
18976                         "Location list where only loc descriptor needed");
18977       return NULL;
18978     }
18979   return ret->expr;
18980 }
18981
18982 /* Given a value, round it up to the lowest multiple of `boundary'
18983    which is not less than the value itself.  */
18984
18985 static inline HOST_WIDE_INT
18986 ceiling (HOST_WIDE_INT value, unsigned int boundary)
18987 {
18988   return (((value + boundary - 1) / boundary) * boundary);
18989 }
18990
18991 /* Given a pointer to what is assumed to be a FIELD_DECL node, return a
18992    pointer to the declared type for the relevant field variable, or return
18993    `integer_type_node' if the given node turns out to be an
18994    ERROR_MARK node.  */
18995
18996 static inline tree
18997 field_type (const_tree decl)
18998 {
18999   tree type;
19000
19001   if (TREE_CODE (decl) == ERROR_MARK)
19002     return integer_type_node;
19003
19004   type = DECL_BIT_FIELD_TYPE (decl);
19005   if (type == NULL_TREE)
19006     type = TREE_TYPE (decl);
19007
19008   return type;
19009 }
19010
19011 /* Given a pointer to a tree node, return the alignment in bits for
19012    it, or else return BITS_PER_WORD if the node actually turns out to
19013    be an ERROR_MARK node.  */
19014
19015 static inline unsigned
19016 simple_type_align_in_bits (const_tree type)
19017 {
19018   return (TREE_CODE (type) != ERROR_MARK) ? TYPE_ALIGN (type) : BITS_PER_WORD;
19019 }
19020
19021 static inline unsigned
19022 simple_decl_align_in_bits (const_tree decl)
19023 {
19024   return (TREE_CODE (decl) != ERROR_MARK) ? DECL_ALIGN (decl) : BITS_PER_WORD;
19025 }
19026
19027 /* Return the result of rounding T up to ALIGN.  */
19028
19029 static inline offset_int
19030 round_up_to_align (const offset_int &t, unsigned int align)
19031 {
19032   return wi::udiv_trunc (t + align - 1, align) * align;
19033 }
19034
19035 /* Compute the size of TYPE in bytes.  If possible, return NULL and store the
19036    size as an integer constant in CST_SIZE.  Otherwise, if possible, return a
19037    DWARF expression that computes the size.  Return NULL and set CST_SIZE to -1
19038    if we fail to return the size in one of these two forms.  */
19039
19040 static dw_loc_descr_ref
19041 type_byte_size (const_tree type, HOST_WIDE_INT *cst_size)
19042 {
19043   tree tree_size;
19044   struct loc_descr_context ctx;
19045
19046   /* Return a constant integer in priority, if possible.  */
19047   *cst_size = int_size_in_bytes (type);
19048   if (*cst_size != -1)
19049     return NULL;
19050
19051   ctx.context_type = const_cast<tree> (type);
19052   ctx.base_decl = NULL_TREE;
19053   ctx.dpi = NULL;
19054   ctx.placeholder_arg = false;
19055   ctx.placeholder_seen = false;
19056
19057   type = TYPE_MAIN_VARIANT (type);
19058   tree_size = TYPE_SIZE_UNIT (type);
19059   return ((tree_size != NULL_TREE)
19060           ? loc_descriptor_from_tree (tree_size, 0, &ctx)
19061           : NULL);
19062 }
19063
19064 /* Helper structure for RECORD_TYPE processing.  */
19065 struct vlr_context
19066 {
19067   /* Root RECORD_TYPE.  It is needed to generate data member location
19068      descriptions in variable-length records (VLR), but also to cope with
19069      variants, which are composed of nested structures multiplexed with
19070      QUAL_UNION_TYPE nodes.  Each time such a structure is passed to a
19071      function processing a FIELD_DECL, it is required to be non null.  */
19072   tree struct_type;
19073   /* When generating a variant part in a RECORD_TYPE (i.e. a nested
19074      QUAL_UNION_TYPE), this holds an expression that computes the offset for
19075      this variant part as part of the root record (in storage units).  For
19076      regular records, it must be NULL_TREE.  */
19077   tree variant_part_offset;
19078 };
19079
19080 /* Given a pointer to a FIELD_DECL, compute the byte offset of the lowest
19081    addressed byte of the "containing object" for the given FIELD_DECL. If
19082    possible, return a native constant through CST_OFFSET (in which case NULL is
19083    returned); otherwise return a DWARF expression that computes the offset.
19084
19085    Set *CST_OFFSET to 0 and return NULL if we are unable to determine what
19086    that offset is, either because the argument turns out to be a pointer to an
19087    ERROR_MARK node, or because the offset expression is too complex for us.
19088
19089    CTX is required: see the comment for VLR_CONTEXT.  */
19090
19091 static dw_loc_descr_ref
19092 field_byte_offset (const_tree decl, struct vlr_context *ctx,
19093                    HOST_WIDE_INT *cst_offset)
19094 {
19095   tree tree_result;
19096   dw_loc_list_ref loc_result;
19097
19098   *cst_offset = 0;
19099
19100   if (TREE_CODE (decl) == ERROR_MARK)
19101     return NULL;
19102   else
19103     gcc_assert (TREE_CODE (decl) == FIELD_DECL);
19104
19105   /* We cannot handle variable bit offsets at the moment, so abort if it's the
19106      case.  */
19107   if (TREE_CODE (DECL_FIELD_BIT_OFFSET (decl)) != INTEGER_CST)
19108     return NULL;
19109
19110 #ifdef PCC_BITFIELD_TYPE_MATTERS
19111   /* We used to handle only constant offsets in all cases.  Now, we handle
19112      properly dynamic byte offsets only when PCC bitfield type doesn't
19113      matter.  */
19114   if (PCC_BITFIELD_TYPE_MATTERS
19115       && TREE_CODE (DECL_FIELD_OFFSET (decl)) == INTEGER_CST)
19116     {
19117       offset_int object_offset_in_bits;
19118       offset_int object_offset_in_bytes;
19119       offset_int bitpos_int;
19120       tree type;
19121       tree field_size_tree;
19122       offset_int deepest_bitpos;
19123       offset_int field_size_in_bits;
19124       unsigned int type_align_in_bits;
19125       unsigned int decl_align_in_bits;
19126       offset_int type_size_in_bits;
19127
19128       bitpos_int = wi::to_offset (bit_position (decl));
19129       type = field_type (decl);
19130       type_size_in_bits = offset_int_type_size_in_bits (type);
19131       type_align_in_bits = simple_type_align_in_bits (type);
19132
19133       field_size_tree = DECL_SIZE (decl);
19134
19135       /* The size could be unspecified if there was an error, or for
19136          a flexible array member.  */
19137       if (!field_size_tree)
19138         field_size_tree = bitsize_zero_node;
19139
19140       /* If the size of the field is not constant, use the type size.  */
19141       if (TREE_CODE (field_size_tree) == INTEGER_CST)
19142         field_size_in_bits = wi::to_offset (field_size_tree);
19143       else
19144         field_size_in_bits = type_size_in_bits;
19145
19146       decl_align_in_bits = simple_decl_align_in_bits (decl);
19147
19148       /* The GCC front-end doesn't make any attempt to keep track of the
19149          starting bit offset (relative to the start of the containing
19150          structure type) of the hypothetical "containing object" for a
19151          bit-field.  Thus, when computing the byte offset value for the
19152          start of the "containing object" of a bit-field, we must deduce
19153          this information on our own. This can be rather tricky to do in
19154          some cases.  For example, handling the following structure type
19155          definition when compiling for an i386/i486 target (which only
19156          aligns long long's to 32-bit boundaries) can be very tricky:
19157
19158          struct S { int field1; long long field2:31; };
19159
19160          Fortunately, there is a simple rule-of-thumb which can be used
19161          in such cases.  When compiling for an i386/i486, GCC will
19162          allocate 8 bytes for the structure shown above.  It decides to
19163          do this based upon one simple rule for bit-field allocation.
19164          GCC allocates each "containing object" for each bit-field at
19165          the first (i.e. lowest addressed) legitimate alignment boundary
19166          (based upon the required minimum alignment for the declared
19167          type of the field) which it can possibly use, subject to the
19168          condition that there is still enough available space remaining
19169          in the containing object (when allocated at the selected point)
19170          to fully accommodate all of the bits of the bit-field itself.
19171
19172          This simple rule makes it obvious why GCC allocates 8 bytes for
19173          each object of the structure type shown above.  When looking
19174          for a place to allocate the "containing object" for `field2',
19175          the compiler simply tries to allocate a 64-bit "containing
19176          object" at each successive 32-bit boundary (starting at zero)
19177          until it finds a place to allocate that 64- bit field such that
19178          at least 31 contiguous (and previously unallocated) bits remain
19179          within that selected 64 bit field.  (As it turns out, for the
19180          example above, the compiler finds it is OK to allocate the
19181          "containing object" 64-bit field at bit-offset zero within the
19182          structure type.)
19183
19184          Here we attempt to work backwards from the limited set of facts
19185          we're given, and we try to deduce from those facts, where GCC
19186          must have believed that the containing object started (within
19187          the structure type). The value we deduce is then used (by the
19188          callers of this routine) to generate DW_AT_location and
19189          DW_AT_bit_offset attributes for fields (both bit-fields and, in
19190          the case of DW_AT_location, regular fields as well).  */
19191
19192       /* Figure out the bit-distance from the start of the structure to
19193          the "deepest" bit of the bit-field.  */
19194       deepest_bitpos = bitpos_int + field_size_in_bits;
19195
19196       /* This is the tricky part.  Use some fancy footwork to deduce
19197          where the lowest addressed bit of the containing object must
19198          be.  */
19199       object_offset_in_bits = deepest_bitpos - type_size_in_bits;
19200
19201       /* Round up to type_align by default.  This works best for
19202          bitfields.  */
19203       object_offset_in_bits
19204         = round_up_to_align (object_offset_in_bits, type_align_in_bits);
19205
19206       if (wi::gtu_p (object_offset_in_bits, bitpos_int))
19207         {
19208           object_offset_in_bits = deepest_bitpos - type_size_in_bits;
19209
19210           /* Round up to decl_align instead.  */
19211           object_offset_in_bits
19212             = round_up_to_align (object_offset_in_bits, decl_align_in_bits);
19213         }
19214
19215       object_offset_in_bytes
19216         = wi::lrshift (object_offset_in_bits, LOG2_BITS_PER_UNIT);
19217       if (ctx->variant_part_offset == NULL_TREE)
19218         {
19219           *cst_offset = object_offset_in_bytes.to_shwi ();
19220           return NULL;
19221         }
19222       tree_result = wide_int_to_tree (sizetype, object_offset_in_bytes);
19223     }
19224   else
19225 #endif /* PCC_BITFIELD_TYPE_MATTERS */
19226     tree_result = byte_position (decl);
19227
19228   if (ctx->variant_part_offset != NULL_TREE)
19229     tree_result = fold_build2 (PLUS_EXPR, TREE_TYPE (tree_result),
19230                                ctx->variant_part_offset, tree_result);
19231
19232   /* If the byte offset is a constant, it's simplier to handle a native
19233      constant rather than a DWARF expression.  */
19234   if (TREE_CODE (tree_result) == INTEGER_CST)
19235     {
19236       *cst_offset = wi::to_offset (tree_result).to_shwi ();
19237       return NULL;
19238     }
19239   struct loc_descr_context loc_ctx = {
19240     ctx->struct_type, /* context_type */
19241     NULL_TREE,        /* base_decl */
19242     NULL,             /* dpi */
19243     false,            /* placeholder_arg */
19244     false             /* placeholder_seen */
19245   };
19246   loc_result = loc_list_from_tree (tree_result, 0, &loc_ctx);
19247
19248   /* We want a DWARF expression: abort if we only have a location list with
19249      multiple elements.  */
19250   if (!loc_result || !single_element_loc_list_p (loc_result))
19251     return NULL;
19252   else
19253     return loc_result->expr;
19254 }
19255 \f
19256 /* The following routines define various Dwarf attributes and any data
19257    associated with them.  */
19258
19259 /* Add a location description attribute value to a DIE.
19260
19261    This emits location attributes suitable for whole variables and
19262    whole parameters.  Note that the location attributes for struct fields are
19263    generated by the routine `data_member_location_attribute' below.  */
19264
19265 static inline void
19266 add_AT_location_description (dw_die_ref die, enum dwarf_attribute attr_kind,
19267                              dw_loc_list_ref descr)
19268 {
19269   bool check_no_locviews = true;
19270   if (descr == 0)
19271     return;
19272   if (single_element_loc_list_p (descr))
19273     add_AT_loc (die, attr_kind, descr->expr);
19274   else
19275     {
19276       add_AT_loc_list (die, attr_kind, descr);
19277       gcc_assert (descr->ll_symbol);
19278       if (attr_kind == DW_AT_location && descr->vl_symbol
19279           && dwarf2out_locviews_in_attribute ())
19280         {
19281           add_AT_view_list (die, DW_AT_GNU_locviews);
19282           check_no_locviews = false;
19283         }
19284     }
19285
19286   if (check_no_locviews)
19287     gcc_assert (!get_AT (die, DW_AT_GNU_locviews));
19288 }
19289
19290 /* Add DW_AT_accessibility attribute to DIE if needed.  */
19291
19292 static void
19293 add_accessibility_attribute (dw_die_ref die, tree decl)
19294 {
19295   /* In DWARF3+ the default is DW_ACCESS_private only in DW_TAG_class_type
19296      children, otherwise the default is DW_ACCESS_public.  In DWARF2
19297      the default has always been DW_ACCESS_public.  */
19298   if (TREE_PROTECTED (decl))
19299     add_AT_unsigned (die, DW_AT_accessibility, DW_ACCESS_protected);
19300   else if (TREE_PRIVATE (decl))
19301     {
19302       if (dwarf_version == 2
19303           || die->die_parent == NULL
19304           || die->die_parent->die_tag != DW_TAG_class_type)
19305         add_AT_unsigned (die, DW_AT_accessibility, DW_ACCESS_private);
19306     }
19307   else if (dwarf_version > 2
19308            && die->die_parent
19309            && die->die_parent->die_tag == DW_TAG_class_type)
19310     add_AT_unsigned (die, DW_AT_accessibility, DW_ACCESS_public);
19311 }
19312
19313 /* Attach the specialized form of location attribute used for data members of
19314    struct and union types.  In the special case of a FIELD_DECL node which
19315    represents a bit-field, the "offset" part of this special location
19316    descriptor must indicate the distance in bytes from the lowest-addressed
19317    byte of the containing struct or union type to the lowest-addressed byte of
19318    the "containing object" for the bit-field.  (See the `field_byte_offset'
19319    function above).
19320
19321    For any given bit-field, the "containing object" is a hypothetical object
19322    (of some integral or enum type) within which the given bit-field lives.  The
19323    type of this hypothetical "containing object" is always the same as the
19324    declared type of the individual bit-field itself (for GCC anyway... the
19325    DWARF spec doesn't actually mandate this).  Note that it is the size (in
19326    bytes) of the hypothetical "containing object" which will be given in the
19327    DW_AT_byte_size attribute for this bit-field.  (See the
19328    `byte_size_attribute' function below.)  It is also used when calculating the
19329    value of the DW_AT_bit_offset attribute.  (See the `bit_offset_attribute'
19330    function below.)
19331
19332    CTX is required: see the comment for VLR_CONTEXT.  */
19333
19334 static void
19335 add_data_member_location_attribute (dw_die_ref die,
19336                                     tree decl,
19337                                     struct vlr_context *ctx)
19338 {
19339   HOST_WIDE_INT offset;
19340   dw_loc_descr_ref loc_descr = 0;
19341
19342   if (TREE_CODE (decl) == TREE_BINFO)
19343     {
19344       /* We're working on the TAG_inheritance for a base class.  */
19345       if (BINFO_VIRTUAL_P (decl) && is_cxx ())
19346         {
19347           /* For C++ virtual bases we can't just use BINFO_OFFSET, as they
19348              aren't at a fixed offset from all (sub)objects of the same
19349              type.  We need to extract the appropriate offset from our
19350              vtable.  The following dwarf expression means
19351
19352                BaseAddr = ObAddr + *((*ObAddr) - Offset)
19353
19354              This is specific to the V3 ABI, of course.  */
19355
19356           dw_loc_descr_ref tmp;
19357
19358           /* Make a copy of the object address.  */
19359           tmp = new_loc_descr (DW_OP_dup, 0, 0);
19360           add_loc_descr (&loc_descr, tmp);
19361
19362           /* Extract the vtable address.  */
19363           tmp = new_loc_descr (DW_OP_deref, 0, 0);
19364           add_loc_descr (&loc_descr, tmp);
19365
19366           /* Calculate the address of the offset.  */
19367           offset = tree_to_shwi (BINFO_VPTR_FIELD (decl));
19368           gcc_assert (offset < 0);
19369
19370           tmp = int_loc_descriptor (-offset);
19371           add_loc_descr (&loc_descr, tmp);
19372           tmp = new_loc_descr (DW_OP_minus, 0, 0);
19373           add_loc_descr (&loc_descr, tmp);
19374
19375           /* Extract the offset.  */
19376           tmp = new_loc_descr (DW_OP_deref, 0, 0);
19377           add_loc_descr (&loc_descr, tmp);
19378
19379           /* Add it to the object address.  */
19380           tmp = new_loc_descr (DW_OP_plus, 0, 0);
19381           add_loc_descr (&loc_descr, tmp);
19382         }
19383       else
19384         offset = tree_to_shwi (BINFO_OFFSET (decl));
19385     }
19386   else
19387     {
19388       loc_descr = field_byte_offset (decl, ctx, &offset);
19389
19390       /* If loc_descr is available then we know the field offset is dynamic.
19391          However, GDB does not handle dynamic field offsets very well at the
19392          moment.  */
19393       if (loc_descr != NULL && gnat_encodings != DWARF_GNAT_ENCODINGS_MINIMAL)
19394         {
19395           loc_descr = NULL;
19396           offset = 0;
19397         }
19398
19399       /* Data member location evalutation starts with the base address on the
19400          stack.  Compute the field offset and add it to this base address.  */
19401       else if (loc_descr != NULL)
19402         add_loc_descr (&loc_descr, new_loc_descr (DW_OP_plus, 0, 0));
19403     }
19404
19405   if (! loc_descr)
19406     {
19407       /* While DW_AT_data_bit_offset has been added already in DWARF4,
19408          e.g. GDB only added support to it in November 2016.  For DWARF5
19409          we need newer debug info consumers anyway.  We might change this
19410          to dwarf_version >= 4 once most consumers catched up.  */
19411       if (dwarf_version >= 5
19412           && TREE_CODE (decl) == FIELD_DECL
19413           && DECL_BIT_FIELD_TYPE (decl))
19414         {
19415           tree off = bit_position (decl);
19416           if (tree_fits_uhwi_p (off) && get_AT (die, DW_AT_bit_size))
19417             {
19418               remove_AT (die, DW_AT_byte_size);
19419               remove_AT (die, DW_AT_bit_offset);
19420               add_AT_unsigned (die, DW_AT_data_bit_offset, tree_to_uhwi (off));
19421               return;
19422             }
19423         }
19424       if (dwarf_version > 2)
19425         {
19426           /* Don't need to output a location expression, just the constant. */
19427           if (offset < 0)
19428             add_AT_int (die, DW_AT_data_member_location, offset);
19429           else
19430             add_AT_unsigned (die, DW_AT_data_member_location, offset);
19431           return;
19432         }
19433       else
19434         {
19435           enum dwarf_location_atom op;
19436
19437           /* The DWARF2 standard says that we should assume that the structure
19438              address is already on the stack, so we can specify a structure
19439              field address by using DW_OP_plus_uconst.  */
19440           op = DW_OP_plus_uconst;
19441           loc_descr = new_loc_descr (op, offset, 0);
19442         }
19443     }
19444
19445   add_AT_loc (die, DW_AT_data_member_location, loc_descr);
19446 }
19447
19448 /* Writes integer values to dw_vec_const array.  */
19449
19450 static void
19451 insert_int (HOST_WIDE_INT val, unsigned int size, unsigned char *dest)
19452 {
19453   while (size != 0)
19454     {
19455       *dest++ = val & 0xff;
19456       val >>= 8;
19457       --size;
19458     }
19459 }
19460
19461 /* Reads integers from dw_vec_const array.  Inverse of insert_int.  */
19462
19463 static HOST_WIDE_INT
19464 extract_int (const unsigned char *src, unsigned int size)
19465 {
19466   HOST_WIDE_INT val = 0;
19467
19468   src += size;
19469   while (size != 0)
19470     {
19471       val <<= 8;
19472       val |= *--src & 0xff;
19473       --size;
19474     }
19475   return val;
19476 }
19477
19478 /* Writes wide_int values to dw_vec_const array.  */
19479
19480 static void
19481 insert_wide_int (const wide_int &val, unsigned char *dest, int elt_size)
19482 {
19483   int i;
19484
19485   if (elt_size <= HOST_BITS_PER_WIDE_INT/BITS_PER_UNIT)
19486     {
19487       insert_int ((HOST_WIDE_INT) val.elt (0), elt_size, dest);
19488       return;
19489     }
19490
19491   /* We'd have to extend this code to support odd sizes.  */
19492   gcc_assert (elt_size % (HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT) == 0);
19493
19494   int n = elt_size / (HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT);
19495
19496   if (WORDS_BIG_ENDIAN)
19497     for (i = n - 1; i >= 0; i--)
19498       {
19499         insert_int ((HOST_WIDE_INT) val.elt (i), sizeof (HOST_WIDE_INT), dest);
19500         dest += sizeof (HOST_WIDE_INT);
19501       }
19502   else
19503     for (i = 0; i < n; i++)
19504       {
19505         insert_int ((HOST_WIDE_INT) val.elt (i), sizeof (HOST_WIDE_INT), dest);
19506         dest += sizeof (HOST_WIDE_INT);
19507       }
19508 }
19509
19510 /* Writes floating point values to dw_vec_const array.  */
19511
19512 static void
19513 insert_float (const_rtx rtl, unsigned char *array)
19514 {
19515   long val[4];
19516   int i;
19517   scalar_float_mode mode = as_a <scalar_float_mode> (GET_MODE (rtl));
19518
19519   real_to_target (val, CONST_DOUBLE_REAL_VALUE (rtl), mode);
19520
19521   /* real_to_target puts 32-bit pieces in each long.  Pack them.  */
19522   for (i = 0; i < GET_MODE_SIZE (mode) / 4; i++)
19523     {
19524       insert_int (val[i], 4, array);
19525       array += 4;
19526     }
19527 }
19528
19529 /* Attach a DW_AT_const_value attribute for a variable or a parameter which
19530    does not have a "location" either in memory or in a register.  These
19531    things can arise in GNU C when a constant is passed as an actual parameter
19532    to an inlined function.  They can also arise in C++ where declared
19533    constants do not necessarily get memory "homes".  */
19534
19535 static bool
19536 add_const_value_attribute (dw_die_ref die, rtx rtl)
19537 {
19538   switch (GET_CODE (rtl))
19539     {
19540     case CONST_INT:
19541       {
19542         HOST_WIDE_INT val = INTVAL (rtl);
19543
19544         if (val < 0)
19545           add_AT_int (die, DW_AT_const_value, val);
19546         else
19547           add_AT_unsigned (die, DW_AT_const_value, (unsigned HOST_WIDE_INT) val);
19548       }
19549       return true;
19550
19551     case CONST_WIDE_INT:
19552       {
19553         wide_int w1 = rtx_mode_t (rtl, MAX_MODE_INT);
19554         unsigned int prec = MIN (wi::min_precision (w1, UNSIGNED),
19555                                  (unsigned int)CONST_WIDE_INT_NUNITS (rtl) * HOST_BITS_PER_WIDE_INT);
19556         wide_int w = wi::zext (w1, prec);
19557         add_AT_wide (die, DW_AT_const_value, w);
19558       }
19559       return true;
19560
19561     case CONST_DOUBLE:
19562       /* Note that a CONST_DOUBLE rtx could represent either an integer or a
19563          floating-point constant.  A CONST_DOUBLE is used whenever the
19564          constant requires more than one word in order to be adequately
19565          represented.  */
19566       if (TARGET_SUPPORTS_WIDE_INT == 0
19567           && !SCALAR_FLOAT_MODE_P (GET_MODE (rtl)))
19568         add_AT_double (die, DW_AT_const_value,
19569                        CONST_DOUBLE_HIGH (rtl), CONST_DOUBLE_LOW (rtl));
19570       else
19571         {
19572           scalar_float_mode mode = as_a <scalar_float_mode> (GET_MODE (rtl));
19573           unsigned int length = GET_MODE_SIZE (mode);
19574           unsigned char *array = ggc_vec_alloc<unsigned char> (length);
19575
19576           insert_float (rtl, array);
19577           add_AT_vec (die, DW_AT_const_value, length / 4, 4, array);
19578         }
19579       return true;
19580
19581     case CONST_VECTOR:
19582       {
19583         unsigned int length;
19584         if (!CONST_VECTOR_NUNITS (rtl).is_constant (&length))
19585           return false;
19586
19587         machine_mode mode = GET_MODE (rtl);
19588         unsigned int elt_size = GET_MODE_UNIT_SIZE (mode);
19589         unsigned char *array
19590           = ggc_vec_alloc<unsigned char> (length * elt_size);
19591         unsigned int i;
19592         unsigned char *p;
19593         machine_mode imode = GET_MODE_INNER (mode);
19594
19595         switch (GET_MODE_CLASS (mode))
19596           {
19597           case MODE_VECTOR_INT:
19598             for (i = 0, p = array; i < length; i++, p += elt_size)
19599               {
19600                 rtx elt = CONST_VECTOR_ELT (rtl, i);
19601                 insert_wide_int (rtx_mode_t (elt, imode), p, elt_size);
19602               }
19603             break;
19604
19605           case MODE_VECTOR_FLOAT:
19606             for (i = 0, p = array; i < length; i++, p += elt_size)
19607               {
19608                 rtx elt = CONST_VECTOR_ELT (rtl, i);
19609                 insert_float (elt, p);
19610               }
19611             break;
19612
19613           default:
19614             gcc_unreachable ();
19615           }
19616
19617         add_AT_vec (die, DW_AT_const_value, length, elt_size, array);
19618       }
19619       return true;
19620
19621     case CONST_STRING:
19622       if (dwarf_version >= 4 || !dwarf_strict)
19623         {
19624           dw_loc_descr_ref loc_result;
19625           resolve_one_addr (&rtl);
19626         rtl_addr:
19627           loc_result = new_addr_loc_descr (rtl, dtprel_false);
19628           add_loc_descr (&loc_result, new_loc_descr (DW_OP_stack_value, 0, 0));
19629           add_AT_loc (die, DW_AT_location, loc_result);
19630           vec_safe_push (used_rtx_array, rtl);
19631           return true;
19632         }
19633       return false;
19634
19635     case CONST:
19636       if (CONSTANT_P (XEXP (rtl, 0)))
19637         return add_const_value_attribute (die, XEXP (rtl, 0));
19638       /* FALLTHROUGH */
19639     case SYMBOL_REF:
19640       if (!const_ok_for_output (rtl))
19641         return false;
19642       /* FALLTHROUGH */
19643     case LABEL_REF:
19644       if (dwarf_version >= 4 || !dwarf_strict)
19645         goto rtl_addr;
19646       return false;
19647
19648     case PLUS:
19649       /* In cases where an inlined instance of an inline function is passed
19650          the address of an `auto' variable (which is local to the caller) we
19651          can get a situation where the DECL_RTL of the artificial local
19652          variable (for the inlining) which acts as a stand-in for the
19653          corresponding formal parameter (of the inline function) will look
19654          like (plus:SI (reg:SI FRAME_PTR) (const_int ...)).  This is not
19655          exactly a compile-time constant expression, but it isn't the address
19656          of the (artificial) local variable either.  Rather, it represents the
19657          *value* which the artificial local variable always has during its
19658          lifetime.  We currently have no way to represent such quasi-constant
19659          values in Dwarf, so for now we just punt and generate nothing.  */
19660       return false;
19661
19662     case HIGH:
19663     case CONST_FIXED:
19664       return false;
19665
19666     case MEM:
19667       if (GET_CODE (XEXP (rtl, 0)) == CONST_STRING
19668           && MEM_READONLY_P (rtl)
19669           && GET_MODE (rtl) == BLKmode)
19670         {
19671           add_AT_string (die, DW_AT_const_value, XSTR (XEXP (rtl, 0), 0));
19672           return true;
19673         }
19674       return false;
19675
19676     default:
19677       /* No other kinds of rtx should be possible here.  */
19678       gcc_unreachable ();
19679     }
19680   return false;
19681 }
19682
19683 /* Determine whether the evaluation of EXPR references any variables
19684    or functions which aren't otherwise used (and therefore may not be
19685    output).  */
19686 static tree
19687 reference_to_unused (tree * tp, int * walk_subtrees,
19688                      void * data ATTRIBUTE_UNUSED)
19689 {
19690   if (! EXPR_P (*tp) && ! CONSTANT_CLASS_P (*tp))
19691     *walk_subtrees = 0;
19692
19693   if (DECL_P (*tp) && ! TREE_PUBLIC (*tp) && ! TREE_USED (*tp)
19694       && ! TREE_ASM_WRITTEN (*tp))
19695     return *tp;
19696   /* ???  The C++ FE emits debug information for using decls, so
19697      putting gcc_unreachable here falls over.  See PR31899.  For now
19698      be conservative.  */
19699   else if (!symtab->global_info_ready && VAR_OR_FUNCTION_DECL_P (*tp))
19700     return *tp;
19701   else if (VAR_P (*tp))
19702     {
19703       varpool_node *node = varpool_node::get (*tp);
19704       if (!node || !node->definition)
19705         return *tp;
19706     }
19707   else if (TREE_CODE (*tp) == FUNCTION_DECL
19708            && (!DECL_EXTERNAL (*tp) || DECL_DECLARED_INLINE_P (*tp)))
19709     {
19710       /* The call graph machinery must have finished analyzing,
19711          optimizing and gimplifying the CU by now.
19712          So if *TP has no call graph node associated
19713          to it, it means *TP will not be emitted.  */
19714       if (!cgraph_node::get (*tp))
19715         return *tp;
19716     }
19717   else if (TREE_CODE (*tp) == STRING_CST && !TREE_ASM_WRITTEN (*tp))
19718     return *tp;
19719
19720   return NULL_TREE;
19721 }
19722
19723 /* Generate an RTL constant from a decl initializer INIT with decl type TYPE,
19724    for use in a later add_const_value_attribute call.  */
19725
19726 static rtx
19727 rtl_for_decl_init (tree init, tree type)
19728 {
19729   rtx rtl = NULL_RTX;
19730
19731   STRIP_NOPS (init);
19732
19733   /* If a variable is initialized with a string constant without embedded
19734      zeros, build CONST_STRING.  */
19735   if (TREE_CODE (init) == STRING_CST && TREE_CODE (type) == ARRAY_TYPE)
19736     {
19737       tree enttype = TREE_TYPE (type);
19738       tree domain = TYPE_DOMAIN (type);
19739       scalar_int_mode mode;
19740
19741       if (is_int_mode (TYPE_MODE (enttype), &mode)
19742           && GET_MODE_SIZE (mode) == 1
19743           && domain
19744           && TYPE_MAX_VALUE (domain)
19745           && TREE_CODE (TYPE_MAX_VALUE (domain)) == INTEGER_CST
19746           && integer_zerop (TYPE_MIN_VALUE (domain))
19747           && compare_tree_int (TYPE_MAX_VALUE (domain),
19748                                TREE_STRING_LENGTH (init) - 1) == 0
19749           && ((size_t) TREE_STRING_LENGTH (init)
19750               == strlen (TREE_STRING_POINTER (init)) + 1))
19751         {
19752           rtl = gen_rtx_CONST_STRING (VOIDmode,
19753                                       ggc_strdup (TREE_STRING_POINTER (init)));
19754           rtl = gen_rtx_MEM (BLKmode, rtl);
19755           MEM_READONLY_P (rtl) = 1;
19756         }
19757     }
19758   /* Other aggregates, and complex values, could be represented using
19759      CONCAT: FIXME!  */
19760   else if (AGGREGATE_TYPE_P (type)
19761            || (TREE_CODE (init) == VIEW_CONVERT_EXPR
19762                && AGGREGATE_TYPE_P (TREE_TYPE (TREE_OPERAND (init, 0))))
19763            || TREE_CODE (type) == COMPLEX_TYPE)
19764     ;
19765   /* Vectors only work if their mode is supported by the target.
19766      FIXME: generic vectors ought to work too.  */
19767   else if (TREE_CODE (type) == VECTOR_TYPE
19768            && !VECTOR_MODE_P (TYPE_MODE (type)))
19769     ;
19770   /* If the initializer is something that we know will expand into an
19771      immediate RTL constant, expand it now.  We must be careful not to
19772      reference variables which won't be output.  */
19773   else if (initializer_constant_valid_p (init, type)
19774            && ! walk_tree (&init, reference_to_unused, NULL, NULL))
19775     {
19776       /* Convert vector CONSTRUCTOR initializers to VECTOR_CST if
19777          possible.  */
19778       if (TREE_CODE (type) == VECTOR_TYPE)
19779         switch (TREE_CODE (init))
19780           {
19781           case VECTOR_CST:
19782             break;
19783           case CONSTRUCTOR:
19784             if (TREE_CONSTANT (init))
19785               {
19786                 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (init);
19787                 bool constant_p = true;
19788                 tree value;
19789                 unsigned HOST_WIDE_INT ix;
19790
19791                 /* Even when ctor is constant, it might contain non-*_CST
19792                    elements (e.g. { 1.0/0.0 - 1.0/0.0, 0.0 }) and those don't
19793                    belong into VECTOR_CST nodes.  */
19794                 FOR_EACH_CONSTRUCTOR_VALUE (elts, ix, value)
19795                   if (!CONSTANT_CLASS_P (value))
19796                     {
19797                       constant_p = false;
19798                       break;
19799                     }
19800
19801                 if (constant_p)
19802                   {
19803                     init = build_vector_from_ctor (type, elts);
19804                     break;
19805                   }
19806               }
19807             /* FALLTHRU */
19808
19809           default:
19810             return NULL;
19811           }
19812
19813       rtl = expand_expr (init, NULL_RTX, VOIDmode, EXPAND_INITIALIZER);
19814
19815       /* If expand_expr returns a MEM, it wasn't immediate.  */
19816       gcc_assert (!rtl || !MEM_P (rtl));
19817     }
19818
19819   return rtl;
19820 }
19821
19822 /* Generate RTL for the variable DECL to represent its location.  */
19823
19824 static rtx
19825 rtl_for_decl_location (tree decl)
19826 {
19827   rtx rtl;
19828
19829   /* Here we have to decide where we are going to say the parameter "lives"
19830      (as far as the debugger is concerned).  We only have a couple of
19831      choices.  GCC provides us with DECL_RTL and with DECL_INCOMING_RTL.
19832
19833      DECL_RTL normally indicates where the parameter lives during most of the
19834      activation of the function.  If optimization is enabled however, this
19835      could be either NULL or else a pseudo-reg.  Both of those cases indicate
19836      that the parameter doesn't really live anywhere (as far as the code
19837      generation parts of GCC are concerned) during most of the function's
19838      activation.  That will happen (for example) if the parameter is never
19839      referenced within the function.
19840
19841      We could just generate a location descriptor here for all non-NULL
19842      non-pseudo values of DECL_RTL and ignore all of the rest, but we can be
19843      a little nicer than that if we also consider DECL_INCOMING_RTL in cases
19844      where DECL_RTL is NULL or is a pseudo-reg.
19845
19846      Note however that we can only get away with using DECL_INCOMING_RTL as
19847      a backup substitute for DECL_RTL in certain limited cases.  In cases
19848      where DECL_ARG_TYPE (decl) indicates the same type as TREE_TYPE (decl),
19849      we can be sure that the parameter was passed using the same type as it is
19850      declared to have within the function, and that its DECL_INCOMING_RTL
19851      points us to a place where a value of that type is passed.
19852
19853      In cases where DECL_ARG_TYPE (decl) and TREE_TYPE (decl) are different,
19854      we cannot (in general) use DECL_INCOMING_RTL as a substitute for DECL_RTL
19855      because in these cases DECL_INCOMING_RTL points us to a value of some
19856      type which is *different* from the type of the parameter itself.  Thus,
19857      if we tried to use DECL_INCOMING_RTL to generate a location attribute in
19858      such cases, the debugger would end up (for example) trying to fetch a
19859      `float' from a place which actually contains the first part of a
19860      `double'.  That would lead to really incorrect and confusing
19861      output at debug-time.
19862
19863      So, in general, we *do not* use DECL_INCOMING_RTL as a backup for DECL_RTL
19864      in cases where DECL_ARG_TYPE (decl) != TREE_TYPE (decl).  There
19865      are a couple of exceptions however.  On little-endian machines we can
19866      get away with using DECL_INCOMING_RTL even when DECL_ARG_TYPE (decl) is
19867      not the same as TREE_TYPE (decl), but only when DECL_ARG_TYPE (decl) is
19868      an integral type that is smaller than TREE_TYPE (decl). These cases arise
19869      when (on a little-endian machine) a non-prototyped function has a
19870      parameter declared to be of type `short' or `char'.  In such cases,
19871      TREE_TYPE (decl) will be `short' or `char', DECL_ARG_TYPE (decl) will
19872      be `int', and DECL_INCOMING_RTL will point to the lowest-order byte of the
19873      passed `int' value.  If the debugger then uses that address to fetch
19874      a `short' or a `char' (on a little-endian machine) the result will be
19875      the correct data, so we allow for such exceptional cases below.
19876
19877      Note that our goal here is to describe the place where the given formal
19878      parameter lives during most of the function's activation (i.e. between the
19879      end of the prologue and the start of the epilogue).  We'll do that as best
19880      as we can. Note however that if the given formal parameter is modified
19881      sometime during the execution of the function, then a stack backtrace (at
19882      debug-time) will show the function as having been called with the *new*
19883      value rather than the value which was originally passed in.  This happens
19884      rarely enough that it is not a major problem, but it *is* a problem, and
19885      I'd like to fix it.
19886
19887      A future version of dwarf2out.c may generate two additional attributes for
19888      any given DW_TAG_formal_parameter DIE which will describe the "passed
19889      type" and the "passed location" for the given formal parameter in addition
19890      to the attributes we now generate to indicate the "declared type" and the
19891      "active location" for each parameter.  This additional set of attributes
19892      could be used by debuggers for stack backtraces. Separately, note that
19893      sometimes DECL_RTL can be NULL and DECL_INCOMING_RTL can be NULL also.
19894      This happens (for example) for inlined-instances of inline function formal
19895      parameters which are never referenced.  This really shouldn't be
19896      happening.  All PARM_DECL nodes should get valid non-NULL
19897      DECL_INCOMING_RTL values.  FIXME.  */
19898
19899   /* Use DECL_RTL as the "location" unless we find something better.  */
19900   rtl = DECL_RTL_IF_SET (decl);
19901
19902   /* When generating abstract instances, ignore everything except
19903      constants, symbols living in memory, and symbols living in
19904      fixed registers.  */
19905   if (! reload_completed)
19906     {
19907       if (rtl
19908           && (CONSTANT_P (rtl)
19909               || (MEM_P (rtl)
19910                   && CONSTANT_P (XEXP (rtl, 0)))
19911               || (REG_P (rtl)
19912                   && VAR_P (decl)
19913                   && TREE_STATIC (decl))))
19914         {
19915           rtl = targetm.delegitimize_address (rtl);
19916           return rtl;
19917         }
19918       rtl = NULL_RTX;
19919     }
19920   else if (TREE_CODE (decl) == PARM_DECL)
19921     {
19922       if (rtl == NULL_RTX
19923           || is_pseudo_reg (rtl)
19924           || (MEM_P (rtl)
19925               && is_pseudo_reg (XEXP (rtl, 0))
19926               && DECL_INCOMING_RTL (decl)
19927               && MEM_P (DECL_INCOMING_RTL (decl))
19928               && GET_MODE (rtl) == GET_MODE (DECL_INCOMING_RTL (decl))))
19929         {
19930           tree declared_type = TREE_TYPE (decl);
19931           tree passed_type = DECL_ARG_TYPE (decl);
19932           machine_mode dmode = TYPE_MODE (declared_type);
19933           machine_mode pmode = TYPE_MODE (passed_type);
19934
19935           /* This decl represents a formal parameter which was optimized out.
19936              Note that DECL_INCOMING_RTL may be NULL in here, but we handle
19937              all cases where (rtl == NULL_RTX) just below.  */
19938           if (dmode == pmode)
19939             rtl = DECL_INCOMING_RTL (decl);
19940           else if ((rtl == NULL_RTX || is_pseudo_reg (rtl))
19941                    && SCALAR_INT_MODE_P (dmode)
19942                    && known_le (GET_MODE_SIZE (dmode), GET_MODE_SIZE (pmode))
19943                    && DECL_INCOMING_RTL (decl))
19944             {
19945               rtx inc = DECL_INCOMING_RTL (decl);
19946               if (REG_P (inc))
19947                 rtl = inc;
19948               else if (MEM_P (inc))
19949                 {
19950                   if (BYTES_BIG_ENDIAN)
19951                     rtl = adjust_address_nv (inc, dmode,
19952                                              GET_MODE_SIZE (pmode)
19953                                              - GET_MODE_SIZE (dmode));
19954                   else
19955                     rtl = inc;
19956                 }
19957             }
19958         }
19959
19960       /* If the parm was passed in registers, but lives on the stack, then
19961          make a big endian correction if the mode of the type of the
19962          parameter is not the same as the mode of the rtl.  */
19963       /* ??? This is the same series of checks that are made in dbxout.c before
19964          we reach the big endian correction code there.  It isn't clear if all
19965          of these checks are necessary here, but keeping them all is the safe
19966          thing to do.  */
19967       else if (MEM_P (rtl)
19968                && XEXP (rtl, 0) != const0_rtx
19969                && ! CONSTANT_P (XEXP (rtl, 0))
19970                /* Not passed in memory.  */
19971                && !MEM_P (DECL_INCOMING_RTL (decl))
19972                /* Not passed by invisible reference.  */
19973                && (!REG_P (XEXP (rtl, 0))
19974                    || REGNO (XEXP (rtl, 0)) == HARD_FRAME_POINTER_REGNUM
19975                    || REGNO (XEXP (rtl, 0)) == STACK_POINTER_REGNUM
19976 #if !HARD_FRAME_POINTER_IS_ARG_POINTER
19977                    || REGNO (XEXP (rtl, 0)) == ARG_POINTER_REGNUM
19978 #endif
19979                      )
19980                /* Big endian correction check.  */
19981                && BYTES_BIG_ENDIAN
19982                && TYPE_MODE (TREE_TYPE (decl)) != GET_MODE (rtl)
19983                && known_lt (GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (decl))),
19984                             UNITS_PER_WORD))
19985         {
19986           machine_mode addr_mode = get_address_mode (rtl);
19987           poly_int64 offset = (UNITS_PER_WORD
19988                                - GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (decl))));
19989
19990           rtl = gen_rtx_MEM (TYPE_MODE (TREE_TYPE (decl)),
19991                              plus_constant (addr_mode, XEXP (rtl, 0), offset));
19992         }
19993     }
19994   else if (VAR_P (decl)
19995            && rtl
19996            && MEM_P (rtl)
19997            && GET_MODE (rtl) != TYPE_MODE (TREE_TYPE (decl)))
19998     {
19999       machine_mode addr_mode = get_address_mode (rtl);
20000       poly_int64 offset = byte_lowpart_offset (TYPE_MODE (TREE_TYPE (decl)),
20001                                                GET_MODE (rtl));
20002
20003       /* If a variable is declared "register" yet is smaller than
20004          a register, then if we store the variable to memory, it
20005          looks like we're storing a register-sized value, when in
20006          fact we are not.  We need to adjust the offset of the
20007          storage location to reflect the actual value's bytes,
20008          else gdb will not be able to display it.  */
20009       if (maybe_ne (offset, 0))
20010         rtl = gen_rtx_MEM (TYPE_MODE (TREE_TYPE (decl)),
20011                            plus_constant (addr_mode, XEXP (rtl, 0), offset));
20012     }
20013
20014   /* A variable with no DECL_RTL but a DECL_INITIAL is a compile-time constant,
20015      and will have been substituted directly into all expressions that use it.
20016      C does not have such a concept, but C++ and other languages do.  */
20017   if (!rtl && VAR_P (decl) && DECL_INITIAL (decl))
20018     rtl = rtl_for_decl_init (DECL_INITIAL (decl), TREE_TYPE (decl));
20019
20020   if (rtl)
20021     rtl = targetm.delegitimize_address (rtl);
20022
20023   /* If we don't look past the constant pool, we risk emitting a
20024      reference to a constant pool entry that isn't referenced from
20025      code, and thus is not emitted.  */
20026   if (rtl)
20027     rtl = avoid_constant_pool_reference (rtl);
20028
20029   /* Try harder to get a rtl.  If this symbol ends up not being emitted
20030      in the current CU, resolve_addr will remove the expression referencing
20031      it.  */
20032   if (rtl == NULL_RTX
20033       && !(early_dwarf && (flag_generate_lto || flag_generate_offload))
20034       && VAR_P (decl)
20035       && !DECL_EXTERNAL (decl)
20036       && TREE_STATIC (decl)
20037       && DECL_NAME (decl)
20038       && !DECL_HARD_REGISTER (decl)
20039       && DECL_MODE (decl) != VOIDmode)
20040     {
20041       rtl = make_decl_rtl_for_debug (decl);
20042       if (!MEM_P (rtl)
20043           || GET_CODE (XEXP (rtl, 0)) != SYMBOL_REF
20044           || SYMBOL_REF_DECL (XEXP (rtl, 0)) != decl)
20045         rtl = NULL_RTX;
20046     }
20047
20048   return rtl;
20049 }
20050
20051 /* Check whether decl is a Fortran COMMON symbol.  If not, NULL_TREE is
20052    returned.  If so, the decl for the COMMON block is returned, and the
20053    value is the offset into the common block for the symbol.  */
20054
20055 static tree
20056 fortran_common (tree decl, HOST_WIDE_INT *value)
20057 {
20058   tree val_expr, cvar;
20059   machine_mode mode;
20060   poly_int64 bitsize, bitpos;
20061   tree offset;
20062   HOST_WIDE_INT cbitpos;
20063   int unsignedp, reversep, volatilep = 0;
20064
20065   /* If the decl isn't a VAR_DECL, or if it isn't static, or if
20066      it does not have a value (the offset into the common area), or if it
20067      is thread local (as opposed to global) then it isn't common, and shouldn't
20068      be handled as such.  */
20069   if (!VAR_P (decl)
20070       || !TREE_STATIC (decl)
20071       || !DECL_HAS_VALUE_EXPR_P (decl)
20072       || !is_fortran ())
20073     return NULL_TREE;
20074
20075   val_expr = DECL_VALUE_EXPR (decl);
20076   if (TREE_CODE (val_expr) != COMPONENT_REF)
20077     return NULL_TREE;
20078
20079   cvar = get_inner_reference (val_expr, &bitsize, &bitpos, &offset, &mode,
20080                               &unsignedp, &reversep, &volatilep);
20081
20082   if (cvar == NULL_TREE
20083       || !VAR_P (cvar)
20084       || DECL_ARTIFICIAL (cvar)
20085       || !TREE_PUBLIC (cvar)
20086       /* We don't expect to have to cope with variable offsets,
20087          since at present all static data must have a constant size.  */
20088       || !bitpos.is_constant (&cbitpos))
20089     return NULL_TREE;
20090
20091   *value = 0;
20092   if (offset != NULL)
20093     {
20094       if (!tree_fits_shwi_p (offset))
20095         return NULL_TREE;
20096       *value = tree_to_shwi (offset);
20097     }
20098   if (cbitpos != 0)
20099     *value += cbitpos / BITS_PER_UNIT;
20100
20101   return cvar;
20102 }
20103
20104 /* Generate *either* a DW_AT_location attribute or else a DW_AT_const_value
20105    data attribute for a variable or a parameter.  We generate the
20106    DW_AT_const_value attribute only in those cases where the given variable
20107    or parameter does not have a true "location" either in memory or in a
20108    register.  This can happen (for example) when a constant is passed as an
20109    actual argument in a call to an inline function.  (It's possible that
20110    these things can crop up in other ways also.)  Note that one type of
20111    constant value which can be passed into an inlined function is a constant
20112    pointer.  This can happen for example if an actual argument in an inlined
20113    function call evaluates to a compile-time constant address.
20114
20115    CACHE_P is true if it is worth caching the location list for DECL,
20116    so that future calls can reuse it rather than regenerate it from scratch.
20117    This is true for BLOCK_NONLOCALIZED_VARS in inlined subroutines,
20118    since we will need to refer to them each time the function is inlined.  */
20119
20120 static bool
20121 add_location_or_const_value_attribute (dw_die_ref die, tree decl, bool cache_p)
20122 {
20123   rtx rtl;
20124   dw_loc_list_ref list;
20125   var_loc_list *loc_list;
20126   cached_dw_loc_list *cache;
20127
20128   if (early_dwarf)
20129     return false;
20130
20131   if (TREE_CODE (decl) == ERROR_MARK)
20132     return false;
20133
20134   if (get_AT (die, DW_AT_location)
20135       || get_AT (die, DW_AT_const_value))
20136     return true;
20137
20138   gcc_assert (VAR_P (decl) || TREE_CODE (decl) == PARM_DECL
20139               || TREE_CODE (decl) == RESULT_DECL);
20140
20141   /* Try to get some constant RTL for this decl, and use that as the value of
20142      the location.  */
20143
20144   rtl = rtl_for_decl_location (decl);
20145   if (rtl && (CONSTANT_P (rtl) || GET_CODE (rtl) == CONST_STRING)
20146       && add_const_value_attribute (die, rtl))
20147     return true;
20148
20149   /* See if we have single element location list that is equivalent to
20150      a constant value.  That way we are better to use add_const_value_attribute
20151      rather than expanding constant value equivalent.  */
20152   loc_list = lookup_decl_loc (decl);
20153   if (loc_list
20154       && loc_list->first
20155       && loc_list->first->next == NULL
20156       && NOTE_P (loc_list->first->loc)
20157       && NOTE_VAR_LOCATION (loc_list->first->loc)
20158       && NOTE_VAR_LOCATION_LOC (loc_list->first->loc))
20159     {
20160       struct var_loc_node *node;
20161
20162       node = loc_list->first;
20163       rtl = NOTE_VAR_LOCATION_LOC (node->loc);
20164       if (GET_CODE (rtl) == EXPR_LIST)
20165         rtl = XEXP (rtl, 0);
20166       if ((CONSTANT_P (rtl) || GET_CODE (rtl) == CONST_STRING)
20167           && add_const_value_attribute (die, rtl))
20168          return true;
20169     }
20170   /* If this decl is from BLOCK_NONLOCALIZED_VARS, we might need its
20171      list several times.  See if we've already cached the contents.  */
20172   list = NULL;
20173   if (loc_list == NULL || cached_dw_loc_list_table == NULL)
20174     cache_p = false;
20175   if (cache_p)
20176     {
20177       cache = cached_dw_loc_list_table->find_with_hash (decl, DECL_UID (decl));
20178       if (cache)
20179         list = cache->loc_list;
20180     }
20181   if (list == NULL)
20182     {
20183       list = loc_list_from_tree (decl, decl_by_reference_p (decl) ? 0 : 2,
20184                                  NULL);
20185       /* It is usually worth caching this result if the decl is from
20186          BLOCK_NONLOCALIZED_VARS and if the list has at least two elements.  */
20187       if (cache_p && list && list->dw_loc_next)
20188         {
20189           cached_dw_loc_list **slot
20190             = cached_dw_loc_list_table->find_slot_with_hash (decl,
20191                                                              DECL_UID (decl),
20192                                                              INSERT);
20193           cache = ggc_cleared_alloc<cached_dw_loc_list> ();
20194           cache->decl_id = DECL_UID (decl);
20195           cache->loc_list = list;
20196           *slot = cache;
20197         }
20198     }
20199   if (list)
20200     {
20201       add_AT_location_description (die, DW_AT_location, list);
20202       return true;
20203     }
20204   /* None of that worked, so it must not really have a location;
20205      try adding a constant value attribute from the DECL_INITIAL.  */
20206   return tree_add_const_value_attribute_for_decl (die, decl);
20207 }
20208
20209 /* Helper function for tree_add_const_value_attribute.  Natively encode
20210    initializer INIT into an array.  Return true if successful.  */
20211
20212 static bool
20213 native_encode_initializer (tree init, unsigned char *array, int size)
20214 {
20215   tree type;
20216
20217   if (init == NULL_TREE)
20218     return false;
20219
20220   STRIP_NOPS (init);
20221   switch (TREE_CODE (init))
20222     {
20223     case STRING_CST:
20224       type = TREE_TYPE (init);
20225       if (TREE_CODE (type) == ARRAY_TYPE)
20226         {
20227           tree enttype = TREE_TYPE (type);
20228           scalar_int_mode mode;
20229
20230           if (!is_int_mode (TYPE_MODE (enttype), &mode)
20231               || GET_MODE_SIZE (mode) != 1)
20232             return false;
20233           if (int_size_in_bytes (type) != size)
20234             return false;
20235           if (size > TREE_STRING_LENGTH (init))
20236             {
20237               memcpy (array, TREE_STRING_POINTER (init),
20238                       TREE_STRING_LENGTH (init));
20239               memset (array + TREE_STRING_LENGTH (init),
20240                       '\0', size - TREE_STRING_LENGTH (init));
20241             }
20242           else
20243             memcpy (array, TREE_STRING_POINTER (init), size);
20244           return true;
20245         }
20246       return false;
20247     case CONSTRUCTOR:
20248       type = TREE_TYPE (init);
20249       if (int_size_in_bytes (type) != size)
20250         return false;
20251       if (TREE_CODE (type) == ARRAY_TYPE)
20252         {
20253           HOST_WIDE_INT min_index;
20254           unsigned HOST_WIDE_INT cnt;
20255           int curpos = 0, fieldsize;
20256           constructor_elt *ce;
20257
20258           if (TYPE_DOMAIN (type) == NULL_TREE
20259               || !tree_fits_shwi_p (TYPE_MIN_VALUE (TYPE_DOMAIN (type))))
20260             return false;
20261
20262           fieldsize = int_size_in_bytes (TREE_TYPE (type));
20263           if (fieldsize <= 0)
20264             return false;
20265
20266           min_index = tree_to_shwi (TYPE_MIN_VALUE (TYPE_DOMAIN (type)));
20267           memset (array, '\0', size);
20268           FOR_EACH_VEC_SAFE_ELT (CONSTRUCTOR_ELTS (init), cnt, ce)
20269             {
20270               tree val = ce->value;
20271               tree index = ce->index;
20272               int pos = curpos;
20273               if (index && TREE_CODE (index) == RANGE_EXPR)
20274                 pos = (tree_to_shwi (TREE_OPERAND (index, 0)) - min_index)
20275                       * fieldsize;
20276               else if (index)
20277                 pos = (tree_to_shwi (index) - min_index) * fieldsize;
20278
20279               if (val)
20280                 {
20281                   STRIP_NOPS (val);
20282                   if (!native_encode_initializer (val, array + pos, fieldsize))
20283                     return false;
20284                 }
20285               curpos = pos + fieldsize;
20286               if (index && TREE_CODE (index) == RANGE_EXPR)
20287                 {
20288                   int count = tree_to_shwi (TREE_OPERAND (index, 1))
20289                               - tree_to_shwi (TREE_OPERAND (index, 0));
20290                   while (count-- > 0)
20291                     {
20292                       if (val)
20293                         memcpy (array + curpos, array + pos, fieldsize);
20294                       curpos += fieldsize;
20295                     }
20296                 }
20297               gcc_assert (curpos <= size);
20298             }
20299           return true;
20300         }
20301       else if (TREE_CODE (type) == RECORD_TYPE
20302                || TREE_CODE (type) == UNION_TYPE)
20303         {
20304           tree field = NULL_TREE;
20305           unsigned HOST_WIDE_INT cnt;
20306           constructor_elt *ce;
20307
20308           if (int_size_in_bytes (type) != size)
20309             return false;
20310
20311           if (TREE_CODE (type) == RECORD_TYPE)
20312             field = TYPE_FIELDS (type);
20313
20314           FOR_EACH_VEC_SAFE_ELT (CONSTRUCTOR_ELTS (init), cnt, ce)
20315             {
20316               tree val = ce->value;
20317               int pos, fieldsize;
20318
20319               if (ce->index != 0)
20320                 field = ce->index;
20321
20322               if (val)
20323                 STRIP_NOPS (val);
20324
20325               if (field == NULL_TREE || DECL_BIT_FIELD (field))
20326                 return false;
20327
20328               if (TREE_CODE (TREE_TYPE (field)) == ARRAY_TYPE
20329                   && TYPE_DOMAIN (TREE_TYPE (field))
20330                   && ! TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (field))))
20331                 return false;
20332               else if (DECL_SIZE_UNIT (field) == NULL_TREE
20333                        || !tree_fits_shwi_p (DECL_SIZE_UNIT (field)))
20334                 return false;
20335               fieldsize = tree_to_shwi (DECL_SIZE_UNIT (field));
20336               pos = int_byte_position (field);
20337               gcc_assert (pos + fieldsize <= size);
20338               if (val && fieldsize != 0
20339                   && !native_encode_initializer (val, array + pos, fieldsize))
20340                 return false;
20341             }
20342           return true;
20343         }
20344       return false;
20345     case VIEW_CONVERT_EXPR:
20346     case NON_LVALUE_EXPR:
20347       return native_encode_initializer (TREE_OPERAND (init, 0), array, size);
20348     default:
20349       return native_encode_expr (init, array, size) == size;
20350     }
20351 }
20352
20353 /* Attach a DW_AT_const_value attribute to DIE. The value of the
20354    attribute is the const value T.  */
20355
20356 static bool
20357 tree_add_const_value_attribute (dw_die_ref die, tree t)
20358 {
20359   tree init;
20360   tree type = TREE_TYPE (t);
20361   rtx rtl;
20362
20363   if (!t || !TREE_TYPE (t) || TREE_TYPE (t) == error_mark_node)
20364     return false;
20365
20366   init = t;
20367   gcc_assert (!DECL_P (init));
20368
20369   if (TREE_CODE (init) == INTEGER_CST)
20370     {
20371       if (tree_fits_uhwi_p (init))
20372         {
20373           add_AT_unsigned (die, DW_AT_const_value, tree_to_uhwi (init));
20374           return true;
20375         }
20376       if (tree_fits_shwi_p (init))
20377         {
20378           add_AT_int (die, DW_AT_const_value, tree_to_shwi (init));
20379           return true;
20380         }
20381     }
20382   if (! early_dwarf)
20383     {
20384       rtl = rtl_for_decl_init (init, type);
20385       if (rtl)
20386         return add_const_value_attribute (die, rtl);
20387     }
20388   /* If the host and target are sane, try harder.  */
20389   if (CHAR_BIT == 8 && BITS_PER_UNIT == 8
20390       && initializer_constant_valid_p (init, type))
20391     {
20392       HOST_WIDE_INT size = int_size_in_bytes (TREE_TYPE (init));
20393       if (size > 0 && (int) size == size)
20394         {
20395           unsigned char *array = ggc_cleared_vec_alloc<unsigned char> (size);
20396
20397           if (native_encode_initializer (init, array, size))
20398             {
20399               add_AT_vec (die, DW_AT_const_value, size, 1, array);
20400               return true;
20401             }
20402           ggc_free (array);
20403         }
20404     }
20405   return false;
20406 }
20407
20408 /* Attach a DW_AT_const_value attribute to VAR_DIE. The value of the
20409    attribute is the const value of T, where T is an integral constant
20410    variable with static storage duration
20411    (so it can't be a PARM_DECL or a RESULT_DECL).  */
20412
20413 static bool
20414 tree_add_const_value_attribute_for_decl (dw_die_ref var_die, tree decl)
20415 {
20416
20417   if (!decl
20418       || (!VAR_P (decl) && TREE_CODE (decl) != CONST_DECL)
20419       || (VAR_P (decl) && !TREE_STATIC (decl)))
20420     return false;
20421
20422   if (TREE_READONLY (decl)
20423       && ! TREE_THIS_VOLATILE (decl)
20424       && DECL_INITIAL (decl))
20425     /* OK */;
20426   else
20427     return false;
20428
20429   /* Don't add DW_AT_const_value if abstract origin already has one.  */
20430   if (get_AT (var_die, DW_AT_const_value))
20431     return false;
20432
20433   return tree_add_const_value_attribute (var_die, DECL_INITIAL (decl));
20434 }
20435
20436 /* Convert the CFI instructions for the current function into a
20437    location list.  This is used for DW_AT_frame_base when we targeting
20438    a dwarf2 consumer that does not support the dwarf3
20439    DW_OP_call_frame_cfa.  OFFSET is a constant to be added to all CFA
20440    expressions.  */
20441
20442 static dw_loc_list_ref
20443 convert_cfa_to_fb_loc_list (HOST_WIDE_INT offset)
20444 {
20445   int ix;
20446   dw_fde_ref fde;
20447   dw_loc_list_ref list, *list_tail;
20448   dw_cfi_ref cfi;
20449   dw_cfa_location last_cfa, next_cfa;
20450   const char *start_label, *last_label, *section;
20451   dw_cfa_location remember;
20452
20453   fde = cfun->fde;
20454   gcc_assert (fde != NULL);
20455
20456   section = secname_for_decl (current_function_decl);
20457   list_tail = &list;
20458   list = NULL;
20459
20460   memset (&next_cfa, 0, sizeof (next_cfa));
20461   next_cfa.reg = INVALID_REGNUM;
20462   remember = next_cfa;
20463
20464   start_label = fde->dw_fde_begin;
20465
20466   /* ??? Bald assumption that the CIE opcode list does not contain
20467      advance opcodes.  */
20468   FOR_EACH_VEC_ELT (*cie_cfi_vec, ix, cfi)
20469     lookup_cfa_1 (cfi, &next_cfa, &remember);
20470
20471   last_cfa = next_cfa;
20472   last_label = start_label;
20473
20474   if (fde->dw_fde_second_begin && fde->dw_fde_switch_cfi_index == 0)
20475     {
20476       /* If the first partition contained no CFI adjustments, the
20477          CIE opcodes apply to the whole first partition.  */
20478       *list_tail = new_loc_list (build_cfa_loc (&last_cfa, offset),
20479                                  fde->dw_fde_begin, 0, fde->dw_fde_end, 0, section);
20480       list_tail =&(*list_tail)->dw_loc_next;
20481       start_label = last_label = fde->dw_fde_second_begin;
20482     }
20483
20484   FOR_EACH_VEC_SAFE_ELT (fde->dw_fde_cfi, ix, cfi)
20485     {
20486       switch (cfi->dw_cfi_opc)
20487         {
20488         case DW_CFA_set_loc:
20489         case DW_CFA_advance_loc1:
20490         case DW_CFA_advance_loc2:
20491         case DW_CFA_advance_loc4:
20492           if (!cfa_equal_p (&last_cfa, &next_cfa))
20493             {
20494               *list_tail = new_loc_list (build_cfa_loc (&last_cfa, offset),
20495                                          start_label, 0, last_label, 0, section);
20496
20497               list_tail = &(*list_tail)->dw_loc_next;
20498               last_cfa = next_cfa;
20499               start_label = last_label;
20500             }
20501           last_label = cfi->dw_cfi_oprnd1.dw_cfi_addr;
20502           break;
20503
20504         case DW_CFA_advance_loc:
20505           /* The encoding is complex enough that we should never emit this.  */
20506           gcc_unreachable ();
20507
20508         default:
20509           lookup_cfa_1 (cfi, &next_cfa, &remember);
20510           break;
20511         }
20512       if (ix + 1 == fde->dw_fde_switch_cfi_index)
20513         {
20514           if (!cfa_equal_p (&last_cfa, &next_cfa))
20515             {
20516               *list_tail = new_loc_list (build_cfa_loc (&last_cfa, offset),
20517                                          start_label, 0, last_label, 0, section);
20518
20519               list_tail = &(*list_tail)->dw_loc_next;
20520               last_cfa = next_cfa;
20521               start_label = last_label;
20522             }
20523           *list_tail = new_loc_list (build_cfa_loc (&last_cfa, offset),
20524                                      start_label, 0, fde->dw_fde_end, 0, section);
20525           list_tail = &(*list_tail)->dw_loc_next;
20526           start_label = last_label = fde->dw_fde_second_begin;
20527         }
20528     }
20529
20530   if (!cfa_equal_p (&last_cfa, &next_cfa))
20531     {
20532       *list_tail = new_loc_list (build_cfa_loc (&last_cfa, offset),
20533                                  start_label, 0, last_label, 0, section);
20534       list_tail = &(*list_tail)->dw_loc_next;
20535       start_label = last_label;
20536     }
20537
20538   *list_tail = new_loc_list (build_cfa_loc (&next_cfa, offset),
20539                              start_label, 0,
20540                              fde->dw_fde_second_begin
20541                              ? fde->dw_fde_second_end : fde->dw_fde_end, 0,
20542                              section);
20543
20544   maybe_gen_llsym (list);
20545
20546   return list;
20547 }
20548
20549 /* Compute a displacement from the "steady-state frame pointer" to the
20550    frame base (often the same as the CFA), and store it in
20551    frame_pointer_fb_offset.  OFFSET is added to the displacement
20552    before the latter is negated.  */
20553
20554 static void
20555 compute_frame_pointer_to_fb_displacement (poly_int64 offset)
20556 {
20557   rtx reg, elim;
20558
20559 #ifdef FRAME_POINTER_CFA_OFFSET
20560   reg = frame_pointer_rtx;
20561   offset += FRAME_POINTER_CFA_OFFSET (current_function_decl);
20562 #else
20563   reg = arg_pointer_rtx;
20564   offset += ARG_POINTER_CFA_OFFSET (current_function_decl);
20565 #endif
20566
20567   elim = (ira_use_lra_p
20568           ? lra_eliminate_regs (reg, VOIDmode, NULL_RTX)
20569           : eliminate_regs (reg, VOIDmode, NULL_RTX));
20570   elim = strip_offset_and_add (elim, &offset);
20571
20572   frame_pointer_fb_offset = -offset;
20573
20574   /* ??? AVR doesn't set up valid eliminations when there is no stack frame
20575      in which to eliminate.  This is because it's stack pointer isn't 
20576      directly accessible as a register within the ISA.  To work around
20577      this, assume that while we cannot provide a proper value for
20578      frame_pointer_fb_offset, we won't need one either.  */
20579   frame_pointer_fb_offset_valid
20580     = ((SUPPORTS_STACK_ALIGNMENT
20581         && (elim == hard_frame_pointer_rtx
20582             || elim == stack_pointer_rtx))
20583        || elim == (frame_pointer_needed
20584                    ? hard_frame_pointer_rtx
20585                    : stack_pointer_rtx));
20586 }
20587
20588 /* Generate a DW_AT_name attribute given some string value to be included as
20589    the value of the attribute.  */
20590
20591 static void
20592 add_name_attribute (dw_die_ref die, const char *name_string)
20593 {
20594   if (name_string != NULL && *name_string != 0)
20595     {
20596       if (demangle_name_func)
20597         name_string = (*demangle_name_func) (name_string);
20598
20599       add_AT_string (die, DW_AT_name, name_string);
20600     }
20601 }
20602
20603 /* Retrieve the descriptive type of TYPE, if any, make sure it has a
20604    DIE and attach a DW_AT_GNAT_descriptive_type attribute to the DIE
20605    of TYPE accordingly.
20606
20607    ??? This is a temporary measure until after we're able to generate
20608    regular DWARF for the complex Ada type system.  */
20609
20610 static void 
20611 add_gnat_descriptive_type_attribute (dw_die_ref die, tree type,
20612                                      dw_die_ref context_die)
20613 {
20614   tree dtype;
20615   dw_die_ref dtype_die;
20616
20617   if (!lang_hooks.types.descriptive_type)
20618     return;
20619
20620   dtype = lang_hooks.types.descriptive_type (type);
20621   if (!dtype)
20622     return;
20623
20624   dtype_die = lookup_type_die (dtype);
20625   if (!dtype_die)
20626     {
20627       gen_type_die (dtype, context_die);
20628       dtype_die = lookup_type_die (dtype);
20629       gcc_assert (dtype_die);
20630     }
20631
20632   add_AT_die_ref (die, DW_AT_GNAT_descriptive_type, dtype_die);
20633 }
20634
20635 /* Retrieve the comp_dir string suitable for use with DW_AT_comp_dir.  */
20636
20637 static const char *
20638 comp_dir_string (void)
20639 {
20640   const char *wd;
20641   char *wd1;
20642   static const char *cached_wd = NULL;
20643
20644   if (cached_wd != NULL)
20645     return cached_wd;
20646
20647   wd = get_src_pwd ();
20648   if (wd == NULL)
20649     return NULL;
20650
20651   if (DWARF2_DIR_SHOULD_END_WITH_SEPARATOR)
20652     {
20653       int wdlen;
20654
20655       wdlen = strlen (wd);
20656       wd1 = ggc_vec_alloc<char> (wdlen + 2);
20657       strcpy (wd1, wd);
20658       wd1 [wdlen] = DIR_SEPARATOR;
20659       wd1 [wdlen + 1] = 0;
20660       wd = wd1;
20661     }
20662
20663   cached_wd = remap_debug_filename (wd);
20664   return cached_wd;
20665 }
20666
20667 /* Generate a DW_AT_comp_dir attribute for DIE.  */
20668
20669 static void
20670 add_comp_dir_attribute (dw_die_ref die)
20671 {
20672   const char * wd = comp_dir_string ();
20673   if (wd != NULL)
20674     add_AT_string (die, DW_AT_comp_dir, wd);
20675 }
20676
20677 /* Given a tree node VALUE describing a scalar attribute ATTR (i.e. a bound, a
20678    pointer computation, ...), output a representation for that bound according
20679    to the accepted FORMS (see enum dw_scalar_form) and add it to DIE.  See
20680    loc_list_from_tree for the meaning of CONTEXT.  */
20681
20682 static void
20683 add_scalar_info (dw_die_ref die, enum dwarf_attribute attr, tree value,
20684                  int forms, struct loc_descr_context *context)
20685 {
20686   dw_die_ref context_die, decl_die;
20687   dw_loc_list_ref list;
20688   bool strip_conversions = true;
20689   bool placeholder_seen = false;
20690
20691   while (strip_conversions)
20692     switch (TREE_CODE (value))
20693       {
20694       case ERROR_MARK:
20695       case SAVE_EXPR:
20696         return;
20697
20698       CASE_CONVERT:
20699       case VIEW_CONVERT_EXPR:
20700         value = TREE_OPERAND (value, 0);
20701         break;
20702
20703       default:
20704         strip_conversions = false;
20705         break;
20706       }
20707
20708   /* If possible and permitted, output the attribute as a constant.  */
20709   if ((forms & dw_scalar_form_constant) != 0
20710       && TREE_CODE (value) == INTEGER_CST)
20711     {
20712       unsigned int prec = simple_type_size_in_bits (TREE_TYPE (value));
20713
20714       /* If HOST_WIDE_INT is big enough then represent the bound as
20715          a constant value.  We need to choose a form based on
20716          whether the type is signed or unsigned.  We cannot just
20717          call add_AT_unsigned if the value itself is positive
20718          (add_AT_unsigned might add the unsigned value encoded as
20719          DW_FORM_data[1248]).  Some DWARF consumers will lookup the
20720          bounds type and then sign extend any unsigned values found
20721          for signed types.  This is needed only for
20722          DW_AT_{lower,upper}_bound, since for most other attributes,
20723          consumers will treat DW_FORM_data[1248] as unsigned values,
20724          regardless of the underlying type.  */
20725       if (prec <= HOST_BITS_PER_WIDE_INT
20726           || tree_fits_uhwi_p (value))
20727         {
20728           if (TYPE_UNSIGNED (TREE_TYPE (value)))
20729             add_AT_unsigned (die, attr, TREE_INT_CST_LOW (value));
20730           else
20731             add_AT_int (die, attr, TREE_INT_CST_LOW (value));
20732         }
20733       else
20734         /* Otherwise represent the bound as an unsigned value with
20735            the precision of its type.  The precision and signedness
20736            of the type will be necessary to re-interpret it
20737            unambiguously.  */
20738         add_AT_wide (die, attr, wi::to_wide (value));
20739       return;
20740     }
20741
20742   /* Otherwise, if it's possible and permitted too, output a reference to
20743      another DIE.  */
20744   if ((forms & dw_scalar_form_reference) != 0)
20745     {
20746       tree decl = NULL_TREE;
20747
20748       /* Some type attributes reference an outer type.  For instance, the upper
20749          bound of an array may reference an embedding record (this happens in
20750          Ada).  */
20751       if (TREE_CODE (value) == COMPONENT_REF
20752           && TREE_CODE (TREE_OPERAND (value, 0)) == PLACEHOLDER_EXPR
20753           && TREE_CODE (TREE_OPERAND (value, 1)) == FIELD_DECL)
20754         decl = TREE_OPERAND (value, 1);
20755
20756       else if (VAR_P (value)
20757                || TREE_CODE (value) == PARM_DECL
20758                || TREE_CODE (value) == RESULT_DECL)
20759         decl = value;
20760
20761       if (decl != NULL_TREE)
20762         {
20763           dw_die_ref decl_die = lookup_decl_die (decl);
20764
20765           /* ??? Can this happen, or should the variable have been bound
20766              first?  Probably it can, since I imagine that we try to create
20767              the types of parameters in the order in which they exist in
20768              the list, and won't have created a forward reference to a
20769              later parameter.  */
20770           if (decl_die != NULL)
20771             {
20772               add_AT_die_ref (die, attr, decl_die);
20773               return;
20774             }
20775         }
20776     }
20777
20778   /* Last chance: try to create a stack operation procedure to evaluate the
20779      value.  Do nothing if even that is not possible or permitted.  */
20780   if ((forms & dw_scalar_form_exprloc) == 0)
20781     return;
20782
20783   list = loc_list_from_tree (value, 2, context);
20784   if (context && context->placeholder_arg)
20785     {
20786       placeholder_seen = context->placeholder_seen;
20787       context->placeholder_seen = false;
20788     }
20789   if (list == NULL || single_element_loc_list_p (list))
20790     {
20791       /* If this attribute is not a reference nor constant, it is
20792          a DWARF expression rather than location description.  For that
20793          loc_list_from_tree (value, 0, &context) is needed.  */
20794       dw_loc_list_ref list2 = loc_list_from_tree (value, 0, context);
20795       if (list2 && single_element_loc_list_p (list2))
20796         {
20797           if (placeholder_seen)
20798             {
20799               struct dwarf_procedure_info dpi;
20800               dpi.fndecl = NULL_TREE;
20801               dpi.args_count = 1;
20802               if (!resolve_args_picking (list2->expr, 1, &dpi))
20803                 return;
20804             }
20805           add_AT_loc (die, attr, list2->expr);
20806           return;
20807         }
20808     }
20809
20810   /* If that failed to give a single element location list, fall back to
20811      outputting this as a reference... still if permitted.  */
20812   if (list == NULL
20813       || (forms & dw_scalar_form_reference) == 0
20814       || placeholder_seen)
20815     return;
20816
20817   if (current_function_decl == 0)
20818     context_die = comp_unit_die ();
20819   else
20820     context_die = lookup_decl_die (current_function_decl);
20821
20822   decl_die = new_die (DW_TAG_variable, context_die, value);
20823   add_AT_flag (decl_die, DW_AT_artificial, 1);
20824   add_type_attribute (decl_die, TREE_TYPE (value), TYPE_QUAL_CONST, false,
20825                       context_die);
20826   add_AT_location_description (decl_die, DW_AT_location, list);
20827   add_AT_die_ref (die, attr, decl_die);
20828 }
20829
20830 /* Return the default for DW_AT_lower_bound, or -1 if there is not any
20831    default.  */
20832
20833 static int
20834 lower_bound_default (void)
20835 {
20836   switch (get_AT_unsigned (comp_unit_die (), DW_AT_language))
20837     {
20838     case DW_LANG_C:
20839     case DW_LANG_C89:
20840     case DW_LANG_C99:
20841     case DW_LANG_C11:
20842     case DW_LANG_C_plus_plus:
20843     case DW_LANG_C_plus_plus_11:
20844     case DW_LANG_C_plus_plus_14:
20845     case DW_LANG_ObjC:
20846     case DW_LANG_ObjC_plus_plus:
20847       return 0;
20848     case DW_LANG_Fortran77:
20849     case DW_LANG_Fortran90:
20850     case DW_LANG_Fortran95:
20851     case DW_LANG_Fortran03:
20852     case DW_LANG_Fortran08:
20853       return 1;
20854     case DW_LANG_UPC:
20855     case DW_LANG_D:
20856     case DW_LANG_Python:
20857       return dwarf_version >= 4 ? 0 : -1;
20858     case DW_LANG_Ada95:
20859     case DW_LANG_Ada83:
20860     case DW_LANG_Cobol74:
20861     case DW_LANG_Cobol85:
20862     case DW_LANG_Modula2:
20863     case DW_LANG_PLI:
20864       return dwarf_version >= 4 ? 1 : -1;
20865     default:
20866       return -1;
20867     }
20868 }
20869
20870 /* Given a tree node describing an array bound (either lower or upper) output
20871    a representation for that bound.  */
20872
20873 static void
20874 add_bound_info (dw_die_ref subrange_die, enum dwarf_attribute bound_attr,
20875                 tree bound, struct loc_descr_context *context)
20876 {
20877   int dflt;
20878
20879   while (1)
20880     switch (TREE_CODE (bound))
20881       {
20882       /* Strip all conversions.  */
20883       CASE_CONVERT:
20884       case VIEW_CONVERT_EXPR:
20885         bound = TREE_OPERAND (bound, 0);
20886         break;
20887
20888       /* All fixed-bounds are represented by INTEGER_CST nodes.  Lower bounds
20889          are even omitted when they are the default.  */
20890       case INTEGER_CST:
20891         /* If the value for this bound is the default one, we can even omit the
20892            attribute.  */
20893         if (bound_attr == DW_AT_lower_bound
20894             && tree_fits_shwi_p (bound)
20895             && (dflt = lower_bound_default ()) != -1
20896             && tree_to_shwi (bound) == dflt)
20897           return;
20898
20899         /* FALLTHRU */
20900
20901       default:
20902         /* Because of the complex interaction there can be with other GNAT
20903            encodings, GDB isn't ready yet to handle proper DWARF description
20904            for self-referencial subrange bounds: let GNAT encodings do the
20905            magic in such a case.  */
20906         if (is_ada ()
20907             && gnat_encodings != DWARF_GNAT_ENCODINGS_MINIMAL
20908             && contains_placeholder_p (bound))
20909           return;
20910
20911         add_scalar_info (subrange_die, bound_attr, bound,
20912                          dw_scalar_form_constant
20913                          | dw_scalar_form_exprloc
20914                          | dw_scalar_form_reference,
20915                          context);
20916         return;
20917       }
20918 }
20919
20920 /* Add subscript info to TYPE_DIE, describing an array TYPE, collapsing
20921    possibly nested array subscripts in a flat sequence if COLLAPSE_P is true.
20922    Note that the block of subscript information for an array type also
20923    includes information about the element type of the given array type.
20924
20925    This function reuses previously set type and bound information if
20926    available.  */
20927
20928 static void
20929 add_subscript_info (dw_die_ref type_die, tree type, bool collapse_p)
20930 {
20931   unsigned dimension_number;
20932   tree lower, upper;
20933   dw_die_ref child = type_die->die_child;
20934
20935   for (dimension_number = 0;
20936        TREE_CODE (type) == ARRAY_TYPE && (dimension_number == 0 || collapse_p);
20937        type = TREE_TYPE (type), dimension_number++)
20938     {
20939       tree domain = TYPE_DOMAIN (type);
20940
20941       if (TYPE_STRING_FLAG (type) && is_fortran () && dimension_number > 0)
20942         break;
20943
20944       /* Arrays come in three flavors: Unspecified bounds, fixed bounds,
20945          and (in GNU C only) variable bounds.  Handle all three forms
20946          here.  */
20947
20948       /* Find and reuse a previously generated DW_TAG_subrange_type if
20949          available.
20950
20951          For multi-dimensional arrays, as we iterate through the
20952          various dimensions in the enclosing for loop above, we also
20953          iterate through the DIE children and pick at each
20954          DW_TAG_subrange_type previously generated (if available).
20955          Each child DW_TAG_subrange_type DIE describes the range of
20956          the current dimension.  At this point we should have as many
20957          DW_TAG_subrange_type's as we have dimensions in the
20958          array.  */
20959       dw_die_ref subrange_die = NULL;
20960       if (child)
20961         while (1)
20962           {
20963             child = child->die_sib;
20964             if (child->die_tag == DW_TAG_subrange_type)
20965               subrange_die = child;
20966             if (child == type_die->die_child)
20967               {
20968                 /* If we wrapped around, stop looking next time.  */
20969                 child = NULL;
20970                 break;
20971               }
20972             if (child->die_tag == DW_TAG_subrange_type)
20973               break;
20974           }
20975       if (!subrange_die)
20976         subrange_die = new_die (DW_TAG_subrange_type, type_die, NULL);
20977
20978       if (domain)
20979         {
20980           /* We have an array type with specified bounds.  */
20981           lower = TYPE_MIN_VALUE (domain);
20982           upper = TYPE_MAX_VALUE (domain);
20983
20984           /* Define the index type.  */
20985           if (TREE_TYPE (domain)
20986               && !get_AT (subrange_die, DW_AT_type))
20987             {
20988               /* ??? This is probably an Ada unnamed subrange type.  Ignore the
20989                  TREE_TYPE field.  We can't emit debug info for this
20990                  because it is an unnamed integral type.  */
20991               if (TREE_CODE (domain) == INTEGER_TYPE
20992                   && TYPE_NAME (domain) == NULL_TREE
20993                   && TREE_CODE (TREE_TYPE (domain)) == INTEGER_TYPE
20994                   && TYPE_NAME (TREE_TYPE (domain)) == NULL_TREE)
20995                 ;
20996               else
20997                 add_type_attribute (subrange_die, TREE_TYPE (domain),
20998                                     TYPE_UNQUALIFIED, false, type_die);
20999             }
21000
21001           /* ??? If upper is NULL, the array has unspecified length,
21002              but it does have a lower bound.  This happens with Fortran
21003                dimension arr(N:*)
21004              Since the debugger is definitely going to need to know N
21005              to produce useful results, go ahead and output the lower
21006              bound solo, and hope the debugger can cope.  */
21007
21008           if (!get_AT (subrange_die, DW_AT_lower_bound))
21009             add_bound_info (subrange_die, DW_AT_lower_bound, lower, NULL);
21010           if (upper && !get_AT (subrange_die, DW_AT_upper_bound))
21011             add_bound_info (subrange_die, DW_AT_upper_bound, upper, NULL);
21012         }
21013
21014       /* Otherwise we have an array type with an unspecified length.  The
21015          DWARF-2 spec does not say how to handle this; let's just leave out the
21016          bounds.  */
21017     }
21018 }
21019
21020 /* Add a DW_AT_byte_size attribute to DIE with TREE_NODE's size.  */
21021
21022 static void
21023 add_byte_size_attribute (dw_die_ref die, tree tree_node)
21024 {
21025   dw_die_ref decl_die;
21026   HOST_WIDE_INT size;
21027   dw_loc_descr_ref size_expr = NULL;
21028
21029   switch (TREE_CODE (tree_node))
21030     {
21031     case ERROR_MARK:
21032       size = 0;
21033       break;
21034     case ENUMERAL_TYPE:
21035     case RECORD_TYPE:
21036     case UNION_TYPE:
21037     case QUAL_UNION_TYPE:
21038       if (TREE_CODE (TYPE_SIZE_UNIT (tree_node)) == VAR_DECL
21039           && (decl_die = lookup_decl_die (TYPE_SIZE_UNIT (tree_node))))
21040         {
21041           add_AT_die_ref (die, DW_AT_byte_size, decl_die);
21042           return;
21043         }
21044       size_expr = type_byte_size (tree_node, &size);
21045       break;
21046     case FIELD_DECL:
21047       /* For a data member of a struct or union, the DW_AT_byte_size is
21048          generally given as the number of bytes normally allocated for an
21049          object of the *declared* type of the member itself.  This is true
21050          even for bit-fields.  */
21051       size = int_size_in_bytes (field_type (tree_node));
21052       break;
21053     default:
21054       gcc_unreachable ();
21055     }
21056
21057   /* Support for dynamically-sized objects was introduced by DWARFv3.
21058      At the moment, GDB does not handle variable byte sizes very well,
21059      though.  */
21060   if ((dwarf_version >= 3 || !dwarf_strict)
21061       && gnat_encodings == DWARF_GNAT_ENCODINGS_MINIMAL
21062       && size_expr != NULL)
21063     add_AT_loc (die, DW_AT_byte_size, size_expr);
21064
21065   /* Note that `size' might be -1 when we get to this point.  If it is, that
21066      indicates that the byte size of the entity in question is variable and
21067      that we could not generate a DWARF expression that computes it.  */
21068   if (size >= 0)
21069     add_AT_unsigned (die, DW_AT_byte_size, size);
21070 }
21071
21072 /* Add a DW_AT_alignment attribute to DIE with TREE_NODE's non-default
21073    alignment.  */
21074
21075 static void
21076 add_alignment_attribute (dw_die_ref die, tree tree_node)
21077 {
21078   if (dwarf_version < 5 && dwarf_strict)
21079     return;
21080
21081   unsigned align;
21082
21083   if (DECL_P (tree_node))
21084     {
21085       if (!DECL_USER_ALIGN (tree_node))
21086         return;
21087
21088       align = DECL_ALIGN_UNIT (tree_node);
21089     }
21090   else if (TYPE_P (tree_node))
21091     {
21092       if (!TYPE_USER_ALIGN (tree_node))
21093         return;
21094
21095       align = TYPE_ALIGN_UNIT (tree_node);
21096     }
21097   else
21098     gcc_unreachable ();
21099
21100   add_AT_unsigned (die, DW_AT_alignment, align);
21101 }
21102
21103 /* For a FIELD_DECL node which represents a bit-field, output an attribute
21104    which specifies the distance in bits from the highest order bit of the
21105    "containing object" for the bit-field to the highest order bit of the
21106    bit-field itself.
21107
21108    For any given bit-field, the "containing object" is a hypothetical object
21109    (of some integral or enum type) within which the given bit-field lives.  The
21110    type of this hypothetical "containing object" is always the same as the
21111    declared type of the individual bit-field itself.  The determination of the
21112    exact location of the "containing object" for a bit-field is rather
21113    complicated.  It's handled by the `field_byte_offset' function (above).
21114
21115    CTX is required: see the comment for VLR_CONTEXT.
21116
21117    Note that it is the size (in bytes) of the hypothetical "containing object"
21118    which will be given in the DW_AT_byte_size attribute for this bit-field.
21119    (See `byte_size_attribute' above).  */
21120
21121 static inline void
21122 add_bit_offset_attribute (dw_die_ref die, tree decl, struct vlr_context *ctx)
21123 {
21124   HOST_WIDE_INT object_offset_in_bytes;
21125   tree original_type = DECL_BIT_FIELD_TYPE (decl);
21126   HOST_WIDE_INT bitpos_int;
21127   HOST_WIDE_INT highest_order_object_bit_offset;
21128   HOST_WIDE_INT highest_order_field_bit_offset;
21129   HOST_WIDE_INT bit_offset;
21130
21131   field_byte_offset (decl, ctx, &object_offset_in_bytes);
21132
21133   /* Must be a field and a bit field.  */
21134   gcc_assert (original_type && TREE_CODE (decl) == FIELD_DECL);
21135
21136   /* We can't yet handle bit-fields whose offsets are variable, so if we
21137      encounter such things, just return without generating any attribute
21138      whatsoever.  Likewise for variable or too large size.  */
21139   if (! tree_fits_shwi_p (bit_position (decl))
21140       || ! tree_fits_uhwi_p (DECL_SIZE (decl)))
21141     return;
21142
21143   bitpos_int = int_bit_position (decl);
21144
21145   /* Note that the bit offset is always the distance (in bits) from the
21146      highest-order bit of the "containing object" to the highest-order bit of
21147      the bit-field itself.  Since the "high-order end" of any object or field
21148      is different on big-endian and little-endian machines, the computation
21149      below must take account of these differences.  */
21150   highest_order_object_bit_offset = object_offset_in_bytes * BITS_PER_UNIT;
21151   highest_order_field_bit_offset = bitpos_int;
21152
21153   if (! BYTES_BIG_ENDIAN)
21154     {
21155       highest_order_field_bit_offset += tree_to_shwi (DECL_SIZE (decl));
21156       highest_order_object_bit_offset +=
21157         simple_type_size_in_bits (original_type);
21158     }
21159
21160   bit_offset
21161     = (! BYTES_BIG_ENDIAN
21162        ? highest_order_object_bit_offset - highest_order_field_bit_offset
21163        : highest_order_field_bit_offset - highest_order_object_bit_offset);
21164
21165   if (bit_offset < 0)
21166     add_AT_int (die, DW_AT_bit_offset, bit_offset);
21167   else
21168     add_AT_unsigned (die, DW_AT_bit_offset, (unsigned HOST_WIDE_INT) bit_offset);
21169 }
21170
21171 /* For a FIELD_DECL node which represents a bit field, output an attribute
21172    which specifies the length in bits of the given field.  */
21173
21174 static inline void
21175 add_bit_size_attribute (dw_die_ref die, tree decl)
21176 {
21177   /* Must be a field and a bit field.  */
21178   gcc_assert (TREE_CODE (decl) == FIELD_DECL
21179               && DECL_BIT_FIELD_TYPE (decl));
21180
21181   if (tree_fits_uhwi_p (DECL_SIZE (decl)))
21182     add_AT_unsigned (die, DW_AT_bit_size, tree_to_uhwi (DECL_SIZE (decl)));
21183 }
21184
21185 /* If the compiled language is ANSI C, then add a 'prototyped'
21186    attribute, if arg types are given for the parameters of a function.  */
21187
21188 static inline void
21189 add_prototyped_attribute (dw_die_ref die, tree func_type)
21190 {
21191   switch (get_AT_unsigned (comp_unit_die (), DW_AT_language))
21192     {
21193     case DW_LANG_C:
21194     case DW_LANG_C89:
21195     case DW_LANG_C99:
21196     case DW_LANG_C11:
21197     case DW_LANG_ObjC:
21198       if (prototype_p (func_type))
21199         add_AT_flag (die, DW_AT_prototyped, 1);
21200       break;
21201     default:
21202       break;
21203     }
21204 }
21205
21206 /* Add an 'abstract_origin' attribute below a given DIE.  The DIE is found
21207    by looking in the type declaration, the object declaration equate table or
21208    the block mapping.  */
21209
21210 static inline dw_die_ref
21211 add_abstract_origin_attribute (dw_die_ref die, tree origin)
21212 {
21213   dw_die_ref origin_die = NULL;
21214
21215   if (DECL_P (origin))
21216     {
21217       dw_die_ref c;
21218       origin_die = lookup_decl_die (origin);
21219       /* "Unwrap" the decls DIE which we put in the imported unit context.
21220          We are looking for the abstract copy here.  */
21221       if (in_lto_p
21222           && origin_die
21223           && (c = get_AT_ref (origin_die, DW_AT_abstract_origin))
21224           /* ???  Identify this better.  */
21225           && c->with_offset)
21226         origin_die = c;
21227     }
21228   else if (TYPE_P (origin))
21229     origin_die = lookup_type_die (origin);
21230   else if (TREE_CODE (origin) == BLOCK)
21231     origin_die = BLOCK_DIE (origin);
21232
21233   /* XXX: Functions that are never lowered don't always have correct block
21234      trees (in the case of java, they simply have no block tree, in some other
21235      languages).  For these functions, there is nothing we can really do to
21236      output correct debug info for inlined functions in all cases.  Rather
21237      than die, we'll just produce deficient debug info now, in that we will
21238      have variables without a proper abstract origin.  In the future, when all
21239      functions are lowered, we should re-add a gcc_assert (origin_die)
21240      here.  */
21241
21242   if (origin_die)
21243     add_AT_die_ref (die, DW_AT_abstract_origin, origin_die);
21244   return origin_die;
21245 }
21246
21247 /* We do not currently support the pure_virtual attribute.  */
21248
21249 static inline void
21250 add_pure_or_virtual_attribute (dw_die_ref die, tree func_decl)
21251 {
21252   if (DECL_VINDEX (func_decl))
21253     {
21254       add_AT_unsigned (die, DW_AT_virtuality, DW_VIRTUALITY_virtual);
21255
21256       if (tree_fits_shwi_p (DECL_VINDEX (func_decl)))
21257         add_AT_loc (die, DW_AT_vtable_elem_location,
21258                     new_loc_descr (DW_OP_constu,
21259                                    tree_to_shwi (DECL_VINDEX (func_decl)),
21260                                    0));
21261
21262       /* GNU extension: Record what type this method came from originally.  */
21263       if (debug_info_level > DINFO_LEVEL_TERSE
21264           && DECL_CONTEXT (func_decl))
21265         add_AT_die_ref (die, DW_AT_containing_type,
21266                         lookup_type_die (DECL_CONTEXT (func_decl)));
21267     }
21268 }
21269 \f
21270 /* Add a DW_AT_linkage_name or DW_AT_MIPS_linkage_name attribute for the
21271    given decl.  This used to be a vendor extension until after DWARF 4
21272    standardized it.  */
21273
21274 static void
21275 add_linkage_attr (dw_die_ref die, tree decl)
21276 {
21277   const char *name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
21278
21279   /* Mimic what assemble_name_raw does with a leading '*'.  */
21280   if (name[0] == '*')
21281     name = &name[1];
21282
21283   if (dwarf_version >= 4)
21284     add_AT_string (die, DW_AT_linkage_name, name);
21285   else
21286     add_AT_string (die, DW_AT_MIPS_linkage_name, name);
21287 }
21288
21289 /* Add source coordinate attributes for the given decl.  */
21290
21291 static void
21292 add_src_coords_attributes (dw_die_ref die, tree decl)
21293 {
21294   expanded_location s;
21295
21296   if (LOCATION_LOCUS (DECL_SOURCE_LOCATION (decl)) == UNKNOWN_LOCATION)
21297     return;
21298   s = expand_location (DECL_SOURCE_LOCATION (decl));
21299   add_AT_file (die, DW_AT_decl_file, lookup_filename (s.file));
21300   add_AT_unsigned (die, DW_AT_decl_line, s.line);
21301   if (debug_column_info && s.column)
21302     add_AT_unsigned (die, DW_AT_decl_column, s.column);
21303 }
21304
21305 /* Add DW_AT_{,MIPS_}linkage_name attribute for the given decl.  */
21306
21307 static void
21308 add_linkage_name_raw (dw_die_ref die, tree decl)
21309 {
21310   /* Defer until we have an assembler name set.  */
21311   if (!DECL_ASSEMBLER_NAME_SET_P (decl))
21312     {
21313       limbo_die_node *asm_name;
21314
21315       asm_name = ggc_cleared_alloc<limbo_die_node> ();
21316       asm_name->die = die;
21317       asm_name->created_for = decl;
21318       asm_name->next = deferred_asm_name;
21319       deferred_asm_name = asm_name;
21320     }
21321   else if (DECL_ASSEMBLER_NAME (decl) != DECL_NAME (decl))
21322     add_linkage_attr (die, decl);
21323 }
21324
21325 /* Add DW_AT_{,MIPS_}linkage_name attribute for the given decl if desired.  */
21326
21327 static void
21328 add_linkage_name (dw_die_ref die, tree decl)
21329 {
21330   if (debug_info_level > DINFO_LEVEL_NONE
21331       && VAR_OR_FUNCTION_DECL_P (decl)
21332       && TREE_PUBLIC (decl)
21333       && !(VAR_P (decl) && DECL_REGISTER (decl))
21334       && die->die_tag != DW_TAG_member)
21335     add_linkage_name_raw (die, decl);
21336 }
21337
21338 /* Add a DW_AT_name attribute and source coordinate attribute for the
21339    given decl, but only if it actually has a name.  */
21340
21341 static void
21342 add_name_and_src_coords_attributes (dw_die_ref die, tree decl,
21343                                     bool no_linkage_name)
21344 {
21345   tree decl_name;
21346
21347   decl_name = DECL_NAME (decl);
21348   if (decl_name != NULL && IDENTIFIER_POINTER (decl_name) != NULL)
21349     {
21350       const char *name = dwarf2_name (decl, 0);
21351       if (name)
21352         add_name_attribute (die, name);
21353       if (! DECL_ARTIFICIAL (decl))
21354         add_src_coords_attributes (die, decl);
21355
21356       if (!no_linkage_name)
21357         add_linkage_name (die, decl);
21358     }
21359
21360 #ifdef VMS_DEBUGGING_INFO
21361   /* Get the function's name, as described by its RTL.  This may be different
21362      from the DECL_NAME name used in the source file.  */
21363   if (TREE_CODE (decl) == FUNCTION_DECL && TREE_ASM_WRITTEN (decl))
21364     {
21365       add_AT_addr (die, DW_AT_VMS_rtnbeg_pd_address,
21366                   XEXP (DECL_RTL (decl), 0), false);
21367       vec_safe_push (used_rtx_array, XEXP (DECL_RTL (decl), 0));
21368     }
21369 #endif /* VMS_DEBUGGING_INFO */
21370 }
21371
21372 /* Add VALUE as a DW_AT_discr_value attribute to DIE.  */
21373
21374 static void
21375 add_discr_value (dw_die_ref die, dw_discr_value *value)
21376 {
21377   dw_attr_node attr;
21378
21379   attr.dw_attr = DW_AT_discr_value;
21380   attr.dw_attr_val.val_class = dw_val_class_discr_value;
21381   attr.dw_attr_val.val_entry = NULL;
21382   attr.dw_attr_val.v.val_discr_value.pos = value->pos;
21383   if (value->pos)
21384     attr.dw_attr_val.v.val_discr_value.v.uval = value->v.uval;
21385   else
21386     attr.dw_attr_val.v.val_discr_value.v.sval = value->v.sval;
21387   add_dwarf_attr (die, &attr);
21388 }
21389
21390 /* Add DISCR_LIST as a DW_AT_discr_list to DIE.  */
21391
21392 static void
21393 add_discr_list (dw_die_ref die, dw_discr_list_ref discr_list)
21394 {
21395   dw_attr_node attr;
21396
21397   attr.dw_attr = DW_AT_discr_list;
21398   attr.dw_attr_val.val_class = dw_val_class_discr_list;
21399   attr.dw_attr_val.val_entry = NULL;
21400   attr.dw_attr_val.v.val_discr_list = discr_list;
21401   add_dwarf_attr (die, &attr);
21402 }
21403
21404 static inline dw_discr_list_ref
21405 AT_discr_list (dw_attr_node *attr)
21406 {
21407   return attr->dw_attr_val.v.val_discr_list;
21408 }
21409
21410 #ifdef VMS_DEBUGGING_INFO
21411 /* Output the debug main pointer die for VMS */
21412
21413 void
21414 dwarf2out_vms_debug_main_pointer (void)
21415 {
21416   char label[MAX_ARTIFICIAL_LABEL_BYTES];
21417   dw_die_ref die;
21418
21419   /* Allocate the VMS debug main subprogram die.  */
21420   die = new_die_raw (DW_TAG_subprogram);
21421   add_name_attribute (die, VMS_DEBUG_MAIN_POINTER);
21422   ASM_GENERATE_INTERNAL_LABEL (label, PROLOGUE_END_LABEL,
21423                                current_function_funcdef_no);
21424   add_AT_lbl_id (die, DW_AT_entry_pc, label);
21425
21426   /* Make it the first child of comp_unit_die ().  */
21427   die->die_parent = comp_unit_die ();
21428   if (comp_unit_die ()->die_child)
21429     {
21430       die->die_sib = comp_unit_die ()->die_child->die_sib;
21431       comp_unit_die ()->die_child->die_sib = die;
21432     }
21433   else
21434     {
21435       die->die_sib = die;
21436       comp_unit_die ()->die_child = die;
21437     }
21438 }
21439 #endif /* VMS_DEBUGGING_INFO */
21440
21441 /* Push a new declaration scope.  */
21442
21443 static void
21444 push_decl_scope (tree scope)
21445 {
21446   vec_safe_push (decl_scope_table, scope);
21447 }
21448
21449 /* Pop a declaration scope.  */
21450
21451 static inline void
21452 pop_decl_scope (void)
21453 {
21454   decl_scope_table->pop ();
21455 }
21456
21457 /* walk_tree helper function for uses_local_type, below.  */
21458
21459 static tree
21460 uses_local_type_r (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
21461 {
21462   if (!TYPE_P (*tp))
21463     *walk_subtrees = 0;
21464   else
21465     {
21466       tree name = TYPE_NAME (*tp);
21467       if (name && DECL_P (name) && decl_function_context (name))
21468         return *tp;
21469     }
21470   return NULL_TREE;
21471 }
21472
21473 /* If TYPE involves a function-local type (including a local typedef to a
21474    non-local type), returns that type; otherwise returns NULL_TREE.  */
21475
21476 static tree
21477 uses_local_type (tree type)
21478 {
21479   tree used = walk_tree_without_duplicates (&type, uses_local_type_r, NULL);
21480   return used;
21481 }
21482
21483 /* Return the DIE for the scope that immediately contains this type.
21484    Non-named types that do not involve a function-local type get global
21485    scope.  Named types nested in namespaces or other types get their
21486    containing scope.  All other types (i.e. function-local named types) get
21487    the current active scope.  */
21488
21489 static dw_die_ref
21490 scope_die_for (tree t, dw_die_ref context_die)
21491 {
21492   dw_die_ref scope_die = NULL;
21493   tree containing_scope;
21494
21495   /* Non-types always go in the current scope.  */
21496   gcc_assert (TYPE_P (t));
21497
21498   /* Use the scope of the typedef, rather than the scope of the type
21499      it refers to.  */
21500   if (TYPE_NAME (t) && DECL_P (TYPE_NAME (t)))
21501     containing_scope = DECL_CONTEXT (TYPE_NAME (t));
21502   else
21503     containing_scope = TYPE_CONTEXT (t);
21504
21505   /* Use the containing namespace if there is one.  */
21506   if (containing_scope && TREE_CODE (containing_scope) == NAMESPACE_DECL)
21507     {
21508       if (context_die == lookup_decl_die (containing_scope))
21509         /* OK */;
21510       else if (debug_info_level > DINFO_LEVEL_TERSE)
21511         context_die = get_context_die (containing_scope);
21512       else
21513         containing_scope = NULL_TREE;
21514     }
21515
21516   /* Ignore function type "scopes" from the C frontend.  They mean that
21517      a tagged type is local to a parmlist of a function declarator, but
21518      that isn't useful to DWARF.  */
21519   if (containing_scope && TREE_CODE (containing_scope) == FUNCTION_TYPE)
21520     containing_scope = NULL_TREE;
21521
21522   if (SCOPE_FILE_SCOPE_P (containing_scope))
21523     {
21524       /* If T uses a local type keep it local as well, to avoid references
21525          to function-local DIEs from outside the function.  */
21526       if (current_function_decl && uses_local_type (t))
21527         scope_die = context_die;
21528       else
21529         scope_die = comp_unit_die ();
21530     }
21531   else if (TYPE_P (containing_scope))
21532     {
21533       /* For types, we can just look up the appropriate DIE.  */
21534       if (debug_info_level > DINFO_LEVEL_TERSE)
21535         scope_die = get_context_die (containing_scope);
21536       else
21537         {
21538           scope_die = lookup_type_die_strip_naming_typedef (containing_scope);
21539           if (scope_die == NULL)
21540             scope_die = comp_unit_die ();
21541         }
21542     }
21543   else
21544     scope_die = context_die;
21545
21546   return scope_die;
21547 }
21548
21549 /* Returns nonzero if CONTEXT_DIE is internal to a function.  */
21550
21551 static inline int
21552 local_scope_p (dw_die_ref context_die)
21553 {
21554   for (; context_die; context_die = context_die->die_parent)
21555     if (context_die->die_tag == DW_TAG_inlined_subroutine
21556         || context_die->die_tag == DW_TAG_subprogram)
21557       return 1;
21558
21559   return 0;
21560 }
21561
21562 /* Returns nonzero if CONTEXT_DIE is a class.  */
21563
21564 static inline int
21565 class_scope_p (dw_die_ref context_die)
21566 {
21567   return (context_die
21568           && (context_die->die_tag == DW_TAG_structure_type
21569               || context_die->die_tag == DW_TAG_class_type
21570               || context_die->die_tag == DW_TAG_interface_type
21571               || context_die->die_tag == DW_TAG_union_type));
21572 }
21573
21574 /* Returns nonzero if CONTEXT_DIE is a class or namespace, for deciding
21575    whether or not to treat a DIE in this context as a declaration.  */
21576
21577 static inline int
21578 class_or_namespace_scope_p (dw_die_ref context_die)
21579 {
21580   return (class_scope_p (context_die)
21581           || (context_die && context_die->die_tag == DW_TAG_namespace));
21582 }
21583
21584 /* Many forms of DIEs require a "type description" attribute.  This
21585    routine locates the proper "type descriptor" die for the type given
21586    by 'type' plus any additional qualifiers given by 'cv_quals', and
21587    adds a DW_AT_type attribute below the given die.  */
21588
21589 static void
21590 add_type_attribute (dw_die_ref object_die, tree type, int cv_quals,
21591                     bool reverse, dw_die_ref context_die)
21592 {
21593   enum tree_code code  = TREE_CODE (type);
21594   dw_die_ref type_die  = NULL;
21595
21596   /* ??? If this type is an unnamed subrange type of an integral, floating-point
21597      or fixed-point type, use the inner type.  This is because we have no
21598      support for unnamed types in base_type_die.  This can happen if this is
21599      an Ada subrange type.  Correct solution is emit a subrange type die.  */
21600   if ((code == INTEGER_TYPE || code == REAL_TYPE || code == FIXED_POINT_TYPE)
21601       && TREE_TYPE (type) != 0 && TYPE_NAME (type) == 0)
21602     type = TREE_TYPE (type), code = TREE_CODE (type);
21603
21604   if (code == ERROR_MARK
21605       /* Handle a special case.  For functions whose return type is void, we
21606          generate *no* type attribute.  (Note that no object may have type
21607          `void', so this only applies to function return types).  */
21608       || code == VOID_TYPE)
21609     return;
21610
21611   type_die = modified_type_die (type,
21612                                 cv_quals | TYPE_QUALS (type),
21613                                 reverse,
21614                                 context_die);
21615
21616   if (type_die != NULL)
21617     add_AT_die_ref (object_die, DW_AT_type, type_die);
21618 }
21619
21620 /* Given an object die, add the calling convention attribute for the
21621    function call type.  */
21622 static void
21623 add_calling_convention_attribute (dw_die_ref subr_die, tree decl)
21624 {
21625   enum dwarf_calling_convention value = DW_CC_normal;
21626
21627   value = ((enum dwarf_calling_convention)
21628            targetm.dwarf_calling_convention (TREE_TYPE (decl)));
21629
21630   if (is_fortran ()
21631       && id_equal (DECL_ASSEMBLER_NAME (decl), "MAIN__"))
21632     {
21633       /* DWARF 2 doesn't provide a way to identify a program's source-level
21634         entry point.  DW_AT_calling_convention attributes are only meant
21635         to describe functions' calling conventions.  However, lacking a
21636         better way to signal the Fortran main program, we used this for 
21637         a long time, following existing custom.  Now, DWARF 4 has 
21638         DW_AT_main_subprogram, which we add below, but some tools still
21639         rely on the old way, which we thus keep.  */
21640       value = DW_CC_program;
21641
21642       if (dwarf_version >= 4 || !dwarf_strict)
21643         add_AT_flag (subr_die, DW_AT_main_subprogram, 1);
21644     }
21645
21646   /* Only add the attribute if the backend requests it, and
21647      is not DW_CC_normal.  */
21648   if (value && (value != DW_CC_normal))
21649     add_AT_unsigned (subr_die, DW_AT_calling_convention, value);
21650 }
21651
21652 /* Given a tree pointer to a struct, class, union, or enum type node, return
21653    a pointer to the (string) tag name for the given type, or zero if the type
21654    was declared without a tag.  */
21655
21656 static const char *
21657 type_tag (const_tree type)
21658 {
21659   const char *name = 0;
21660
21661   if (TYPE_NAME (type) != 0)
21662     {
21663       tree t = 0;
21664
21665       /* Find the IDENTIFIER_NODE for the type name.  */
21666       if (TREE_CODE (TYPE_NAME (type)) == IDENTIFIER_NODE
21667           && !TYPE_NAMELESS (type))
21668         t = TYPE_NAME (type);
21669
21670       /* The g++ front end makes the TYPE_NAME of *each* tagged type point to
21671          a TYPE_DECL node, regardless of whether or not a `typedef' was
21672          involved.  */
21673       else if (TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
21674                && ! DECL_IGNORED_P (TYPE_NAME (type)))
21675         {
21676           /* We want to be extra verbose.  Don't call dwarf_name if
21677              DECL_NAME isn't set.  The default hook for decl_printable_name
21678              doesn't like that, and in this context it's correct to return
21679              0, instead of "<anonymous>" or the like.  */
21680           if (DECL_NAME (TYPE_NAME (type))
21681               && !DECL_NAMELESS (TYPE_NAME (type)))
21682             name = lang_hooks.dwarf_name (TYPE_NAME (type), 2);
21683         }
21684
21685       /* Now get the name as a string, or invent one.  */
21686       if (!name && t != 0)
21687         name = IDENTIFIER_POINTER (t);
21688     }
21689
21690   return (name == 0 || *name == '\0') ? 0 : name;
21691 }
21692
21693 /* Return the type associated with a data member, make a special check
21694    for bit field types.  */
21695
21696 static inline tree
21697 member_declared_type (const_tree member)
21698 {
21699   return (DECL_BIT_FIELD_TYPE (member)
21700           ? DECL_BIT_FIELD_TYPE (member) : TREE_TYPE (member));
21701 }
21702
21703 /* Get the decl's label, as described by its RTL. This may be different
21704    from the DECL_NAME name used in the source file.  */
21705
21706 #if 0
21707 static const char *
21708 decl_start_label (tree decl)
21709 {
21710   rtx x;
21711   const char *fnname;
21712
21713   x = DECL_RTL (decl);
21714   gcc_assert (MEM_P (x));
21715
21716   x = XEXP (x, 0);
21717   gcc_assert (GET_CODE (x) == SYMBOL_REF);
21718
21719   fnname = XSTR (x, 0);
21720   return fnname;
21721 }
21722 #endif
21723 \f
21724 /* For variable-length arrays that have been previously generated, but
21725    may be incomplete due to missing subscript info, fill the subscript
21726    info.  Return TRUE if this is one of those cases.  */
21727 static bool
21728 fill_variable_array_bounds (tree type)
21729 {
21730   if (TREE_ASM_WRITTEN (type)
21731       && TREE_CODE (type) == ARRAY_TYPE
21732       && variably_modified_type_p (type, NULL))
21733     {
21734       dw_die_ref array_die = lookup_type_die (type);
21735       if (!array_die)
21736         return false;
21737       add_subscript_info (array_die, type, !is_ada ());
21738       return true;
21739     }
21740   return false;
21741 }
21742
21743 /* These routines generate the internal representation of the DIE's for
21744    the compilation unit.  Debugging information is collected by walking
21745    the declaration trees passed in from dwarf2out_decl().  */
21746
21747 static void
21748 gen_array_type_die (tree type, dw_die_ref context_die)
21749 {
21750   dw_die_ref array_die;
21751
21752   /* GNU compilers represent multidimensional array types as sequences of one
21753      dimensional array types whose element types are themselves array types.
21754      We sometimes squish that down to a single array_type DIE with multiple
21755      subscripts in the Dwarf debugging info.  The draft Dwarf specification
21756      say that we are allowed to do this kind of compression in C, because
21757      there is no difference between an array of arrays and a multidimensional
21758      array.  We don't do this for Ada to remain as close as possible to the
21759      actual representation, which is especially important against the language
21760      flexibilty wrt arrays of variable size.  */
21761
21762   bool collapse_nested_arrays = !is_ada ();
21763
21764   if (fill_variable_array_bounds (type))
21765     return;
21766
21767   dw_die_ref scope_die = scope_die_for (type, context_die);
21768   tree element_type;
21769
21770   /* Emit DW_TAG_string_type for Fortran character types (with kind 1 only, as
21771      DW_TAG_string_type doesn't have DW_AT_type attribute).  */
21772   if (TYPE_STRING_FLAG (type)
21773       && TREE_CODE (type) == ARRAY_TYPE
21774       && is_fortran ()
21775       && TYPE_MODE (TREE_TYPE (type)) == TYPE_MODE (char_type_node))
21776     {
21777       HOST_WIDE_INT size;
21778
21779       array_die = new_die (DW_TAG_string_type, scope_die, type);
21780       add_name_attribute (array_die, type_tag (type));
21781       equate_type_number_to_die (type, array_die);
21782       size = int_size_in_bytes (type);
21783       if (size >= 0)
21784         add_AT_unsigned (array_die, DW_AT_byte_size, size);
21785       /* ???  We can't annotate types late, but for LTO we may not
21786          generate a location early either (gfortran.dg/save_6.f90).  */
21787       else if (! (early_dwarf && (flag_generate_lto || flag_generate_offload))
21788                && TYPE_DOMAIN (type) != NULL_TREE
21789                && TYPE_MAX_VALUE (TYPE_DOMAIN (type)) != NULL_TREE)
21790         {
21791           tree szdecl = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
21792           tree rszdecl = szdecl;
21793
21794           size = int_size_in_bytes (TREE_TYPE (szdecl));
21795           if (!DECL_P (szdecl))
21796             {
21797               if (TREE_CODE (szdecl) == INDIRECT_REF
21798                   && DECL_P (TREE_OPERAND (szdecl, 0)))
21799                 {
21800                   rszdecl = TREE_OPERAND (szdecl, 0);
21801                   if (int_size_in_bytes (TREE_TYPE (rszdecl))
21802                       != DWARF2_ADDR_SIZE)
21803                     size = 0;
21804                 }
21805               else
21806                 size = 0;
21807             }
21808           if (size > 0)
21809             {
21810               dw_loc_list_ref loc
21811                 = loc_list_from_tree (rszdecl, szdecl == rszdecl ? 2 : 0,
21812                                       NULL);
21813               if (loc)
21814                 {
21815                   add_AT_location_description (array_die, DW_AT_string_length,
21816                                                loc);
21817                   if (size != DWARF2_ADDR_SIZE)
21818                     add_AT_unsigned (array_die, dwarf_version >= 5
21819                                                 ? DW_AT_string_length_byte_size
21820                                                 : DW_AT_byte_size, size);
21821                 }
21822             }
21823         }
21824       return;
21825     }
21826
21827   array_die = new_die (DW_TAG_array_type, scope_die, type);
21828   add_name_attribute (array_die, type_tag (type));
21829   equate_type_number_to_die (type, array_die);
21830
21831   if (TREE_CODE (type) == VECTOR_TYPE)
21832     add_AT_flag (array_die, DW_AT_GNU_vector, 1);
21833
21834   /* For Fortran multidimensional arrays use DW_ORD_col_major ordering.  */
21835   if (is_fortran ()
21836       && TREE_CODE (type) == ARRAY_TYPE
21837       && TREE_CODE (TREE_TYPE (type)) == ARRAY_TYPE
21838       && !TYPE_STRING_FLAG (TREE_TYPE (type)))
21839     add_AT_unsigned (array_die, DW_AT_ordering, DW_ORD_col_major);
21840
21841 #if 0
21842   /* We default the array ordering.  Debuggers will probably do the right
21843      things even if DW_AT_ordering is not present.  It's not even an issue
21844      until we start to get into multidimensional arrays anyway.  If a debugger
21845      is ever caught doing the Wrong Thing for multi-dimensional arrays,
21846      then we'll have to put the DW_AT_ordering attribute back in.  (But if
21847      and when we find out that we need to put these in, we will only do so
21848      for multidimensional arrays.  */
21849   add_AT_unsigned (array_die, DW_AT_ordering, DW_ORD_row_major);
21850 #endif
21851
21852   if (TREE_CODE (type) == VECTOR_TYPE)
21853     {
21854       /* For VECTOR_TYPEs we use an array die with appropriate bounds.  */
21855       dw_die_ref subrange_die = new_die (DW_TAG_subrange_type, array_die, NULL);
21856       add_bound_info (subrange_die, DW_AT_lower_bound, size_zero_node, NULL);
21857       add_bound_info (subrange_die, DW_AT_upper_bound,
21858                       size_int (TYPE_VECTOR_SUBPARTS (type) - 1), NULL);
21859     }
21860   else
21861     add_subscript_info (array_die, type, collapse_nested_arrays);
21862
21863   /* Add representation of the type of the elements of this array type and
21864      emit the corresponding DIE if we haven't done it already.  */
21865   element_type = TREE_TYPE (type);
21866   if (collapse_nested_arrays)
21867     while (TREE_CODE (element_type) == ARRAY_TYPE)
21868       {
21869         if (TYPE_STRING_FLAG (element_type) && is_fortran ())
21870           break;
21871         element_type = TREE_TYPE (element_type);
21872       }
21873
21874   add_type_attribute (array_die, element_type, TYPE_UNQUALIFIED,
21875                       TREE_CODE (type) == ARRAY_TYPE
21876                       && TYPE_REVERSE_STORAGE_ORDER (type),
21877                       context_die);
21878
21879   add_gnat_descriptive_type_attribute (array_die, type, context_die);
21880   if (TYPE_ARTIFICIAL (type))
21881     add_AT_flag (array_die, DW_AT_artificial, 1);
21882
21883   if (get_AT (array_die, DW_AT_name))
21884     add_pubtype (type, array_die);
21885
21886   add_alignment_attribute (array_die, type);
21887 }
21888
21889 /* This routine generates DIE for array with hidden descriptor, details
21890    are filled into *info by a langhook.  */
21891
21892 static void
21893 gen_descr_array_type_die (tree type, struct array_descr_info *info,
21894                           dw_die_ref context_die)
21895 {
21896   const dw_die_ref scope_die = scope_die_for (type, context_die);
21897   const dw_die_ref array_die = new_die (DW_TAG_array_type, scope_die, type);
21898   struct loc_descr_context context = { type, info->base_decl, NULL,
21899                                        false, false };
21900   enum dwarf_tag subrange_tag = DW_TAG_subrange_type;
21901   int dim;
21902
21903   add_name_attribute (array_die, type_tag (type));
21904   equate_type_number_to_die (type, array_die);
21905
21906   if (info->ndimensions > 1)
21907     switch (info->ordering)
21908       {
21909       case array_descr_ordering_row_major:
21910         add_AT_unsigned (array_die, DW_AT_ordering, DW_ORD_row_major);
21911         break;
21912       case array_descr_ordering_column_major:
21913         add_AT_unsigned (array_die, DW_AT_ordering, DW_ORD_col_major);
21914         break;
21915       default:
21916         break;
21917       }
21918
21919   if (dwarf_version >= 3 || !dwarf_strict)
21920     {
21921       if (info->data_location)
21922         add_scalar_info (array_die, DW_AT_data_location, info->data_location,
21923                          dw_scalar_form_exprloc, &context);
21924       if (info->associated)
21925         add_scalar_info (array_die, DW_AT_associated, info->associated,
21926                          dw_scalar_form_constant
21927                          | dw_scalar_form_exprloc
21928                          | dw_scalar_form_reference, &context);
21929       if (info->allocated)
21930         add_scalar_info (array_die, DW_AT_allocated, info->allocated,
21931                          dw_scalar_form_constant
21932                          | dw_scalar_form_exprloc
21933                          | dw_scalar_form_reference, &context);
21934       if (info->stride)
21935         {
21936           const enum dwarf_attribute attr
21937             = (info->stride_in_bits) ? DW_AT_bit_stride : DW_AT_byte_stride;
21938           const int forms
21939             = (info->stride_in_bits)
21940               ? dw_scalar_form_constant
21941               : (dw_scalar_form_constant
21942                  | dw_scalar_form_exprloc
21943                  | dw_scalar_form_reference);
21944
21945           add_scalar_info (array_die, attr, info->stride, forms, &context);
21946         }
21947     }
21948   if (dwarf_version >= 5)
21949     {
21950       if (info->rank)
21951         {
21952           add_scalar_info (array_die, DW_AT_rank, info->rank,
21953                            dw_scalar_form_constant
21954                            | dw_scalar_form_exprloc, &context);
21955           subrange_tag = DW_TAG_generic_subrange;
21956           context.placeholder_arg = true;
21957         }
21958     }
21959
21960   add_gnat_descriptive_type_attribute (array_die, type, context_die);
21961
21962   for (dim = 0; dim < info->ndimensions; dim++)
21963     {
21964       dw_die_ref subrange_die = new_die (subrange_tag, array_die, NULL);
21965
21966       if (info->dimen[dim].bounds_type)
21967         add_type_attribute (subrange_die,
21968                             info->dimen[dim].bounds_type, TYPE_UNQUALIFIED,
21969                             false, context_die);
21970       if (info->dimen[dim].lower_bound)
21971         add_bound_info (subrange_die, DW_AT_lower_bound,
21972                         info->dimen[dim].lower_bound, &context);
21973       if (info->dimen[dim].upper_bound)
21974         add_bound_info (subrange_die, DW_AT_upper_bound,
21975                         info->dimen[dim].upper_bound, &context);
21976       if ((dwarf_version >= 3 || !dwarf_strict) && info->dimen[dim].stride)
21977         add_scalar_info (subrange_die, DW_AT_byte_stride,
21978                          info->dimen[dim].stride,
21979                          dw_scalar_form_constant
21980                          | dw_scalar_form_exprloc
21981                          | dw_scalar_form_reference,
21982                          &context);
21983     }
21984
21985   gen_type_die (info->element_type, context_die);
21986   add_type_attribute (array_die, info->element_type, TYPE_UNQUALIFIED,
21987                       TREE_CODE (type) == ARRAY_TYPE
21988                       && TYPE_REVERSE_STORAGE_ORDER (type),
21989                       context_die);
21990
21991   if (get_AT (array_die, DW_AT_name))
21992     add_pubtype (type, array_die);
21993
21994   add_alignment_attribute (array_die, type);
21995 }
21996
21997 #if 0
21998 static void
21999 gen_entry_point_die (tree decl, dw_die_ref context_die)
22000 {
22001   tree origin = decl_ultimate_origin (decl);
22002   dw_die_ref decl_die = new_die (DW_TAG_entry_point, context_die, decl);
22003
22004   if (origin != NULL)
22005     add_abstract_origin_attribute (decl_die, origin);
22006   else
22007     {
22008       add_name_and_src_coords_attributes (decl_die, decl);
22009       add_type_attribute (decl_die, TREE_TYPE (TREE_TYPE (decl)),
22010                           TYPE_UNQUALIFIED, false, context_die);
22011     }
22012
22013   if (DECL_ABSTRACT_P (decl))
22014     equate_decl_number_to_die (decl, decl_die);
22015   else
22016     add_AT_lbl_id (decl_die, DW_AT_low_pc, decl_start_label (decl));
22017 }
22018 #endif
22019
22020 /* Walk through the list of incomplete types again, trying once more to
22021    emit full debugging info for them.  */
22022
22023 static void
22024 retry_incomplete_types (void)
22025 {
22026   set_early_dwarf s;
22027   int i;
22028
22029   for (i = vec_safe_length (incomplete_types) - 1; i >= 0; i--)
22030     if (should_emit_struct_debug ((*incomplete_types)[i], DINFO_USAGE_DIR_USE))
22031       gen_type_die ((*incomplete_types)[i], comp_unit_die ());
22032   vec_safe_truncate (incomplete_types, 0);
22033 }
22034
22035 /* Determine what tag to use for a record type.  */
22036
22037 static enum dwarf_tag
22038 record_type_tag (tree type)
22039 {
22040   if (! lang_hooks.types.classify_record)
22041     return DW_TAG_structure_type;
22042
22043   switch (lang_hooks.types.classify_record (type))
22044     {
22045     case RECORD_IS_STRUCT:
22046       return DW_TAG_structure_type;
22047
22048     case RECORD_IS_CLASS:
22049       return DW_TAG_class_type;
22050
22051     case RECORD_IS_INTERFACE:
22052       if (dwarf_version >= 3 || !dwarf_strict)
22053         return DW_TAG_interface_type;
22054       return DW_TAG_structure_type;
22055
22056     default:
22057       gcc_unreachable ();
22058     }
22059 }
22060
22061 /* Generate a DIE to represent an enumeration type.  Note that these DIEs
22062    include all of the information about the enumeration values also. Each
22063    enumerated type name/value is listed as a child of the enumerated type
22064    DIE.  */
22065
22066 static dw_die_ref
22067 gen_enumeration_type_die (tree type, dw_die_ref context_die)
22068 {
22069   dw_die_ref type_die = lookup_type_die (type);
22070   dw_die_ref orig_type_die = type_die;
22071
22072   if (type_die == NULL)
22073     {
22074       type_die = new_die (DW_TAG_enumeration_type,
22075                           scope_die_for (type, context_die), type);
22076       equate_type_number_to_die (type, type_die);
22077       add_name_attribute (type_die, type_tag (type));
22078       if ((dwarf_version >= 4 || !dwarf_strict)
22079           && ENUM_IS_SCOPED (type))
22080         add_AT_flag (type_die, DW_AT_enum_class, 1);
22081       if (ENUM_IS_OPAQUE (type) && TYPE_SIZE (type))
22082         add_AT_flag (type_die, DW_AT_declaration, 1);
22083       if (!dwarf_strict)
22084         add_AT_unsigned (type_die, DW_AT_encoding,
22085                          TYPE_UNSIGNED (type)
22086                          ? DW_ATE_unsigned
22087                          : DW_ATE_signed);
22088     }
22089   else if (! TYPE_SIZE (type) || ENUM_IS_OPAQUE (type))
22090     return type_die;
22091   else
22092     remove_AT (type_die, DW_AT_declaration);
22093
22094   /* Handle a GNU C/C++ extension, i.e. incomplete enum types.  If the
22095      given enum type is incomplete, do not generate the DW_AT_byte_size
22096      attribute or the DW_AT_element_list attribute.  */
22097   if (TYPE_SIZE (type))
22098     {
22099       tree link;
22100
22101       if (!ENUM_IS_OPAQUE (type))
22102         TREE_ASM_WRITTEN (type) = 1;
22103       if (!orig_type_die || !get_AT (type_die, DW_AT_byte_size))
22104         add_byte_size_attribute (type_die, type);
22105       if (!orig_type_die || !get_AT (type_die, DW_AT_alignment))
22106         add_alignment_attribute (type_die, type);
22107       if ((dwarf_version >= 3 || !dwarf_strict)
22108           && (!orig_type_die || !get_AT (type_die, DW_AT_type)))
22109         {
22110           tree underlying = lang_hooks.types.enum_underlying_base_type (type);
22111           add_type_attribute (type_die, underlying, TYPE_UNQUALIFIED, false,
22112                               context_die);
22113         }
22114       if (TYPE_STUB_DECL (type) != NULL_TREE)
22115         {
22116           if (!orig_type_die || !get_AT (type_die, DW_AT_decl_file))
22117             add_src_coords_attributes (type_die, TYPE_STUB_DECL (type));
22118           if (!orig_type_die || !get_AT (type_die, DW_AT_accessibility))
22119             add_accessibility_attribute (type_die, TYPE_STUB_DECL (type));
22120         }
22121
22122       /* If the first reference to this type was as the return type of an
22123          inline function, then it may not have a parent.  Fix this now.  */
22124       if (type_die->die_parent == NULL)
22125         add_child_die (scope_die_for (type, context_die), type_die);
22126
22127       for (link = TYPE_VALUES (type);
22128            link != NULL; link = TREE_CHAIN (link))
22129         {
22130           dw_die_ref enum_die = new_die (DW_TAG_enumerator, type_die, link);
22131           tree value = TREE_VALUE (link);
22132
22133           gcc_assert (!ENUM_IS_OPAQUE (type));
22134           add_name_attribute (enum_die,
22135                               IDENTIFIER_POINTER (TREE_PURPOSE (link)));
22136
22137           if (TREE_CODE (value) == CONST_DECL)
22138             value = DECL_INITIAL (value);
22139
22140           if (simple_type_size_in_bits (TREE_TYPE (value))
22141               <= HOST_BITS_PER_WIDE_INT || tree_fits_shwi_p (value))
22142             {
22143               /* For constant forms created by add_AT_unsigned DWARF
22144                  consumers (GDB, elfutils, etc.) always zero extend
22145                  the value.  Only when the actual value is negative
22146                  do we need to use add_AT_int to generate a constant
22147                  form that can represent negative values.  */
22148               HOST_WIDE_INT val = TREE_INT_CST_LOW (value);
22149               if (TYPE_UNSIGNED (TREE_TYPE (value)) || val >= 0)
22150                 add_AT_unsigned (enum_die, DW_AT_const_value,
22151                                  (unsigned HOST_WIDE_INT) val);
22152               else
22153                 add_AT_int (enum_die, DW_AT_const_value, val);
22154             }
22155           else
22156             /* Enumeration constants may be wider than HOST_WIDE_INT.  Handle
22157                that here.  TODO: This should be re-worked to use correct
22158                signed/unsigned double tags for all cases.  */
22159             add_AT_wide (enum_die, DW_AT_const_value, wi::to_wide (value));
22160         }
22161
22162       add_gnat_descriptive_type_attribute (type_die, type, context_die);
22163       if (TYPE_ARTIFICIAL (type)
22164           && (!orig_type_die || !get_AT (type_die, DW_AT_artificial)))
22165         add_AT_flag (type_die, DW_AT_artificial, 1);
22166     }
22167   else
22168     add_AT_flag (type_die, DW_AT_declaration, 1);
22169
22170   add_pubtype (type, type_die);
22171
22172   return type_die;
22173 }
22174
22175 /* Generate a DIE to represent either a real live formal parameter decl or to
22176    represent just the type of some formal parameter position in some function
22177    type.
22178
22179    Note that this routine is a bit unusual because its argument may be a
22180    ..._DECL node (i.e. either a PARM_DECL or perhaps a VAR_DECL which
22181    represents an inlining of some PARM_DECL) or else some sort of a ..._TYPE
22182    node.  If it's the former then this function is being called to output a
22183    DIE to represent a formal parameter object (or some inlining thereof).  If
22184    it's the latter, then this function is only being called to output a
22185    DW_TAG_formal_parameter DIE to stand as a placeholder for some formal
22186    argument type of some subprogram type.
22187    If EMIT_NAME_P is true, name and source coordinate attributes
22188    are emitted.  */
22189
22190 static dw_die_ref
22191 gen_formal_parameter_die (tree node, tree origin, bool emit_name_p,
22192                           dw_die_ref context_die)
22193 {
22194   tree node_or_origin = node ? node : origin;
22195   tree ultimate_origin;
22196   dw_die_ref parm_die = NULL;
22197   
22198   if (DECL_P (node_or_origin))
22199     {
22200       parm_die = lookup_decl_die (node);
22201
22202       /* If the contexts differ, we may not be talking about the same
22203          thing.
22204          ???  When in LTO the DIE parent is the "abstract" copy and the
22205          context_die is the specification "copy".  But this whole block
22206          should eventually be no longer needed.  */
22207       if (parm_die && parm_die->die_parent != context_die && !in_lto_p)
22208         {
22209           if (!DECL_ABSTRACT_P (node))
22210             {
22211               /* This can happen when creating an inlined instance, in
22212                  which case we need to create a new DIE that will get
22213                  annotated with DW_AT_abstract_origin.  */
22214               parm_die = NULL;
22215             }
22216           else
22217             gcc_unreachable ();
22218         }
22219
22220       if (parm_die && parm_die->die_parent == NULL)
22221         {
22222           /* Check that parm_die already has the right attributes that
22223              we would have added below.  If any attributes are
22224              missing, fall through to add them.  */
22225           if (! DECL_ABSTRACT_P (node_or_origin)
22226               && !get_AT (parm_die, DW_AT_location)
22227               && !get_AT (parm_die, DW_AT_const_value))
22228             /* We are missing  location info, and are about to add it.  */
22229             ;
22230           else
22231             {
22232               add_child_die (context_die, parm_die);
22233               return parm_die;
22234             }
22235         }
22236     }
22237
22238   /* If we have a previously generated DIE, use it, unless this is an
22239      concrete instance (origin != NULL), in which case we need a new
22240      DIE with a corresponding DW_AT_abstract_origin.  */
22241   bool reusing_die;
22242   if (parm_die && origin == NULL)
22243     reusing_die = true;
22244   else
22245     {
22246       parm_die = new_die (DW_TAG_formal_parameter, context_die, node);
22247       reusing_die = false;
22248     }
22249
22250   switch (TREE_CODE_CLASS (TREE_CODE (node_or_origin)))
22251     {
22252     case tcc_declaration:
22253       ultimate_origin = decl_ultimate_origin (node_or_origin);
22254       if (node || ultimate_origin)
22255         origin = ultimate_origin;
22256
22257       if (reusing_die)
22258         goto add_location;
22259
22260       if (origin != NULL)
22261         add_abstract_origin_attribute (parm_die, origin);
22262       else if (emit_name_p)
22263         add_name_and_src_coords_attributes (parm_die, node);
22264       if (origin == NULL
22265           || (! DECL_ABSTRACT_P (node_or_origin)
22266               && variably_modified_type_p (TREE_TYPE (node_or_origin),
22267                                            decl_function_context
22268                                                             (node_or_origin))))
22269         {
22270           tree type = TREE_TYPE (node_or_origin);
22271           if (decl_by_reference_p (node_or_origin))
22272             add_type_attribute (parm_die, TREE_TYPE (type),
22273                                 TYPE_UNQUALIFIED,
22274                                 false, context_die);
22275           else
22276             add_type_attribute (parm_die, type,
22277                                 decl_quals (node_or_origin),
22278                                 false, context_die);
22279         }
22280       if (origin == NULL && DECL_ARTIFICIAL (node))
22281         add_AT_flag (parm_die, DW_AT_artificial, 1);
22282     add_location:
22283       if (node && node != origin)
22284         equate_decl_number_to_die (node, parm_die);
22285       if (! DECL_ABSTRACT_P (node_or_origin))
22286         add_location_or_const_value_attribute (parm_die, node_or_origin,
22287                                                node == NULL);
22288
22289       break;
22290
22291     case tcc_type:
22292       /* We were called with some kind of a ..._TYPE node.  */
22293       add_type_attribute (parm_die, node_or_origin, TYPE_UNQUALIFIED, false,
22294                           context_die);
22295       break;
22296
22297     default:
22298       gcc_unreachable ();
22299     }
22300
22301   return parm_die;
22302 }
22303
22304 /* Generate and return a DW_TAG_GNU_formal_parameter_pack. Also generate
22305    children DW_TAG_formal_parameter DIEs representing the arguments of the
22306    parameter pack.
22307
22308    PARM_PACK must be a function parameter pack.
22309    PACK_ARG is the first argument of the parameter pack. Its TREE_CHAIN
22310    must point to the subsequent arguments of the function PACK_ARG belongs to.
22311    SUBR_DIE is the DIE of the function PACK_ARG belongs to.
22312    If NEXT_ARG is non NULL, *NEXT_ARG is set to the function argument
22313    following the last one for which a DIE was generated.  */
22314
22315 static dw_die_ref
22316 gen_formal_parameter_pack_die  (tree parm_pack,
22317                                 tree pack_arg,
22318                                 dw_die_ref subr_die,
22319                                 tree *next_arg)
22320 {
22321   tree arg;
22322   dw_die_ref parm_pack_die;
22323
22324   gcc_assert (parm_pack
22325               && lang_hooks.function_parameter_pack_p (parm_pack)
22326               && subr_die);
22327
22328   parm_pack_die = new_die (DW_TAG_GNU_formal_parameter_pack, subr_die, parm_pack);
22329   add_src_coords_attributes (parm_pack_die, parm_pack);
22330
22331   for (arg = pack_arg; arg; arg = DECL_CHAIN (arg))
22332     {
22333       if (! lang_hooks.decls.function_parm_expanded_from_pack_p (arg,
22334                                                                  parm_pack))
22335         break;
22336       gen_formal_parameter_die (arg, NULL,
22337                                 false /* Don't emit name attribute.  */,
22338                                 parm_pack_die);
22339     }
22340   if (next_arg)
22341     *next_arg = arg;
22342   return parm_pack_die;
22343 }
22344
22345 /* Generate a special type of DIE used as a stand-in for a trailing ellipsis
22346    at the end of an (ANSI prototyped) formal parameters list.  */
22347
22348 static void
22349 gen_unspecified_parameters_die (tree decl_or_type, dw_die_ref context_die)
22350 {
22351   new_die (DW_TAG_unspecified_parameters, context_die, decl_or_type);
22352 }
22353
22354 /* Generate a list of nameless DW_TAG_formal_parameter DIEs (and perhaps a
22355    DW_TAG_unspecified_parameters DIE) to represent the types of the formal
22356    parameters as specified in some function type specification (except for
22357    those which appear as part of a function *definition*).  */
22358
22359 static void
22360 gen_formal_types_die (tree function_or_method_type, dw_die_ref context_die)
22361 {
22362   tree link;
22363   tree formal_type = NULL;
22364   tree first_parm_type;
22365   tree arg;
22366
22367   if (TREE_CODE (function_or_method_type) == FUNCTION_DECL)
22368     {
22369       arg = DECL_ARGUMENTS (function_or_method_type);
22370       function_or_method_type = TREE_TYPE (function_or_method_type);
22371     }
22372   else
22373     arg = NULL_TREE;
22374
22375   first_parm_type = TYPE_ARG_TYPES (function_or_method_type);
22376
22377   /* Make our first pass over the list of formal parameter types and output a
22378      DW_TAG_formal_parameter DIE for each one.  */
22379   for (link = first_parm_type; link; )
22380     {
22381       dw_die_ref parm_die;
22382
22383       formal_type = TREE_VALUE (link);
22384       if (formal_type == void_type_node)
22385         break;
22386
22387       /* Output a (nameless) DIE to represent the formal parameter itself.  */
22388       if (!POINTER_BOUNDS_TYPE_P (formal_type))
22389         {
22390           parm_die = gen_formal_parameter_die (formal_type, NULL,
22391                                                true /* Emit name attribute.  */,
22392                                                context_die);
22393           if (TREE_CODE (function_or_method_type) == METHOD_TYPE
22394               && link == first_parm_type)
22395             {
22396               add_AT_flag (parm_die, DW_AT_artificial, 1);
22397               if (dwarf_version >= 3 || !dwarf_strict)
22398                 add_AT_die_ref (context_die, DW_AT_object_pointer, parm_die);
22399             }
22400           else if (arg && DECL_ARTIFICIAL (arg))
22401             add_AT_flag (parm_die, DW_AT_artificial, 1);
22402         }
22403
22404       link = TREE_CHAIN (link);
22405       if (arg)
22406         arg = DECL_CHAIN (arg);
22407     }
22408
22409   /* If this function type has an ellipsis, add a
22410      DW_TAG_unspecified_parameters DIE to the end of the parameter list.  */
22411   if (formal_type != void_type_node)
22412     gen_unspecified_parameters_die (function_or_method_type, context_die);
22413
22414   /* Make our second (and final) pass over the list of formal parameter types
22415      and output DIEs to represent those types (as necessary).  */
22416   for (link = TYPE_ARG_TYPES (function_or_method_type);
22417        link && TREE_VALUE (link);
22418        link = TREE_CHAIN (link))
22419     gen_type_die (TREE_VALUE (link), context_die);
22420 }
22421
22422 /* We want to generate the DIE for TYPE so that we can generate the
22423    die for MEMBER, which has been defined; we will need to refer back
22424    to the member declaration nested within TYPE.  If we're trying to
22425    generate minimal debug info for TYPE, processing TYPE won't do the
22426    trick; we need to attach the member declaration by hand.  */
22427
22428 static void
22429 gen_type_die_for_member (tree type, tree member, dw_die_ref context_die)
22430 {
22431   gen_type_die (type, context_die);
22432
22433   /* If we're trying to avoid duplicate debug info, we may not have
22434      emitted the member decl for this function.  Emit it now.  */
22435   if (TYPE_STUB_DECL (type)
22436       && TYPE_DECL_SUPPRESS_DEBUG (TYPE_STUB_DECL (type))
22437       && ! lookup_decl_die (member))
22438     {
22439       dw_die_ref type_die;
22440       gcc_assert (!decl_ultimate_origin (member));
22441
22442       push_decl_scope (type);
22443       type_die = lookup_type_die_strip_naming_typedef (type);
22444       if (TREE_CODE (member) == FUNCTION_DECL)
22445         gen_subprogram_die (member, type_die);
22446       else if (TREE_CODE (member) == FIELD_DECL)
22447         {
22448           /* Ignore the nameless fields that are used to skip bits but handle
22449              C++ anonymous unions and structs.  */
22450           if (DECL_NAME (member) != NULL_TREE
22451               || TREE_CODE (TREE_TYPE (member)) == UNION_TYPE
22452               || TREE_CODE (TREE_TYPE (member)) == RECORD_TYPE)
22453             {
22454               struct vlr_context vlr_ctx = {
22455                 DECL_CONTEXT (member), /* struct_type */
22456                 NULL_TREE /* variant_part_offset */
22457               };
22458               gen_type_die (member_declared_type (member), type_die);
22459               gen_field_die (member, &vlr_ctx, type_die);
22460             }
22461         }
22462       else
22463         gen_variable_die (member, NULL_TREE, type_die);
22464
22465       pop_decl_scope ();
22466     }
22467 }
22468 \f
22469 /* Forward declare these functions, because they are mutually recursive
22470   with their set_block_* pairing functions.  */
22471 static void set_decl_origin_self (tree);
22472
22473 /* Given a pointer to some BLOCK node, if the BLOCK_ABSTRACT_ORIGIN for the
22474    given BLOCK node is NULL, set the BLOCK_ABSTRACT_ORIGIN for the node so
22475    that it points to the node itself, thus indicating that the node is its
22476    own (abstract) origin.  Additionally, if the BLOCK_ABSTRACT_ORIGIN for
22477    the given node is NULL, recursively descend the decl/block tree which
22478    it is the root of, and for each other ..._DECL or BLOCK node contained
22479    therein whose DECL_ABSTRACT_ORIGINs or BLOCK_ABSTRACT_ORIGINs are also
22480    still NULL, set *their* DECL_ABSTRACT_ORIGIN or BLOCK_ABSTRACT_ORIGIN
22481    values to point to themselves.  */
22482
22483 static void
22484 set_block_origin_self (tree stmt)
22485 {
22486   if (BLOCK_ABSTRACT_ORIGIN (stmt) == NULL_TREE)
22487     {
22488       BLOCK_ABSTRACT_ORIGIN (stmt) = stmt;
22489
22490       {
22491         tree local_decl;
22492
22493         for (local_decl = BLOCK_VARS (stmt);
22494              local_decl != NULL_TREE;
22495              local_decl = DECL_CHAIN (local_decl))
22496           /* Do not recurse on nested functions since the inlining status
22497              of parent and child can be different as per the DWARF spec.  */
22498           if (TREE_CODE (local_decl) != FUNCTION_DECL
22499               && !DECL_EXTERNAL (local_decl))
22500             set_decl_origin_self (local_decl);
22501       }
22502
22503       {
22504         tree subblock;
22505
22506         for (subblock = BLOCK_SUBBLOCKS (stmt);
22507              subblock != NULL_TREE;
22508              subblock = BLOCK_CHAIN (subblock))
22509           set_block_origin_self (subblock);     /* Recurse.  */
22510       }
22511     }
22512 }
22513
22514 /* Given a pointer to some ..._DECL node, if the DECL_ABSTRACT_ORIGIN for
22515    the given ..._DECL node is NULL, set the DECL_ABSTRACT_ORIGIN for the
22516    node to so that it points to the node itself, thus indicating that the
22517    node represents its own (abstract) origin.  Additionally, if the
22518    DECL_ABSTRACT_ORIGIN for the given node is NULL, recursively descend
22519    the decl/block tree of which the given node is the root of, and for
22520    each other ..._DECL or BLOCK node contained therein whose
22521    DECL_ABSTRACT_ORIGINs or BLOCK_ABSTRACT_ORIGINs are also still NULL,
22522    set *their* DECL_ABSTRACT_ORIGIN or BLOCK_ABSTRACT_ORIGIN values to
22523    point to themselves.  */
22524
22525 static void
22526 set_decl_origin_self (tree decl)
22527 {
22528   if (DECL_ABSTRACT_ORIGIN (decl) == NULL_TREE)
22529     {
22530       DECL_ABSTRACT_ORIGIN (decl) = decl;
22531       if (TREE_CODE (decl) == FUNCTION_DECL)
22532         {
22533           tree arg;
22534
22535           for (arg = DECL_ARGUMENTS (decl); arg; arg = DECL_CHAIN (arg))
22536             DECL_ABSTRACT_ORIGIN (arg) = arg;
22537           if (DECL_INITIAL (decl) != NULL_TREE
22538               && DECL_INITIAL (decl) != error_mark_node)
22539             set_block_origin_self (DECL_INITIAL (decl));
22540         }
22541     }
22542 }
22543 \f
22544 /* Mark the early DIE for DECL as the abstract instance.  */
22545
22546 static void
22547 dwarf2out_abstract_function (tree decl)
22548 {
22549   dw_die_ref old_die;
22550
22551   /* Make sure we have the actual abstract inline, not a clone.  */
22552   decl = DECL_ORIGIN (decl);
22553
22554   if (DECL_IGNORED_P (decl))
22555     return;
22556
22557   old_die = lookup_decl_die (decl);
22558   /* With early debug we always have an old DIE unless we are in LTO
22559      and the user did not compile but only link with debug.  */
22560   if (in_lto_p && ! old_die)
22561     return;
22562   gcc_assert (old_die != NULL);
22563   if (get_AT (old_die, DW_AT_inline)
22564       || get_AT (old_die, DW_AT_abstract_origin))
22565     /* We've already generated the abstract instance.  */
22566     return;
22567
22568   /* Go ahead and put DW_AT_inline on the DIE.  */
22569   if (DECL_DECLARED_INLINE_P (decl))
22570     {
22571       if (cgraph_function_possibly_inlined_p (decl))
22572         add_AT_unsigned (old_die, DW_AT_inline, DW_INL_declared_inlined);
22573       else
22574         add_AT_unsigned (old_die, DW_AT_inline, DW_INL_declared_not_inlined);
22575     }
22576   else
22577     {
22578       if (cgraph_function_possibly_inlined_p (decl))
22579         add_AT_unsigned (old_die, DW_AT_inline, DW_INL_inlined);
22580       else
22581         add_AT_unsigned (old_die, DW_AT_inline, DW_INL_not_inlined);
22582     }
22583
22584   if (DECL_DECLARED_INLINE_P (decl)
22585       && lookup_attribute ("artificial", DECL_ATTRIBUTES (decl)))
22586     add_AT_flag (old_die, DW_AT_artificial, 1);
22587
22588   set_decl_origin_self (decl);
22589 }
22590
22591 /* Helper function of premark_used_types() which gets called through
22592    htab_traverse.
22593
22594    Marks the DIE of a given type in *SLOT as perennial, so it never gets
22595    marked as unused by prune_unused_types.  */
22596
22597 bool
22598 premark_used_types_helper (tree const &type, void *)
22599 {
22600   dw_die_ref die;
22601
22602   die = lookup_type_die (type);
22603   if (die != NULL)
22604     die->die_perennial_p = 1;
22605   return true;
22606 }
22607
22608 /* Helper function of premark_types_used_by_global_vars which gets called
22609    through htab_traverse.
22610
22611    Marks the DIE of a given type in *SLOT as perennial, so it never gets
22612    marked as unused by prune_unused_types. The DIE of the type is marked
22613    only if the global variable using the type will actually be emitted.  */
22614
22615 int
22616 premark_types_used_by_global_vars_helper (types_used_by_vars_entry **slot,
22617                                           void *)
22618 {
22619   struct types_used_by_vars_entry *entry;
22620   dw_die_ref die;
22621
22622   entry = (struct types_used_by_vars_entry *) *slot;
22623   gcc_assert (entry->type != NULL
22624               && entry->var_decl != NULL);
22625   die = lookup_type_die (entry->type);
22626   if (die)
22627     {
22628       /* Ask cgraph if the global variable really is to be emitted.
22629          If yes, then we'll keep the DIE of ENTRY->TYPE.  */
22630       varpool_node *node = varpool_node::get (entry->var_decl);
22631       if (node && node->definition)
22632         {
22633           die->die_perennial_p = 1;
22634           /* Keep the parent DIEs as well.  */
22635           while ((die = die->die_parent) && die->die_perennial_p == 0)
22636             die->die_perennial_p = 1;
22637         }
22638     }
22639   return 1;
22640 }
22641
22642 /* Mark all members of used_types_hash as perennial.  */
22643
22644 static void
22645 premark_used_types (struct function *fun)
22646 {
22647   if (fun && fun->used_types_hash)
22648     fun->used_types_hash->traverse<void *, premark_used_types_helper> (NULL);
22649 }
22650
22651 /* Mark all members of types_used_by_vars_entry as perennial.  */
22652
22653 static void
22654 premark_types_used_by_global_vars (void)
22655 {
22656   if (types_used_by_vars_hash)
22657     types_used_by_vars_hash
22658       ->traverse<void *, premark_types_used_by_global_vars_helper> (NULL);
22659 }
22660
22661 /* Generate a DW_TAG_call_site DIE in function DECL under SUBR_DIE
22662    for CA_LOC call arg loc node.  */
22663
22664 static dw_die_ref
22665 gen_call_site_die (tree decl, dw_die_ref subr_die,
22666                    struct call_arg_loc_node *ca_loc)
22667 {
22668   dw_die_ref stmt_die = NULL, die;
22669   tree block = ca_loc->block;
22670
22671   while (block
22672          && block != DECL_INITIAL (decl)
22673          && TREE_CODE (block) == BLOCK)
22674     {
22675       stmt_die = BLOCK_DIE (block);
22676       if (stmt_die)
22677         break;
22678       block = BLOCK_SUPERCONTEXT (block);
22679     }
22680   if (stmt_die == NULL)
22681     stmt_die = subr_die;
22682   die = new_die (dwarf_TAG (DW_TAG_call_site), stmt_die, NULL_TREE);
22683   add_AT_lbl_id (die, dwarf_AT (DW_AT_call_return_pc), ca_loc->label);
22684   if (ca_loc->tail_call_p)
22685     add_AT_flag (die, dwarf_AT (DW_AT_call_tail_call), 1);
22686   if (ca_loc->symbol_ref)
22687     {
22688       dw_die_ref tdie = lookup_decl_die (SYMBOL_REF_DECL (ca_loc->symbol_ref));
22689       if (tdie)
22690         add_AT_die_ref (die, dwarf_AT (DW_AT_call_origin), tdie);
22691       else
22692         add_AT_addr (die, dwarf_AT (DW_AT_call_origin), ca_loc->symbol_ref,
22693                      false);
22694     }
22695   return die;
22696 }
22697
22698 /* Generate a DIE to represent a declared function (either file-scope or
22699    block-local).  */
22700
22701 static void
22702 gen_subprogram_die (tree decl, dw_die_ref context_die)
22703 {
22704   tree origin = decl_ultimate_origin (decl);
22705   dw_die_ref subr_die;
22706   dw_die_ref old_die = lookup_decl_die (decl);
22707
22708   /* This function gets called multiple times for different stages of
22709      the debug process.  For example, for func() in this code:
22710
22711         namespace S
22712         {
22713           void func() { ... }
22714         }
22715
22716      ...we get called 4 times.  Twice in early debug and twice in
22717      late debug:
22718
22719      Early debug
22720      -----------
22721
22722        1. Once while generating func() within the namespace.  This is
22723           the declaration.  The declaration bit below is set, as the
22724           context is the namespace.
22725
22726           A new DIE will be generated with DW_AT_declaration set.
22727
22728        2. Once for func() itself.  This is the specification.  The
22729           declaration bit below is clear as the context is the CU.
22730
22731           We will use the cached DIE from (1) to create a new DIE with
22732           DW_AT_specification pointing to the declaration in (1).
22733
22734      Late debug via rest_of_handle_final()
22735      -------------------------------------
22736
22737        3. Once generating func() within the namespace.  This is also the
22738           declaration, as in (1), but this time we will early exit below
22739           as we have a cached DIE and a declaration needs no additional
22740           annotations (no locations), as the source declaration line
22741           info is enough.
22742
22743        4. Once for func() itself.  As in (2), this is the specification,
22744           but this time we will re-use the cached DIE, and just annotate
22745           it with the location information that should now be available.
22746
22747      For something without namespaces, but with abstract instances, we
22748      are also called a multiple times:
22749
22750         class Base
22751         {
22752         public:
22753           Base ();        // constructor declaration (1)
22754         };
22755
22756         Base::Base () { } // constructor specification (2)
22757
22758     Early debug
22759     -----------
22760
22761        1. Once for the Base() constructor by virtue of it being a
22762           member of the Base class.  This is done via
22763           rest_of_type_compilation.
22764
22765           This is a declaration, so a new DIE will be created with
22766           DW_AT_declaration.
22767
22768        2. Once for the Base() constructor definition, but this time
22769           while generating the abstract instance of the base
22770           constructor (__base_ctor) which is being generated via early
22771           debug of reachable functions.
22772
22773           Even though we have a cached version of the declaration (1),
22774           we will create a DW_AT_specification of the declaration DIE
22775           in (1).
22776
22777        3. Once for the __base_ctor itself, but this time, we generate
22778           an DW_AT_abstract_origin version of the DW_AT_specification in
22779           (2).
22780
22781     Late debug via rest_of_handle_final
22782     -----------------------------------
22783
22784        4. One final time for the __base_ctor (which will have a cached
22785           DIE with DW_AT_abstract_origin created in (3).  This time,
22786           we will just annotate the location information now
22787           available.
22788   */
22789   int declaration = (current_function_decl != decl
22790                      || class_or_namespace_scope_p (context_die));
22791
22792   /* A declaration that has been previously dumped needs no
22793      additional information.  */
22794   if (old_die && declaration)
22795     return;
22796
22797   /* Now that the C++ front end lazily declares artificial member fns, we
22798      might need to retrofit the declaration into its class.  */
22799   if (!declaration && !origin && !old_die
22800       && DECL_CONTEXT (decl) && TYPE_P (DECL_CONTEXT (decl))
22801       && !class_or_namespace_scope_p (context_die)
22802       && debug_info_level > DINFO_LEVEL_TERSE)
22803     old_die = force_decl_die (decl);
22804
22805   /* A concrete instance, tag a new DIE with DW_AT_abstract_origin.  */
22806   if (origin != NULL)
22807     {
22808       gcc_assert (!declaration || local_scope_p (context_die));
22809
22810       /* Fixup die_parent for the abstract instance of a nested
22811          inline function.  */
22812       if (old_die && old_die->die_parent == NULL)
22813         add_child_die (context_die, old_die);
22814
22815       if (old_die && get_AT_ref (old_die, DW_AT_abstract_origin))
22816         {
22817           /* If we have a DW_AT_abstract_origin we have a working
22818              cached version.  */
22819           subr_die = old_die;
22820         }
22821       else
22822         {
22823           subr_die = new_die (DW_TAG_subprogram, context_die, decl);
22824           add_abstract_origin_attribute (subr_die, origin);
22825           /*  This is where the actual code for a cloned function is.
22826               Let's emit linkage name attribute for it.  This helps
22827               debuggers to e.g, set breakpoints into
22828               constructors/destructors when the user asks "break
22829               K::K".  */
22830           add_linkage_name (subr_die, decl);
22831         }
22832     }
22833   /* A cached copy, possibly from early dwarf generation.  Reuse as
22834      much as possible.  */
22835   else if (old_die)
22836     {
22837       if (!get_AT_flag (old_die, DW_AT_declaration)
22838           /* We can have a normal definition following an inline one in the
22839              case of redefinition of GNU C extern inlines.
22840              It seems reasonable to use AT_specification in this case.  */
22841           && !get_AT (old_die, DW_AT_inline))
22842         {
22843           /* Detect and ignore this case, where we are trying to output
22844              something we have already output.  */
22845           if (get_AT (old_die, DW_AT_low_pc)
22846               || get_AT (old_die, DW_AT_ranges))
22847             return;
22848
22849           /* If we have no location information, this must be a
22850              partially generated DIE from early dwarf generation.
22851              Fall through and generate it.  */
22852         }
22853
22854       /* If the definition comes from the same place as the declaration,
22855          maybe use the old DIE.  We always want the DIE for this function
22856          that has the *_pc attributes to be under comp_unit_die so the
22857          debugger can find it.  We also need to do this for abstract
22858          instances of inlines, since the spec requires the out-of-line copy
22859          to have the same parent.  For local class methods, this doesn't
22860          apply; we just use the old DIE.  */
22861       expanded_location s = expand_location (DECL_SOURCE_LOCATION (decl));
22862       struct dwarf_file_data * file_index = lookup_filename (s.file);
22863       if ((is_cu_die (old_die->die_parent)
22864            /* This condition fixes the inconsistency/ICE with the
22865               following Fortran test (or some derivative thereof) while
22866               building libgfortran:
22867
22868                  module some_m
22869                  contains
22870                     logical function funky (FLAG)
22871                       funky = .true.
22872                    end function
22873                  end module
22874            */
22875            || (old_die->die_parent
22876                && old_die->die_parent->die_tag == DW_TAG_module)
22877            || context_die == NULL)
22878            && (DECL_ARTIFICIAL (decl)
22879                /* The location attributes may be in the abstract origin
22880                   which in the case of LTO might be not available to
22881                   look at.  */
22882                || get_AT (old_die, DW_AT_abstract_origin)
22883                || (get_AT_file (old_die, DW_AT_decl_file) == file_index
22884                    && (get_AT_unsigned (old_die, DW_AT_decl_line)
22885                        == (unsigned) s.line)
22886                    && (!debug_column_info
22887                        || s.column == 0
22888                        || (get_AT_unsigned (old_die, DW_AT_decl_column)
22889                            == (unsigned) s.column)))))
22890         {
22891           subr_die = old_die;
22892
22893           /* Clear out the declaration attribute, but leave the
22894              parameters so they can be augmented with location
22895              information later.  Unless this was a declaration, in
22896              which case, wipe out the nameless parameters and recreate
22897              them further down.  */
22898           if (remove_AT (subr_die, DW_AT_declaration))
22899             {
22900
22901               remove_AT (subr_die, DW_AT_object_pointer);
22902               remove_child_TAG (subr_die, DW_TAG_formal_parameter);
22903             }
22904         }
22905       /* Make a specification pointing to the previously built
22906          declaration.  */
22907       else
22908         {
22909           subr_die = new_die (DW_TAG_subprogram, context_die, decl);
22910           add_AT_specification (subr_die, old_die);
22911           add_pubname (decl, subr_die);
22912           if (get_AT_file (old_die, DW_AT_decl_file) != file_index)
22913             add_AT_file (subr_die, DW_AT_decl_file, file_index);
22914           if (get_AT_unsigned (old_die, DW_AT_decl_line) != (unsigned) s.line)
22915             add_AT_unsigned (subr_die, DW_AT_decl_line, s.line);
22916           if (debug_column_info
22917               && s.column
22918               && (get_AT_unsigned (old_die, DW_AT_decl_column)
22919                   != (unsigned) s.column))
22920             add_AT_unsigned (subr_die, DW_AT_decl_column, s.column);
22921
22922           /* If the prototype had an 'auto' or 'decltype(auto)' return type,
22923              emit the real type on the definition die.  */
22924           if (is_cxx () && debug_info_level > DINFO_LEVEL_TERSE)
22925             {
22926               dw_die_ref die = get_AT_ref (old_die, DW_AT_type);
22927               if (die == auto_die || die == decltype_auto_die)
22928                 add_type_attribute (subr_die, TREE_TYPE (TREE_TYPE (decl)),
22929                                     TYPE_UNQUALIFIED, false, context_die);
22930             }
22931
22932           /* When we process the method declaration, we haven't seen
22933              the out-of-class defaulted definition yet, so we have to
22934              recheck now.  */
22935           if ((dwarf_version >= 5 || ! dwarf_strict)
22936               && !get_AT (subr_die, DW_AT_defaulted))
22937             {
22938               int defaulted
22939                 = lang_hooks.decls.decl_dwarf_attribute (decl,
22940                                                          DW_AT_defaulted);
22941               if (defaulted != -1)
22942                 {
22943                   /* Other values must have been handled before.  */
22944                   gcc_assert (defaulted == DW_DEFAULTED_out_of_class);
22945                   add_AT_unsigned (subr_die, DW_AT_defaulted, defaulted);
22946                 }
22947             }
22948         }
22949     }
22950   /* Create a fresh DIE for anything else.  */
22951   else
22952     {
22953       subr_die = new_die (DW_TAG_subprogram, context_die, decl);
22954
22955       if (TREE_PUBLIC (decl))
22956         add_AT_flag (subr_die, DW_AT_external, 1);
22957
22958       add_name_and_src_coords_attributes (subr_die, decl);
22959       add_pubname (decl, subr_die);
22960       if (debug_info_level > DINFO_LEVEL_TERSE)
22961         {
22962           add_prototyped_attribute (subr_die, TREE_TYPE (decl));
22963           add_type_attribute (subr_die, TREE_TYPE (TREE_TYPE (decl)),
22964                               TYPE_UNQUALIFIED, false, context_die);
22965         }
22966
22967       add_pure_or_virtual_attribute (subr_die, decl);
22968       if (DECL_ARTIFICIAL (decl))
22969         add_AT_flag (subr_die, DW_AT_artificial, 1);
22970
22971       if (TREE_THIS_VOLATILE (decl) && (dwarf_version >= 5 || !dwarf_strict))
22972         add_AT_flag (subr_die, DW_AT_noreturn, 1);
22973
22974       add_alignment_attribute (subr_die, decl);
22975
22976       add_accessibility_attribute (subr_die, decl);
22977     }
22978
22979   /* Unless we have an existing non-declaration DIE, equate the new
22980      DIE.  */
22981   if (!old_die || is_declaration_die (old_die))
22982     equate_decl_number_to_die (decl, subr_die);
22983
22984   if (declaration)
22985     {
22986       if (!old_die || !get_AT (old_die, DW_AT_inline))
22987         {
22988           add_AT_flag (subr_die, DW_AT_declaration, 1);
22989
22990           /* If this is an explicit function declaration then generate
22991              a DW_AT_explicit attribute.  */
22992           if ((dwarf_version >= 3 || !dwarf_strict)
22993               && lang_hooks.decls.decl_dwarf_attribute (decl,
22994                                                         DW_AT_explicit) == 1)
22995             add_AT_flag (subr_die, DW_AT_explicit, 1);
22996
22997           /* If this is a C++11 deleted special function member then generate
22998              a DW_AT_deleted attribute.  */
22999           if ((dwarf_version >= 5 || !dwarf_strict)
23000               && lang_hooks.decls.decl_dwarf_attribute (decl,
23001                                                         DW_AT_deleted) == 1)
23002             add_AT_flag (subr_die, DW_AT_deleted, 1);
23003
23004           /* If this is a C++11 defaulted special function member then
23005              generate a DW_AT_defaulted attribute.  */
23006           if (dwarf_version >= 5 || !dwarf_strict)
23007             {
23008               int defaulted
23009                 = lang_hooks.decls.decl_dwarf_attribute (decl,
23010                                                          DW_AT_defaulted);
23011               if (defaulted != -1)
23012                 add_AT_unsigned (subr_die, DW_AT_defaulted, defaulted);
23013             }
23014
23015           /* If this is a C++11 non-static member function with & ref-qualifier
23016              then generate a DW_AT_reference attribute.  */
23017           if ((dwarf_version >= 5 || !dwarf_strict)
23018               && lang_hooks.decls.decl_dwarf_attribute (decl,
23019                                                         DW_AT_reference) == 1)
23020             add_AT_flag (subr_die, DW_AT_reference, 1);
23021
23022           /* If this is a C++11 non-static member function with &&
23023              ref-qualifier then generate a DW_AT_reference attribute.  */
23024           if ((dwarf_version >= 5 || !dwarf_strict)
23025               && lang_hooks.decls.decl_dwarf_attribute (decl,
23026                                                         DW_AT_rvalue_reference)
23027                  == 1)
23028             add_AT_flag (subr_die, DW_AT_rvalue_reference, 1);
23029         }
23030     }
23031   /* For non DECL_EXTERNALs, if range information is available, fill
23032      the DIE with it.  */
23033   else if (!DECL_EXTERNAL (decl) && !early_dwarf)
23034     {
23035       HOST_WIDE_INT cfa_fb_offset;
23036
23037       struct function *fun = DECL_STRUCT_FUNCTION (decl);
23038
23039       if (!crtl->has_bb_partition)
23040         {
23041           dw_fde_ref fde = fun->fde;
23042           if (fde->dw_fde_begin)
23043             {
23044               /* We have already generated the labels.  */
23045              add_AT_low_high_pc (subr_die, fde->dw_fde_begin,
23046                                  fde->dw_fde_end, false);
23047             }
23048           else
23049             {
23050               /* Create start/end labels and add the range.  */
23051               char label_id_low[MAX_ARTIFICIAL_LABEL_BYTES];
23052               char label_id_high[MAX_ARTIFICIAL_LABEL_BYTES];
23053               ASM_GENERATE_INTERNAL_LABEL (label_id_low, FUNC_BEGIN_LABEL,
23054                                            current_function_funcdef_no);
23055               ASM_GENERATE_INTERNAL_LABEL (label_id_high, FUNC_END_LABEL,
23056                                            current_function_funcdef_no);
23057              add_AT_low_high_pc (subr_die, label_id_low, label_id_high,
23058                                  false);
23059             }
23060
23061 #if VMS_DEBUGGING_INFO
23062       /* HP OpenVMS Industry Standard 64: DWARF Extensions
23063          Section 2.3 Prologue and Epilogue Attributes:
23064          When a breakpoint is set on entry to a function, it is generally
23065          desirable for execution to be suspended, not on the very first
23066          instruction of the function, but rather at a point after the
23067          function's frame has been set up, after any language defined local
23068          declaration processing has been completed, and before execution of
23069          the first statement of the function begins. Debuggers generally
23070          cannot properly determine where this point is.  Similarly for a
23071          breakpoint set on exit from a function. The prologue and epilogue
23072          attributes allow a compiler to communicate the location(s) to use.  */
23073
23074       {
23075         if (fde->dw_fde_vms_end_prologue)
23076           add_AT_vms_delta (subr_die, DW_AT_HP_prologue,
23077             fde->dw_fde_begin, fde->dw_fde_vms_end_prologue);
23078
23079         if (fde->dw_fde_vms_begin_epilogue)
23080           add_AT_vms_delta (subr_die, DW_AT_HP_epilogue,
23081             fde->dw_fde_begin, fde->dw_fde_vms_begin_epilogue);
23082       }
23083 #endif
23084
23085         }
23086       else
23087         {
23088           /* Generate pubnames entries for the split function code ranges.  */
23089           dw_fde_ref fde = fun->fde;
23090
23091           if (fde->dw_fde_second_begin)
23092             {
23093               if (dwarf_version >= 3 || !dwarf_strict)
23094                 {
23095                   /* We should use ranges for non-contiguous code section 
23096                      addresses.  Use the actual code range for the initial
23097                      section, since the HOT/COLD labels might precede an 
23098                      alignment offset.  */
23099                   bool range_list_added = false;
23100                   add_ranges_by_labels (subr_die, fde->dw_fde_begin,
23101                                         fde->dw_fde_end, &range_list_added,
23102                                         false);
23103                   add_ranges_by_labels (subr_die, fde->dw_fde_second_begin,
23104                                         fde->dw_fde_second_end,
23105                                         &range_list_added, false);
23106                   if (range_list_added)
23107                     add_ranges (NULL);
23108                 }
23109               else
23110                 {
23111                   /* There is no real support in DW2 for this .. so we make
23112                      a work-around.  First, emit the pub name for the segment
23113                      containing the function label.  Then make and emit a
23114                      simplified subprogram DIE for the second segment with the
23115                      name pre-fixed by __hot/cold_sect_of_.  We use the same
23116                      linkage name for the second die so that gdb will find both
23117                      sections when given "b foo".  */
23118                   const char *name = NULL;
23119                   tree decl_name = DECL_NAME (decl);
23120                   dw_die_ref seg_die;
23121
23122                   /* Do the 'primary' section.   */
23123                   add_AT_low_high_pc (subr_die, fde->dw_fde_begin,
23124                                       fde->dw_fde_end, false);
23125
23126                   /* Build a minimal DIE for the secondary section.  */
23127                   seg_die = new_die (DW_TAG_subprogram,
23128                                      subr_die->die_parent, decl);
23129
23130                   if (TREE_PUBLIC (decl))
23131                     add_AT_flag (seg_die, DW_AT_external, 1);
23132
23133                   if (decl_name != NULL 
23134                       && IDENTIFIER_POINTER (decl_name) != NULL)
23135                     {
23136                       name = dwarf2_name (decl, 1);
23137                       if (! DECL_ARTIFICIAL (decl))
23138                         add_src_coords_attributes (seg_die, decl);
23139
23140                       add_linkage_name (seg_die, decl);
23141                     }
23142                   gcc_assert (name != NULL);
23143                   add_pure_or_virtual_attribute (seg_die, decl);
23144                   if (DECL_ARTIFICIAL (decl))
23145                     add_AT_flag (seg_die, DW_AT_artificial, 1);
23146
23147                   name = concat ("__second_sect_of_", name, NULL); 
23148                   add_AT_low_high_pc (seg_die, fde->dw_fde_second_begin,
23149                                       fde->dw_fde_second_end, false);
23150                   add_name_attribute (seg_die, name);
23151                   if (want_pubnames ())
23152                     add_pubname_string (name, seg_die);
23153                 }
23154             }
23155           else
23156            add_AT_low_high_pc (subr_die, fde->dw_fde_begin, fde->dw_fde_end,
23157                                false);
23158         }
23159
23160       cfa_fb_offset = CFA_FRAME_BASE_OFFSET (decl);
23161
23162       /* We define the "frame base" as the function's CFA.  This is more
23163          convenient for several reasons: (1) It's stable across the prologue
23164          and epilogue, which makes it better than just a frame pointer,
23165          (2) With dwarf3, there exists a one-byte encoding that allows us
23166          to reference the .debug_frame data by proxy, but failing that,
23167          (3) We can at least reuse the code inspection and interpretation
23168          code that determines the CFA position at various points in the
23169          function.  */
23170       if (dwarf_version >= 3 && targetm.debug_unwind_info () == UI_DWARF2)
23171         {
23172           dw_loc_descr_ref op = new_loc_descr (DW_OP_call_frame_cfa, 0, 0);
23173           add_AT_loc (subr_die, DW_AT_frame_base, op);
23174         }
23175       else
23176         {
23177           dw_loc_list_ref list = convert_cfa_to_fb_loc_list (cfa_fb_offset);
23178           if (list->dw_loc_next)
23179             add_AT_loc_list (subr_die, DW_AT_frame_base, list);
23180           else
23181             add_AT_loc (subr_die, DW_AT_frame_base, list->expr);
23182         }
23183
23184       /* Compute a displacement from the "steady-state frame pointer" to
23185          the CFA.  The former is what all stack slots and argument slots
23186          will reference in the rtl; the latter is what we've told the
23187          debugger about.  We'll need to adjust all frame_base references
23188          by this displacement.  */
23189       compute_frame_pointer_to_fb_displacement (cfa_fb_offset);
23190
23191       if (fun->static_chain_decl)
23192         {
23193           /* DWARF requires here a location expression that computes the
23194              address of the enclosing subprogram's frame base.  The machinery
23195              in tree-nested.c is supposed to store this specific address in the
23196              last field of the FRAME record.  */
23197           const tree frame_type
23198             = TREE_TYPE (TREE_TYPE (fun->static_chain_decl));
23199           const tree fb_decl = tree_last (TYPE_FIELDS (frame_type));
23200
23201           tree fb_expr
23202             = build1 (INDIRECT_REF, frame_type, fun->static_chain_decl);
23203           fb_expr = build3 (COMPONENT_REF, TREE_TYPE (fb_decl),
23204                             fb_expr, fb_decl, NULL_TREE);
23205
23206           add_AT_location_description (subr_die, DW_AT_static_link,
23207                                        loc_list_from_tree (fb_expr, 0, NULL));
23208         }
23209
23210       resolve_variable_values ();
23211     }
23212
23213   /* Generate child dies for template paramaters.  */
23214   if (early_dwarf && debug_info_level > DINFO_LEVEL_TERSE)
23215     gen_generic_params_dies (decl);
23216
23217   /* Now output descriptions of the arguments for this function. This gets
23218      (unnecessarily?) complex because of the fact that the DECL_ARGUMENT list
23219      for a FUNCTION_DECL doesn't indicate cases where there was a trailing
23220      `...' at the end of the formal parameter list.  In order to find out if
23221      there was a trailing ellipsis or not, we must instead look at the type
23222      associated with the FUNCTION_DECL.  This will be a node of type
23223      FUNCTION_TYPE. If the chain of type nodes hanging off of this
23224      FUNCTION_TYPE node ends with a void_type_node then there should *not* be
23225      an ellipsis at the end.  */
23226
23227   /* In the case where we are describing a mere function declaration, all we
23228      need to do here (and all we *can* do here) is to describe the *types* of
23229      its formal parameters.  */
23230   if (debug_info_level <= DINFO_LEVEL_TERSE)
23231     ;
23232   else if (declaration)
23233     gen_formal_types_die (decl, subr_die);
23234   else
23235     {
23236       /* Generate DIEs to represent all known formal parameters.  */
23237       tree parm = DECL_ARGUMENTS (decl);
23238       tree generic_decl = early_dwarf
23239         ? lang_hooks.decls.get_generic_function_decl (decl) : NULL;
23240       tree generic_decl_parm = generic_decl
23241                                 ? DECL_ARGUMENTS (generic_decl)
23242                                 : NULL;
23243
23244       /* Now we want to walk the list of parameters of the function and
23245          emit their relevant DIEs.
23246
23247          We consider the case of DECL being an instance of a generic function
23248          as well as it being a normal function.
23249
23250          If DECL is an instance of a generic function we walk the
23251          parameters of the generic function declaration _and_ the parameters of
23252          DECL itself. This is useful because we want to emit specific DIEs for
23253          function parameter packs and those are declared as part of the
23254          generic function declaration. In that particular case,
23255          the parameter pack yields a DW_TAG_GNU_formal_parameter_pack DIE.
23256          That DIE has children DIEs representing the set of arguments
23257          of the pack. Note that the set of pack arguments can be empty.
23258          In that case, the DW_TAG_GNU_formal_parameter_pack DIE will not have any
23259          children DIE.
23260
23261          Otherwise, we just consider the parameters of DECL.  */
23262       while (generic_decl_parm || parm)
23263         {
23264           if (generic_decl_parm
23265               && lang_hooks.function_parameter_pack_p (generic_decl_parm))
23266             gen_formal_parameter_pack_die (generic_decl_parm,
23267                                            parm, subr_die,
23268                                            &parm);
23269           else if (parm && !POINTER_BOUNDS_P (parm))
23270             {
23271               dw_die_ref parm_die = gen_decl_die (parm, NULL, NULL, subr_die);
23272
23273               if (early_dwarf
23274                   && parm == DECL_ARGUMENTS (decl)
23275                   && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE
23276                   && parm_die
23277                   && (dwarf_version >= 3 || !dwarf_strict))
23278                 add_AT_die_ref (subr_die, DW_AT_object_pointer, parm_die);
23279
23280               parm = DECL_CHAIN (parm);
23281             }
23282           else if (parm)
23283             parm = DECL_CHAIN (parm);
23284
23285           if (generic_decl_parm)
23286             generic_decl_parm = DECL_CHAIN (generic_decl_parm);
23287         }
23288
23289       /* Decide whether we need an unspecified_parameters DIE at the end.
23290          There are 2 more cases to do this for: 1) the ansi ... declaration -
23291          this is detectable when the end of the arg list is not a
23292          void_type_node 2) an unprototyped function declaration (not a
23293          definition).  This just means that we have no info about the
23294          parameters at all.  */
23295       if (early_dwarf)
23296         {
23297           if (prototype_p (TREE_TYPE (decl)))
23298             {
23299               /* This is the prototyped case, check for....  */
23300               if (stdarg_p (TREE_TYPE (decl)))
23301                 gen_unspecified_parameters_die (decl, subr_die);
23302             }
23303           else if (DECL_INITIAL (decl) == NULL_TREE)
23304             gen_unspecified_parameters_die (decl, subr_die);
23305         }
23306     }
23307
23308   if (subr_die != old_die)
23309     /* Add the calling convention attribute if requested.  */
23310     add_calling_convention_attribute (subr_die, decl);
23311
23312   /* Output Dwarf info for all of the stuff within the body of the function
23313      (if it has one - it may be just a declaration).
23314
23315      OUTER_SCOPE is a pointer to the outermost BLOCK node created to represent
23316      a function.  This BLOCK actually represents the outermost binding contour
23317      for the function, i.e. the contour in which the function's formal
23318      parameters and labels get declared. Curiously, it appears that the front
23319      end doesn't actually put the PARM_DECL nodes for the current function onto
23320      the BLOCK_VARS list for this outer scope, but are strung off of the
23321      DECL_ARGUMENTS list for the function instead.
23322
23323      The BLOCK_VARS list for the `outer_scope' does provide us with a list of
23324      the LABEL_DECL nodes for the function however, and we output DWARF info
23325      for those in decls_for_scope.  Just within the `outer_scope' there will be
23326      a BLOCK node representing the function's outermost pair of curly braces,
23327      and any blocks used for the base and member initializers of a C++
23328      constructor function.  */
23329   tree outer_scope = DECL_INITIAL (decl);
23330   if (! declaration && outer_scope && TREE_CODE (outer_scope) != ERROR_MARK)
23331     {
23332       int call_site_note_count = 0;
23333       int tail_call_site_note_count = 0;
23334
23335       /* Emit a DW_TAG_variable DIE for a named return value.  */
23336       if (DECL_NAME (DECL_RESULT (decl)))
23337         gen_decl_die (DECL_RESULT (decl), NULL, NULL, subr_die);
23338
23339       /* The first time through decls_for_scope we will generate the
23340          DIEs for the locals.  The second time, we fill in the
23341          location info.  */
23342       decls_for_scope (outer_scope, subr_die);
23343
23344       if (call_arg_locations && (!dwarf_strict || dwarf_version >= 5))
23345         {
23346           struct call_arg_loc_node *ca_loc;
23347           for (ca_loc = call_arg_locations; ca_loc; ca_loc = ca_loc->next)
23348             {
23349               dw_die_ref die = NULL;
23350               rtx tloc = NULL_RTX, tlocc = NULL_RTX;
23351               rtx arg, next_arg;
23352
23353               for (arg = (ca_loc->call_arg_loc_note != NULL_RTX
23354                           ? XEXP (ca_loc->call_arg_loc_note, 0)
23355                           : NULL_RTX);
23356                    arg; arg = next_arg)
23357                 {
23358                   dw_loc_descr_ref reg, val;
23359                   machine_mode mode = GET_MODE (XEXP (XEXP (arg, 0), 1));
23360                   dw_die_ref cdie, tdie = NULL;
23361
23362                   next_arg = XEXP (arg, 1);
23363                   if (REG_P (XEXP (XEXP (arg, 0), 0))
23364                       && next_arg
23365                       && MEM_P (XEXP (XEXP (next_arg, 0), 0))
23366                       && REG_P (XEXP (XEXP (XEXP (next_arg, 0), 0), 0))
23367                       && REGNO (XEXP (XEXP (arg, 0), 0))
23368                          == REGNO (XEXP (XEXP (XEXP (next_arg, 0), 0), 0)))
23369                     next_arg = XEXP (next_arg, 1);
23370                   if (mode == VOIDmode)
23371                     {
23372                       mode = GET_MODE (XEXP (XEXP (arg, 0), 0));
23373                       if (mode == VOIDmode)
23374                         mode = GET_MODE (XEXP (arg, 0));
23375                     }
23376                   if (mode == VOIDmode || mode == BLKmode)
23377                     continue;
23378                   /* Get dynamic information about call target only if we
23379                      have no static information: we cannot generate both
23380                      DW_AT_call_origin and DW_AT_call_target
23381                      attributes.  */
23382                   if (ca_loc->symbol_ref == NULL_RTX)
23383                     {
23384                       if (XEXP (XEXP (arg, 0), 0) == pc_rtx)
23385                         {
23386                           tloc = XEXP (XEXP (arg, 0), 1);
23387                           continue;
23388                         }
23389                       else if (GET_CODE (XEXP (XEXP (arg, 0), 0)) == CLOBBER
23390                                && XEXP (XEXP (XEXP (arg, 0), 0), 0) == pc_rtx)
23391                         {
23392                           tlocc = XEXP (XEXP (arg, 0), 1);
23393                           continue;
23394                         }
23395                     }
23396                   reg = NULL;
23397                   if (REG_P (XEXP (XEXP (arg, 0), 0)))
23398                     reg = reg_loc_descriptor (XEXP (XEXP (arg, 0), 0),
23399                                               VAR_INIT_STATUS_INITIALIZED);
23400                   else if (MEM_P (XEXP (XEXP (arg, 0), 0)))
23401                     {
23402                       rtx mem = XEXP (XEXP (arg, 0), 0);
23403                       reg = mem_loc_descriptor (XEXP (mem, 0),
23404                                                 get_address_mode (mem),
23405                                                 GET_MODE (mem),
23406                                                 VAR_INIT_STATUS_INITIALIZED);
23407                     }
23408                   else if (GET_CODE (XEXP (XEXP (arg, 0), 0))
23409                            == DEBUG_PARAMETER_REF)
23410                     {
23411                       tree tdecl
23412                         = DEBUG_PARAMETER_REF_DECL (XEXP (XEXP (arg, 0), 0));
23413                       tdie = lookup_decl_die (tdecl);
23414                       if (tdie == NULL)
23415                         continue;
23416                     }
23417                   else
23418                     continue;
23419                   if (reg == NULL
23420                       && GET_CODE (XEXP (XEXP (arg, 0), 0))
23421                          != DEBUG_PARAMETER_REF)
23422                     continue;
23423                   val = mem_loc_descriptor (XEXP (XEXP (arg, 0), 1), mode,
23424                                             VOIDmode,
23425                                             VAR_INIT_STATUS_INITIALIZED);
23426                   if (val == NULL)
23427                     continue;
23428                   if (die == NULL)
23429                     die = gen_call_site_die (decl, subr_die, ca_loc);
23430                   cdie = new_die (dwarf_TAG (DW_TAG_call_site_parameter), die,
23431                                   NULL_TREE);
23432                   if (reg != NULL)
23433                     add_AT_loc (cdie, DW_AT_location, reg);
23434                   else if (tdie != NULL)
23435                     add_AT_die_ref (cdie, dwarf_AT (DW_AT_call_parameter),
23436                                     tdie);
23437                   add_AT_loc (cdie, dwarf_AT (DW_AT_call_value), val);
23438                   if (next_arg != XEXP (arg, 1))
23439                     {
23440                       mode = GET_MODE (XEXP (XEXP (XEXP (arg, 1), 0), 1));
23441                       if (mode == VOIDmode)
23442                         mode = GET_MODE (XEXP (XEXP (XEXP (arg, 1), 0), 0));
23443                       val = mem_loc_descriptor (XEXP (XEXP (XEXP (arg, 1),
23444                                                             0), 1),
23445                                                 mode, VOIDmode,
23446                                                 VAR_INIT_STATUS_INITIALIZED);
23447                       if (val != NULL)
23448                         add_AT_loc (cdie, dwarf_AT (DW_AT_call_data_value),
23449                                     val);
23450                     }
23451                 }
23452               if (die == NULL
23453                   && (ca_loc->symbol_ref || tloc))
23454                 die = gen_call_site_die (decl, subr_die, ca_loc);
23455               if (die != NULL && (tloc != NULL_RTX || tlocc != NULL_RTX))
23456                 {
23457                   dw_loc_descr_ref tval = NULL;
23458
23459                   if (tloc != NULL_RTX)
23460                     tval = mem_loc_descriptor (tloc,
23461                                                GET_MODE (tloc) == VOIDmode
23462                                                ? Pmode : GET_MODE (tloc),
23463                                                VOIDmode,
23464                                                VAR_INIT_STATUS_INITIALIZED);
23465                   if (tval)
23466                     add_AT_loc (die, dwarf_AT (DW_AT_call_target), tval);
23467                   else if (tlocc != NULL_RTX)
23468                     {
23469                       tval = mem_loc_descriptor (tlocc,
23470                                                  GET_MODE (tlocc) == VOIDmode
23471                                                  ? Pmode : GET_MODE (tlocc),
23472                                                  VOIDmode,
23473                                                  VAR_INIT_STATUS_INITIALIZED);
23474                       if (tval)
23475                         add_AT_loc (die,
23476                                     dwarf_AT (DW_AT_call_target_clobbered),
23477                                     tval);
23478                     }
23479                 }
23480               if (die != NULL)
23481                 {
23482                   call_site_note_count++;
23483                   if (ca_loc->tail_call_p)
23484                     tail_call_site_note_count++;
23485                 }
23486             }
23487         }
23488       call_arg_locations = NULL;
23489       call_arg_loc_last = NULL;
23490       if (tail_call_site_count >= 0
23491           && tail_call_site_count == tail_call_site_note_count
23492           && (!dwarf_strict || dwarf_version >= 5))
23493         {
23494           if (call_site_count >= 0
23495               && call_site_count == call_site_note_count)
23496             add_AT_flag (subr_die, dwarf_AT (DW_AT_call_all_calls), 1);
23497           else
23498             add_AT_flag (subr_die, dwarf_AT (DW_AT_call_all_tail_calls), 1);
23499         }
23500       call_site_count = -1;
23501       tail_call_site_count = -1;
23502     }
23503
23504   /* Mark used types after we have created DIEs for the functions scopes.  */
23505   premark_used_types (DECL_STRUCT_FUNCTION (decl));
23506 }
23507
23508 /* Returns a hash value for X (which really is a die_struct).  */
23509
23510 hashval_t
23511 block_die_hasher::hash (die_struct *d)
23512 {
23513   return (hashval_t) d->decl_id ^ htab_hash_pointer (d->die_parent);
23514 }
23515
23516 /* Return nonzero if decl_id and die_parent of die_struct X is the same
23517    as decl_id and die_parent of die_struct Y.  */
23518
23519 bool
23520 block_die_hasher::equal (die_struct *x, die_struct *y)
23521 {
23522   return x->decl_id == y->decl_id && x->die_parent == y->die_parent;
23523 }
23524
23525 /* Hold information about markers for inlined entry points.  */
23526 struct GTY ((for_user)) inline_entry_data
23527 {
23528   /* The block that's the inlined_function_outer_scope for an inlined
23529      function.  */
23530   tree block;
23531
23532   /* The label at the inlined entry point.  */
23533   const char *label_pfx;
23534   unsigned int label_num;
23535
23536   /* The view number to be used as the inlined entry point.  */
23537   var_loc_view view;
23538 };
23539
23540 struct inline_entry_data_hasher : ggc_ptr_hash <inline_entry_data>
23541 {
23542   typedef tree compare_type;
23543   static inline hashval_t hash (const inline_entry_data *);
23544   static inline bool equal (const inline_entry_data *, const_tree);
23545 };
23546
23547 /* Hash table routines for inline_entry_data.  */
23548
23549 inline hashval_t
23550 inline_entry_data_hasher::hash (const inline_entry_data *data)
23551 {
23552   return htab_hash_pointer (data->block);
23553 }
23554
23555 inline bool
23556 inline_entry_data_hasher::equal (const inline_entry_data *data,
23557                                  const_tree block)
23558 {
23559   return data->block == block;
23560 }
23561
23562 /* Inlined entry points pending DIE creation in this compilation unit.  */
23563
23564 static GTY(()) hash_table<inline_entry_data_hasher> *inline_entry_data_table;
23565
23566
23567 /* Return TRUE if DECL, which may have been previously generated as
23568    OLD_DIE, is a candidate for a DW_AT_specification.  DECLARATION is
23569    true if decl (or its origin) is either an extern declaration or a
23570    class/namespace scoped declaration.
23571
23572    The declare_in_namespace support causes us to get two DIEs for one
23573    variable, both of which are declarations.  We want to avoid
23574    considering one to be a specification, so we must test for
23575    DECLARATION and DW_AT_declaration.  */
23576 static inline bool
23577 decl_will_get_specification_p (dw_die_ref old_die, tree decl, bool declaration)
23578 {
23579   return (old_die && TREE_STATIC (decl) && !declaration
23580           && get_AT_flag (old_die, DW_AT_declaration) == 1);
23581 }
23582
23583 /* Return true if DECL is a local static.  */
23584
23585 static inline bool
23586 local_function_static (tree decl)
23587 {
23588   gcc_assert (VAR_P (decl));
23589   return TREE_STATIC (decl)
23590     && DECL_CONTEXT (decl)
23591     && TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL;
23592 }
23593
23594 /* Generate a DIE to represent a declared data object.
23595    Either DECL or ORIGIN must be non-null.  */
23596
23597 static void
23598 gen_variable_die (tree decl, tree origin, dw_die_ref context_die)
23599 {
23600   HOST_WIDE_INT off = 0;
23601   tree com_decl;
23602   tree decl_or_origin = decl ? decl : origin;
23603   tree ultimate_origin;
23604   dw_die_ref var_die;
23605   dw_die_ref old_die = decl ? lookup_decl_die (decl) : NULL;
23606   bool declaration = (DECL_EXTERNAL (decl_or_origin)
23607                       || class_or_namespace_scope_p (context_die));
23608   bool specialization_p = false;
23609   bool no_linkage_name = false;
23610
23611   /* While C++ inline static data members have definitions inside of the
23612      class, force the first DIE to be a declaration, then let gen_member_die
23613      reparent it to the class context and call gen_variable_die again
23614      to create the outside of the class DIE for the definition.  */
23615   if (!declaration
23616       && old_die == NULL
23617       && decl
23618       && DECL_CONTEXT (decl)
23619       && TYPE_P (DECL_CONTEXT (decl))
23620       && lang_hooks.decls.decl_dwarf_attribute (decl, DW_AT_inline) != -1)
23621     {
23622       declaration = true;
23623       if (dwarf_version < 5)
23624         no_linkage_name = true;
23625     }
23626
23627   ultimate_origin = decl_ultimate_origin (decl_or_origin);
23628   if (decl || ultimate_origin)
23629     origin = ultimate_origin;
23630   com_decl = fortran_common (decl_or_origin, &off);
23631
23632   /* Symbol in common gets emitted as a child of the common block, in the form
23633      of a data member.  */
23634   if (com_decl)
23635     {
23636       dw_die_ref com_die;
23637       dw_loc_list_ref loc = NULL;
23638       die_node com_die_arg;
23639
23640       var_die = lookup_decl_die (decl_or_origin);
23641       if (var_die)
23642         {
23643           if (! early_dwarf && get_AT (var_die, DW_AT_location) == NULL)
23644             {
23645               loc = loc_list_from_tree (com_decl, off ? 1 : 2, NULL);
23646               if (loc)
23647                 {
23648                   if (off)
23649                     {
23650                       /* Optimize the common case.  */
23651                       if (single_element_loc_list_p (loc)
23652                           && loc->expr->dw_loc_opc == DW_OP_addr
23653                           && loc->expr->dw_loc_next == NULL
23654                           && GET_CODE (loc->expr->dw_loc_oprnd1.v.val_addr)
23655                              == SYMBOL_REF)
23656                         {
23657                           rtx x = loc->expr->dw_loc_oprnd1.v.val_addr;
23658                           loc->expr->dw_loc_oprnd1.v.val_addr
23659                             = plus_constant (GET_MODE (x), x , off);
23660                         }
23661                       else
23662                         loc_list_plus_const (loc, off);
23663                     }
23664                   add_AT_location_description (var_die, DW_AT_location, loc);
23665                   remove_AT (var_die, DW_AT_declaration);
23666                 }
23667             }
23668           return;
23669         }
23670
23671       if (common_block_die_table == NULL)
23672         common_block_die_table = hash_table<block_die_hasher>::create_ggc (10);
23673
23674       com_die_arg.decl_id = DECL_UID (com_decl);
23675       com_die_arg.die_parent = context_die;
23676       com_die = common_block_die_table->find (&com_die_arg);
23677       if (! early_dwarf)
23678         loc = loc_list_from_tree (com_decl, 2, NULL);
23679       if (com_die == NULL)
23680         {
23681           const char *cnam
23682             = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (com_decl));
23683           die_node **slot;
23684
23685           com_die = new_die (DW_TAG_common_block, context_die, decl);
23686           add_name_and_src_coords_attributes (com_die, com_decl);
23687           if (loc)
23688             {
23689               add_AT_location_description (com_die, DW_AT_location, loc);
23690               /* Avoid sharing the same loc descriptor between
23691                  DW_TAG_common_block and DW_TAG_variable.  */
23692               loc = loc_list_from_tree (com_decl, 2, NULL);
23693             }
23694           else if (DECL_EXTERNAL (decl_or_origin))
23695             add_AT_flag (com_die, DW_AT_declaration, 1);
23696           if (want_pubnames ())
23697             add_pubname_string (cnam, com_die); /* ??? needed? */
23698           com_die->decl_id = DECL_UID (com_decl);
23699           slot = common_block_die_table->find_slot (com_die, INSERT);
23700           *slot = com_die;
23701         }
23702       else if (get_AT (com_die, DW_AT_location) == NULL && loc)
23703         {
23704           add_AT_location_description (com_die, DW_AT_location, loc);
23705           loc = loc_list_from_tree (com_decl, 2, NULL);
23706           remove_AT (com_die, DW_AT_declaration);
23707         }
23708       var_die = new_die (DW_TAG_variable, com_die, decl);
23709       add_name_and_src_coords_attributes (var_die, decl_or_origin);
23710       add_type_attribute (var_die, TREE_TYPE (decl_or_origin),
23711                           decl_quals (decl_or_origin), false,
23712                           context_die);
23713       add_alignment_attribute (var_die, decl);
23714       add_AT_flag (var_die, DW_AT_external, 1);
23715       if (loc)
23716         {
23717           if (off)
23718             {
23719               /* Optimize the common case.  */
23720               if (single_element_loc_list_p (loc)
23721                   && loc->expr->dw_loc_opc == DW_OP_addr
23722                   && loc->expr->dw_loc_next == NULL
23723                   && GET_CODE (loc->expr->dw_loc_oprnd1.v.val_addr) == SYMBOL_REF)
23724                 {
23725                   rtx x = loc->expr->dw_loc_oprnd1.v.val_addr;
23726                   loc->expr->dw_loc_oprnd1.v.val_addr
23727                     = plus_constant (GET_MODE (x), x, off);
23728                 }
23729               else
23730                 loc_list_plus_const (loc, off);
23731             }
23732           add_AT_location_description (var_die, DW_AT_location, loc);
23733         }
23734       else if (DECL_EXTERNAL (decl_or_origin))
23735         add_AT_flag (var_die, DW_AT_declaration, 1);
23736       if (decl)
23737         equate_decl_number_to_die (decl, var_die);
23738       return;
23739     }
23740
23741   if (old_die)
23742     {
23743       if (declaration)
23744         {
23745           /* A declaration that has been previously dumped, needs no
23746              further annotations, since it doesn't need location on
23747              the second pass.  */
23748           return;
23749         }
23750       else if (decl_will_get_specification_p (old_die, decl, declaration)
23751                && !get_AT (old_die, DW_AT_specification))
23752         {
23753           /* Fall-thru so we can make a new variable die along with a
23754              DW_AT_specification.  */
23755         }
23756       else if (origin && old_die->die_parent != context_die)
23757         {
23758           /* If we will be creating an inlined instance, we need a
23759              new DIE that will get annotated with
23760              DW_AT_abstract_origin.  */
23761           gcc_assert (!DECL_ABSTRACT_P (decl));
23762         }
23763       else
23764         {
23765           /* If a DIE was dumped early, it still needs location info.
23766              Skip to where we fill the location bits.  */
23767           var_die = old_die;
23768
23769           /* ???  In LTRANS we cannot annotate early created variably
23770              modified type DIEs without copying them and adjusting all
23771              references to them.  Thus we dumped them again.  Also add a
23772              reference to them but beware of -g0 compile and -g link
23773              in which case the reference will be already present.  */
23774           tree type = TREE_TYPE (decl_or_origin);
23775           if (in_lto_p
23776               && ! get_AT (var_die, DW_AT_type)
23777               && variably_modified_type_p
23778                    (type, decl_function_context (decl_or_origin)))
23779             {
23780               if (decl_by_reference_p (decl_or_origin))
23781                 add_type_attribute (var_die, TREE_TYPE (type),
23782                                     TYPE_UNQUALIFIED, false, context_die);
23783               else
23784                 add_type_attribute (var_die, type, decl_quals (decl_or_origin),
23785                                     false, context_die);
23786             }
23787
23788           goto gen_variable_die_location;
23789         }
23790     }
23791
23792   /* For static data members, the declaration in the class is supposed
23793      to have DW_TAG_member tag in DWARF{3,4} and we emit it for compatibility
23794      also in DWARF2; the specification should still be DW_TAG_variable
23795      referencing the DW_TAG_member DIE.  */
23796   if (declaration && class_scope_p (context_die) && dwarf_version < 5)
23797     var_die = new_die (DW_TAG_member, context_die, decl);
23798   else
23799     var_die = new_die (DW_TAG_variable, context_die, decl);
23800
23801   if (origin != NULL)
23802     add_abstract_origin_attribute (var_die, origin);
23803
23804   /* Loop unrolling can create multiple blocks that refer to the same
23805      static variable, so we must test for the DW_AT_declaration flag.
23806
23807      ??? Loop unrolling/reorder_blocks should perhaps be rewritten to
23808      copy decls and set the DECL_ABSTRACT_P flag on them instead of
23809      sharing them.
23810
23811      ??? Duplicated blocks have been rewritten to use .debug_ranges.  */
23812   else if (decl_will_get_specification_p (old_die, decl, declaration))
23813     {
23814       /* This is a definition of a C++ class level static.  */
23815       add_AT_specification (var_die, old_die);
23816       specialization_p = true;
23817       if (DECL_NAME (decl))
23818         {
23819           expanded_location s = expand_location (DECL_SOURCE_LOCATION (decl));
23820           struct dwarf_file_data * file_index = lookup_filename (s.file);
23821
23822           if (get_AT_file (old_die, DW_AT_decl_file) != file_index)
23823             add_AT_file (var_die, DW_AT_decl_file, file_index);
23824
23825           if (get_AT_unsigned (old_die, DW_AT_decl_line) != (unsigned) s.line)
23826             add_AT_unsigned (var_die, DW_AT_decl_line, s.line);
23827
23828           if (debug_column_info
23829               && s.column
23830               && (get_AT_unsigned (old_die, DW_AT_decl_column)
23831                   != (unsigned) s.column))
23832             add_AT_unsigned (var_die, DW_AT_decl_column, s.column);
23833
23834           if (old_die->die_tag == DW_TAG_member)
23835             add_linkage_name (var_die, decl);
23836         }
23837     }
23838   else
23839     add_name_and_src_coords_attributes (var_die, decl, no_linkage_name);
23840
23841   if ((origin == NULL && !specialization_p)
23842       || (origin != NULL
23843           && !DECL_ABSTRACT_P (decl_or_origin)
23844           && variably_modified_type_p (TREE_TYPE (decl_or_origin),
23845                                        decl_function_context
23846                                                         (decl_or_origin))))
23847     {
23848       tree type = TREE_TYPE (decl_or_origin);
23849
23850       if (decl_by_reference_p (decl_or_origin))
23851         add_type_attribute (var_die, TREE_TYPE (type), TYPE_UNQUALIFIED, false,
23852                             context_die);
23853       else
23854         add_type_attribute (var_die, type, decl_quals (decl_or_origin), false,
23855                             context_die);
23856     }
23857
23858   if (origin == NULL && !specialization_p)
23859     {
23860       if (TREE_PUBLIC (decl))
23861         add_AT_flag (var_die, DW_AT_external, 1);
23862
23863       if (DECL_ARTIFICIAL (decl))
23864         add_AT_flag (var_die, DW_AT_artificial, 1);
23865
23866       add_alignment_attribute (var_die, decl);
23867
23868       add_accessibility_attribute (var_die, decl);
23869     }
23870
23871   if (declaration)
23872     add_AT_flag (var_die, DW_AT_declaration, 1);
23873
23874   if (decl && (DECL_ABSTRACT_P (decl)
23875                || !old_die || is_declaration_die (old_die)))
23876     equate_decl_number_to_die (decl, var_die);
23877
23878  gen_variable_die_location:
23879   if (! declaration
23880       && (! DECL_ABSTRACT_P (decl_or_origin)
23881           /* Local static vars are shared between all clones/inlines,
23882              so emit DW_AT_location on the abstract DIE if DECL_RTL is
23883              already set.  */
23884           || (VAR_P (decl_or_origin)
23885               && TREE_STATIC (decl_or_origin)
23886               && DECL_RTL_SET_P (decl_or_origin))))
23887     {
23888       if (early_dwarf)
23889         add_pubname (decl_or_origin, var_die);
23890       else
23891         add_location_or_const_value_attribute (var_die, decl_or_origin,
23892                                                decl == NULL);
23893     }
23894   else
23895     tree_add_const_value_attribute_for_decl (var_die, decl_or_origin);
23896
23897   if ((dwarf_version >= 4 || !dwarf_strict)
23898       && lang_hooks.decls.decl_dwarf_attribute (decl_or_origin,
23899                                                 DW_AT_const_expr) == 1
23900       && !get_AT (var_die, DW_AT_const_expr)
23901       && !specialization_p)
23902     add_AT_flag (var_die, DW_AT_const_expr, 1);
23903
23904   if (!dwarf_strict)
23905     {
23906       int inl = lang_hooks.decls.decl_dwarf_attribute (decl_or_origin,
23907                                                        DW_AT_inline);
23908       if (inl != -1
23909           && !get_AT (var_die, DW_AT_inline)
23910           && !specialization_p)
23911         add_AT_unsigned (var_die, DW_AT_inline, inl);
23912     }
23913 }
23914
23915 /* Generate a DIE to represent a named constant.  */
23916
23917 static void
23918 gen_const_die (tree decl, dw_die_ref context_die)
23919 {
23920   dw_die_ref const_die;
23921   tree type = TREE_TYPE (decl);
23922
23923   const_die = lookup_decl_die (decl);
23924   if (const_die)
23925     return;
23926
23927   const_die = new_die (DW_TAG_constant, context_die, decl);
23928   equate_decl_number_to_die (decl, const_die);
23929   add_name_and_src_coords_attributes (const_die, decl);
23930   add_type_attribute (const_die, type, TYPE_QUAL_CONST, false, context_die);
23931   if (TREE_PUBLIC (decl))
23932     add_AT_flag (const_die, DW_AT_external, 1);
23933   if (DECL_ARTIFICIAL (decl))
23934     add_AT_flag (const_die, DW_AT_artificial, 1);
23935   tree_add_const_value_attribute_for_decl (const_die, decl);
23936 }
23937
23938 /* Generate a DIE to represent a label identifier.  */
23939
23940 static void
23941 gen_label_die (tree decl, dw_die_ref context_die)
23942 {
23943   tree origin = decl_ultimate_origin (decl);
23944   dw_die_ref lbl_die = lookup_decl_die (decl);
23945   rtx insn;
23946   char label[MAX_ARTIFICIAL_LABEL_BYTES];
23947
23948   if (!lbl_die)
23949     {
23950       lbl_die = new_die (DW_TAG_label, context_die, decl);
23951       equate_decl_number_to_die (decl, lbl_die);
23952
23953       if (origin != NULL)
23954         add_abstract_origin_attribute (lbl_die, origin);
23955       else
23956         add_name_and_src_coords_attributes (lbl_die, decl);
23957     }
23958
23959   if (DECL_ABSTRACT_P (decl))
23960     equate_decl_number_to_die (decl, lbl_die);
23961   else if (! early_dwarf)
23962     {
23963       insn = DECL_RTL_IF_SET (decl);
23964
23965       /* Deleted labels are programmer specified labels which have been
23966          eliminated because of various optimizations.  We still emit them
23967          here so that it is possible to put breakpoints on them.  */
23968       if (insn
23969           && (LABEL_P (insn)
23970               || ((NOTE_P (insn)
23971                    && NOTE_KIND (insn) == NOTE_INSN_DELETED_LABEL))))
23972         {
23973           /* When optimization is enabled (via -O) some parts of the compiler
23974              (e.g. jump.c and cse.c) may try to delete CODE_LABEL insns which
23975              represent source-level labels which were explicitly declared by
23976              the user.  This really shouldn't be happening though, so catch
23977              it if it ever does happen.  */
23978           gcc_assert (!as_a<rtx_insn *> (insn)->deleted ());
23979
23980           ASM_GENERATE_INTERNAL_LABEL (label, "L", CODE_LABEL_NUMBER (insn));
23981           add_AT_lbl_id (lbl_die, DW_AT_low_pc, label);
23982         }
23983       else if (insn
23984                && NOTE_P (insn)
23985                && NOTE_KIND (insn) == NOTE_INSN_DELETED_DEBUG_LABEL
23986                && CODE_LABEL_NUMBER (insn) != -1)
23987         {
23988           ASM_GENERATE_INTERNAL_LABEL (label, "LDL", CODE_LABEL_NUMBER (insn));
23989           add_AT_lbl_id (lbl_die, DW_AT_low_pc, label);
23990         }
23991     }
23992 }
23993
23994 /* A helper function for gen_inlined_subroutine_die.  Add source coordinate
23995    attributes to the DIE for a block STMT, to describe where the inlined
23996    function was called from.  This is similar to add_src_coords_attributes.  */
23997
23998 static inline void
23999 add_call_src_coords_attributes (tree stmt, dw_die_ref die)
24000 {
24001   /* We can end up with BUILTINS_LOCATION here.  */
24002   if (RESERVED_LOCATION_P (BLOCK_SOURCE_LOCATION (stmt)))
24003     return;
24004
24005   expanded_location s = expand_location (BLOCK_SOURCE_LOCATION (stmt));
24006
24007   if (dwarf_version >= 3 || !dwarf_strict)
24008     {
24009       add_AT_file (die, DW_AT_call_file, lookup_filename (s.file));
24010       add_AT_unsigned (die, DW_AT_call_line, s.line);
24011       if (debug_column_info && s.column)
24012         add_AT_unsigned (die, DW_AT_call_column, s.column);
24013     }
24014 }
24015
24016
24017 /* A helper function for gen_lexical_block_die and gen_inlined_subroutine_die.
24018    Add low_pc and high_pc attributes to the DIE for a block STMT.  */
24019
24020 static inline void
24021 add_high_low_attributes (tree stmt, dw_die_ref die)
24022 {
24023   char label[MAX_ARTIFICIAL_LABEL_BYTES];
24024
24025   if (inline_entry_data **iedp
24026       = !inline_entry_data_table ? NULL
24027       : inline_entry_data_table->find_slot_with_hash (stmt,
24028                                                       htab_hash_pointer (stmt),
24029                                                       NO_INSERT))
24030     {
24031       inline_entry_data *ied = *iedp;
24032       gcc_assert (MAY_HAVE_DEBUG_MARKER_INSNS);
24033       gcc_assert (debug_inline_points);
24034       gcc_assert (inlined_function_outer_scope_p (stmt));
24035
24036       ASM_GENERATE_INTERNAL_LABEL (label, ied->label_pfx, ied->label_num);
24037       add_AT_lbl_id (die, DW_AT_entry_pc, label);
24038
24039       if (debug_variable_location_views && !ZERO_VIEW_P (ied->view)
24040           && !dwarf_strict)
24041         {
24042           if (!output_asm_line_debug_info ())
24043             add_AT_unsigned (die, DW_AT_GNU_entry_view, ied->view);
24044           else
24045             {
24046               ASM_GENERATE_INTERNAL_LABEL (label, "LVU", ied->view);
24047               /* FIXME: this will resolve to a small number.  Could we
24048                  possibly emit smaller data?  Ideally we'd emit a
24049                  uleb128, but that would make the size of DIEs
24050                  impossible for the compiler to compute, since it's
24051                  the assembler that computes the value of the view
24052                  label in this case.  Ideally, we'd have a single form
24053                  encompassing both the address and the view, and
24054                  indirecting them through a table might make things
24055                  easier, but even that would be more wasteful,
24056                  space-wise, than what we have now.  */
24057               add_AT_symview (die, DW_AT_GNU_entry_view, label);
24058             }
24059         }
24060
24061       inline_entry_data_table->clear_slot (iedp);
24062     }
24063
24064   if (BLOCK_FRAGMENT_CHAIN (stmt)
24065       && (dwarf_version >= 3 || !dwarf_strict))
24066     {
24067       tree chain, superblock = NULL_TREE;
24068       dw_die_ref pdie;
24069       dw_attr_node *attr = NULL;
24070
24071       if (!debug_inline_points && inlined_function_outer_scope_p (stmt))
24072         {
24073           ASM_GENERATE_INTERNAL_LABEL (label, BLOCK_BEGIN_LABEL,
24074                                        BLOCK_NUMBER (stmt));
24075           add_AT_lbl_id (die, DW_AT_entry_pc, label);
24076         }
24077
24078       /* Optimize duplicate .debug_ranges lists or even tails of
24079          lists.  If this BLOCK has same ranges as its supercontext,
24080          lookup DW_AT_ranges attribute in the supercontext (and
24081          recursively so), verify that the ranges_table contains the
24082          right values and use it instead of adding a new .debug_range.  */
24083       for (chain = stmt, pdie = die;
24084            BLOCK_SAME_RANGE (chain);
24085            chain = BLOCK_SUPERCONTEXT (chain))
24086         {
24087           dw_attr_node *new_attr;
24088
24089           pdie = pdie->die_parent;
24090           if (pdie == NULL)
24091             break;
24092           if (BLOCK_SUPERCONTEXT (chain) == NULL_TREE)
24093             break;
24094           new_attr = get_AT (pdie, DW_AT_ranges);
24095           if (new_attr == NULL
24096               || new_attr->dw_attr_val.val_class != dw_val_class_range_list)
24097             break;
24098           attr = new_attr;
24099           superblock = BLOCK_SUPERCONTEXT (chain);
24100         }
24101       if (attr != NULL
24102           && ((*ranges_table)[attr->dw_attr_val.v.val_offset].num
24103               == BLOCK_NUMBER (superblock))
24104           && BLOCK_FRAGMENT_CHAIN (superblock))
24105         {
24106           unsigned long off = attr->dw_attr_val.v.val_offset;
24107           unsigned long supercnt = 0, thiscnt = 0;
24108           for (chain = BLOCK_FRAGMENT_CHAIN (superblock);
24109                chain; chain = BLOCK_FRAGMENT_CHAIN (chain))
24110             {
24111               ++supercnt;
24112               gcc_checking_assert ((*ranges_table)[off + supercnt].num
24113                                    == BLOCK_NUMBER (chain));
24114             }
24115           gcc_checking_assert ((*ranges_table)[off + supercnt + 1].num == 0);
24116           for (chain = BLOCK_FRAGMENT_CHAIN (stmt);
24117                chain; chain = BLOCK_FRAGMENT_CHAIN (chain))
24118             ++thiscnt;
24119           gcc_assert (supercnt >= thiscnt);
24120           add_AT_range_list (die, DW_AT_ranges, off + supercnt - thiscnt,
24121                              false);
24122           note_rnglist_head (off + supercnt - thiscnt);
24123           return;
24124         }
24125
24126       unsigned int offset = add_ranges (stmt, true);
24127       add_AT_range_list (die, DW_AT_ranges, offset, false);
24128       note_rnglist_head (offset);
24129
24130       bool prev_in_cold = BLOCK_IN_COLD_SECTION_P (stmt);
24131       chain = BLOCK_FRAGMENT_CHAIN (stmt);
24132       do
24133         {
24134           add_ranges (chain, prev_in_cold != BLOCK_IN_COLD_SECTION_P (chain));
24135           prev_in_cold = BLOCK_IN_COLD_SECTION_P (chain);
24136           chain = BLOCK_FRAGMENT_CHAIN (chain);
24137         }
24138       while (chain);
24139       add_ranges (NULL);
24140     }
24141   else
24142     {
24143       char label_high[MAX_ARTIFICIAL_LABEL_BYTES];
24144       ASM_GENERATE_INTERNAL_LABEL (label, BLOCK_BEGIN_LABEL,
24145                                    BLOCK_NUMBER (stmt));
24146       ASM_GENERATE_INTERNAL_LABEL (label_high, BLOCK_END_LABEL,
24147                                    BLOCK_NUMBER (stmt));
24148       add_AT_low_high_pc (die, label, label_high, false);
24149     }
24150 }
24151
24152 /* Generate a DIE for a lexical block.  */
24153
24154 static void
24155 gen_lexical_block_die (tree stmt, dw_die_ref context_die)
24156 {
24157   dw_die_ref old_die = BLOCK_DIE (stmt);
24158   dw_die_ref stmt_die = NULL;
24159   if (!old_die)
24160     {
24161       stmt_die = new_die (DW_TAG_lexical_block, context_die, stmt);
24162       BLOCK_DIE (stmt) = stmt_die;
24163     }
24164
24165   if (BLOCK_ABSTRACT (stmt))
24166     {
24167       if (old_die)
24168         {
24169           /* This must have been generated early and it won't even
24170              need location information since it's a DW_AT_inline
24171              function.  */
24172           if (flag_checking)
24173             for (dw_die_ref c = context_die; c; c = c->die_parent)
24174               if (c->die_tag == DW_TAG_inlined_subroutine
24175                   || c->die_tag == DW_TAG_subprogram)
24176                 {
24177                   gcc_assert (get_AT (c, DW_AT_inline));
24178                   break;
24179                 }
24180           return;
24181         }
24182     }
24183   else if (BLOCK_ABSTRACT_ORIGIN (stmt))
24184     {
24185       /* If this is an inlined instance, create a new lexical die for
24186          anything below to attach DW_AT_abstract_origin to.  */
24187       if (old_die)
24188         {
24189           stmt_die = new_die (DW_TAG_lexical_block, context_die, stmt);
24190           BLOCK_DIE (stmt) = stmt_die;
24191           old_die = NULL;
24192         }
24193
24194       tree origin = block_ultimate_origin (stmt);
24195       if (origin != NULL_TREE && origin != stmt)
24196         add_abstract_origin_attribute (stmt_die, origin);
24197     }
24198
24199   if (old_die)
24200     stmt_die = old_die;
24201
24202   /* A non abstract block whose blocks have already been reordered
24203      should have the instruction range for this block.  If so, set the
24204      high/low attributes.  */
24205   if (!early_dwarf && !BLOCK_ABSTRACT (stmt) && TREE_ASM_WRITTEN (stmt))
24206     {
24207       gcc_assert (stmt_die);
24208       add_high_low_attributes (stmt, stmt_die);
24209     }
24210
24211   decls_for_scope (stmt, stmt_die);
24212 }
24213
24214 /* Generate a DIE for an inlined subprogram.  */
24215
24216 static void
24217 gen_inlined_subroutine_die (tree stmt, dw_die_ref context_die)
24218 {
24219   tree decl;
24220
24221   /* The instance of function that is effectively being inlined shall not
24222      be abstract.  */
24223   gcc_assert (! BLOCK_ABSTRACT (stmt));
24224
24225   decl = block_ultimate_origin (stmt);
24226
24227   /* Make sure any inlined functions are known to be inlineable.  */
24228   gcc_checking_assert (DECL_ABSTRACT_P (decl)
24229                        || cgraph_function_possibly_inlined_p (decl));
24230
24231   if (! BLOCK_ABSTRACT (stmt))
24232     {
24233       dw_die_ref subr_die
24234         = new_die (DW_TAG_inlined_subroutine, context_die, stmt);
24235
24236       if (call_arg_locations || debug_inline_points)
24237         BLOCK_DIE (stmt) = subr_die;
24238       add_abstract_origin_attribute (subr_die, decl);
24239       if (TREE_ASM_WRITTEN (stmt))
24240         add_high_low_attributes (stmt, subr_die);
24241       add_call_src_coords_attributes (stmt, subr_die);
24242
24243       decls_for_scope (stmt, subr_die);
24244     }
24245 }
24246
24247 /* Generate a DIE for a field in a record, or structure.  CTX is required: see
24248    the comment for VLR_CONTEXT.  */
24249
24250 static void
24251 gen_field_die (tree decl, struct vlr_context *ctx, dw_die_ref context_die)
24252 {
24253   dw_die_ref decl_die;
24254
24255   if (TREE_TYPE (decl) == error_mark_node)
24256     return;
24257
24258   decl_die = new_die (DW_TAG_member, context_die, decl);
24259   add_name_and_src_coords_attributes (decl_die, decl);
24260   add_type_attribute (decl_die, member_declared_type (decl), decl_quals (decl),
24261                       TYPE_REVERSE_STORAGE_ORDER (DECL_FIELD_CONTEXT (decl)),
24262                       context_die);
24263
24264   if (DECL_BIT_FIELD_TYPE (decl))
24265     {
24266       add_byte_size_attribute (decl_die, decl);
24267       add_bit_size_attribute (decl_die, decl);
24268       add_bit_offset_attribute (decl_die, decl, ctx);
24269     }
24270
24271   add_alignment_attribute (decl_die, decl);
24272
24273   /* If we have a variant part offset, then we are supposed to process a member
24274      of a QUAL_UNION_TYPE, which is how we represent variant parts in
24275      trees.  */
24276   gcc_assert (ctx->variant_part_offset == NULL_TREE
24277               || TREE_CODE (DECL_FIELD_CONTEXT (decl)) != QUAL_UNION_TYPE);
24278   if (TREE_CODE (DECL_FIELD_CONTEXT (decl)) != UNION_TYPE)
24279     add_data_member_location_attribute (decl_die, decl, ctx);
24280
24281   if (DECL_ARTIFICIAL (decl))
24282     add_AT_flag (decl_die, DW_AT_artificial, 1);
24283
24284   add_accessibility_attribute (decl_die, decl);
24285
24286   /* Equate decl number to die, so that we can look up this decl later on.  */
24287   equate_decl_number_to_die (decl, decl_die);
24288 }
24289
24290 /* Generate a DIE for a pointer to a member type.  TYPE can be an
24291    OFFSET_TYPE, for a pointer to data member, or a RECORD_TYPE, for a
24292    pointer to member function.  */
24293
24294 static void
24295 gen_ptr_to_mbr_type_die (tree type, dw_die_ref context_die)
24296 {
24297   if (lookup_type_die (type))
24298     return;
24299
24300   dw_die_ref ptr_die = new_die (DW_TAG_ptr_to_member_type,
24301                                 scope_die_for (type, context_die), type);
24302
24303   equate_type_number_to_die (type, ptr_die);
24304   add_AT_die_ref (ptr_die, DW_AT_containing_type,
24305                   lookup_type_die (TYPE_OFFSET_BASETYPE (type)));
24306   add_type_attribute (ptr_die, TREE_TYPE (type), TYPE_UNQUALIFIED, false,
24307                       context_die);
24308   add_alignment_attribute (ptr_die, type);
24309
24310   if (TREE_CODE (TREE_TYPE (type)) != FUNCTION_TYPE
24311       && TREE_CODE (TREE_TYPE (type)) != METHOD_TYPE)
24312     {
24313       dw_loc_descr_ref op = new_loc_descr (DW_OP_plus, 0, 0);
24314       add_AT_loc (ptr_die, DW_AT_use_location, op);
24315     }
24316 }
24317
24318 static char *producer_string;
24319
24320 /* Return a heap allocated producer string including command line options
24321    if -grecord-gcc-switches.  */
24322
24323 static char *
24324 gen_producer_string (void)
24325 {
24326   size_t j;
24327   auto_vec<const char *> switches;
24328   const char *language_string = lang_hooks.name;
24329   char *producer, *tail;
24330   const char *p;
24331   size_t len = dwarf_record_gcc_switches ? 0 : 3;
24332   size_t plen = strlen (language_string) + 1 + strlen (version_string);
24333
24334   for (j = 1; dwarf_record_gcc_switches && j < save_decoded_options_count; j++)
24335     switch (save_decoded_options[j].opt_index)
24336       {
24337       case OPT_o:
24338       case OPT_d:
24339       case OPT_dumpbase:
24340       case OPT_dumpdir:
24341       case OPT_auxbase:
24342       case OPT_auxbase_strip:
24343       case OPT_quiet:
24344       case OPT_version:
24345       case OPT_v:
24346       case OPT_w:
24347       case OPT_L:
24348       case OPT_D:
24349       case OPT_I:
24350       case OPT_U:
24351       case OPT_SPECIAL_unknown:
24352       case OPT_SPECIAL_ignore:
24353       case OPT_SPECIAL_program_name:
24354       case OPT_SPECIAL_input_file:
24355       case OPT_grecord_gcc_switches:
24356       case OPT__output_pch_:
24357       case OPT_fdiagnostics_show_location_:
24358       case OPT_fdiagnostics_show_option:
24359       case OPT_fdiagnostics_show_caret:
24360       case OPT_fdiagnostics_color_:
24361       case OPT_fverbose_asm:
24362       case OPT____:
24363       case OPT__sysroot_:
24364       case OPT_nostdinc:
24365       case OPT_nostdinc__:
24366       case OPT_fpreprocessed:
24367       case OPT_fltrans_output_list_:
24368       case OPT_fresolution_:
24369       case OPT_fdebug_prefix_map_:
24370       case OPT_fmacro_prefix_map_:
24371       case OPT_ffile_prefix_map_:
24372       case OPT_fcompare_debug:
24373         /* Ignore these.  */
24374         continue;
24375       default:
24376         if (cl_options[save_decoded_options[j].opt_index].flags
24377             & CL_NO_DWARF_RECORD)
24378           continue;
24379         gcc_checking_assert (save_decoded_options[j].canonical_option[0][0]
24380                              == '-');
24381         switch (save_decoded_options[j].canonical_option[0][1])
24382           {
24383           case 'M':
24384           case 'i':
24385           case 'W':
24386             continue;
24387           case 'f':
24388             if (strncmp (save_decoded_options[j].canonical_option[0] + 2,
24389                          "dump", 4) == 0)
24390               continue;
24391             break;
24392           default:
24393             break;
24394           }
24395         switches.safe_push (save_decoded_options[j].orig_option_with_args_text);
24396         len += strlen (save_decoded_options[j].orig_option_with_args_text) + 1;
24397         break;
24398       }
24399
24400   producer = XNEWVEC (char, plen + 1 + len + 1);
24401   tail = producer;
24402   sprintf (tail, "%s %s", language_string, version_string);
24403   tail += plen;
24404
24405   FOR_EACH_VEC_ELT (switches, j, p)
24406     {
24407       len = strlen (p);
24408       *tail = ' ';
24409       memcpy (tail + 1, p, len);
24410       tail += len + 1;
24411     }
24412
24413   *tail = '\0';
24414   return producer;
24415 }
24416
24417 /* Given a C and/or C++ language/version string return the "highest".
24418    C++ is assumed to be "higher" than C in this case.  Used for merging
24419    LTO translation unit languages.  */
24420 static const char *
24421 highest_c_language (const char *lang1, const char *lang2)
24422 {
24423   if (strcmp ("GNU C++17", lang1) == 0 || strcmp ("GNU C++17", lang2) == 0)
24424     return "GNU C++17";
24425   if (strcmp ("GNU C++14", lang1) == 0 || strcmp ("GNU C++14", lang2) == 0)
24426     return "GNU C++14";
24427   if (strcmp ("GNU C++11", lang1) == 0 || strcmp ("GNU C++11", lang2) == 0)
24428     return "GNU C++11";
24429   if (strcmp ("GNU C++98", lang1) == 0 || strcmp ("GNU C++98", lang2) == 0)
24430     return "GNU C++98";
24431
24432   if (strcmp ("GNU C17", lang1) == 0 || strcmp ("GNU C17", lang2) == 0)
24433     return "GNU C17";
24434   if (strcmp ("GNU C11", lang1) == 0 || strcmp ("GNU C11", lang2) == 0)
24435     return "GNU C11";
24436   if (strcmp ("GNU C99", lang1) == 0 || strcmp ("GNU C99", lang2) == 0)
24437     return "GNU C99";
24438   if (strcmp ("GNU C89", lang1) == 0 || strcmp ("GNU C89", lang2) == 0)
24439     return "GNU C89";
24440
24441   gcc_unreachable ();
24442 }
24443
24444
24445 /* Generate the DIE for the compilation unit.  */
24446
24447 static dw_die_ref
24448 gen_compile_unit_die (const char *filename)
24449 {
24450   dw_die_ref die;
24451   const char *language_string = lang_hooks.name;
24452   int language;
24453
24454   die = new_die (DW_TAG_compile_unit, NULL, NULL);
24455
24456   if (filename)
24457     {
24458       add_name_attribute (die, filename);
24459       /* Don't add cwd for <built-in>.  */
24460       if (filename[0] != '<')
24461         add_comp_dir_attribute (die);
24462     }
24463
24464   add_AT_string (die, DW_AT_producer, producer_string ? producer_string : "");
24465
24466   /* If our producer is LTO try to figure out a common language to use
24467      from the global list of translation units.  */
24468   if (strcmp (language_string, "GNU GIMPLE") == 0)
24469     {
24470       unsigned i;
24471       tree t;
24472       const char *common_lang = NULL;
24473
24474       FOR_EACH_VEC_SAFE_ELT (all_translation_units, i, t)
24475         {
24476           if (!TRANSLATION_UNIT_LANGUAGE (t))
24477             continue;
24478           if (!common_lang)
24479             common_lang = TRANSLATION_UNIT_LANGUAGE (t);
24480           else if (strcmp (common_lang, TRANSLATION_UNIT_LANGUAGE (t)) == 0)
24481             ;
24482           else if (strncmp (common_lang, "GNU C", 5) == 0
24483                     && strncmp (TRANSLATION_UNIT_LANGUAGE (t), "GNU C", 5) == 0)
24484             /* Mixing C and C++ is ok, use C++ in that case.  */
24485             common_lang = highest_c_language (common_lang,
24486                                               TRANSLATION_UNIT_LANGUAGE (t));
24487           else
24488             {
24489               /* Fall back to C.  */
24490               common_lang = NULL;
24491               break;
24492             }
24493         }
24494
24495       if (common_lang)
24496         language_string = common_lang;
24497     }
24498
24499   language = DW_LANG_C;
24500   if (strncmp (language_string, "GNU C", 5) == 0
24501       && ISDIGIT (language_string[5]))
24502     {
24503       language = DW_LANG_C89;
24504       if (dwarf_version >= 3 || !dwarf_strict)
24505         {
24506           if (strcmp (language_string, "GNU C89") != 0)
24507             language = DW_LANG_C99;
24508
24509           if (dwarf_version >= 5 /* || !dwarf_strict */)
24510             if (strcmp (language_string, "GNU C11") == 0
24511                 || strcmp (language_string, "GNU C17") == 0)
24512               language = DW_LANG_C11;
24513         }
24514     }
24515   else if (strncmp (language_string, "GNU C++", 7) == 0)
24516     {
24517       language = DW_LANG_C_plus_plus;
24518       if (dwarf_version >= 5 /* || !dwarf_strict */)
24519         {
24520           if (strcmp (language_string, "GNU C++11") == 0)
24521             language = DW_LANG_C_plus_plus_11;
24522           else if (strcmp (language_string, "GNU C++14") == 0)
24523             language = DW_LANG_C_plus_plus_14;
24524           else if (strcmp (language_string, "GNU C++17") == 0)
24525             /* For now.  */
24526             language = DW_LANG_C_plus_plus_14;
24527         }
24528     }
24529   else if (strcmp (language_string, "GNU F77") == 0)
24530     language = DW_LANG_Fortran77;
24531   else if (dwarf_version >= 3 || !dwarf_strict)
24532     {
24533       if (strcmp (language_string, "GNU Ada") == 0)
24534         language = DW_LANG_Ada95;
24535       else if (strncmp (language_string, "GNU Fortran", 11) == 0)
24536         {
24537           language = DW_LANG_Fortran95;
24538           if (dwarf_version >= 5 /* || !dwarf_strict */)
24539             {
24540               if (strcmp (language_string, "GNU Fortran2003") == 0)
24541                 language = DW_LANG_Fortran03;
24542               else if (strcmp (language_string, "GNU Fortran2008") == 0)
24543                 language = DW_LANG_Fortran08;
24544             }
24545         }
24546       else if (strcmp (language_string, "GNU Objective-C") == 0)
24547         language = DW_LANG_ObjC;
24548       else if (strcmp (language_string, "GNU Objective-C++") == 0)
24549         language = DW_LANG_ObjC_plus_plus;
24550       else if (dwarf_version >= 5 || !dwarf_strict)
24551         {
24552           if (strcmp (language_string, "GNU Go") == 0)
24553             language = DW_LANG_Go;
24554         }
24555     }
24556   /* Use a degraded Fortran setting in strict DWARF2 so is_fortran works.  */
24557   else if (strncmp (language_string, "GNU Fortran", 11) == 0)
24558     language = DW_LANG_Fortran90;
24559
24560   add_AT_unsigned (die, DW_AT_language, language);
24561
24562   switch (language)
24563     {
24564     case DW_LANG_Fortran77:
24565     case DW_LANG_Fortran90:
24566     case DW_LANG_Fortran95:
24567     case DW_LANG_Fortran03:
24568     case DW_LANG_Fortran08:
24569       /* Fortran has case insensitive identifiers and the front-end
24570          lowercases everything.  */
24571       add_AT_unsigned (die, DW_AT_identifier_case, DW_ID_down_case);
24572       break;
24573     default:
24574       /* The default DW_ID_case_sensitive doesn't need to be specified.  */
24575       break;
24576     }
24577   return die;
24578 }
24579
24580 /* Generate the DIE for a base class.  */
24581
24582 static void
24583 gen_inheritance_die (tree binfo, tree access, tree type,
24584                      dw_die_ref context_die)
24585 {
24586   dw_die_ref die = new_die (DW_TAG_inheritance, context_die, binfo);
24587   struct vlr_context ctx = { type, NULL };
24588
24589   add_type_attribute (die, BINFO_TYPE (binfo), TYPE_UNQUALIFIED, false,
24590                       context_die);
24591   add_data_member_location_attribute (die, binfo, &ctx);
24592
24593   if (BINFO_VIRTUAL_P (binfo))
24594     add_AT_unsigned (die, DW_AT_virtuality, DW_VIRTUALITY_virtual);
24595
24596   /* In DWARF3+ the default is DW_ACCESS_private only in DW_TAG_class_type
24597      children, otherwise the default is DW_ACCESS_public.  In DWARF2
24598      the default has always been DW_ACCESS_private.  */
24599   if (access == access_public_node)
24600     {
24601       if (dwarf_version == 2
24602           || context_die->die_tag == DW_TAG_class_type)
24603       add_AT_unsigned (die, DW_AT_accessibility, DW_ACCESS_public);
24604     }
24605   else if (access == access_protected_node)
24606     add_AT_unsigned (die, DW_AT_accessibility, DW_ACCESS_protected);
24607   else if (dwarf_version > 2
24608            && context_die->die_tag != DW_TAG_class_type)
24609     add_AT_unsigned (die, DW_AT_accessibility, DW_ACCESS_private);
24610 }
24611
24612 /* Return whether DECL is a FIELD_DECL that represents the variant part of a
24613    structure.  */
24614 static bool
24615 is_variant_part (tree decl)
24616 {
24617   return (TREE_CODE (decl) == FIELD_DECL
24618           && TREE_CODE (TREE_TYPE (decl)) == QUAL_UNION_TYPE);
24619 }
24620
24621 /* Check that OPERAND is a reference to a field in STRUCT_TYPE.  If it is,
24622    return the FIELD_DECL.  Return NULL_TREE otherwise.  */
24623
24624 static tree
24625 analyze_discr_in_predicate (tree operand, tree struct_type)
24626 {
24627   bool continue_stripping = true;
24628   while (continue_stripping)
24629     switch (TREE_CODE (operand))
24630       {
24631       CASE_CONVERT:
24632         operand = TREE_OPERAND (operand, 0);
24633         break;
24634       default:
24635         continue_stripping = false;
24636         break;
24637       }
24638
24639   /* Match field access to members of struct_type only.  */
24640   if (TREE_CODE (operand) == COMPONENT_REF
24641       && TREE_CODE (TREE_OPERAND (operand, 0)) == PLACEHOLDER_EXPR
24642       && TREE_TYPE (TREE_OPERAND (operand, 0)) == struct_type
24643       && TREE_CODE (TREE_OPERAND (operand, 1)) == FIELD_DECL)
24644     return TREE_OPERAND (operand, 1);
24645   else
24646     return NULL_TREE;
24647 }
24648
24649 /* Check that SRC is a constant integer that can be represented as a native
24650    integer constant (either signed or unsigned).  If so, store it into DEST and
24651    return true.  Return false otherwise. */
24652
24653 static bool
24654 get_discr_value (tree src, dw_discr_value *dest)
24655 {
24656   tree discr_type = TREE_TYPE (src);
24657
24658   if (lang_hooks.types.get_debug_type)
24659     {
24660       tree debug_type = lang_hooks.types.get_debug_type (discr_type);
24661       if (debug_type != NULL)
24662         discr_type = debug_type;
24663     }
24664
24665   if (TREE_CODE (src) != INTEGER_CST || !INTEGRAL_TYPE_P (discr_type))
24666     return false;
24667
24668   /* Signedness can vary between the original type and the debug type. This
24669      can happen for character types in Ada for instance: the character type
24670      used for code generation can be signed, to be compatible with the C one,
24671      but from a debugger point of view, it must be unsigned.  */
24672   bool is_orig_unsigned = TYPE_UNSIGNED (TREE_TYPE (src));
24673   bool is_debug_unsigned = TYPE_UNSIGNED (discr_type);
24674
24675   if (is_orig_unsigned != is_debug_unsigned)
24676     src = fold_convert (discr_type, src);
24677
24678   if (!(is_debug_unsigned ? tree_fits_uhwi_p (src) : tree_fits_shwi_p (src)))
24679     return false;
24680
24681   dest->pos = is_debug_unsigned;
24682   if (is_debug_unsigned)
24683     dest->v.uval = tree_to_uhwi (src);
24684   else
24685     dest->v.sval = tree_to_shwi (src);
24686
24687   return true;
24688 }
24689
24690 /* Try to extract synthetic properties out of VARIANT_PART_DECL, which is a
24691    FIELD_DECL in STRUCT_TYPE that represents a variant part.  If unsuccessful,
24692    store NULL_TREE in DISCR_DECL.  Otherwise:
24693
24694      - store the discriminant field in STRUCT_TYPE that controls the variant
24695        part to *DISCR_DECL
24696
24697      - put in *DISCR_LISTS_P an array where for each variant, the item
24698        represents the corresponding matching list of discriminant values.
24699
24700      - put in *DISCR_LISTS_LENGTH the number of variants, which is the size of
24701        the above array.
24702
24703    Note that when the array is allocated (i.e. when the analysis is
24704    successful), it is up to the caller to free the array.  */
24705
24706 static void
24707 analyze_variants_discr (tree variant_part_decl,
24708                         tree struct_type,
24709                         tree *discr_decl,
24710                         dw_discr_list_ref **discr_lists_p,
24711                         unsigned *discr_lists_length)
24712 {
24713   tree variant_part_type = TREE_TYPE (variant_part_decl);
24714   tree variant;
24715   dw_discr_list_ref *discr_lists;
24716   unsigned i;
24717
24718   /* Compute how many variants there are in this variant part.  */
24719   *discr_lists_length = 0;
24720   for (variant = TYPE_FIELDS (variant_part_type);
24721        variant != NULL_TREE;
24722        variant = DECL_CHAIN (variant))
24723     ++*discr_lists_length;
24724
24725   *discr_decl = NULL_TREE;
24726   *discr_lists_p
24727     = (dw_discr_list_ref *) xcalloc (*discr_lists_length,
24728                                      sizeof (**discr_lists_p));
24729   discr_lists = *discr_lists_p;
24730
24731   /* And then analyze all variants to extract discriminant information for all
24732      of them.  This analysis is conservative: as soon as we detect something we
24733      do not support, abort everything and pretend we found nothing.  */
24734   for (variant = TYPE_FIELDS (variant_part_type), i = 0;
24735        variant != NULL_TREE;
24736        variant = DECL_CHAIN (variant), ++i)
24737     {
24738       tree match_expr = DECL_QUALIFIER (variant);
24739
24740       /* Now, try to analyze the predicate and deduce a discriminant for
24741          it.  */
24742       if (match_expr == boolean_true_node)
24743         /* Typically happens for the default variant: it matches all cases that
24744            previous variants rejected.  Don't output any matching value for
24745            this one.  */
24746         continue;
24747
24748       /* The following loop tries to iterate over each discriminant
24749          possibility: single values or ranges.  */
24750       while (match_expr != NULL_TREE)
24751         {
24752           tree next_round_match_expr;
24753           tree candidate_discr = NULL_TREE;
24754           dw_discr_list_ref new_node = NULL;
24755
24756           /* Possibilities are matched one after the other by nested
24757              TRUTH_ORIF_EXPR expressions.  Process the current possibility and
24758              continue with the rest at next iteration.  */
24759           if (TREE_CODE (match_expr) == TRUTH_ORIF_EXPR)
24760             {
24761               next_round_match_expr = TREE_OPERAND (match_expr, 0);
24762               match_expr = TREE_OPERAND (match_expr, 1);
24763             }
24764           else
24765             next_round_match_expr = NULL_TREE;
24766
24767           if (match_expr == boolean_false_node)
24768             /* This sub-expression matches nothing: just wait for the next
24769                one.  */
24770             ;
24771
24772           else if (TREE_CODE (match_expr) == EQ_EXPR)
24773             {
24774               /* We are matching:  <discr_field> == <integer_cst>
24775                  This sub-expression matches a single value.  */
24776               tree integer_cst = TREE_OPERAND (match_expr, 1);
24777
24778               candidate_discr
24779                = analyze_discr_in_predicate (TREE_OPERAND (match_expr, 0),
24780                                              struct_type);
24781
24782               new_node = ggc_cleared_alloc<dw_discr_list_node> ();
24783               if (!get_discr_value (integer_cst,
24784                                     &new_node->dw_discr_lower_bound))
24785                 goto abort;
24786               new_node->dw_discr_range = false;
24787             }
24788
24789           else if (TREE_CODE (match_expr) == TRUTH_ANDIF_EXPR)
24790             {
24791               /* We are matching:
24792                    <discr_field> > <integer_cst>
24793                    && <discr_field> < <integer_cst>.
24794                  This sub-expression matches the range of values between the
24795                  two matched integer constants.  Note that comparisons can be
24796                  inclusive or exclusive.  */
24797               tree candidate_discr_1, candidate_discr_2;
24798               tree lower_cst, upper_cst;
24799               bool lower_cst_included, upper_cst_included;
24800               tree lower_op = TREE_OPERAND (match_expr, 0);
24801               tree upper_op = TREE_OPERAND (match_expr, 1);
24802
24803               /* When the comparison is exclusive, the integer constant is not
24804                  the discriminant range bound we are looking for: we will have
24805                  to increment or decrement it.  */
24806               if (TREE_CODE (lower_op) == GE_EXPR)
24807                 lower_cst_included = true;
24808               else if (TREE_CODE (lower_op) == GT_EXPR)
24809                 lower_cst_included = false;
24810               else
24811                 goto abort;
24812
24813               if (TREE_CODE (upper_op) == LE_EXPR)
24814                 upper_cst_included = true;
24815               else if (TREE_CODE (upper_op) == LT_EXPR)
24816                 upper_cst_included = false;
24817               else
24818                 goto abort;
24819
24820               /* Extract the discriminant from the first operand and check it
24821                  is consistant with the same analysis in the second
24822                  operand.  */
24823               candidate_discr_1
24824                 = analyze_discr_in_predicate (TREE_OPERAND (lower_op, 0),
24825                                               struct_type);
24826               candidate_discr_2
24827                 = analyze_discr_in_predicate (TREE_OPERAND (upper_op, 0),
24828                                               struct_type);
24829               if (candidate_discr_1 == candidate_discr_2)
24830                 candidate_discr = candidate_discr_1;
24831               else
24832                 goto abort;
24833
24834               /* Extract bounds from both.  */
24835               new_node = ggc_cleared_alloc<dw_discr_list_node> ();
24836               lower_cst = TREE_OPERAND (lower_op, 1);
24837               upper_cst = TREE_OPERAND (upper_op, 1);
24838
24839               if (!lower_cst_included)
24840                 lower_cst
24841                   = fold_build2 (PLUS_EXPR, TREE_TYPE (lower_cst), lower_cst,
24842                                  build_int_cst (TREE_TYPE (lower_cst), 1));
24843               if (!upper_cst_included)
24844                 upper_cst
24845                   = fold_build2 (MINUS_EXPR, TREE_TYPE (upper_cst), upper_cst,
24846                                  build_int_cst (TREE_TYPE (upper_cst), 1));
24847
24848               if (!get_discr_value (lower_cst,
24849                                     &new_node->dw_discr_lower_bound)
24850                   || !get_discr_value (upper_cst,
24851                                        &new_node->dw_discr_upper_bound))
24852                 goto abort;
24853
24854               new_node->dw_discr_range = true;
24855             }
24856
24857           else
24858             /* Unsupported sub-expression: we cannot determine the set of
24859                matching discriminant values.  Abort everything.  */
24860             goto abort;
24861
24862           /* If the discriminant info is not consistant with what we saw so
24863              far, consider the analysis failed and abort everything.  */
24864           if (candidate_discr == NULL_TREE
24865               || (*discr_decl != NULL_TREE && candidate_discr != *discr_decl))
24866             goto abort;
24867           else
24868             *discr_decl = candidate_discr;
24869
24870           if (new_node != NULL)
24871             {
24872               new_node->dw_discr_next = discr_lists[i];
24873               discr_lists[i] = new_node;
24874             }
24875           match_expr = next_round_match_expr;
24876         }
24877     }
24878
24879   /* If we reach this point, we could match everything we were interested
24880      in.  */
24881   return;
24882
24883 abort:
24884   /* Clean all data structure and return no result.  */
24885   free (*discr_lists_p);
24886   *discr_lists_p = NULL;
24887   *discr_decl = NULL_TREE;
24888 }
24889
24890 /* Generate a DIE to represent VARIANT_PART_DECL, a variant part that is part
24891    of STRUCT_TYPE, a record type.  This new DIE is emitted as the next child
24892    under CONTEXT_DIE.
24893
24894    Variant parts are supposed to be implemented as a FIELD_DECL whose type is a
24895    QUAL_UNION_TYPE: this is the VARIANT_PART_DECL parameter.  The members for
24896    this type, which are record types, represent the available variants and each
24897    has a DECL_QUALIFIER attribute.  The discriminant and the discriminant
24898    values are inferred from these attributes.
24899
24900    In trees, the offsets for the fields inside these sub-records are relative
24901    to the variant part itself, whereas the corresponding DIEs should have
24902    offset attributes that are relative to the embedding record base address.
24903    This is why the caller must provide a VARIANT_PART_OFFSET expression: it
24904    must be an expression that computes the offset of the variant part to
24905    describe in DWARF.  */
24906
24907 static void
24908 gen_variant_part (tree variant_part_decl, struct vlr_context *vlr_ctx,
24909                   dw_die_ref context_die)
24910 {
24911   const tree variant_part_type = TREE_TYPE (variant_part_decl);
24912   tree variant_part_offset = vlr_ctx->variant_part_offset;
24913   struct loc_descr_context ctx = {
24914     vlr_ctx->struct_type, /* context_type */
24915     NULL_TREE,            /* base_decl */
24916     NULL,                 /* dpi */
24917     false,                /* placeholder_arg */
24918     false                 /* placeholder_seen */
24919   };
24920
24921   /* The FIELD_DECL node in STRUCT_TYPE that acts as the discriminant, or
24922      NULL_TREE if there is no such field.  */
24923   tree discr_decl = NULL_TREE;
24924   dw_discr_list_ref *discr_lists;
24925   unsigned discr_lists_length = 0;
24926   unsigned i;
24927
24928   dw_die_ref dwarf_proc_die = NULL;
24929   dw_die_ref variant_part_die
24930     = new_die (DW_TAG_variant_part, context_die, variant_part_type);
24931
24932   equate_decl_number_to_die (variant_part_decl, variant_part_die);
24933
24934   analyze_variants_discr (variant_part_decl, vlr_ctx->struct_type,
24935                           &discr_decl, &discr_lists, &discr_lists_length);
24936
24937   if (discr_decl != NULL_TREE)
24938     {
24939       dw_die_ref discr_die = lookup_decl_die (discr_decl);
24940
24941       if (discr_die)
24942         add_AT_die_ref (variant_part_die, DW_AT_discr, discr_die);
24943       else
24944         /* We have no DIE for the discriminant, so just discard all
24945            discrimimant information in the output.  */
24946         discr_decl = NULL_TREE;
24947     }
24948
24949   /* If the offset for this variant part is more complex than a constant,
24950      create a DWARF procedure for it so that we will not have to generate DWARF
24951      expressions for it for each member.  */
24952   if (TREE_CODE (variant_part_offset) != INTEGER_CST
24953       && (dwarf_version >= 3 || !dwarf_strict))
24954     {
24955       const tree dwarf_proc_fndecl
24956         = build_decl (UNKNOWN_LOCATION, FUNCTION_DECL, NULL_TREE,
24957                       build_function_type (TREE_TYPE (variant_part_offset),
24958                                            NULL_TREE));
24959       const tree dwarf_proc_call = build_call_expr (dwarf_proc_fndecl, 0);
24960       const dw_loc_descr_ref dwarf_proc_body
24961         = loc_descriptor_from_tree (variant_part_offset, 0, &ctx);
24962
24963       dwarf_proc_die = new_dwarf_proc_die (dwarf_proc_body,
24964                                            dwarf_proc_fndecl, context_die);
24965       if (dwarf_proc_die != NULL)
24966         variant_part_offset = dwarf_proc_call;
24967     }
24968
24969   /* Output DIEs for all variants.  */
24970   i = 0;
24971   for (tree variant = TYPE_FIELDS (variant_part_type);
24972        variant != NULL_TREE;
24973        variant = DECL_CHAIN (variant), ++i)
24974     {
24975       tree variant_type = TREE_TYPE (variant);
24976       dw_die_ref variant_die;
24977
24978       /* All variants (i.e. members of a variant part) are supposed to be
24979          encoded as structures.  Sub-variant parts are QUAL_UNION_TYPE fields
24980          under these records.  */
24981       gcc_assert (TREE_CODE (variant_type) == RECORD_TYPE);
24982
24983       variant_die = new_die (DW_TAG_variant, variant_part_die, variant_type);
24984       equate_decl_number_to_die (variant, variant_die);
24985
24986       /* Output discriminant values this variant matches, if any.  */
24987       if (discr_decl == NULL || discr_lists[i] == NULL)
24988         /* In the case we have discriminant information at all, this is
24989            probably the default variant: as the standard says, don't
24990            output any discriminant value/list attribute.  */
24991         ;
24992       else if (discr_lists[i]->dw_discr_next == NULL
24993                && !discr_lists[i]->dw_discr_range)
24994         /* If there is only one accepted value, don't bother outputting a
24995            list.  */
24996         add_discr_value (variant_die, &discr_lists[i]->dw_discr_lower_bound);
24997       else
24998         add_discr_list (variant_die, discr_lists[i]);
24999
25000       for (tree member = TYPE_FIELDS (variant_type);
25001            member != NULL_TREE;
25002            member = DECL_CHAIN (member))
25003         {
25004           struct vlr_context vlr_sub_ctx = {
25005             vlr_ctx->struct_type, /* struct_type */
25006             NULL                  /* variant_part_offset */
25007           };
25008           if (is_variant_part (member))
25009             {
25010               /* All offsets for fields inside variant parts are relative to
25011                  the top-level embedding RECORD_TYPE's base address.  On the
25012                  other hand, offsets in GCC's types are relative to the
25013                  nested-most variant part.  So we have to sum offsets each time
25014                  we recurse.  */
25015
25016               vlr_sub_ctx.variant_part_offset
25017                 = fold_build2 (PLUS_EXPR, TREE_TYPE (variant_part_offset),
25018                                variant_part_offset, byte_position (member));
25019               gen_variant_part (member, &vlr_sub_ctx, variant_die);
25020             }
25021           else
25022             {
25023               vlr_sub_ctx.variant_part_offset = variant_part_offset;
25024               gen_decl_die (member, NULL, &vlr_sub_ctx, variant_die);
25025             }
25026         }
25027     }
25028
25029   free (discr_lists);
25030 }
25031
25032 /* Generate a DIE for a class member.  */
25033
25034 static void
25035 gen_member_die (tree type, dw_die_ref context_die)
25036 {
25037   tree member;
25038   tree binfo = TYPE_BINFO (type);
25039
25040   gcc_assert (TYPE_MAIN_VARIANT (type) == type);
25041
25042   /* If this is not an incomplete type, output descriptions of each of its
25043      members. Note that as we output the DIEs necessary to represent the
25044      members of this record or union type, we will also be trying to output
25045      DIEs to represent the *types* of those members. However the `type'
25046      function (above) will specifically avoid generating type DIEs for member
25047      types *within* the list of member DIEs for this (containing) type except
25048      for those types (of members) which are explicitly marked as also being
25049      members of this (containing) type themselves.  The g++ front- end can
25050      force any given type to be treated as a member of some other (containing)
25051      type by setting the TYPE_CONTEXT of the given (member) type to point to
25052      the TREE node representing the appropriate (containing) type.  */
25053
25054   /* First output info about the base classes.  */
25055   if (binfo && early_dwarf)
25056     {
25057       vec<tree, va_gc> *accesses = BINFO_BASE_ACCESSES (binfo);
25058       int i;
25059       tree base;
25060
25061       for (i = 0; BINFO_BASE_ITERATE (binfo, i, base); i++)
25062         gen_inheritance_die (base,
25063                              (accesses ? (*accesses)[i] : access_public_node),
25064                              type,
25065                              context_die);
25066     }
25067
25068   /* Now output info about the data members and type members.  */
25069   for (member = TYPE_FIELDS (type); member; member = DECL_CHAIN (member))
25070     {
25071       struct vlr_context vlr_ctx = { type, NULL_TREE };
25072       bool static_inline_p
25073         = (TREE_STATIC (member)
25074            && (lang_hooks.decls.decl_dwarf_attribute (member, DW_AT_inline)
25075                != -1));
25076
25077       /* Ignore clones.  */
25078       if (DECL_ABSTRACT_ORIGIN (member))
25079         continue;
25080
25081       /* If we thought we were generating minimal debug info for TYPE
25082          and then changed our minds, some of the member declarations
25083          may have already been defined.  Don't define them again, but
25084          do put them in the right order.  */
25085
25086       if (dw_die_ref child = lookup_decl_die (member))
25087         {
25088           /* Handle inline static data members, which only have in-class
25089              declarations.  */
25090           dw_die_ref ref = NULL; 
25091           if (child->die_tag == DW_TAG_variable
25092               && child->die_parent == comp_unit_die ())
25093             {
25094               ref = get_AT_ref (child, DW_AT_specification);
25095               /* For C++17 inline static data members followed by redundant
25096                  out of class redeclaration, we might get here with
25097                  child being the DIE created for the out of class
25098                  redeclaration and with its DW_AT_specification being
25099                  the DIE created for in-class definition.  We want to
25100                  reparent the latter, and don't want to create another
25101                  DIE with DW_AT_specification in that case, because
25102                  we already have one.  */
25103               if (ref
25104                   && static_inline_p
25105                   && ref->die_tag == DW_TAG_variable
25106                   && ref->die_parent == comp_unit_die ()
25107                   && get_AT (ref, DW_AT_specification) == NULL)
25108                 {
25109                   child = ref;
25110                   ref = NULL;
25111                   static_inline_p = false;
25112                 }
25113             }
25114
25115           if (child->die_tag == DW_TAG_variable
25116               && child->die_parent == comp_unit_die ()
25117               && ref == NULL)
25118             {
25119               reparent_child (child, context_die);
25120               if (dwarf_version < 5)
25121                 child->die_tag = DW_TAG_member;
25122             }
25123           else
25124             splice_child_die (context_die, child);
25125         }
25126
25127       /* Do not generate standard DWARF for variant parts if we are generating
25128          the corresponding GNAT encodings: DIEs generated for both would
25129          conflict in our mappings.  */
25130       else if (is_variant_part (member)
25131                && gnat_encodings == DWARF_GNAT_ENCODINGS_MINIMAL)
25132         {
25133           vlr_ctx.variant_part_offset = byte_position (member);
25134           gen_variant_part (member, &vlr_ctx, context_die);
25135         }
25136       else
25137         {
25138           vlr_ctx.variant_part_offset = NULL_TREE;
25139           gen_decl_die (member, NULL, &vlr_ctx, context_die);
25140         }
25141
25142       /* For C++ inline static data members emit immediately a DW_TAG_variable
25143          DIE that will refer to that DW_TAG_member/DW_TAG_variable through
25144          DW_AT_specification.  */
25145       if (static_inline_p)
25146         {
25147           int old_extern = DECL_EXTERNAL (member);
25148           DECL_EXTERNAL (member) = 0;
25149           gen_decl_die (member, NULL, NULL, comp_unit_die ());
25150           DECL_EXTERNAL (member) = old_extern;
25151         }
25152     }
25153 }
25154
25155 /* Generate a DIE for a structure or union type.  If TYPE_DECL_SUPPRESS_DEBUG
25156    is set, we pretend that the type was never defined, so we only get the
25157    member DIEs needed by later specification DIEs.  */
25158
25159 static void
25160 gen_struct_or_union_type_die (tree type, dw_die_ref context_die,
25161                                 enum debug_info_usage usage)
25162 {
25163   if (TREE_ASM_WRITTEN (type))
25164     {
25165       /* Fill in the bound of variable-length fields in late dwarf if
25166          still incomplete.  */
25167       if (!early_dwarf && variably_modified_type_p (type, NULL))
25168         for (tree member = TYPE_FIELDS (type);
25169              member;
25170              member = DECL_CHAIN (member))
25171           fill_variable_array_bounds (TREE_TYPE (member));
25172       return;
25173     }
25174
25175   dw_die_ref type_die = lookup_type_die (type);
25176   dw_die_ref scope_die = 0;
25177   int nested = 0;
25178   int complete = (TYPE_SIZE (type)
25179                   && (! TYPE_STUB_DECL (type)
25180                       || ! TYPE_DECL_SUPPRESS_DEBUG (TYPE_STUB_DECL (type))));
25181   int ns_decl = (context_die && context_die->die_tag == DW_TAG_namespace);
25182   complete = complete && should_emit_struct_debug (type, usage);
25183
25184   if (type_die && ! complete)
25185     return;
25186
25187   if (TYPE_CONTEXT (type) != NULL_TREE
25188       && (AGGREGATE_TYPE_P (TYPE_CONTEXT (type))
25189           || TREE_CODE (TYPE_CONTEXT (type)) == NAMESPACE_DECL))
25190     nested = 1;
25191
25192   scope_die = scope_die_for (type, context_die);
25193
25194   /* Generate child dies for template paramaters.  */
25195   if (!type_die && debug_info_level > DINFO_LEVEL_TERSE)
25196     schedule_generic_params_dies_gen (type);
25197
25198   if (! type_die || (nested && is_cu_die (scope_die)))
25199     /* First occurrence of type or toplevel definition of nested class.  */
25200     {
25201       dw_die_ref old_die = type_die;
25202
25203       type_die = new_die (TREE_CODE (type) == RECORD_TYPE
25204                           ? record_type_tag (type) : DW_TAG_union_type,
25205                           scope_die, type);
25206       equate_type_number_to_die (type, type_die);
25207       if (old_die)
25208         add_AT_specification (type_die, old_die);
25209       else
25210         add_name_attribute (type_die, type_tag (type));
25211     }
25212   else
25213     remove_AT (type_die, DW_AT_declaration);
25214
25215   /* If this type has been completed, then give it a byte_size attribute and
25216      then give a list of members.  */
25217   if (complete && !ns_decl)
25218     {
25219       /* Prevent infinite recursion in cases where the type of some member of
25220          this type is expressed in terms of this type itself.  */
25221       TREE_ASM_WRITTEN (type) = 1;
25222       add_byte_size_attribute (type_die, type);
25223       add_alignment_attribute (type_die, type);
25224       if (TYPE_STUB_DECL (type) != NULL_TREE)
25225         {
25226           add_src_coords_attributes (type_die, TYPE_STUB_DECL (type));
25227           add_accessibility_attribute (type_die, TYPE_STUB_DECL (type));
25228         }
25229
25230       /* If the first reference to this type was as the return type of an
25231          inline function, then it may not have a parent.  Fix this now.  */
25232       if (type_die->die_parent == NULL)
25233         add_child_die (scope_die, type_die);
25234
25235       push_decl_scope (type);
25236       gen_member_die (type, type_die);
25237       pop_decl_scope ();
25238
25239       add_gnat_descriptive_type_attribute (type_die, type, context_die);
25240       if (TYPE_ARTIFICIAL (type))
25241         add_AT_flag (type_die, DW_AT_artificial, 1);
25242
25243       /* GNU extension: Record what type our vtable lives in.  */
25244       if (TYPE_VFIELD (type))
25245         {
25246           tree vtype = DECL_FCONTEXT (TYPE_VFIELD (type));
25247
25248           gen_type_die (vtype, context_die);
25249           add_AT_die_ref (type_die, DW_AT_containing_type,
25250                           lookup_type_die (vtype));
25251         }
25252     }
25253   else
25254     {
25255       add_AT_flag (type_die, DW_AT_declaration, 1);
25256
25257       /* We don't need to do this for function-local types.  */
25258       if (TYPE_STUB_DECL (type)
25259           && ! decl_function_context (TYPE_STUB_DECL (type)))
25260         vec_safe_push (incomplete_types, type);
25261     }
25262
25263   if (get_AT (type_die, DW_AT_name))
25264     add_pubtype (type, type_die);
25265 }
25266
25267 /* Generate a DIE for a subroutine _type_.  */
25268
25269 static void
25270 gen_subroutine_type_die (tree type, dw_die_ref context_die)
25271 {
25272   tree return_type = TREE_TYPE (type);
25273   dw_die_ref subr_die
25274     = new_die (DW_TAG_subroutine_type,
25275                scope_die_for (type, context_die), type);
25276
25277   equate_type_number_to_die (type, subr_die);
25278   add_prototyped_attribute (subr_die, type);
25279   add_type_attribute (subr_die, return_type, TYPE_UNQUALIFIED, false,
25280                       context_die);
25281   add_alignment_attribute (subr_die, type);
25282   gen_formal_types_die (type, subr_die);
25283
25284   if (get_AT (subr_die, DW_AT_name))
25285     add_pubtype (type, subr_die);
25286   if ((dwarf_version >= 5 || !dwarf_strict)
25287       && lang_hooks.types.type_dwarf_attribute (type, DW_AT_reference) != -1)
25288     add_AT_flag (subr_die, DW_AT_reference, 1);
25289   if ((dwarf_version >= 5 || !dwarf_strict)
25290       && lang_hooks.types.type_dwarf_attribute (type,
25291                                                 DW_AT_rvalue_reference) != -1)
25292     add_AT_flag (subr_die, DW_AT_rvalue_reference, 1);
25293 }
25294
25295 /* Generate a DIE for a type definition.  */
25296
25297 static void
25298 gen_typedef_die (tree decl, dw_die_ref context_die)
25299 {
25300   dw_die_ref type_die;
25301   tree type;
25302
25303   if (TREE_ASM_WRITTEN (decl))
25304     {
25305       if (DECL_ORIGINAL_TYPE (decl))
25306         fill_variable_array_bounds (DECL_ORIGINAL_TYPE (decl));
25307       return;
25308     }
25309
25310   /* As we avoid creating DIEs for local typedefs (see decl_ultimate_origin
25311      checks in process_scope_var and modified_type_die), this should be called
25312      only for original types.  */
25313   gcc_assert (decl_ultimate_origin (decl) == NULL
25314               || decl_ultimate_origin (decl) == decl);
25315
25316   TREE_ASM_WRITTEN (decl) = 1;
25317   type_die = new_die (DW_TAG_typedef, context_die, decl);
25318
25319   add_name_and_src_coords_attributes (type_die, decl);
25320   if (DECL_ORIGINAL_TYPE (decl))
25321     {
25322       type = DECL_ORIGINAL_TYPE (decl);
25323       if (type == error_mark_node)
25324         return;
25325
25326       gcc_assert (type != TREE_TYPE (decl));
25327       equate_type_number_to_die (TREE_TYPE (decl), type_die);
25328     }
25329   else
25330     {
25331       type = TREE_TYPE (decl);
25332       if (type == error_mark_node)
25333         return;
25334
25335       if (is_naming_typedef_decl (TYPE_NAME (type)))
25336         {
25337           /* Here, we are in the case of decl being a typedef naming
25338              an anonymous type, e.g:
25339                  typedef struct {...} foo;
25340              In that case TREE_TYPE (decl) is not a typedef variant
25341              type and TYPE_NAME of the anonymous type is set to the
25342              TYPE_DECL of the typedef. This construct is emitted by
25343              the C++ FE.
25344
25345              TYPE is the anonymous struct named by the typedef
25346              DECL. As we need the DW_AT_type attribute of the
25347              DW_TAG_typedef to point to the DIE of TYPE, let's
25348              generate that DIE right away. add_type_attribute
25349              called below will then pick (via lookup_type_die) that
25350              anonymous struct DIE.  */
25351           if (!TREE_ASM_WRITTEN (type))
25352             gen_tagged_type_die (type, context_die, DINFO_USAGE_DIR_USE);
25353
25354           /* This is a GNU Extension.  We are adding a
25355              DW_AT_linkage_name attribute to the DIE of the
25356              anonymous struct TYPE.  The value of that attribute
25357              is the name of the typedef decl naming the anonymous
25358              struct.  This greatly eases the work of consumers of
25359              this debug info.  */
25360           add_linkage_name_raw (lookup_type_die (type), decl);
25361         }
25362     }
25363
25364   add_type_attribute (type_die, type, decl_quals (decl), false,
25365                       context_die);
25366
25367   if (is_naming_typedef_decl (decl))
25368     /* We want that all subsequent calls to lookup_type_die with
25369        TYPE in argument yield the DW_TAG_typedef we have just
25370        created.  */
25371     equate_type_number_to_die (type, type_die);
25372
25373   add_alignment_attribute (type_die, TREE_TYPE (decl));
25374
25375   add_accessibility_attribute (type_die, decl);
25376
25377   if (DECL_ABSTRACT_P (decl))
25378     equate_decl_number_to_die (decl, type_die);
25379
25380   if (get_AT (type_die, DW_AT_name))
25381     add_pubtype (decl, type_die);
25382 }
25383
25384 /* Generate a DIE for a struct, class, enum or union type.  */
25385
25386 static void
25387 gen_tagged_type_die (tree type,
25388                      dw_die_ref context_die,
25389                      enum debug_info_usage usage)
25390 {
25391   int need_pop;
25392
25393   if (type == NULL_TREE
25394       || !is_tagged_type (type))
25395     return;
25396
25397   if (TREE_ASM_WRITTEN (type))
25398     need_pop = 0;
25399   /* If this is a nested type whose containing class hasn't been written
25400      out yet, writing it out will cover this one, too.  This does not apply
25401      to instantiations of member class templates; they need to be added to
25402      the containing class as they are generated.  FIXME: This hurts the
25403      idea of combining type decls from multiple TUs, since we can't predict
25404      what set of template instantiations we'll get.  */
25405   else if (TYPE_CONTEXT (type)
25406       && AGGREGATE_TYPE_P (TYPE_CONTEXT (type))
25407       && ! TREE_ASM_WRITTEN (TYPE_CONTEXT (type)))
25408     {
25409       gen_type_die_with_usage (TYPE_CONTEXT (type), context_die, usage);
25410
25411       if (TREE_ASM_WRITTEN (type))
25412         return;
25413
25414       /* If that failed, attach ourselves to the stub.  */
25415       push_decl_scope (TYPE_CONTEXT (type));
25416       context_die = lookup_type_die (TYPE_CONTEXT (type));
25417       need_pop = 1;
25418     }
25419   else if (TYPE_CONTEXT (type) != NULL_TREE
25420            && (TREE_CODE (TYPE_CONTEXT (type)) == FUNCTION_DECL))
25421     {
25422       /* If this type is local to a function that hasn't been written
25423          out yet, use a NULL context for now; it will be fixed up in
25424          decls_for_scope.  */
25425       context_die = lookup_decl_die (TYPE_CONTEXT (type));
25426       /* A declaration DIE doesn't count; nested types need to go in the
25427          specification.  */
25428       if (context_die && is_declaration_die (context_die))
25429         context_die = NULL;
25430       need_pop = 0;
25431     }
25432   else
25433     {
25434       context_die = declare_in_namespace (type, context_die);
25435       need_pop = 0;
25436     }
25437
25438   if (TREE_CODE (type) == ENUMERAL_TYPE)
25439     {
25440       /* This might have been written out by the call to
25441          declare_in_namespace.  */
25442       if (!TREE_ASM_WRITTEN (type))
25443         gen_enumeration_type_die (type, context_die);
25444     }
25445   else
25446     gen_struct_or_union_type_die (type, context_die, usage);
25447
25448   if (need_pop)
25449     pop_decl_scope ();
25450
25451   /* Don't set TREE_ASM_WRITTEN on an incomplete struct; we want to fix
25452      it up if it is ever completed.  gen_*_type_die will set it for us
25453      when appropriate.  */
25454 }
25455
25456 /* Generate a type description DIE.  */
25457
25458 static void
25459 gen_type_die_with_usage (tree type, dw_die_ref context_die,
25460                          enum debug_info_usage usage)
25461 {
25462   struct array_descr_info info;
25463
25464   if (type == NULL_TREE || type == error_mark_node)
25465     return;
25466
25467   if (flag_checking && type)
25468      verify_type (type);
25469
25470   if (TYPE_NAME (type) != NULL_TREE
25471       && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
25472       && is_redundant_typedef (TYPE_NAME (type))
25473       && DECL_ORIGINAL_TYPE (TYPE_NAME (type)))
25474     /* The DECL of this type is a typedef we don't want to emit debug
25475        info for but we want debug info for its underlying typedef.
25476        This can happen for e.g, the injected-class-name of a C++
25477        type.  */
25478     type = DECL_ORIGINAL_TYPE (TYPE_NAME (type));
25479
25480   /* If TYPE is a typedef type variant, let's generate debug info
25481      for the parent typedef which TYPE is a type of.  */
25482   if (typedef_variant_p (type))
25483     {
25484       if (TREE_ASM_WRITTEN (type))
25485         return;
25486
25487       tree name = TYPE_NAME (type);
25488       tree origin = decl_ultimate_origin (name);
25489       if (origin != NULL && origin != name)
25490         {
25491           gen_decl_die (origin, NULL, NULL, context_die);
25492           return;
25493         }
25494
25495       /* Prevent broken recursion; we can't hand off to the same type.  */
25496       gcc_assert (DECL_ORIGINAL_TYPE (name) != type);
25497
25498       /* Give typedefs the right scope.  */
25499       context_die = scope_die_for (type, context_die);
25500
25501       TREE_ASM_WRITTEN (type) = 1;
25502
25503       gen_decl_die (name, NULL, NULL, context_die);
25504       return;
25505     }
25506
25507   /* If type is an anonymous tagged type named by a typedef, let's
25508      generate debug info for the typedef.  */
25509   if (is_naming_typedef_decl (TYPE_NAME (type)))
25510     {
25511       /* Give typedefs the right scope.  */
25512       context_die = scope_die_for (type, context_die);
25513
25514       gen_decl_die (TYPE_NAME (type), NULL, NULL, context_die);
25515       return;
25516     }
25517
25518   if (lang_hooks.types.get_debug_type)
25519     {
25520       tree debug_type = lang_hooks.types.get_debug_type (type);
25521
25522       if (debug_type != NULL_TREE && debug_type != type)
25523         {
25524           gen_type_die_with_usage (debug_type, context_die, usage);
25525           return;
25526         }
25527     }
25528
25529   /* We are going to output a DIE to represent the unqualified version
25530      of this type (i.e. without any const or volatile qualifiers) so
25531      get the main variant (i.e. the unqualified version) of this type
25532      now.  (Vectors and arrays are special because the debugging info is in the
25533      cloned type itself.  Similarly function/method types can contain extra
25534      ref-qualification).  */
25535   if (TREE_CODE (type) == FUNCTION_TYPE
25536       || TREE_CODE (type) == METHOD_TYPE)
25537     {
25538       /* For function/method types, can't use type_main_variant here,
25539          because that can have different ref-qualifiers for C++,
25540          but try to canonicalize.  */
25541       tree main = TYPE_MAIN_VARIANT (type);
25542       for (tree t = main; t; t = TYPE_NEXT_VARIANT (t))
25543         if (TYPE_QUALS_NO_ADDR_SPACE (t) == 0
25544             && check_base_type (t, main)
25545             && check_lang_type (t, type))
25546           {
25547             type = t;
25548             break;
25549           }
25550     }
25551   else if (TREE_CODE (type) != VECTOR_TYPE
25552            && TREE_CODE (type) != ARRAY_TYPE)
25553     type = type_main_variant (type);
25554
25555   /* If this is an array type with hidden descriptor, handle it first.  */
25556   if (!TREE_ASM_WRITTEN (type)
25557       && lang_hooks.types.get_array_descr_info)
25558     {
25559       memset (&info, 0, sizeof (info));
25560       if (lang_hooks.types.get_array_descr_info (type, &info))
25561         {
25562           /* Fortran sometimes emits array types with no dimension.  */
25563           gcc_assert (info.ndimensions >= 0
25564                       && (info.ndimensions
25565                           <= DWARF2OUT_ARRAY_DESCR_INFO_MAX_DIMEN));
25566           gen_descr_array_type_die (type, &info, context_die);
25567           TREE_ASM_WRITTEN (type) = 1;
25568           return;
25569         }
25570     }
25571
25572   if (TREE_ASM_WRITTEN (type))
25573     {
25574       /* Variable-length types may be incomplete even if
25575          TREE_ASM_WRITTEN.  For such types, fall through to
25576          gen_array_type_die() and possibly fill in
25577          DW_AT_{upper,lower}_bound attributes.  */
25578       if ((TREE_CODE (type) != ARRAY_TYPE
25579            && TREE_CODE (type) != RECORD_TYPE
25580            && TREE_CODE (type) != UNION_TYPE
25581            && TREE_CODE (type) != QUAL_UNION_TYPE)
25582           || !variably_modified_type_p (type, NULL))
25583         return;
25584     }
25585
25586   switch (TREE_CODE (type))
25587     {
25588     case ERROR_MARK:
25589       break;
25590
25591     case POINTER_TYPE:
25592     case REFERENCE_TYPE:
25593       /* We must set TREE_ASM_WRITTEN in case this is a recursive type.  This
25594          ensures that the gen_type_die recursion will terminate even if the
25595          type is recursive.  Recursive types are possible in Ada.  */
25596       /* ??? We could perhaps do this for all types before the switch
25597          statement.  */
25598       TREE_ASM_WRITTEN (type) = 1;
25599
25600       /* For these types, all that is required is that we output a DIE (or a
25601          set of DIEs) to represent the "basis" type.  */
25602       gen_type_die_with_usage (TREE_TYPE (type), context_die,
25603                                DINFO_USAGE_IND_USE);
25604       break;
25605
25606     case OFFSET_TYPE:
25607       /* This code is used for C++ pointer-to-data-member types.
25608          Output a description of the relevant class type.  */
25609       gen_type_die_with_usage (TYPE_OFFSET_BASETYPE (type), context_die,
25610                                DINFO_USAGE_IND_USE);
25611
25612       /* Output a description of the type of the object pointed to.  */
25613       gen_type_die_with_usage (TREE_TYPE (type), context_die,
25614                                DINFO_USAGE_IND_USE);
25615
25616       /* Now output a DIE to represent this pointer-to-data-member type
25617          itself.  */
25618       gen_ptr_to_mbr_type_die (type, context_die);
25619       break;
25620
25621     case FUNCTION_TYPE:
25622       /* Force out return type (in case it wasn't forced out already).  */
25623       gen_type_die_with_usage (TREE_TYPE (type), context_die,
25624                                DINFO_USAGE_DIR_USE);
25625       gen_subroutine_type_die (type, context_die);
25626       break;
25627
25628     case METHOD_TYPE:
25629       /* Force out return type (in case it wasn't forced out already).  */
25630       gen_type_die_with_usage (TREE_TYPE (type), context_die,
25631                                DINFO_USAGE_DIR_USE);
25632       gen_subroutine_type_die (type, context_die);
25633       break;
25634
25635     case ARRAY_TYPE:
25636     case VECTOR_TYPE:
25637       gen_array_type_die (type, context_die);
25638       break;
25639
25640     case ENUMERAL_TYPE:
25641     case RECORD_TYPE:
25642     case UNION_TYPE:
25643     case QUAL_UNION_TYPE:
25644       gen_tagged_type_die (type, context_die, usage);
25645       return;
25646
25647     case VOID_TYPE:
25648     case INTEGER_TYPE:
25649     case REAL_TYPE:
25650     case FIXED_POINT_TYPE:
25651     case COMPLEX_TYPE:
25652     case BOOLEAN_TYPE:
25653     case POINTER_BOUNDS_TYPE:
25654       /* No DIEs needed for fundamental types.  */
25655       break;
25656
25657     case NULLPTR_TYPE:
25658     case LANG_TYPE:
25659       /* Just use DW_TAG_unspecified_type.  */
25660       {
25661         dw_die_ref type_die = lookup_type_die (type);
25662         if (type_die == NULL)
25663           {
25664             tree name = TYPE_IDENTIFIER (type);
25665             type_die = new_die (DW_TAG_unspecified_type, comp_unit_die (),
25666                                 type);
25667             add_name_attribute (type_die, IDENTIFIER_POINTER (name));
25668             equate_type_number_to_die (type, type_die);
25669           }
25670       }
25671       break;
25672
25673     default:
25674       if (is_cxx_auto (type))
25675         {
25676           tree name = TYPE_IDENTIFIER (type);
25677           dw_die_ref *die = (name == get_identifier ("auto")
25678                              ? &auto_die : &decltype_auto_die);
25679           if (!*die)
25680             {
25681               *die = new_die (DW_TAG_unspecified_type,
25682                               comp_unit_die (), NULL_TREE);
25683               add_name_attribute (*die, IDENTIFIER_POINTER (name));
25684             }
25685           equate_type_number_to_die (type, *die);
25686           break;
25687         }
25688       gcc_unreachable ();
25689     }
25690
25691   TREE_ASM_WRITTEN (type) = 1;
25692 }
25693
25694 static void
25695 gen_type_die (tree type, dw_die_ref context_die)
25696 {
25697   if (type != error_mark_node)
25698     {
25699       gen_type_die_with_usage (type, context_die, DINFO_USAGE_DIR_USE);
25700       if (flag_checking)
25701         {
25702           dw_die_ref die = lookup_type_die (type);
25703           if (die)
25704             check_die (die);
25705         }
25706     }
25707 }
25708
25709 /* Generate a DW_TAG_lexical_block DIE followed by DIEs to represent all of the
25710    things which are local to the given block.  */
25711
25712 static void
25713 gen_block_die (tree stmt, dw_die_ref context_die)
25714 {
25715   int must_output_die = 0;
25716   bool inlined_func;
25717
25718   /* Ignore blocks that are NULL.  */
25719   if (stmt == NULL_TREE)
25720     return;
25721
25722   inlined_func = inlined_function_outer_scope_p (stmt);
25723
25724   /* If the block is one fragment of a non-contiguous block, do not
25725      process the variables, since they will have been done by the
25726      origin block.  Do process subblocks.  */
25727   if (BLOCK_FRAGMENT_ORIGIN (stmt))
25728     {
25729       tree sub;
25730
25731       for (sub = BLOCK_SUBBLOCKS (stmt); sub; sub = BLOCK_CHAIN (sub))
25732         gen_block_die (sub, context_die);
25733
25734       return;
25735     }
25736
25737   /* Determine if we need to output any Dwarf DIEs at all to represent this
25738      block.  */
25739   if (inlined_func)
25740     /* The outer scopes for inlinings *must* always be represented.  We
25741        generate DW_TAG_inlined_subroutine DIEs for them.  (See below.) */
25742     must_output_die = 1;
25743   else
25744     {
25745       /* Determine if this block directly contains any "significant"
25746          local declarations which we will need to output DIEs for.  */
25747       if (debug_info_level > DINFO_LEVEL_TERSE)
25748         /* We are not in terse mode so *any* local declaration counts
25749            as being a "significant" one.  */
25750         must_output_die = ((BLOCK_VARS (stmt) != NULL
25751                             || BLOCK_NUM_NONLOCALIZED_VARS (stmt))
25752                            && (TREE_USED (stmt)
25753                                || TREE_ASM_WRITTEN (stmt)
25754                                || BLOCK_ABSTRACT (stmt)));
25755       else if ((TREE_USED (stmt)
25756                 || TREE_ASM_WRITTEN (stmt)
25757                 || BLOCK_ABSTRACT (stmt))
25758                && !dwarf2out_ignore_block (stmt))
25759         must_output_die = 1;
25760     }
25761
25762   /* It would be a waste of space to generate a Dwarf DW_TAG_lexical_block
25763      DIE for any block which contains no significant local declarations at
25764      all.  Rather, in such cases we just call `decls_for_scope' so that any
25765      needed Dwarf info for any sub-blocks will get properly generated. Note
25766      that in terse mode, our definition of what constitutes a "significant"
25767      local declaration gets restricted to include only inlined function
25768      instances and local (nested) function definitions.  */
25769   if (must_output_die)
25770     {
25771       if (inlined_func)
25772         {
25773           /* If STMT block is abstract, that means we have been called
25774              indirectly from dwarf2out_abstract_function.
25775              That function rightfully marks the descendent blocks (of
25776              the abstract function it is dealing with) as being abstract,
25777              precisely to prevent us from emitting any
25778              DW_TAG_inlined_subroutine DIE as a descendent
25779              of an abstract function instance. So in that case, we should
25780              not call gen_inlined_subroutine_die.
25781
25782              Later though, when cgraph asks dwarf2out to emit info
25783              for the concrete instance of the function decl into which
25784              the concrete instance of STMT got inlined, the later will lead
25785              to the generation of a DW_TAG_inlined_subroutine DIE.  */
25786           if (! BLOCK_ABSTRACT (stmt))
25787             gen_inlined_subroutine_die (stmt, context_die);
25788         }
25789       else
25790         gen_lexical_block_die (stmt, context_die);
25791     }
25792   else
25793     decls_for_scope (stmt, context_die);
25794 }
25795
25796 /* Process variable DECL (or variable with origin ORIGIN) within
25797    block STMT and add it to CONTEXT_DIE.  */
25798 static void
25799 process_scope_var (tree stmt, tree decl, tree origin, dw_die_ref context_die)
25800 {
25801   dw_die_ref die;
25802   tree decl_or_origin = decl ? decl : origin;
25803
25804   if (TREE_CODE (decl_or_origin) == FUNCTION_DECL)
25805     die = lookup_decl_die (decl_or_origin);
25806   else if (TREE_CODE (decl_or_origin) == TYPE_DECL)
25807     {
25808       if (TYPE_DECL_IS_STUB (decl_or_origin))
25809         die = lookup_type_die (TREE_TYPE (decl_or_origin));
25810       else
25811         die = lookup_decl_die (decl_or_origin);
25812       /* Avoid re-creating the DIE late if it was optimized as unused early.  */
25813       if (! die && ! early_dwarf)
25814         return;
25815     }
25816   else
25817     die = NULL;
25818
25819   /* Avoid creating DIEs for local typedefs and concrete static variables that
25820      will only be pruned later.  */
25821   if ((origin || decl_ultimate_origin (decl))
25822       && (TREE_CODE (decl_or_origin) == TYPE_DECL
25823           || (VAR_P (decl_or_origin) && TREE_STATIC (decl_or_origin))))
25824     {
25825       origin = decl_ultimate_origin (decl_or_origin);
25826       if (decl && VAR_P (decl) && die != NULL)
25827         {
25828           die = lookup_decl_die (origin);
25829           if (die != NULL)
25830             equate_decl_number_to_die (decl, die);
25831         }
25832       return;
25833     }
25834
25835   if (die != NULL && die->die_parent == NULL)
25836     add_child_die (context_die, die);
25837   else if (TREE_CODE (decl_or_origin) == IMPORTED_DECL)
25838     {
25839       if (early_dwarf)
25840         dwarf2out_imported_module_or_decl_1 (decl_or_origin, DECL_NAME (decl_or_origin),
25841                                              stmt, context_die);
25842     }
25843   else
25844     {
25845       if (decl && DECL_P (decl))
25846         {
25847           die = lookup_decl_die (decl);
25848
25849           /* Early created DIEs do not have a parent as the decls refer
25850              to the function as DECL_CONTEXT rather than the BLOCK.  */
25851           if (die && die->die_parent == NULL)
25852             {
25853               gcc_assert (in_lto_p);
25854               add_child_die (context_die, die);
25855             }
25856         }
25857
25858       gen_decl_die (decl, origin, NULL, context_die);
25859     }
25860 }
25861
25862 /* Generate all of the decls declared within a given scope and (recursively)
25863    all of its sub-blocks.  */
25864
25865 static void
25866 decls_for_scope (tree stmt, dw_die_ref context_die)
25867 {
25868   tree decl;
25869   unsigned int i;
25870   tree subblocks;
25871
25872   /* Ignore NULL blocks.  */
25873   if (stmt == NULL_TREE)
25874     return;
25875
25876   /* Output the DIEs to represent all of the data objects and typedefs
25877      declared directly within this block but not within any nested
25878      sub-blocks.  Also, nested function and tag DIEs have been
25879      generated with a parent of NULL; fix that up now.  We don't
25880      have to do this if we're at -g1.  */
25881   if (debug_info_level > DINFO_LEVEL_TERSE)
25882     {
25883       for (decl = BLOCK_VARS (stmt); decl != NULL; decl = DECL_CHAIN (decl))
25884         process_scope_var (stmt, decl, NULL_TREE, context_die);
25885       /* BLOCK_NONLOCALIZED_VARs simply generate DIE stubs with abstract
25886          origin - avoid doing this twice as we have no good way to see
25887          if we've done it once already.  */
25888       if (! early_dwarf)
25889         for (i = 0; i < BLOCK_NUM_NONLOCALIZED_VARS (stmt); i++)
25890           {
25891             decl = BLOCK_NONLOCALIZED_VAR (stmt, i);
25892             if (decl == current_function_decl)
25893               /* Ignore declarations of the current function, while they
25894                  are declarations, gen_subprogram_die would treat them
25895                  as definitions again, because they are equal to
25896                  current_function_decl and endlessly recurse.  */;
25897             else if (TREE_CODE (decl) == FUNCTION_DECL)
25898               process_scope_var (stmt, decl, NULL_TREE, context_die);
25899             else
25900               process_scope_var (stmt, NULL_TREE, decl, context_die);
25901           }
25902     }
25903
25904   /* Even if we're at -g1, we need to process the subblocks in order to get
25905      inlined call information.  */
25906
25907   /* Output the DIEs to represent all sub-blocks (and the items declared
25908      therein) of this block.  */
25909   for (subblocks = BLOCK_SUBBLOCKS (stmt);
25910        subblocks != NULL;
25911        subblocks = BLOCK_CHAIN (subblocks))
25912     gen_block_die (subblocks, context_die);
25913 }
25914
25915 /* Is this a typedef we can avoid emitting?  */
25916
25917 bool
25918 is_redundant_typedef (const_tree decl)
25919 {
25920   if (TYPE_DECL_IS_STUB (decl))
25921     return true;
25922
25923   if (DECL_ARTIFICIAL (decl)
25924       && DECL_CONTEXT (decl)
25925       && is_tagged_type (DECL_CONTEXT (decl))
25926       && TREE_CODE (TYPE_NAME (DECL_CONTEXT (decl))) == TYPE_DECL
25927       && DECL_NAME (decl) == DECL_NAME (TYPE_NAME (DECL_CONTEXT (decl))))
25928     /* Also ignore the artificial member typedef for the class name.  */
25929     return true;
25930
25931   return false;
25932 }
25933
25934 /* Return TRUE if TYPE is a typedef that names a type for linkage
25935    purposes. This kind of typedefs is produced by the C++ FE for
25936    constructs like:
25937
25938    typedef struct {...} foo;
25939
25940    In that case, there is no typedef variant type produced for foo.
25941    Rather, the TREE_TYPE of the TYPE_DECL of foo is the anonymous
25942    struct type.  */
25943
25944 static bool
25945 is_naming_typedef_decl (const_tree decl)
25946 {
25947   if (decl == NULL_TREE
25948       || TREE_CODE (decl) != TYPE_DECL
25949       || DECL_NAMELESS (decl)
25950       || !is_tagged_type (TREE_TYPE (decl))
25951       || DECL_IS_BUILTIN (decl)
25952       || is_redundant_typedef (decl)
25953       /* It looks like Ada produces TYPE_DECLs that are very similar
25954          to C++ naming typedefs but that have different
25955          semantics. Let's be specific to c++ for now.  */
25956       || !is_cxx (decl))
25957     return FALSE;
25958
25959   return (DECL_ORIGINAL_TYPE (decl) == NULL_TREE
25960           && TYPE_NAME (TREE_TYPE (decl)) == decl
25961           && (TYPE_STUB_DECL (TREE_TYPE (decl))
25962               != TYPE_NAME (TREE_TYPE (decl))));
25963 }
25964
25965 /* Looks up the DIE for a context.  */
25966
25967 static inline dw_die_ref
25968 lookup_context_die (tree context)
25969 {
25970   if (context)
25971     {
25972       /* Find die that represents this context.  */
25973       if (TYPE_P (context))
25974         {
25975           context = TYPE_MAIN_VARIANT (context);
25976           dw_die_ref ctx = lookup_type_die (context);
25977           if (!ctx)
25978             return NULL;
25979           return strip_naming_typedef (context, ctx);
25980         }
25981       else
25982         return lookup_decl_die (context);
25983     }
25984   return comp_unit_die ();
25985 }
25986
25987 /* Returns the DIE for a context.  */
25988
25989 static inline dw_die_ref
25990 get_context_die (tree context)
25991 {
25992   if (context)
25993     {
25994       /* Find die that represents this context.  */
25995       if (TYPE_P (context))
25996         {
25997           context = TYPE_MAIN_VARIANT (context);
25998           return strip_naming_typedef (context, force_type_die (context));
25999         }
26000       else
26001         return force_decl_die (context);
26002     }
26003   return comp_unit_die ();
26004 }
26005
26006 /* Returns the DIE for decl.  A DIE will always be returned.  */
26007
26008 static dw_die_ref
26009 force_decl_die (tree decl)
26010 {
26011   dw_die_ref decl_die;
26012   unsigned saved_external_flag;
26013   tree save_fn = NULL_TREE;
26014   decl_die = lookup_decl_die (decl);
26015   if (!decl_die)
26016     {
26017       dw_die_ref context_die = get_context_die (DECL_CONTEXT (decl));
26018
26019       decl_die = lookup_decl_die (decl);
26020       if (decl_die)
26021         return decl_die;
26022
26023       switch (TREE_CODE (decl))
26024         {
26025         case FUNCTION_DECL:
26026           /* Clear current_function_decl, so that gen_subprogram_die thinks
26027              that this is a declaration. At this point, we just want to force
26028              declaration die.  */
26029           save_fn = current_function_decl;
26030           current_function_decl = NULL_TREE;
26031           gen_subprogram_die (decl, context_die);
26032           current_function_decl = save_fn;
26033           break;
26034
26035         case VAR_DECL:
26036           /* Set external flag to force declaration die. Restore it after
26037            gen_decl_die() call.  */
26038           saved_external_flag = DECL_EXTERNAL (decl);
26039           DECL_EXTERNAL (decl) = 1;
26040           gen_decl_die (decl, NULL, NULL, context_die);
26041           DECL_EXTERNAL (decl) = saved_external_flag;
26042           break;
26043
26044         case NAMESPACE_DECL:
26045           if (dwarf_version >= 3 || !dwarf_strict)
26046             dwarf2out_decl (decl);
26047           else
26048             /* DWARF2 has neither DW_TAG_module, nor DW_TAG_namespace.  */
26049             decl_die = comp_unit_die ();
26050           break;
26051
26052         case TRANSLATION_UNIT_DECL:
26053           decl_die = comp_unit_die ();
26054           break;
26055
26056         default:
26057           gcc_unreachable ();
26058         }
26059
26060       /* We should be able to find the DIE now.  */
26061       if (!decl_die)
26062         decl_die = lookup_decl_die (decl);
26063       gcc_assert (decl_die);
26064     }
26065
26066   return decl_die;
26067 }
26068
26069 /* Returns the DIE for TYPE, that must not be a base type.  A DIE is
26070    always returned.  */
26071
26072 static dw_die_ref
26073 force_type_die (tree type)
26074 {
26075   dw_die_ref type_die;
26076
26077   type_die = lookup_type_die (type);
26078   if (!type_die)
26079     {
26080       dw_die_ref context_die = get_context_die (TYPE_CONTEXT (type));
26081
26082       type_die = modified_type_die (type, TYPE_QUALS_NO_ADDR_SPACE (type),
26083                                     false, context_die);
26084       gcc_assert (type_die);
26085     }
26086   return type_die;
26087 }
26088
26089 /* Force out any required namespaces to be able to output DECL,
26090    and return the new context_die for it, if it's changed.  */
26091
26092 static dw_die_ref
26093 setup_namespace_context (tree thing, dw_die_ref context_die)
26094 {
26095   tree context = (DECL_P (thing)
26096                   ? DECL_CONTEXT (thing) : TYPE_CONTEXT (thing));
26097   if (context && TREE_CODE (context) == NAMESPACE_DECL)
26098     /* Force out the namespace.  */
26099     context_die = force_decl_die (context);
26100
26101   return context_die;
26102 }
26103
26104 /* Emit a declaration DIE for THING (which is either a DECL or a tagged
26105    type) within its namespace, if appropriate.
26106
26107    For compatibility with older debuggers, namespace DIEs only contain
26108    declarations; all definitions are emitted at CU scope, with
26109    DW_AT_specification pointing to the declaration (like with class
26110    members).  */
26111
26112 static dw_die_ref
26113 declare_in_namespace (tree thing, dw_die_ref context_die)
26114 {
26115   dw_die_ref ns_context;
26116
26117   if (debug_info_level <= DINFO_LEVEL_TERSE)
26118     return context_die;
26119
26120   /* External declarations in the local scope only need to be emitted
26121      once, not once in the namespace and once in the scope.
26122
26123      This avoids declaring the `extern' below in the
26124      namespace DIE as well as in the innermost scope:
26125
26126           namespace S
26127           {
26128             int i=5;
26129             int foo()
26130             {
26131               int i=8;
26132               extern int i;
26133               return i;
26134             }
26135           }
26136   */
26137   if (DECL_P (thing) && DECL_EXTERNAL (thing) && local_scope_p (context_die))
26138     return context_die;
26139
26140   /* If this decl is from an inlined function, then don't try to emit it in its
26141      namespace, as we will get confused.  It would have already been emitted
26142      when the abstract instance of the inline function was emitted anyways.  */
26143   if (DECL_P (thing) && DECL_ABSTRACT_ORIGIN (thing))
26144     return context_die;
26145
26146   ns_context = setup_namespace_context (thing, context_die);
26147
26148   if (ns_context != context_die)
26149     {
26150       if (is_fortran ())
26151         return ns_context;
26152       if (DECL_P (thing))
26153         gen_decl_die (thing, NULL, NULL, ns_context);
26154       else
26155         gen_type_die (thing, ns_context);
26156     }
26157   return context_die;
26158 }
26159
26160 /* Generate a DIE for a namespace or namespace alias.  */
26161
26162 static void
26163 gen_namespace_die (tree decl, dw_die_ref context_die)
26164 {
26165   dw_die_ref namespace_die;
26166
26167   /* Namespace aliases have a DECL_ABSTRACT_ORIGIN of the namespace
26168      they are an alias of.  */
26169   if (DECL_ABSTRACT_ORIGIN (decl) == NULL)
26170     {
26171       /* Output a real namespace or module.  */
26172       context_die = setup_namespace_context (decl, comp_unit_die ());
26173       namespace_die = new_die (is_fortran ()
26174                                ? DW_TAG_module : DW_TAG_namespace,
26175                                context_die, decl);
26176       /* For Fortran modules defined in different CU don't add src coords.  */
26177       if (namespace_die->die_tag == DW_TAG_module && DECL_EXTERNAL (decl))
26178         {
26179           const char *name = dwarf2_name (decl, 0);
26180           if (name)
26181             add_name_attribute (namespace_die, name);
26182         }
26183       else
26184         add_name_and_src_coords_attributes (namespace_die, decl);
26185       if (DECL_EXTERNAL (decl))
26186         add_AT_flag (namespace_die, DW_AT_declaration, 1);
26187       equate_decl_number_to_die (decl, namespace_die);
26188     }
26189   else
26190     {
26191       /* Output a namespace alias.  */
26192
26193       /* Force out the namespace we are an alias of, if necessary.  */
26194       dw_die_ref origin_die
26195         = force_decl_die (DECL_ABSTRACT_ORIGIN (decl));
26196
26197       if (DECL_FILE_SCOPE_P (decl)
26198           || TREE_CODE (DECL_CONTEXT (decl)) == NAMESPACE_DECL)
26199         context_die = setup_namespace_context (decl, comp_unit_die ());
26200       /* Now create the namespace alias DIE.  */
26201       namespace_die = new_die (DW_TAG_imported_declaration, context_die, decl);
26202       add_name_and_src_coords_attributes (namespace_die, decl);
26203       add_AT_die_ref (namespace_die, DW_AT_import, origin_die);
26204       equate_decl_number_to_die (decl, namespace_die);
26205     }
26206   if ((dwarf_version >= 5 || !dwarf_strict)
26207       && lang_hooks.decls.decl_dwarf_attribute (decl,
26208                                                 DW_AT_export_symbols) == 1)
26209     add_AT_flag (namespace_die, DW_AT_export_symbols, 1);
26210
26211   /* Bypass dwarf2_name's check for DECL_NAMELESS.  */
26212   if (want_pubnames ())
26213     add_pubname_string (lang_hooks.dwarf_name (decl, 1), namespace_die);
26214 }
26215
26216 /* Generate Dwarf debug information for a decl described by DECL.
26217    The return value is currently only meaningful for PARM_DECLs,
26218    for all other decls it returns NULL.
26219
26220    If DECL is a FIELD_DECL, CTX is required: see the comment for VLR_CONTEXT.
26221    It can be NULL otherwise.  */
26222
26223 static dw_die_ref
26224 gen_decl_die (tree decl, tree origin, struct vlr_context *ctx,
26225               dw_die_ref context_die)
26226 {
26227   tree decl_or_origin = decl ? decl : origin;
26228   tree class_origin = NULL, ultimate_origin;
26229
26230   if (DECL_P (decl_or_origin) && DECL_IGNORED_P (decl_or_origin))
26231     return NULL;
26232
26233   /* Ignore pointer bounds decls.  */
26234   if (DECL_P (decl_or_origin)
26235       && TREE_TYPE (decl_or_origin)
26236       && POINTER_BOUNDS_P (decl_or_origin))
26237     return NULL;
26238
26239   switch (TREE_CODE (decl_or_origin))
26240     {
26241     case ERROR_MARK:
26242       break;
26243
26244     case CONST_DECL:
26245       if (!is_fortran () && !is_ada ())
26246         {
26247           /* The individual enumerators of an enum type get output when we output
26248              the Dwarf representation of the relevant enum type itself.  */
26249           break;
26250         }
26251
26252       /* Emit its type.  */
26253       gen_type_die (TREE_TYPE (decl), context_die);
26254
26255       /* And its containing namespace.  */
26256       context_die = declare_in_namespace (decl, context_die);
26257
26258       gen_const_die (decl, context_die);
26259       break;
26260
26261     case FUNCTION_DECL:
26262 #if 0
26263       /* FIXME */
26264       /* This doesn't work because the C frontend sets DECL_ABSTRACT_ORIGIN
26265          on local redeclarations of global functions.  That seems broken.  */
26266       if (current_function_decl != decl)
26267         /* This is only a declaration.  */;
26268 #endif
26269
26270       /* We should have abstract copies already and should not generate
26271          stray type DIEs in late LTO dumping.  */
26272       if (! early_dwarf)
26273         ;
26274
26275       /* If we're emitting a clone, emit info for the abstract instance.  */
26276       else if (origin || DECL_ORIGIN (decl) != decl)
26277         dwarf2out_abstract_function (origin
26278                                      ? DECL_ORIGIN (origin)
26279                                      : DECL_ABSTRACT_ORIGIN (decl));
26280
26281       /* If we're emitting a possibly inlined function emit it as
26282          abstract instance.  */
26283       else if (cgraph_function_possibly_inlined_p (decl)
26284                && ! DECL_ABSTRACT_P (decl)
26285                && ! class_or_namespace_scope_p (context_die)
26286                /* dwarf2out_abstract_function won't emit a die if this is just
26287                   a declaration.  We must avoid setting DECL_ABSTRACT_ORIGIN in
26288                   that case, because that works only if we have a die.  */
26289                && DECL_INITIAL (decl) != NULL_TREE)
26290         dwarf2out_abstract_function (decl);
26291
26292       /* Otherwise we're emitting the primary DIE for this decl.  */
26293       else if (debug_info_level > DINFO_LEVEL_TERSE)
26294         {
26295           /* Before we describe the FUNCTION_DECL itself, make sure that we
26296              have its containing type.  */
26297           if (!origin)
26298             origin = decl_class_context (decl);
26299           if (origin != NULL_TREE)
26300             gen_type_die (origin, context_die);
26301
26302           /* And its return type.  */
26303           gen_type_die (TREE_TYPE (TREE_TYPE (decl)), context_die);
26304
26305           /* And its virtual context.  */
26306           if (DECL_VINDEX (decl) != NULL_TREE)
26307             gen_type_die (DECL_CONTEXT (decl), context_die);
26308
26309           /* Make sure we have a member DIE for decl.  */
26310           if (origin != NULL_TREE)
26311             gen_type_die_for_member (origin, decl, context_die);
26312
26313           /* And its containing namespace.  */
26314           context_die = declare_in_namespace (decl, context_die);
26315         }
26316
26317       /* Now output a DIE to represent the function itself.  */
26318       if (decl)
26319         gen_subprogram_die (decl, context_die);
26320       break;
26321
26322     case TYPE_DECL:
26323       /* If we are in terse mode, don't generate any DIEs to represent any
26324          actual typedefs.  */
26325       if (debug_info_level <= DINFO_LEVEL_TERSE)
26326         break;
26327
26328       /* In the special case of a TYPE_DECL node representing the declaration
26329          of some type tag, if the given TYPE_DECL is marked as having been
26330          instantiated from some other (original) TYPE_DECL node (e.g. one which
26331          was generated within the original definition of an inline function) we
26332          used to generate a special (abbreviated) DW_TAG_structure_type,
26333          DW_TAG_union_type, or DW_TAG_enumeration_type DIE here.  But nothing
26334          should be actually referencing those DIEs, as variable DIEs with that
26335          type would be emitted already in the abstract origin, so it was always
26336          removed during unused type prunning.  Don't add anything in this
26337          case.  */
26338       if (TYPE_DECL_IS_STUB (decl) && decl_ultimate_origin (decl) != NULL_TREE)
26339         break;
26340
26341       if (is_redundant_typedef (decl))
26342         gen_type_die (TREE_TYPE (decl), context_die);
26343       else
26344         /* Output a DIE to represent the typedef itself.  */
26345         gen_typedef_die (decl, context_die);
26346       break;
26347
26348     case LABEL_DECL:
26349       if (debug_info_level >= DINFO_LEVEL_NORMAL)
26350         gen_label_die (decl, context_die);
26351       break;
26352
26353     case VAR_DECL:
26354     case RESULT_DECL:
26355       /* If we are in terse mode, don't generate any DIEs to represent any
26356          variable declarations or definitions.  */
26357       if (debug_info_level <= DINFO_LEVEL_TERSE)
26358         break;
26359
26360       /* Avoid generating stray type DIEs during late dwarf dumping.
26361          All types have been dumped early.  */
26362       if (early_dwarf
26363           /* ???  But in LTRANS we cannot annotate early created variably
26364              modified type DIEs without copying them and adjusting all
26365              references to them.  Dump them again as happens for inlining
26366              which copies both the decl and the types.  */
26367           /* ???  And even non-LTO needs to re-visit type DIEs to fill
26368              in VLA bound information for example.  */
26369           || (decl && variably_modified_type_p (TREE_TYPE (decl),
26370                                                 current_function_decl)))
26371         {
26372           /* Output any DIEs that are needed to specify the type of this data
26373              object.  */
26374           if (decl_by_reference_p (decl_or_origin))
26375             gen_type_die (TREE_TYPE (TREE_TYPE (decl_or_origin)), context_die);
26376           else
26377             gen_type_die (TREE_TYPE (decl_or_origin), context_die);
26378         }
26379
26380       if (early_dwarf)
26381         {
26382           /* And its containing type.  */
26383           class_origin = decl_class_context (decl_or_origin);
26384           if (class_origin != NULL_TREE)
26385             gen_type_die_for_member (class_origin, decl_or_origin, context_die);
26386
26387           /* And its containing namespace.  */
26388           context_die = declare_in_namespace (decl_or_origin, context_die);
26389         }
26390
26391       /* Now output the DIE to represent the data object itself.  This gets
26392          complicated because of the possibility that the VAR_DECL really
26393          represents an inlined instance of a formal parameter for an inline
26394          function.  */
26395       ultimate_origin = decl_ultimate_origin (decl_or_origin);
26396       if (ultimate_origin != NULL_TREE
26397           && TREE_CODE (ultimate_origin) == PARM_DECL)
26398         gen_formal_parameter_die (decl, origin,
26399                                   true /* Emit name attribute.  */,
26400                                   context_die);
26401       else
26402         gen_variable_die (decl, origin, context_die);
26403       break;
26404
26405     case FIELD_DECL:
26406       gcc_assert (ctx != NULL && ctx->struct_type != NULL);
26407       /* Ignore the nameless fields that are used to skip bits but handle C++
26408          anonymous unions and structs.  */
26409       if (DECL_NAME (decl) != NULL_TREE
26410           || TREE_CODE (TREE_TYPE (decl)) == UNION_TYPE
26411           || TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE)
26412         {
26413           gen_type_die (member_declared_type (decl), context_die);
26414           gen_field_die (decl, ctx, context_die);
26415         }
26416       break;
26417
26418     case PARM_DECL:
26419       /* Avoid generating stray type DIEs during late dwarf dumping.
26420          All types have been dumped early.  */
26421       if (early_dwarf
26422           /* ???  But in LTRANS we cannot annotate early created variably
26423              modified type DIEs without copying them and adjusting all
26424              references to them.  Dump them again as happens for inlining
26425              which copies both the decl and the types.  */
26426           /* ???  And even non-LTO needs to re-visit type DIEs to fill
26427              in VLA bound information for example.  */
26428           || (decl && variably_modified_type_p (TREE_TYPE (decl),
26429                                                 current_function_decl)))
26430         {
26431           if (DECL_BY_REFERENCE (decl_or_origin))
26432             gen_type_die (TREE_TYPE (TREE_TYPE (decl_or_origin)), context_die);
26433           else
26434             gen_type_die (TREE_TYPE (decl_or_origin), context_die);
26435         }
26436       return gen_formal_parameter_die (decl, origin,
26437                                        true /* Emit name attribute.  */,
26438                                        context_die);
26439
26440     case NAMESPACE_DECL:
26441       if (dwarf_version >= 3 || !dwarf_strict)
26442         gen_namespace_die (decl, context_die);
26443       break;
26444
26445     case IMPORTED_DECL:
26446       dwarf2out_imported_module_or_decl_1 (decl, DECL_NAME (decl),
26447                                            DECL_CONTEXT (decl), context_die);
26448       break;
26449
26450     case NAMELIST_DECL:
26451       gen_namelist_decl (DECL_NAME (decl), context_die,
26452                          NAMELIST_DECL_ASSOCIATED_DECL (decl));
26453       break;
26454
26455     default:
26456       /* Probably some frontend-internal decl.  Assume we don't care.  */
26457       gcc_assert ((int)TREE_CODE (decl) > NUM_TREE_CODES);
26458       break;
26459     }
26460
26461   return NULL;
26462 }
26463 \f
26464 /* Output initial debug information for global DECL.  Called at the
26465    end of the parsing process.
26466
26467    This is the initial debug generation process.  As such, the DIEs
26468    generated may be incomplete.  A later debug generation pass
26469    (dwarf2out_late_global_decl) will augment the information generated
26470    in this pass (e.g., with complete location info).  */
26471
26472 static void
26473 dwarf2out_early_global_decl (tree decl)
26474 {
26475   set_early_dwarf s;
26476
26477   /* gen_decl_die() will set DECL_ABSTRACT because
26478      cgraph_function_possibly_inlined_p() returns true.  This is in
26479      turn will cause DW_AT_inline attributes to be set.
26480
26481      This happens because at early dwarf generation, there is no
26482      cgraph information, causing cgraph_function_possibly_inlined_p()
26483      to return true.  Trick cgraph_function_possibly_inlined_p()
26484      while we generate dwarf early.  */
26485   bool save = symtab->global_info_ready;
26486   symtab->global_info_ready = true;
26487
26488   /* We don't handle TYPE_DECLs.  If required, they'll be reached via
26489      other DECLs and they can point to template types or other things
26490      that dwarf2out can't handle when done via dwarf2out_decl.  */
26491   if (TREE_CODE (decl) != TYPE_DECL
26492       && TREE_CODE (decl) != PARM_DECL)
26493     {
26494       if (TREE_CODE (decl) == FUNCTION_DECL)
26495         {
26496           tree save_fndecl = current_function_decl;
26497
26498           /* For nested functions, make sure we have DIEs for the parents first
26499              so that all nested DIEs are generated at the proper scope in the
26500              first shot.  */
26501           tree context = decl_function_context (decl);
26502           if (context != NULL)
26503             {
26504               dw_die_ref context_die = lookup_decl_die (context);
26505               current_function_decl = context;
26506
26507               /* Avoid emitting DIEs multiple times, but still process CONTEXT
26508                  enough so that it lands in its own context.  This avoids type
26509                  pruning issues later on.  */
26510               if (context_die == NULL || is_declaration_die (context_die))
26511                 dwarf2out_early_global_decl (context);
26512             }
26513
26514           /* Emit an abstract origin of a function first.  This happens
26515              with C++ constructor clones for example and makes
26516              dwarf2out_abstract_function happy which requires the early
26517              DIE of the abstract instance to be present.  */
26518           tree origin = DECL_ABSTRACT_ORIGIN (decl);
26519           dw_die_ref origin_die;
26520           if (origin != NULL
26521               /* Do not emit the DIE multiple times but make sure to
26522                  process it fully here in case we just saw a declaration.  */
26523               && ((origin_die = lookup_decl_die (origin)) == NULL
26524                   || is_declaration_die (origin_die)))
26525             {
26526               current_function_decl = origin;
26527               dwarf2out_decl (origin);
26528             }
26529
26530           /* Emit the DIE for decl but avoid doing that multiple times.  */
26531           dw_die_ref old_die;
26532           if ((old_die = lookup_decl_die (decl)) == NULL
26533               || is_declaration_die (old_die))
26534             {
26535               current_function_decl = decl;
26536               dwarf2out_decl (decl);
26537             }
26538
26539           current_function_decl = save_fndecl;
26540         }
26541       else
26542         dwarf2out_decl (decl);
26543     }
26544   symtab->global_info_ready = save;
26545 }
26546
26547 /* Return whether EXPR is an expression with the following pattern:
26548    INDIRECT_REF (NOP_EXPR (INTEGER_CST)).  */
26549
26550 static bool
26551 is_trivial_indirect_ref (tree expr)
26552 {
26553   if (expr == NULL_TREE || TREE_CODE (expr) != INDIRECT_REF)
26554     return false;
26555
26556   tree nop = TREE_OPERAND (expr, 0);
26557   if (nop == NULL_TREE || TREE_CODE (nop) != NOP_EXPR)
26558     return false;
26559
26560   tree int_cst = TREE_OPERAND (nop, 0);
26561   return int_cst != NULL_TREE && TREE_CODE (int_cst) == INTEGER_CST;
26562 }
26563
26564 /* Output debug information for global decl DECL.  Called from
26565    toplev.c after compilation proper has finished.  */
26566
26567 static void
26568 dwarf2out_late_global_decl (tree decl)
26569 {
26570   /* Fill-in any location information we were unable to determine
26571      on the first pass.  */
26572   if (VAR_P (decl) && !POINTER_BOUNDS_P (decl))
26573     {
26574       dw_die_ref die = lookup_decl_die (decl);
26575
26576       /* We may have to generate early debug late for LTO in case debug
26577          was not enabled at compile-time or the target doesn't support
26578          the LTO early debug scheme.  */
26579       if (! die && in_lto_p)
26580         {
26581           dwarf2out_decl (decl);
26582           die = lookup_decl_die (decl);
26583         }
26584
26585       if (die)
26586         {
26587           /* We get called via the symtab code invoking late_global_decl
26588              for symbols that are optimized out.
26589
26590              Do not add locations for those, except if they have a
26591              DECL_VALUE_EXPR, in which case they are relevant for debuggers.
26592              Still don't add a location if the DECL_VALUE_EXPR is not a trivial
26593              INDIRECT_REF expression, as this could generate relocations to
26594              text symbols in LTO object files, which is invalid.  */
26595           varpool_node *node = varpool_node::get (decl);
26596           if ((! node || ! node->definition)
26597               && ! (DECL_HAS_VALUE_EXPR_P (decl)
26598                     && is_trivial_indirect_ref (DECL_VALUE_EXPR (decl))))
26599             tree_add_const_value_attribute_for_decl (die, decl);
26600           else
26601             add_location_or_const_value_attribute (die, decl, false);
26602         }
26603     }
26604 }
26605
26606 /* Output debug information for type decl DECL.  Called from toplev.c
26607    and from language front ends (to record built-in types).  */
26608 static void
26609 dwarf2out_type_decl (tree decl, int local)
26610 {
26611   if (!local)
26612     {
26613       set_early_dwarf s;
26614       dwarf2out_decl (decl);
26615     }
26616 }
26617
26618 /* Output debug information for imported module or decl DECL.
26619    NAME is non-NULL name in the lexical block if the decl has been renamed.
26620    LEXICAL_BLOCK is the lexical block (which TREE_CODE is a BLOCK)
26621    that DECL belongs to.
26622    LEXICAL_BLOCK_DIE is the DIE of LEXICAL_BLOCK.  */
26623 static void
26624 dwarf2out_imported_module_or_decl_1 (tree decl,
26625                                      tree name,
26626                                      tree lexical_block,
26627                                      dw_die_ref lexical_block_die)
26628 {
26629   expanded_location xloc;
26630   dw_die_ref imported_die = NULL;
26631   dw_die_ref at_import_die;
26632
26633   if (TREE_CODE (decl) == IMPORTED_DECL)
26634     {
26635       xloc = expand_location (DECL_SOURCE_LOCATION (decl));
26636       decl = IMPORTED_DECL_ASSOCIATED_DECL (decl);
26637       gcc_assert (decl);
26638     }
26639   else
26640     xloc = expand_location (input_location);
26641
26642   if (TREE_CODE (decl) == TYPE_DECL || TREE_CODE (decl) == CONST_DECL)
26643     {
26644       at_import_die = force_type_die (TREE_TYPE (decl));
26645       /* For namespace N { typedef void T; } using N::T; base_type_die
26646          returns NULL, but DW_TAG_imported_declaration requires
26647          the DW_AT_import tag.  Force creation of DW_TAG_typedef.  */
26648       if (!at_import_die)
26649         {
26650           gcc_assert (TREE_CODE (decl) == TYPE_DECL);
26651           gen_typedef_die (decl, get_context_die (DECL_CONTEXT (decl)));
26652           at_import_die = lookup_type_die (TREE_TYPE (decl));
26653           gcc_assert (at_import_die);
26654         }
26655     }
26656   else
26657     {
26658       at_import_die = lookup_decl_die (decl);
26659       if (!at_import_die)
26660         {
26661           /* If we're trying to avoid duplicate debug info, we may not have
26662              emitted the member decl for this field.  Emit it now.  */
26663           if (TREE_CODE (decl) == FIELD_DECL)
26664             {
26665               tree type = DECL_CONTEXT (decl);
26666
26667               if (TYPE_CONTEXT (type)
26668                   && TYPE_P (TYPE_CONTEXT (type))
26669                   && !should_emit_struct_debug (TYPE_CONTEXT (type),
26670                                                 DINFO_USAGE_DIR_USE))
26671                 return;
26672               gen_type_die_for_member (type, decl,
26673                                        get_context_die (TYPE_CONTEXT (type)));
26674             }
26675           if (TREE_CODE (decl) == NAMELIST_DECL)
26676             at_import_die = gen_namelist_decl (DECL_NAME (decl),
26677                                          get_context_die (DECL_CONTEXT (decl)),
26678                                          NULL_TREE);
26679           else
26680             at_import_die = force_decl_die (decl);
26681         }
26682     }
26683
26684   if (TREE_CODE (decl) == NAMESPACE_DECL)
26685     {
26686       if (dwarf_version >= 3 || !dwarf_strict)
26687         imported_die = new_die (DW_TAG_imported_module,
26688                                 lexical_block_die,
26689                                 lexical_block);
26690       else
26691         return;
26692     }
26693   else
26694     imported_die = new_die (DW_TAG_imported_declaration,
26695                             lexical_block_die,
26696                             lexical_block);
26697
26698   add_AT_file (imported_die, DW_AT_decl_file, lookup_filename (xloc.file));
26699   add_AT_unsigned (imported_die, DW_AT_decl_line, xloc.line);
26700   if (debug_column_info && xloc.column)
26701     add_AT_unsigned (imported_die, DW_AT_decl_column, xloc.column);
26702   if (name)
26703     add_AT_string (imported_die, DW_AT_name,
26704                    IDENTIFIER_POINTER (name));
26705   add_AT_die_ref (imported_die, DW_AT_import, at_import_die);
26706 }
26707
26708 /* Output debug information for imported module or decl DECL.
26709    NAME is non-NULL name in context if the decl has been renamed.
26710    CHILD is true if decl is one of the renamed decls as part of
26711    importing whole module.
26712    IMPLICIT is set if this hook is called for an implicit import
26713    such as inline namespace.  */
26714
26715 static void
26716 dwarf2out_imported_module_or_decl (tree decl, tree name, tree context,
26717                                    bool child, bool implicit)
26718 {
26719   /* dw_die_ref at_import_die;  */
26720   dw_die_ref scope_die;
26721
26722   if (debug_info_level <= DINFO_LEVEL_TERSE)
26723     return;
26724
26725   gcc_assert (decl);
26726
26727   /* For DWARF5, just DW_AT_export_symbols on the DW_TAG_namespace
26728      should be enough, for DWARF4 and older even if we emit as extension
26729      DW_AT_export_symbols add the implicit DW_TAG_imported_module anyway
26730      for the benefit of consumers unaware of DW_AT_export_symbols.  */
26731   if (implicit
26732       && dwarf_version >= 5
26733       && lang_hooks.decls.decl_dwarf_attribute (decl,
26734                                                 DW_AT_export_symbols) == 1)
26735     return;
26736
26737   set_early_dwarf s;
26738
26739   /* To emit DW_TAG_imported_module or DW_TAG_imported_decl, we need two DIEs.
26740      We need decl DIE for reference and scope die. First, get DIE for the decl
26741      itself.  */
26742
26743   /* Get the scope die for decl context. Use comp_unit_die for global module
26744      or decl. If die is not found for non globals, force new die.  */
26745   if (context
26746       && TYPE_P (context)
26747       && !should_emit_struct_debug (context, DINFO_USAGE_DIR_USE))
26748     return;
26749
26750   scope_die = get_context_die (context);
26751
26752   if (child)
26753     {
26754       /* DW_TAG_imported_module was introduced in the DWARFv3 specification, so
26755          there is nothing we can do, here.  */
26756       if (dwarf_version < 3 && dwarf_strict)
26757         return;
26758
26759       gcc_assert (scope_die->die_child);
26760       gcc_assert (scope_die->die_child->die_tag == DW_TAG_imported_module);
26761       gcc_assert (TREE_CODE (decl) != NAMESPACE_DECL);
26762       scope_die = scope_die->die_child;
26763     }
26764
26765   /* OK, now we have DIEs for decl as well as scope. Emit imported die.  */
26766   dwarf2out_imported_module_or_decl_1 (decl, name, context, scope_die);
26767 }
26768
26769 /* Output debug information for namelists.   */
26770
26771 static dw_die_ref
26772 gen_namelist_decl (tree name, dw_die_ref scope_die, tree item_decls)
26773 {
26774   dw_die_ref nml_die, nml_item_die, nml_item_ref_die;
26775   tree value;
26776   unsigned i;
26777
26778   if (debug_info_level <= DINFO_LEVEL_TERSE)
26779     return NULL;
26780
26781   gcc_assert (scope_die != NULL);
26782   nml_die = new_die (DW_TAG_namelist, scope_die, NULL);
26783   add_AT_string (nml_die, DW_AT_name, IDENTIFIER_POINTER (name));
26784
26785   /* If there are no item_decls, we have a nondefining namelist, e.g.
26786      with USE association; hence, set DW_AT_declaration.  */
26787   if (item_decls == NULL_TREE)
26788     {
26789       add_AT_flag (nml_die, DW_AT_declaration, 1);
26790       return nml_die;
26791     }
26792
26793   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (item_decls), i, value)
26794     {
26795       nml_item_ref_die = lookup_decl_die (value);
26796       if (!nml_item_ref_die)
26797         nml_item_ref_die = force_decl_die (value);
26798
26799       nml_item_die = new_die (DW_TAG_namelist_item, nml_die, NULL);
26800       add_AT_die_ref (nml_item_die, DW_AT_namelist_items, nml_item_ref_die);
26801     }
26802   return nml_die;
26803 }
26804
26805
26806 /* Write the debugging output for DECL and return the DIE.  */
26807
26808 static void
26809 dwarf2out_decl (tree decl)
26810 {
26811   dw_die_ref context_die = comp_unit_die ();
26812
26813   switch (TREE_CODE (decl))
26814     {
26815     case ERROR_MARK:
26816       return;
26817
26818     case FUNCTION_DECL:
26819       /* If we're a nested function, initially use a parent of NULL; if we're
26820          a plain function, this will be fixed up in decls_for_scope.  If
26821          we're a method, it will be ignored, since we already have a DIE.  */
26822       if (decl_function_context (decl)
26823           /* But if we're in terse mode, we don't care about scope.  */
26824           && debug_info_level > DINFO_LEVEL_TERSE)
26825         context_die = NULL;
26826       break;
26827
26828     case VAR_DECL:
26829       /* For local statics lookup proper context die.  */
26830       if (local_function_static (decl))
26831         context_die = lookup_decl_die (DECL_CONTEXT (decl));
26832
26833       /* If we are in terse mode, don't generate any DIEs to represent any
26834          variable declarations or definitions.  */
26835       if (debug_info_level <= DINFO_LEVEL_TERSE)
26836         return;
26837       break;
26838
26839     case CONST_DECL:
26840       if (debug_info_level <= DINFO_LEVEL_TERSE)
26841         return;
26842       if (!is_fortran () && !is_ada ())
26843         return;
26844       if (TREE_STATIC (decl) && decl_function_context (decl))
26845         context_die = lookup_decl_die (DECL_CONTEXT (decl));
26846       break;
26847
26848     case NAMESPACE_DECL:
26849     case IMPORTED_DECL:
26850       if (debug_info_level <= DINFO_LEVEL_TERSE)
26851         return;
26852       if (lookup_decl_die (decl) != NULL)
26853         return;
26854       break;
26855
26856     case TYPE_DECL:
26857       /* Don't emit stubs for types unless they are needed by other DIEs.  */
26858       if (TYPE_DECL_SUPPRESS_DEBUG (decl))
26859         return;
26860
26861       /* Don't bother trying to generate any DIEs to represent any of the
26862          normal built-in types for the language we are compiling.  */
26863       if (DECL_IS_BUILTIN (decl))
26864         return;
26865
26866       /* If we are in terse mode, don't generate any DIEs for types.  */
26867       if (debug_info_level <= DINFO_LEVEL_TERSE)
26868         return;
26869
26870       /* If we're a function-scope tag, initially use a parent of NULL;
26871          this will be fixed up in decls_for_scope.  */
26872       if (decl_function_context (decl))
26873         context_die = NULL;
26874
26875       break;
26876
26877     case NAMELIST_DECL:
26878       break;
26879
26880     default:
26881       return;
26882     }
26883
26884   gen_decl_die (decl, NULL, NULL, context_die);
26885
26886   if (flag_checking)
26887     {
26888       dw_die_ref die = lookup_decl_die (decl);
26889       if (die)
26890         check_die (die);
26891     }
26892 }
26893
26894 /* Write the debugging output for DECL.  */
26895
26896 static void
26897 dwarf2out_function_decl (tree decl)
26898 {
26899   dwarf2out_decl (decl);
26900   call_arg_locations = NULL;
26901   call_arg_loc_last = NULL;
26902   call_site_count = -1;
26903   tail_call_site_count = -1;
26904   decl_loc_table->empty ();
26905   cached_dw_loc_list_table->empty ();
26906 }
26907
26908 /* Output a marker (i.e. a label) for the beginning of the generated code for
26909    a lexical block.  */
26910
26911 static void
26912 dwarf2out_begin_block (unsigned int line ATTRIBUTE_UNUSED,
26913                        unsigned int blocknum)
26914 {
26915   switch_to_section (current_function_section ());
26916   ASM_OUTPUT_DEBUG_LABEL (asm_out_file, BLOCK_BEGIN_LABEL, blocknum);
26917 }
26918
26919 /* Output a marker (i.e. a label) for the end of the generated code for a
26920    lexical block.  */
26921
26922 static void
26923 dwarf2out_end_block (unsigned int line ATTRIBUTE_UNUSED, unsigned int blocknum)
26924 {
26925   switch_to_section (current_function_section ());
26926   ASM_OUTPUT_DEBUG_LABEL (asm_out_file, BLOCK_END_LABEL, blocknum);
26927 }
26928
26929 /* Returns nonzero if it is appropriate not to emit any debugging
26930    information for BLOCK, because it doesn't contain any instructions.
26931
26932    Don't allow this for blocks with nested functions or local classes
26933    as we would end up with orphans, and in the presence of scheduling
26934    we may end up calling them anyway.  */
26935
26936 static bool
26937 dwarf2out_ignore_block (const_tree block)
26938 {
26939   tree decl;
26940   unsigned int i;
26941
26942   for (decl = BLOCK_VARS (block); decl; decl = DECL_CHAIN (decl))
26943     if (TREE_CODE (decl) == FUNCTION_DECL
26944         || (TREE_CODE (decl) == TYPE_DECL && TYPE_DECL_IS_STUB (decl)))
26945       return 0;
26946   for (i = 0; i < BLOCK_NUM_NONLOCALIZED_VARS (block); i++)
26947     {
26948       decl = BLOCK_NONLOCALIZED_VAR (block, i);
26949       if (TREE_CODE (decl) == FUNCTION_DECL
26950           || (TREE_CODE (decl) == TYPE_DECL && TYPE_DECL_IS_STUB (decl)))
26951       return 0;
26952     }
26953
26954   return 1;
26955 }
26956
26957 /* Hash table routines for file_hash.  */
26958
26959 bool
26960 dwarf_file_hasher::equal (dwarf_file_data *p1, const char *p2)
26961 {
26962   return filename_cmp (p1->filename, p2) == 0;
26963 }
26964
26965 hashval_t
26966 dwarf_file_hasher::hash (dwarf_file_data *p)
26967 {
26968   return htab_hash_string (p->filename);
26969 }
26970
26971 /* Lookup FILE_NAME (in the list of filenames that we know about here in
26972    dwarf2out.c) and return its "index".  The index of each (known) filename is
26973    just a unique number which is associated with only that one filename.  We
26974    need such numbers for the sake of generating labels (in the .debug_sfnames
26975    section) and references to those files numbers (in the .debug_srcinfo
26976    and .debug_macinfo sections).  If the filename given as an argument is not
26977    found in our current list, add it to the list and assign it the next
26978    available unique index number.  */
26979
26980 static struct dwarf_file_data *
26981 lookup_filename (const char *file_name)
26982 {
26983   struct dwarf_file_data * created;
26984
26985   if (!file_name)
26986     return NULL;
26987
26988   dwarf_file_data **slot
26989     = file_table->find_slot_with_hash (file_name, htab_hash_string (file_name),
26990                                        INSERT);
26991   if (*slot)
26992     return *slot;
26993
26994   created = ggc_alloc<dwarf_file_data> ();
26995   created->filename = file_name;
26996   created->emitted_number = 0;
26997   *slot = created;
26998   return created;
26999 }
27000
27001 /* If the assembler will construct the file table, then translate the compiler
27002    internal file table number into the assembler file table number, and emit
27003    a .file directive if we haven't already emitted one yet.  The file table
27004    numbers are different because we prune debug info for unused variables and
27005    types, which may include filenames.  */
27006
27007 static int
27008 maybe_emit_file (struct dwarf_file_data * fd)
27009 {
27010   if (! fd->emitted_number)
27011     {
27012       if (last_emitted_file)
27013         fd->emitted_number = last_emitted_file->emitted_number + 1;
27014       else
27015         fd->emitted_number = 1;
27016       last_emitted_file = fd;
27017
27018       if (output_asm_line_debug_info ())
27019         {
27020           fprintf (asm_out_file, "\t.file %u ", fd->emitted_number);
27021           output_quoted_string (asm_out_file,
27022                                 remap_debug_filename (fd->filename));
27023           fputc ('\n', asm_out_file);
27024         }
27025     }
27026
27027   return fd->emitted_number;
27028 }
27029
27030 /* Schedule generation of a DW_AT_const_value attribute to DIE.
27031    That generation should happen after function debug info has been
27032    generated. The value of the attribute is the constant value of ARG.  */
27033
27034 static void
27035 append_entry_to_tmpl_value_parm_die_table (dw_die_ref die, tree arg)
27036 {
27037   die_arg_entry entry;
27038
27039   if (!die || !arg)
27040     return;
27041
27042   gcc_assert (early_dwarf);
27043
27044   if (!tmpl_value_parm_die_table)
27045     vec_alloc (tmpl_value_parm_die_table, 32);
27046
27047   entry.die = die;
27048   entry.arg = arg;
27049   vec_safe_push (tmpl_value_parm_die_table, entry);
27050 }
27051
27052 /* Return TRUE if T is an instance of generic type, FALSE
27053    otherwise.  */
27054
27055 static bool
27056 generic_type_p (tree t)
27057 {
27058   if (t == NULL_TREE || !TYPE_P (t))
27059     return false;
27060   return lang_hooks.get_innermost_generic_parms (t) != NULL_TREE;
27061 }
27062
27063 /* Schedule the generation of the generic parameter dies for the
27064   instance of generic type T. The proper generation itself is later
27065   done by gen_scheduled_generic_parms_dies. */
27066
27067 static void
27068 schedule_generic_params_dies_gen (tree t)
27069 {
27070   if (!generic_type_p (t))
27071     return;
27072
27073   gcc_assert (early_dwarf);
27074
27075   if (!generic_type_instances)
27076     vec_alloc (generic_type_instances, 256);
27077
27078   vec_safe_push (generic_type_instances, t);
27079 }
27080
27081 /* Add a DW_AT_const_value attribute to DIEs that were scheduled
27082    by append_entry_to_tmpl_value_parm_die_table. This function must
27083    be called after function DIEs have been generated.  */
27084
27085 static void
27086 gen_remaining_tmpl_value_param_die_attribute (void)
27087 {
27088   if (tmpl_value_parm_die_table)
27089     {
27090       unsigned i, j;
27091       die_arg_entry *e;
27092
27093       /* We do this in two phases - first get the cases we can
27094          handle during early-finish, preserving those we cannot
27095          (containing symbolic constants where we don't yet know
27096          whether we are going to output the referenced symbols).
27097          For those we try again at late-finish.  */
27098       j = 0;
27099       FOR_EACH_VEC_ELT (*tmpl_value_parm_die_table, i, e)
27100         {
27101           if (!e->die->removed
27102               && !tree_add_const_value_attribute (e->die, e->arg))
27103             {
27104               dw_loc_descr_ref loc = NULL;
27105               if (! early_dwarf
27106                   && (dwarf_version >= 5 || !dwarf_strict))
27107                 loc = loc_descriptor_from_tree (e->arg, 2, NULL);
27108               if (loc)
27109                 add_AT_loc (e->die, DW_AT_location, loc);
27110               else
27111                 (*tmpl_value_parm_die_table)[j++] = *e;
27112             }
27113         }
27114       tmpl_value_parm_die_table->truncate (j);
27115     }
27116 }
27117
27118 /* Generate generic parameters DIEs for instances of generic types
27119    that have been previously scheduled by
27120    schedule_generic_params_dies_gen. This function must be called
27121    after all the types of the CU have been laid out.  */
27122
27123 static void
27124 gen_scheduled_generic_parms_dies (void)
27125 {
27126   unsigned i;
27127   tree t;
27128
27129   if (!generic_type_instances)
27130     return;
27131   
27132   FOR_EACH_VEC_ELT (*generic_type_instances, i, t)
27133     if (COMPLETE_TYPE_P (t))
27134       gen_generic_params_dies (t);
27135
27136   generic_type_instances = NULL;
27137 }
27138
27139
27140 /* Replace DW_AT_name for the decl with name.  */
27141
27142 static void
27143 dwarf2out_set_name (tree decl, tree name)
27144 {
27145   dw_die_ref die;
27146   dw_attr_node *attr;
27147   const char *dname;
27148
27149   die = TYPE_SYMTAB_DIE (decl);
27150   if (!die)
27151     return;
27152
27153   dname = dwarf2_name (name, 0);
27154   if (!dname)
27155     return;
27156
27157   attr = get_AT (die, DW_AT_name);
27158   if (attr)
27159     {
27160       struct indirect_string_node *node;
27161
27162       node = find_AT_string (dname);
27163       /* replace the string.  */
27164       attr->dw_attr_val.v.val_str = node;
27165     }
27166
27167   else
27168     add_name_attribute (die, dname);
27169 }
27170
27171 /* True if before or during processing of the first function being emitted.  */
27172 static bool in_first_function_p = true;
27173 /* True if loc_note during dwarf2out_var_location call might still be
27174    before first real instruction at address equal to .Ltext0.  */
27175 static bool maybe_at_text_label_p = true;
27176 /* One above highest N where .LVLN label might be equal to .Ltext0 label.  */
27177 static unsigned int first_loclabel_num_not_at_text_label;
27178
27179 /* Look ahead for a real insn, or for a begin stmt marker.  */
27180
27181 static rtx_insn *
27182 dwarf2out_next_real_insn (rtx_insn *loc_note)
27183 {
27184   rtx_insn *next_real = NEXT_INSN (loc_note);
27185
27186   while (next_real)
27187     if (INSN_P (next_real))
27188       break;
27189     else
27190       next_real = NEXT_INSN (next_real);
27191
27192   return next_real;
27193 }
27194
27195 /* Called by the final INSN scan whenever we see a var location.  We
27196    use it to drop labels in the right places, and throw the location in
27197    our lookup table.  */
27198
27199 static void
27200 dwarf2out_var_location (rtx_insn *loc_note)
27201 {
27202   char loclabel[MAX_ARTIFICIAL_LABEL_BYTES + 2];
27203   struct var_loc_node *newloc;
27204   rtx_insn *next_real, *next_note;
27205   rtx_insn *call_insn = NULL;
27206   static const char *last_label;
27207   static const char *last_postcall_label;
27208   static bool last_in_cold_section_p;
27209   static rtx_insn *expected_next_loc_note;
27210   tree decl;
27211   bool var_loc_p;
27212   var_loc_view view = 0;
27213
27214   if (!NOTE_P (loc_note))
27215     {
27216       if (CALL_P (loc_note))
27217         {
27218           maybe_reset_location_view (loc_note, cur_line_info_table);
27219           call_site_count++;
27220           if (SIBLING_CALL_P (loc_note))
27221             tail_call_site_count++;
27222           if (find_reg_note (loc_note, REG_CALL_ARG_LOCATION, NULL_RTX))
27223             {
27224               call_insn = loc_note;
27225               loc_note = NULL;
27226               var_loc_p = false;
27227
27228               next_real = dwarf2out_next_real_insn (call_insn);
27229               next_note = NULL;
27230               cached_next_real_insn = NULL;
27231               goto create_label;
27232             }
27233           if (optimize == 0 && !flag_var_tracking)
27234             {
27235               /* When the var-tracking pass is not running, there is no note
27236                  for indirect calls whose target is compile-time known. In this
27237                  case, process such calls specifically so that we generate call
27238                  sites for them anyway.  */
27239               rtx x = PATTERN (loc_note);
27240               if (GET_CODE (x) == PARALLEL)
27241                 x = XVECEXP (x, 0, 0);
27242               if (GET_CODE (x) == SET)
27243                 x = SET_SRC (x);
27244               if (GET_CODE (x) == CALL)
27245                 x = XEXP (x, 0);
27246               if (!MEM_P (x)
27247                   || GET_CODE (XEXP (x, 0)) != SYMBOL_REF
27248                   || !SYMBOL_REF_DECL (XEXP (x, 0))
27249                   || (TREE_CODE (SYMBOL_REF_DECL (XEXP (x, 0)))
27250                       != FUNCTION_DECL))
27251                 {
27252                   call_insn = loc_note;
27253                   loc_note = NULL;
27254                   var_loc_p = false;
27255
27256                   next_real = dwarf2out_next_real_insn (call_insn);
27257                   next_note = NULL;
27258                   cached_next_real_insn = NULL;
27259                   goto create_label;
27260                 }
27261             }
27262         }
27263       else if (!debug_variable_location_views)
27264         gcc_unreachable ();
27265       else
27266         maybe_reset_location_view (loc_note, cur_line_info_table);
27267
27268       return;
27269     }
27270
27271   var_loc_p = NOTE_KIND (loc_note) == NOTE_INSN_VAR_LOCATION;
27272   if (var_loc_p && !DECL_P (NOTE_VAR_LOCATION_DECL (loc_note)))
27273     return;
27274
27275   /* Optimize processing a large consecutive sequence of location
27276      notes so we don't spend too much time in next_real_insn.  If the
27277      next insn is another location note, remember the next_real_insn
27278      calculation for next time.  */
27279   next_real = cached_next_real_insn;
27280   if (next_real)
27281     {
27282       if (expected_next_loc_note != loc_note)
27283         next_real = NULL;
27284     }
27285
27286   next_note = NEXT_INSN (loc_note);
27287   if (! next_note
27288       || next_note->deleted ()
27289       || ! NOTE_P (next_note)
27290       || (NOTE_KIND (next_note) != NOTE_INSN_VAR_LOCATION
27291           && NOTE_KIND (next_note) != NOTE_INSN_BEGIN_STMT
27292           && NOTE_KIND (next_note) != NOTE_INSN_INLINE_ENTRY))
27293     next_note = NULL;
27294
27295   if (! next_real)
27296     next_real = dwarf2out_next_real_insn (loc_note);
27297
27298   if (next_note)
27299     {
27300       expected_next_loc_note = next_note;
27301       cached_next_real_insn = next_real;
27302     }
27303   else
27304     cached_next_real_insn = NULL;
27305
27306   /* If there are no instructions which would be affected by this note,
27307      don't do anything.  */
27308   if (var_loc_p
27309       && next_real == NULL_RTX
27310       && !NOTE_DURING_CALL_P (loc_note))
27311     return;
27312
27313 create_label:
27314
27315   if (next_real == NULL_RTX)
27316     next_real = get_last_insn ();
27317
27318   /* If there were any real insns between note we processed last time
27319      and this note (or if it is the first note), clear
27320      last_{,postcall_}label so that they are not reused this time.  */
27321   if (last_var_location_insn == NULL_RTX
27322       || last_var_location_insn != next_real
27323       || last_in_cold_section_p != in_cold_section_p)
27324     {
27325       last_label = NULL;
27326       last_postcall_label = NULL;
27327     }
27328
27329   if (var_loc_p)
27330     {
27331       const char *label
27332         = NOTE_DURING_CALL_P (loc_note) ? last_postcall_label : last_label;
27333       view = cur_line_info_table->view;
27334       decl = NOTE_VAR_LOCATION_DECL (loc_note);
27335       newloc = add_var_loc_to_decl (decl, loc_note, label, view);
27336       if (newloc == NULL)
27337         return;
27338     }
27339   else
27340     {
27341       decl = NULL_TREE;
27342       newloc = NULL;
27343     }
27344
27345   /* If there were no real insns between note we processed last time
27346      and this note, use the label we emitted last time.  Otherwise
27347      create a new label and emit it.  */
27348   if (last_label == NULL)
27349     {
27350       ASM_GENERATE_INTERNAL_LABEL (loclabel, "LVL", loclabel_num);
27351       ASM_OUTPUT_DEBUG_LABEL (asm_out_file, "LVL", loclabel_num);
27352       loclabel_num++;
27353       last_label = ggc_strdup (loclabel);
27354       /* See if loclabel might be equal to .Ltext0.  If yes,
27355          bump first_loclabel_num_not_at_text_label.  */
27356       if (!have_multiple_function_sections
27357           && in_first_function_p
27358           && maybe_at_text_label_p)
27359         {
27360           static rtx_insn *last_start;
27361           rtx_insn *insn;
27362           for (insn = loc_note; insn; insn = previous_insn (insn))
27363             if (insn == last_start)
27364               break;
27365             else if (!NONDEBUG_INSN_P (insn))
27366               continue;
27367             else
27368               {
27369                 rtx body = PATTERN (insn);
27370                 if (GET_CODE (body) == USE || GET_CODE (body) == CLOBBER)
27371                   continue;
27372                 /* Inline asm could occupy zero bytes.  */
27373                 else if (GET_CODE (body) == ASM_INPUT
27374                          || asm_noperands (body) >= 0)
27375                   continue;
27376 #ifdef HAVE_ATTR_length /* ??? We don't include insn-attr.h.  */
27377                 else if (HAVE_ATTR_length && get_attr_min_length (insn) == 0)
27378                   continue;
27379 #endif
27380                 else
27381                   {
27382                     /* Assume insn has non-zero length.  */
27383                     maybe_at_text_label_p = false;
27384                     break;
27385                   }
27386               }
27387           if (maybe_at_text_label_p)
27388             {
27389               last_start = loc_note;
27390               first_loclabel_num_not_at_text_label = loclabel_num;
27391             }
27392         }
27393     }
27394
27395   gcc_assert ((loc_note == NULL_RTX && call_insn != NULL_RTX)
27396               || (loc_note != NULL_RTX && call_insn == NULL_RTX));
27397
27398   if (!var_loc_p)
27399     {
27400       struct call_arg_loc_node *ca_loc
27401         = ggc_cleared_alloc<call_arg_loc_node> ();
27402       rtx_insn *prev = call_insn;
27403
27404       ca_loc->call_arg_loc_note
27405         = find_reg_note (call_insn, REG_CALL_ARG_LOCATION, NULL_RTX);
27406       ca_loc->next = NULL;
27407       ca_loc->label = last_label;
27408       gcc_assert (prev
27409                   && (CALL_P (prev)
27410                       || (NONJUMP_INSN_P (prev)
27411                           && GET_CODE (PATTERN (prev)) == SEQUENCE
27412                           && CALL_P (XVECEXP (PATTERN (prev), 0, 0)))));
27413       if (!CALL_P (prev))
27414         prev = as_a <rtx_sequence *> (PATTERN (prev))->insn (0);
27415       ca_loc->tail_call_p = SIBLING_CALL_P (prev);
27416
27417       /* Look for a SYMBOL_REF in the "prev" instruction.  */
27418       rtx x = get_call_rtx_from (PATTERN (prev));
27419       if (x)
27420         {
27421           /* Try to get the call symbol, if any.  */
27422           if (MEM_P (XEXP (x, 0)))
27423             x = XEXP (x, 0);
27424           /* First, look for a memory access to a symbol_ref.  */
27425           if (GET_CODE (XEXP (x, 0)) == SYMBOL_REF
27426               && SYMBOL_REF_DECL (XEXP (x, 0))
27427               && TREE_CODE (SYMBOL_REF_DECL (XEXP (x, 0))) == FUNCTION_DECL)
27428             ca_loc->symbol_ref = XEXP (x, 0);
27429           /* Otherwise, look at a compile-time known user-level function
27430              declaration.  */
27431           else if (MEM_P (x)
27432                    && MEM_EXPR (x)
27433                    && TREE_CODE (MEM_EXPR (x)) == FUNCTION_DECL)
27434             ca_loc->symbol_ref = XEXP (DECL_RTL (MEM_EXPR (x)), 0);
27435         }
27436
27437       ca_loc->block = insn_scope (prev);
27438       if (call_arg_locations)
27439         call_arg_loc_last->next = ca_loc;
27440       else
27441         call_arg_locations = ca_loc;
27442       call_arg_loc_last = ca_loc;
27443     }
27444   else if (loc_note != NULL_RTX && !NOTE_DURING_CALL_P (loc_note))
27445     {
27446       newloc->label = last_label;
27447       newloc->view = view;
27448     }
27449   else
27450     {
27451       if (!last_postcall_label)
27452         {
27453           sprintf (loclabel, "%s-1", last_label);
27454           last_postcall_label = ggc_strdup (loclabel);
27455         }
27456       newloc->label = last_postcall_label;
27457       /* ??? This view is at last_label, not last_label-1, but we
27458          could only assume view at last_label-1 is zero if we could
27459          assume calls always have length greater than one.  This is
27460          probably true in general, though there might be a rare
27461          exception to this rule, e.g. if a call insn is optimized out
27462          by target magic.  Then, even the -1 in the label will be
27463          wrong, which might invalidate the range.  Anyway, using view,
27464          though technically possibly incorrect, will work as far as
27465          ranges go: since L-1 is in the middle of the call insn,
27466          (L-1).0 and (L-1).V shouldn't make any difference, and having
27467          the loclist entry refer to the .loc entry might be useful, so
27468          leave it like this.  */
27469       newloc->view = view;
27470     }
27471
27472   if (var_loc_p && flag_debug_asm)
27473     {
27474       const char *name, *sep, *patstr;
27475       if (decl && DECL_NAME (decl))
27476         name = IDENTIFIER_POINTER (DECL_NAME (decl));
27477       else
27478         name = "";
27479       if (NOTE_VAR_LOCATION_LOC (loc_note))
27480         {
27481           sep = " => ";
27482           patstr = str_pattern_slim (NOTE_VAR_LOCATION_LOC (loc_note));
27483         }
27484       else
27485         {
27486           sep = " ";
27487           patstr = "RESET";
27488         }
27489       fprintf (asm_out_file, "\t%s DEBUG %s%s%s\n", ASM_COMMENT_START,
27490                name, sep, patstr);
27491     }
27492
27493   last_var_location_insn = next_real;
27494   last_in_cold_section_p = in_cold_section_p;
27495 }
27496
27497 /* Check whether BLOCK, a lexical block, is nested within OUTER, or is
27498    OUTER itself.  If BOTHWAYS, check not only that BLOCK can reach
27499    OUTER through BLOCK_SUPERCONTEXT links, but also that there is a
27500    path from OUTER to BLOCK through BLOCK_SUBBLOCKs and
27501    BLOCK_FRAGMENT_ORIGIN links.  */
27502 static bool
27503 block_within_block_p (tree block, tree outer, bool bothways)
27504 {
27505   if (block == outer)
27506     return true;
27507
27508   /* Quickly check that OUTER is up BLOCK's supercontext chain.  */
27509   for (tree context = BLOCK_SUPERCONTEXT (block);
27510        context != outer;
27511        context = BLOCK_SUPERCONTEXT (context))
27512     if (!context || TREE_CODE (context) != BLOCK)
27513       return false;
27514
27515   if (!bothways)
27516     return true;
27517
27518   /* Now check that each block is actually referenced by its
27519      parent.  */
27520   for (tree context = BLOCK_SUPERCONTEXT (block); ;
27521        context = BLOCK_SUPERCONTEXT (context))
27522     {
27523       if (BLOCK_FRAGMENT_ORIGIN (context))
27524         {
27525           gcc_assert (!BLOCK_SUBBLOCKS (context));
27526           context = BLOCK_FRAGMENT_ORIGIN (context);
27527         }
27528       for (tree sub = BLOCK_SUBBLOCKS (context);
27529            sub != block;
27530            sub = BLOCK_CHAIN (sub))
27531         if (!sub)
27532           return false;
27533       if (context == outer)
27534         return true;
27535       else
27536         block = context;
27537     }
27538 }
27539
27540 /* Called during final while assembling the marker of the entry point
27541    for an inlined function.  */
27542
27543 static void
27544 dwarf2out_inline_entry (tree block)
27545 {
27546   gcc_assert (debug_inline_points);
27547
27548   /* If we can't represent it, don't bother.  */
27549   if (!(dwarf_version >= 3 || !dwarf_strict))
27550     return;
27551
27552   gcc_assert (DECL_P (block_ultimate_origin (block)));
27553
27554   /* Sanity check the block tree.  This would catch a case in which
27555      BLOCK got removed from the tree reachable from the outermost
27556      lexical block, but got retained in markers.  It would still link
27557      back to its parents, but some ancestor would be missing a link
27558      down the path to the sub BLOCK.  If the block got removed, its
27559      BLOCK_NUMBER will not be a usable value.  */
27560   if (flag_checking)
27561     gcc_assert (block_within_block_p (block,
27562                                       DECL_INITIAL (current_function_decl),
27563                                       true));
27564
27565   gcc_assert (inlined_function_outer_scope_p (block));
27566   gcc_assert (!BLOCK_DIE (block));
27567
27568   if (BLOCK_FRAGMENT_ORIGIN (block))
27569     block = BLOCK_FRAGMENT_ORIGIN (block);
27570   /* Can the entry point ever not be at the beginning of an
27571      unfragmented lexical block?  */
27572   else if (!(BLOCK_FRAGMENT_CHAIN (block)
27573              || (cur_line_info_table
27574                  && !ZERO_VIEW_P (cur_line_info_table->view))))
27575     return;
27576
27577   if (!inline_entry_data_table)
27578     inline_entry_data_table
27579       = hash_table<inline_entry_data_hasher>::create_ggc (10);
27580
27581
27582   inline_entry_data **iedp
27583     = inline_entry_data_table->find_slot_with_hash (block,
27584                                                     htab_hash_pointer (block),
27585                                                     INSERT);
27586   if (*iedp)
27587     /* ??? Ideally, we'd record all entry points for the same inlined
27588        function (some may have been duplicated by e.g. unrolling), but
27589        we have no way to represent that ATM.  */
27590     return;
27591
27592   inline_entry_data *ied = *iedp = ggc_cleared_alloc<inline_entry_data> ();
27593   ied->block = block;
27594   ied->label_pfx = BLOCK_INLINE_ENTRY_LABEL;
27595   ied->label_num = BLOCK_NUMBER (block);
27596   if (cur_line_info_table)
27597     ied->view = cur_line_info_table->view;
27598
27599   char label[MAX_ARTIFICIAL_LABEL_BYTES];
27600
27601   ASM_GENERATE_INTERNAL_LABEL (label, BLOCK_INLINE_ENTRY_LABEL,
27602                                BLOCK_NUMBER (block));
27603   ASM_OUTPUT_LABEL (asm_out_file, label);
27604 }
27605
27606 /* Called from finalize_size_functions for size functions so that their body
27607    can be encoded in the debug info to describe the layout of variable-length
27608    structures.  */
27609
27610 static void
27611 dwarf2out_size_function (tree decl)
27612 {
27613   function_to_dwarf_procedure (decl);
27614 }
27615
27616 /* Note in one location list that text section has changed.  */
27617
27618 int
27619 var_location_switch_text_section_1 (var_loc_list **slot, void *)
27620 {
27621   var_loc_list *list = *slot;
27622   if (list->first)
27623     list->last_before_switch
27624       = list->last->next ? list->last->next : list->last;
27625   return 1;
27626 }
27627
27628 /* Note in all location lists that text section has changed.  */
27629
27630 static void
27631 var_location_switch_text_section (void)
27632 {
27633   if (decl_loc_table == NULL)
27634     return;
27635
27636   decl_loc_table->traverse<void *, var_location_switch_text_section_1> (NULL);
27637 }
27638
27639 /* Create a new line number table.  */
27640
27641 static dw_line_info_table *
27642 new_line_info_table (void)
27643 {
27644   dw_line_info_table *table;
27645
27646   table = ggc_cleared_alloc<dw_line_info_table> ();
27647   table->file_num = 1;
27648   table->line_num = 1;
27649   table->is_stmt = DWARF_LINE_DEFAULT_IS_STMT_START;
27650   FORCE_RESET_NEXT_VIEW (table->view);
27651   table->symviews_since_reset = 0;
27652
27653   return table;
27654 }
27655
27656 /* Lookup the "current" table into which we emit line info, so
27657    that we don't have to do it for every source line.  */
27658
27659 static void
27660 set_cur_line_info_table (section *sec)
27661 {
27662   dw_line_info_table *table;
27663
27664   if (sec == text_section)
27665     table = text_section_line_info;
27666   else if (sec == cold_text_section)
27667     {
27668       table = cold_text_section_line_info;
27669       if (!table)
27670         {
27671           cold_text_section_line_info = table = new_line_info_table ();
27672           table->end_label = cold_end_label;
27673         }
27674     }
27675   else
27676     {
27677       const char *end_label;
27678
27679       if (crtl->has_bb_partition)
27680         {
27681           if (in_cold_section_p)
27682             end_label = crtl->subsections.cold_section_end_label;
27683           else
27684             end_label = crtl->subsections.hot_section_end_label;
27685         }
27686       else
27687         {
27688           char label[MAX_ARTIFICIAL_LABEL_BYTES];
27689           ASM_GENERATE_INTERNAL_LABEL (label, FUNC_END_LABEL,
27690                                        current_function_funcdef_no);
27691           end_label = ggc_strdup (label);
27692         }
27693
27694       table = new_line_info_table ();
27695       table->end_label = end_label;
27696
27697       vec_safe_push (separate_line_info, table);
27698     }
27699
27700   if (output_asm_line_debug_info ())
27701     table->is_stmt = (cur_line_info_table
27702                       ? cur_line_info_table->is_stmt
27703                       : DWARF_LINE_DEFAULT_IS_STMT_START);
27704   cur_line_info_table = table;
27705 }
27706
27707
27708 /* We need to reset the locations at the beginning of each
27709    function. We can't do this in the end_function hook, because the
27710    declarations that use the locations won't have been output when
27711    that hook is called.  Also compute have_multiple_function_sections here.  */
27712
27713 static void
27714 dwarf2out_begin_function (tree fun)
27715 {
27716   section *sec = function_section (fun);
27717
27718   if (sec != text_section)
27719     have_multiple_function_sections = true;
27720
27721   if (crtl->has_bb_partition && !cold_text_section)
27722     {
27723       gcc_assert (current_function_decl == fun);
27724       cold_text_section = unlikely_text_section ();
27725       switch_to_section (cold_text_section);
27726       ASM_OUTPUT_LABEL (asm_out_file, cold_text_section_label);
27727       switch_to_section (sec);
27728     }
27729
27730   dwarf2out_note_section_used ();
27731   call_site_count = 0;
27732   tail_call_site_count = 0;
27733
27734   set_cur_line_info_table (sec);
27735   FORCE_RESET_NEXT_VIEW (cur_line_info_table->view);
27736 }
27737
27738 /* Helper function of dwarf2out_end_function, called only after emitting
27739    the very first function into assembly.  Check if some .debug_loc range
27740    might end with a .LVL* label that could be equal to .Ltext0.
27741    In that case we must force using absolute addresses in .debug_loc ranges,
27742    because this range could be .LVLN-.Ltext0 .. .LVLM-.Ltext0 for
27743    .LVLN == .LVLM == .Ltext0, thus 0 .. 0, which is a .debug_loc
27744    list terminator.
27745    Set have_multiple_function_sections to true in that case and
27746    terminate htab traversal.  */
27747
27748 int
27749 find_empty_loc_ranges_at_text_label (var_loc_list **slot, int)
27750 {
27751   var_loc_list *entry = *slot;
27752   struct var_loc_node *node;
27753
27754   node = entry->first;
27755   if (node && node->next && node->next->label)
27756     {
27757       unsigned int i;
27758       const char *label = node->next->label;
27759       char loclabel[MAX_ARTIFICIAL_LABEL_BYTES];
27760
27761       for (i = 0; i < first_loclabel_num_not_at_text_label; i++)
27762         {
27763           ASM_GENERATE_INTERNAL_LABEL (loclabel, "LVL", i);
27764           if (strcmp (label, loclabel) == 0)
27765             {
27766               have_multiple_function_sections = true;
27767               return 0;
27768             }
27769         }
27770     }
27771   return 1;
27772 }
27773
27774 /* Hook called after emitting a function into assembly.
27775    This does something only for the very first function emitted.  */
27776
27777 static void
27778 dwarf2out_end_function (unsigned int)
27779 {
27780   if (in_first_function_p
27781       && !have_multiple_function_sections
27782       && first_loclabel_num_not_at_text_label
27783       && decl_loc_table)
27784     decl_loc_table->traverse<int, find_empty_loc_ranges_at_text_label> (0);
27785   in_first_function_p = false;
27786   maybe_at_text_label_p = false;
27787 }
27788
27789 /* Temporary holder for dwarf2out_register_main_translation_unit.  Used to let
27790    front-ends register a translation unit even before dwarf2out_init is
27791    called.  */
27792 static tree main_translation_unit = NULL_TREE;
27793
27794 /* Hook called by front-ends after they built their main translation unit.
27795    Associate comp_unit_die to UNIT.  */
27796
27797 static void
27798 dwarf2out_register_main_translation_unit (tree unit)
27799 {
27800   gcc_assert (TREE_CODE (unit) == TRANSLATION_UNIT_DECL
27801               && main_translation_unit == NULL_TREE);
27802   main_translation_unit = unit;
27803   /* If dwarf2out_init has not been called yet, it will perform the association
27804      itself looking at main_translation_unit.  */
27805   if (decl_die_table != NULL)
27806     equate_decl_number_to_die (unit, comp_unit_die ());
27807 }
27808
27809 /* Add OPCODE+VAL as an entry at the end of the opcode array in TABLE.  */
27810
27811 static void
27812 push_dw_line_info_entry (dw_line_info_table *table,
27813                          enum dw_line_info_opcode opcode, unsigned int val)
27814 {
27815   dw_line_info_entry e;
27816   e.opcode = opcode;
27817   e.val = val;
27818   vec_safe_push (table->entries, e);
27819 }
27820
27821 /* Output a label to mark the beginning of a source code line entry
27822    and record information relating to this source line, in
27823    'line_info_table' for later output of the .debug_line section.  */
27824 /* ??? The discriminator parameter ought to be unsigned.  */
27825
27826 static void
27827 dwarf2out_source_line (unsigned int line, unsigned int column,
27828                        const char *filename,
27829                        int discriminator, bool is_stmt)
27830 {
27831   unsigned int file_num;
27832   dw_line_info_table *table;
27833   static var_loc_view lvugid;
27834
27835   if (debug_info_level < DINFO_LEVEL_TERSE)
27836     return;
27837
27838   table = cur_line_info_table;
27839
27840   if (line == 0)
27841     {
27842       if (debug_variable_location_views
27843           && output_asm_line_debug_info ()
27844           && table && !RESETTING_VIEW_P (table->view))
27845         {
27846           /* If we're using the assembler to compute view numbers, we
27847              can't issue a .loc directive for line zero, so we can't
27848              get a view number at this point.  We might attempt to
27849              compute it from the previous view, or equate it to a
27850              subsequent view (though it might not be there!), but
27851              since we're omitting the line number entry, we might as
27852              well omit the view number as well.  That means pretending
27853              it's a view number zero, which might very well turn out
27854              to be correct.  ??? Extend the assembler so that the
27855              compiler could emit e.g. ".locview .LVU#", to output a
27856              view without changing line number information.  We'd then
27857              have to count it in symviews_since_reset; when it's omitted,
27858              it doesn't count.  */
27859           if (!zero_view_p)
27860             zero_view_p = BITMAP_GGC_ALLOC ();
27861           bitmap_set_bit (zero_view_p, table->view);
27862           if (flag_debug_asm)
27863             {
27864               char label[MAX_ARTIFICIAL_LABEL_BYTES];
27865               ASM_GENERATE_INTERNAL_LABEL (label, "LVU", table->view);
27866               fprintf (asm_out_file, "\t%s line 0, omitted view ",
27867                        ASM_COMMENT_START);
27868               assemble_name (asm_out_file, label);
27869               putc ('\n', asm_out_file);
27870             }
27871           table->view = ++lvugid;
27872         }
27873       return;
27874     }
27875
27876   /* The discriminator column was added in dwarf4.  Simplify the below
27877      by simply removing it if we're not supposed to output it.  */
27878   if (dwarf_version < 4 && dwarf_strict)
27879     discriminator = 0;
27880
27881   if (!debug_column_info)
27882     column = 0;
27883
27884   file_num = maybe_emit_file (lookup_filename (filename));
27885
27886   /* ??? TODO: Elide duplicate line number entries.  Traditionally,
27887      the debugger has used the second (possibly duplicate) line number
27888      at the beginning of the function to mark the end of the prologue.
27889      We could eliminate any other duplicates within the function.  For
27890      Dwarf3, we ought to include the DW_LNS_set_prologue_end mark in
27891      that second line number entry.  */
27892   /* Recall that this end-of-prologue indication is *not* the same thing
27893      as the end_prologue debug hook.  The NOTE_INSN_PROLOGUE_END note,
27894      to which the hook corresponds, follows the last insn that was 
27895      emitted by gen_prologue.  What we need is to precede the first insn
27896      that had been emitted after NOTE_INSN_FUNCTION_BEG, i.e. the first
27897      insn that corresponds to something the user wrote.  These may be
27898      very different locations once scheduling is enabled.  */
27899
27900   if (0 && file_num == table->file_num
27901       && line == table->line_num
27902       && column == table->column_num
27903       && discriminator == table->discrim_num
27904       && is_stmt == table->is_stmt)
27905     return;
27906
27907   switch_to_section (current_function_section ());
27908
27909   /* If requested, emit something human-readable.  */
27910   if (flag_debug_asm)
27911     {
27912       if (debug_column_info)
27913         fprintf (asm_out_file, "\t%s %s:%d:%d\n", ASM_COMMENT_START,
27914                  filename, line, column);
27915       else
27916         fprintf (asm_out_file, "\t%s %s:%d\n", ASM_COMMENT_START,
27917                  filename, line);
27918     }
27919
27920   if (output_asm_line_debug_info ())
27921     {
27922       /* Emit the .loc directive understood by GNU as.  */
27923       /* "\t.loc %u %u 0 is_stmt %u discriminator %u",
27924          file_num, line, is_stmt, discriminator */
27925       fputs ("\t.loc ", asm_out_file);
27926       fprint_ul (asm_out_file, file_num);
27927       putc (' ', asm_out_file);
27928       fprint_ul (asm_out_file, line);
27929       putc (' ', asm_out_file);
27930       fprint_ul (asm_out_file, column);
27931
27932       if (is_stmt != table->is_stmt)
27933         {
27934           fputs (" is_stmt ", asm_out_file);
27935           putc (is_stmt ? '1' : '0', asm_out_file);
27936         }
27937       if (SUPPORTS_DISCRIMINATOR && discriminator != 0)
27938         {
27939           gcc_assert (discriminator > 0);
27940           fputs (" discriminator ", asm_out_file);
27941           fprint_ul (asm_out_file, (unsigned long) discriminator);
27942         }
27943       if (debug_variable_location_views)
27944         {
27945           if (!RESETTING_VIEW_P (table->view))
27946             {
27947               table->symviews_since_reset++;
27948               if (table->symviews_since_reset > symview_upper_bound)
27949                 symview_upper_bound = table->symviews_since_reset;
27950               /* When we're using the assembler to compute view
27951                  numbers, we output symbolic labels after "view" in
27952                  .loc directives, and the assembler will set them for
27953                  us, so that we can refer to the view numbers in
27954                  location lists.  The only exceptions are when we know
27955                  a view will be zero: "-0" is a forced reset, used
27956                  e.g. in the beginning of functions, whereas "0" tells
27957                  the assembler to check that there was a PC change
27958                  since the previous view, in a way that implicitly
27959                  resets the next view.  */
27960               fputs (" view ", asm_out_file);
27961               char label[MAX_ARTIFICIAL_LABEL_BYTES];
27962               ASM_GENERATE_INTERNAL_LABEL (label, "LVU", table->view);
27963               assemble_name (asm_out_file, label);
27964               table->view = ++lvugid;
27965             }
27966           else
27967             {
27968               table->symviews_since_reset = 0;
27969               if (FORCE_RESETTING_VIEW_P (table->view))
27970                 fputs (" view -0", asm_out_file);
27971               else
27972                 fputs (" view 0", asm_out_file);
27973               /* Mark the present view as a zero view.  Earlier debug
27974                  binds may have already added its id to loclists to be
27975                  emitted later, so we can't reuse the id for something
27976                  else.  However, it's good to know whether a view is
27977                  known to be zero, because then we may be able to
27978                  optimize out locviews that are all zeros, so take
27979                  note of it in zero_view_p.  */
27980               if (!zero_view_p)
27981                 zero_view_p = BITMAP_GGC_ALLOC ();
27982               bitmap_set_bit (zero_view_p, lvugid);
27983               table->view = ++lvugid;
27984             }
27985         }
27986       putc ('\n', asm_out_file);
27987     }
27988   else
27989     {
27990       unsigned int label_num = ++line_info_label_num;
27991
27992       targetm.asm_out.internal_label (asm_out_file, LINE_CODE_LABEL, label_num);
27993
27994       if (debug_variable_location_views && !RESETTING_VIEW_P (table->view))
27995         push_dw_line_info_entry (table, LI_adv_address, label_num);
27996       else
27997         push_dw_line_info_entry (table, LI_set_address, label_num);
27998       if (debug_variable_location_views)
27999         {
28000           bool resetting = FORCE_RESETTING_VIEW_P (table->view);
28001           if (resetting)
28002             table->view = 0;
28003
28004           if (flag_debug_asm)
28005             fprintf (asm_out_file, "\t%s view %s%d\n",
28006                      ASM_COMMENT_START,
28007                      resetting ? "-" : "",
28008                      table->view);
28009
28010           table->view++;
28011         }
28012       if (file_num != table->file_num)
28013         push_dw_line_info_entry (table, LI_set_file, file_num);
28014       if (discriminator != table->discrim_num)
28015         push_dw_line_info_entry (table, LI_set_discriminator, discriminator);
28016       if (is_stmt != table->is_stmt)
28017         push_dw_line_info_entry (table, LI_negate_stmt, 0);
28018       push_dw_line_info_entry (table, LI_set_line, line);
28019       if (debug_column_info)
28020         push_dw_line_info_entry (table, LI_set_column, column);
28021     }
28022
28023   table->file_num = file_num;
28024   table->line_num = line;
28025   table->column_num = column;
28026   table->discrim_num = discriminator;
28027   table->is_stmt = is_stmt;
28028   table->in_use = true;
28029 }
28030
28031 /* Record the beginning of a new source file.  */
28032
28033 static void
28034 dwarf2out_start_source_file (unsigned int lineno, const char *filename)
28035 {
28036   if (debug_info_level >= DINFO_LEVEL_VERBOSE)
28037     {
28038       macinfo_entry e;
28039       e.code = DW_MACINFO_start_file;
28040       e.lineno = lineno;
28041       e.info = ggc_strdup (filename);
28042       vec_safe_push (macinfo_table, e);
28043     }
28044 }
28045
28046 /* Record the end of a source file.  */
28047
28048 static void
28049 dwarf2out_end_source_file (unsigned int lineno ATTRIBUTE_UNUSED)
28050 {
28051   if (debug_info_level >= DINFO_LEVEL_VERBOSE)
28052     {
28053       macinfo_entry e;
28054       e.code = DW_MACINFO_end_file;
28055       e.lineno = lineno;
28056       e.info = NULL;
28057       vec_safe_push (macinfo_table, e);
28058     }
28059 }
28060
28061 /* Called from debug_define in toplev.c.  The `buffer' parameter contains
28062    the tail part of the directive line, i.e. the part which is past the
28063    initial whitespace, #, whitespace, directive-name, whitespace part.  */
28064
28065 static void
28066 dwarf2out_define (unsigned int lineno ATTRIBUTE_UNUSED,
28067                   const char *buffer ATTRIBUTE_UNUSED)
28068 {
28069   if (debug_info_level >= DINFO_LEVEL_VERBOSE)
28070     {
28071       macinfo_entry e;
28072       /* Insert a dummy first entry to be able to optimize the whole
28073          predefined macro block using DW_MACRO_import.  */
28074       if (macinfo_table->is_empty () && lineno <= 1)
28075         {
28076           e.code = 0;
28077           e.lineno = 0;
28078           e.info = NULL;
28079           vec_safe_push (macinfo_table, e);
28080         }
28081       e.code = DW_MACINFO_define;
28082       e.lineno = lineno;
28083       e.info = ggc_strdup (buffer);
28084       vec_safe_push (macinfo_table, e);
28085     }
28086 }
28087
28088 /* Called from debug_undef in toplev.c.  The `buffer' parameter contains
28089    the tail part of the directive line, i.e. the part which is past the
28090    initial whitespace, #, whitespace, directive-name, whitespace part.  */
28091
28092 static void
28093 dwarf2out_undef (unsigned int lineno ATTRIBUTE_UNUSED,
28094                  const char *buffer ATTRIBUTE_UNUSED)
28095 {
28096   if (debug_info_level >= DINFO_LEVEL_VERBOSE)
28097     {
28098       macinfo_entry e;
28099       /* Insert a dummy first entry to be able to optimize the whole
28100          predefined macro block using DW_MACRO_import.  */
28101       if (macinfo_table->is_empty () && lineno <= 1)
28102         {
28103           e.code = 0;
28104           e.lineno = 0;
28105           e.info = NULL;
28106           vec_safe_push (macinfo_table, e);
28107         }
28108       e.code = DW_MACINFO_undef;
28109       e.lineno = lineno;
28110       e.info = ggc_strdup (buffer);
28111       vec_safe_push (macinfo_table, e);
28112     }
28113 }
28114
28115 /* Helpers to manipulate hash table of CUs.  */
28116
28117 struct macinfo_entry_hasher : nofree_ptr_hash <macinfo_entry>
28118 {
28119   static inline hashval_t hash (const macinfo_entry *);
28120   static inline bool equal (const macinfo_entry *, const macinfo_entry *);
28121 };
28122
28123 inline hashval_t
28124 macinfo_entry_hasher::hash (const macinfo_entry *entry)
28125 {
28126   return htab_hash_string (entry->info);
28127 }
28128
28129 inline bool
28130 macinfo_entry_hasher::equal (const macinfo_entry *entry1,
28131                              const macinfo_entry *entry2)
28132 {
28133   return !strcmp (entry1->info, entry2->info);
28134 }
28135
28136 typedef hash_table<macinfo_entry_hasher> macinfo_hash_type;
28137
28138 /* Output a single .debug_macinfo entry.  */
28139
28140 static void
28141 output_macinfo_op (macinfo_entry *ref)
28142 {
28143   int file_num;
28144   size_t len;
28145   struct indirect_string_node *node;
28146   char label[MAX_ARTIFICIAL_LABEL_BYTES];
28147   struct dwarf_file_data *fd;
28148
28149   switch (ref->code)
28150     {
28151     case DW_MACINFO_start_file:
28152       fd = lookup_filename (ref->info);
28153       file_num = maybe_emit_file (fd);
28154       dw2_asm_output_data (1, DW_MACINFO_start_file, "Start new file");
28155       dw2_asm_output_data_uleb128 (ref->lineno,
28156                                    "Included from line number %lu", 
28157                                    (unsigned long) ref->lineno);
28158       dw2_asm_output_data_uleb128 (file_num, "file %s", ref->info);
28159       break;
28160     case DW_MACINFO_end_file:
28161       dw2_asm_output_data (1, DW_MACINFO_end_file, "End file");
28162       break;
28163     case DW_MACINFO_define:
28164     case DW_MACINFO_undef:
28165       len = strlen (ref->info) + 1;
28166       if (!dwarf_strict
28167           && len > DWARF_OFFSET_SIZE
28168           && !DWARF2_INDIRECT_STRING_SUPPORT_MISSING_ON_TARGET
28169           && (debug_str_section->common.flags & SECTION_MERGE) != 0)
28170         {
28171           ref->code = ref->code == DW_MACINFO_define
28172                       ? DW_MACRO_define_strp : DW_MACRO_undef_strp;
28173           output_macinfo_op (ref);
28174           return;
28175         }
28176       dw2_asm_output_data (1, ref->code,
28177                            ref->code == DW_MACINFO_define
28178                            ? "Define macro" : "Undefine macro");
28179       dw2_asm_output_data_uleb128 (ref->lineno, "At line number %lu", 
28180                                    (unsigned long) ref->lineno);
28181       dw2_asm_output_nstring (ref->info, -1, "The macro");
28182       break;
28183     case DW_MACRO_define_strp:
28184     case DW_MACRO_undef_strp:
28185       node = find_AT_string (ref->info);
28186       gcc_assert (node
28187                   && (node->form == DW_FORM_strp
28188                       || node->form == DW_FORM_GNU_str_index));
28189       dw2_asm_output_data (1, ref->code,
28190                            ref->code == DW_MACRO_define_strp
28191                            ? "Define macro strp"
28192                            : "Undefine macro strp");
28193       dw2_asm_output_data_uleb128 (ref->lineno, "At line number %lu",
28194                                    (unsigned long) ref->lineno);
28195       if (node->form == DW_FORM_strp)
28196         dw2_asm_output_offset (DWARF_OFFSET_SIZE, node->label,
28197                                debug_str_section, "The macro: \"%s\"",
28198                                ref->info);
28199       else
28200         dw2_asm_output_data_uleb128 (node->index, "The macro: \"%s\"",
28201                                      ref->info);
28202       break;
28203     case DW_MACRO_import:
28204       dw2_asm_output_data (1, ref->code, "Import");
28205       ASM_GENERATE_INTERNAL_LABEL (label,
28206                                    DEBUG_MACRO_SECTION_LABEL,
28207                                    ref->lineno + macinfo_label_base);
28208       dw2_asm_output_offset (DWARF_OFFSET_SIZE, label, NULL, NULL);
28209       break;
28210     default:
28211       fprintf (asm_out_file, "%s unrecognized macinfo code %lu\n",
28212                ASM_COMMENT_START, (unsigned long) ref->code);
28213       break;
28214     }
28215 }
28216
28217 /* Attempt to make a sequence of define/undef macinfo ops shareable with
28218    other compilation unit .debug_macinfo sections.  IDX is the first
28219    index of a define/undef, return the number of ops that should be
28220    emitted in a comdat .debug_macinfo section and emit
28221    a DW_MACRO_import entry referencing it.
28222    If the define/undef entry should be emitted normally, return 0.  */
28223
28224 static unsigned
28225 optimize_macinfo_range (unsigned int idx, vec<macinfo_entry, va_gc> *files,
28226                         macinfo_hash_type **macinfo_htab)
28227 {
28228   macinfo_entry *first, *second, *cur, *inc;
28229   char linebuf[sizeof (HOST_WIDE_INT) * 3 + 1];
28230   unsigned char checksum[16];
28231   struct md5_ctx ctx;
28232   char *grp_name, *tail;
28233   const char *base;
28234   unsigned int i, count, encoded_filename_len, linebuf_len;
28235   macinfo_entry **slot;
28236
28237   first = &(*macinfo_table)[idx];
28238   second = &(*macinfo_table)[idx + 1];
28239
28240   /* Optimize only if there are at least two consecutive define/undef ops,
28241      and either all of them are before first DW_MACINFO_start_file
28242      with lineno {0,1} (i.e. predefined macro block), or all of them are
28243      in some included header file.  */
28244   if (second->code != DW_MACINFO_define && second->code != DW_MACINFO_undef)
28245     return 0;
28246   if (vec_safe_is_empty (files))
28247     {
28248       if (first->lineno > 1 || second->lineno > 1)
28249         return 0;
28250     }
28251   else if (first->lineno == 0)
28252     return 0;
28253
28254   /* Find the last define/undef entry that can be grouped together
28255      with first and at the same time compute md5 checksum of their
28256      codes, linenumbers and strings.  */
28257   md5_init_ctx (&ctx);
28258   for (i = idx; macinfo_table->iterate (i, &cur); i++)
28259     if (cur->code != DW_MACINFO_define && cur->code != DW_MACINFO_undef)
28260       break;
28261     else if (vec_safe_is_empty (files) && cur->lineno > 1)
28262       break;
28263     else
28264       {
28265         unsigned char code = cur->code;
28266         md5_process_bytes (&code, 1, &ctx);
28267         checksum_uleb128 (cur->lineno, &ctx);
28268         md5_process_bytes (cur->info, strlen (cur->info) + 1, &ctx);
28269       }
28270   md5_finish_ctx (&ctx, checksum);
28271   count = i - idx;
28272
28273   /* From the containing include filename (if any) pick up just
28274      usable characters from its basename.  */
28275   if (vec_safe_is_empty (files))
28276     base = "";
28277   else
28278     base = lbasename (files->last ().info);
28279   for (encoded_filename_len = 0, i = 0; base[i]; i++)
28280     if (ISIDNUM (base[i]) || base[i] == '.')
28281       encoded_filename_len++;
28282   /* Count . at the end.  */
28283   if (encoded_filename_len)
28284     encoded_filename_len++;
28285
28286   sprintf (linebuf, HOST_WIDE_INT_PRINT_UNSIGNED, first->lineno);
28287   linebuf_len = strlen (linebuf);
28288
28289   /* The group name format is: wmN.[<encoded filename>.]<lineno>.<md5sum>  */
28290   grp_name = XALLOCAVEC (char, 4 + encoded_filename_len + linebuf_len + 1
28291                          + 16 * 2 + 1);
28292   memcpy (grp_name, DWARF_OFFSET_SIZE == 4 ? "wm4." : "wm8.", 4);
28293   tail = grp_name + 4;
28294   if (encoded_filename_len)
28295     {
28296       for (i = 0; base[i]; i++)
28297         if (ISIDNUM (base[i]) || base[i] == '.')
28298           *tail++ = base[i];
28299       *tail++ = '.';
28300     }
28301   memcpy (tail, linebuf, linebuf_len);
28302   tail += linebuf_len;
28303   *tail++ = '.';
28304   for (i = 0; i < 16; i++)
28305     sprintf (tail + i * 2, "%02x", checksum[i] & 0xff);
28306
28307   /* Construct a macinfo_entry for DW_MACRO_import
28308      in the empty vector entry before the first define/undef.  */
28309   inc = &(*macinfo_table)[idx - 1];
28310   inc->code = DW_MACRO_import;
28311   inc->lineno = 0;
28312   inc->info = ggc_strdup (grp_name);
28313   if (!*macinfo_htab)
28314     *macinfo_htab = new macinfo_hash_type (10);
28315   /* Avoid emitting duplicates.  */
28316   slot = (*macinfo_htab)->find_slot (inc, INSERT);
28317   if (*slot != NULL)
28318     {
28319       inc->code = 0;
28320       inc->info = NULL;
28321       /* If such an entry has been used before, just emit
28322          a DW_MACRO_import op.  */
28323       inc = *slot;
28324       output_macinfo_op (inc);
28325       /* And clear all macinfo_entry in the range to avoid emitting them
28326          in the second pass.  */
28327       for (i = idx; macinfo_table->iterate (i, &cur) && i < idx + count; i++)
28328         {
28329           cur->code = 0;
28330           cur->info = NULL;
28331         }
28332     }
28333   else
28334     {
28335       *slot = inc;
28336       inc->lineno = (*macinfo_htab)->elements ();
28337       output_macinfo_op (inc);
28338     }
28339   return count;
28340 }
28341
28342 /* Save any strings needed by the macinfo table in the debug str
28343    table.  All strings must be collected into the table by the time
28344    index_string is called.  */
28345
28346 static void
28347 save_macinfo_strings (void)
28348 {
28349   unsigned len;
28350   unsigned i;
28351   macinfo_entry *ref;
28352
28353   for (i = 0; macinfo_table && macinfo_table->iterate (i, &ref); i++)
28354     {
28355       switch (ref->code)
28356         {
28357           /* Match the logic in output_macinfo_op to decide on
28358              indirect strings.  */
28359           case DW_MACINFO_define:
28360           case DW_MACINFO_undef:
28361             len = strlen (ref->info) + 1;
28362             if (!dwarf_strict
28363                 && len > DWARF_OFFSET_SIZE
28364                 && !DWARF2_INDIRECT_STRING_SUPPORT_MISSING_ON_TARGET
28365                 && (debug_str_section->common.flags & SECTION_MERGE) != 0)
28366               set_indirect_string (find_AT_string (ref->info));
28367             break;
28368           case DW_MACRO_define_strp:
28369           case DW_MACRO_undef_strp:
28370             set_indirect_string (find_AT_string (ref->info));
28371             break;
28372           default:
28373             break;
28374         }
28375     }
28376 }
28377
28378 /* Output macinfo section(s).  */
28379
28380 static void
28381 output_macinfo (const char *debug_line_label, bool early_lto_debug)
28382 {
28383   unsigned i;
28384   unsigned long length = vec_safe_length (macinfo_table);
28385   macinfo_entry *ref;
28386   vec<macinfo_entry, va_gc> *files = NULL;
28387   macinfo_hash_type *macinfo_htab = NULL;
28388   char dl_section_ref[MAX_ARTIFICIAL_LABEL_BYTES];
28389
28390   if (! length)
28391     return;
28392
28393   /* output_macinfo* uses these interchangeably.  */
28394   gcc_assert ((int) DW_MACINFO_define == (int) DW_MACRO_define
28395               && (int) DW_MACINFO_undef == (int) DW_MACRO_undef
28396               && (int) DW_MACINFO_start_file == (int) DW_MACRO_start_file
28397               && (int) DW_MACINFO_end_file == (int) DW_MACRO_end_file);
28398
28399   /* AIX Assembler inserts the length, so adjust the reference to match the
28400      offset expected by debuggers.  */
28401   strcpy (dl_section_ref, debug_line_label);
28402   if (XCOFF_DEBUGGING_INFO)
28403     strcat (dl_section_ref, DWARF_INITIAL_LENGTH_SIZE_STR);
28404
28405   /* For .debug_macro emit the section header.  */
28406   if (!dwarf_strict || dwarf_version >= 5)
28407     {
28408       dw2_asm_output_data (2, dwarf_version >= 5 ? 5 : 4,
28409                            "DWARF macro version number");
28410       if (DWARF_OFFSET_SIZE == 8)
28411         dw2_asm_output_data (1, 3, "Flags: 64-bit, lineptr present");
28412       else
28413         dw2_asm_output_data (1, 2, "Flags: 32-bit, lineptr present");
28414       dw2_asm_output_offset (DWARF_OFFSET_SIZE, debug_line_label,
28415                              debug_line_section, NULL);
28416     }
28417
28418   /* In the first loop, it emits the primary .debug_macinfo section
28419      and after each emitted op the macinfo_entry is cleared.
28420      If a longer range of define/undef ops can be optimized using
28421      DW_MACRO_import, the DW_MACRO_import op is emitted and kept in
28422      the vector before the first define/undef in the range and the
28423      whole range of define/undef ops is not emitted and kept.  */
28424   for (i = 0; macinfo_table->iterate (i, &ref); i++)
28425     {
28426       switch (ref->code)
28427         {
28428         case DW_MACINFO_start_file:
28429           vec_safe_push (files, *ref);
28430           break;
28431         case DW_MACINFO_end_file:
28432           if (!vec_safe_is_empty (files))
28433             files->pop ();
28434           break;
28435         case DW_MACINFO_define:
28436         case DW_MACINFO_undef:
28437           if ((!dwarf_strict || dwarf_version >= 5)
28438               && HAVE_COMDAT_GROUP
28439               && vec_safe_length (files) != 1
28440               && i > 0
28441               && i + 1 < length
28442               && (*macinfo_table)[i - 1].code == 0)
28443             {
28444               unsigned count = optimize_macinfo_range (i, files, &macinfo_htab);
28445               if (count)
28446                 {
28447                   i += count - 1;
28448                   continue;
28449                 }
28450             }
28451           break;
28452         case 0:
28453           /* A dummy entry may be inserted at the beginning to be able
28454              to optimize the whole block of predefined macros.  */
28455           if (i == 0)
28456             continue;
28457         default:
28458           break;
28459         }
28460       output_macinfo_op (ref);
28461       ref->info = NULL;
28462       ref->code = 0;
28463     }
28464
28465   if (!macinfo_htab)
28466     return;
28467
28468   /* Save the number of transparent includes so we can adjust the
28469      label number for the fat LTO object DWARF.  */
28470   unsigned macinfo_label_base_adj = macinfo_htab->elements ();
28471
28472   delete macinfo_htab;
28473   macinfo_htab = NULL;
28474
28475   /* If any DW_MACRO_import were used, on those DW_MACRO_import entries
28476      terminate the current chain and switch to a new comdat .debug_macinfo
28477      section and emit the define/undef entries within it.  */
28478   for (i = 0; macinfo_table->iterate (i, &ref); i++)
28479     switch (ref->code)
28480       {
28481       case 0:
28482         continue;
28483       case DW_MACRO_import:
28484         {
28485           char label[MAX_ARTIFICIAL_LABEL_BYTES];
28486           tree comdat_key = get_identifier (ref->info);
28487           /* Terminate the previous .debug_macinfo section.  */
28488           dw2_asm_output_data (1, 0, "End compilation unit");
28489           targetm.asm_out.named_section (debug_macinfo_section_name,
28490                                          SECTION_DEBUG
28491                                          | SECTION_LINKONCE
28492                                          | (early_lto_debug
28493                                             ? SECTION_EXCLUDE : 0),
28494                                          comdat_key);
28495           ASM_GENERATE_INTERNAL_LABEL (label,
28496                                        DEBUG_MACRO_SECTION_LABEL,
28497                                        ref->lineno + macinfo_label_base);
28498           ASM_OUTPUT_LABEL (asm_out_file, label);
28499           ref->code = 0;
28500           ref->info = NULL;
28501           dw2_asm_output_data (2, dwarf_version >= 5 ? 5 : 4,
28502                                "DWARF macro version number");
28503           if (DWARF_OFFSET_SIZE == 8)
28504             dw2_asm_output_data (1, 1, "Flags: 64-bit");
28505           else
28506             dw2_asm_output_data (1, 0, "Flags: 32-bit");
28507         }
28508         break;
28509       case DW_MACINFO_define:
28510       case DW_MACINFO_undef:
28511         output_macinfo_op (ref);
28512         ref->code = 0;
28513         ref->info = NULL;
28514         break;
28515       default:
28516         gcc_unreachable ();
28517       }
28518
28519   macinfo_label_base += macinfo_label_base_adj;
28520 }
28521
28522 /* Initialize the various sections and labels for dwarf output and prefix
28523    them with PREFIX if non-NULL.  Returns the generation (zero based
28524    number of times function was called).  */
28525
28526 static unsigned
28527 init_sections_and_labels (bool early_lto_debug)
28528 {
28529   /* As we may get called multiple times have a generation count for
28530      labels.  */
28531   static unsigned generation = 0;
28532
28533   if (early_lto_debug)
28534     {
28535       if (!dwarf_split_debug_info)
28536         {
28537           debug_info_section = get_section (DEBUG_LTO_INFO_SECTION,
28538                                             SECTION_DEBUG | SECTION_EXCLUDE,
28539                                             NULL);
28540           debug_abbrev_section = get_section (DEBUG_LTO_ABBREV_SECTION,
28541                                               SECTION_DEBUG | SECTION_EXCLUDE,
28542                                               NULL);
28543           debug_macinfo_section_name
28544             = ((dwarf_strict && dwarf_version < 5)
28545                ? DEBUG_LTO_MACINFO_SECTION : DEBUG_LTO_MACRO_SECTION);
28546           debug_macinfo_section = get_section (debug_macinfo_section_name,
28547                                                SECTION_DEBUG
28548                                                | SECTION_EXCLUDE, NULL);
28549         }
28550       else
28551         {
28552           /* ???  Which of the following do we need early?  */
28553           debug_info_section = get_section (DEBUG_LTO_DWO_INFO_SECTION,
28554                                             SECTION_DEBUG | SECTION_EXCLUDE,
28555                                             NULL);
28556           debug_abbrev_section = get_section (DEBUG_LTO_DWO_ABBREV_SECTION,
28557                                               SECTION_DEBUG | SECTION_EXCLUDE,
28558                                               NULL);
28559           debug_skeleton_info_section = get_section (DEBUG_LTO_INFO_SECTION,
28560                                                      SECTION_DEBUG
28561                                                      | SECTION_EXCLUDE, NULL);
28562           debug_skeleton_abbrev_section
28563             = get_section (DEBUG_LTO_ABBREV_SECTION,
28564                            SECTION_DEBUG | SECTION_EXCLUDE, NULL);
28565           ASM_GENERATE_INTERNAL_LABEL (debug_skeleton_abbrev_section_label,
28566                                        DEBUG_SKELETON_ABBREV_SECTION_LABEL,
28567                                        generation);
28568
28569           /* Somewhat confusing detail: The skeleton_[abbrev|info] sections
28570              stay in the main .o, but the skeleton_line goes into the split
28571              off dwo.  */
28572           debug_skeleton_line_section
28573             = get_section (DEBUG_LTO_LINE_SECTION,
28574                            SECTION_DEBUG | SECTION_EXCLUDE, NULL);
28575           ASM_GENERATE_INTERNAL_LABEL (debug_skeleton_line_section_label,
28576                                        DEBUG_SKELETON_LINE_SECTION_LABEL,
28577                                        generation);
28578           debug_str_offsets_section
28579             = get_section (DEBUG_LTO_DWO_STR_OFFSETS_SECTION,
28580                            SECTION_DEBUG | SECTION_EXCLUDE,
28581                            NULL);
28582           ASM_GENERATE_INTERNAL_LABEL (debug_skeleton_info_section_label,
28583                                        DEBUG_SKELETON_INFO_SECTION_LABEL,
28584                                        generation);
28585           debug_str_dwo_section = get_section (DEBUG_LTO_STR_DWO_SECTION,
28586                                                DEBUG_STR_DWO_SECTION_FLAGS,
28587                                                NULL);
28588           debug_macinfo_section_name
28589             = ((dwarf_strict && dwarf_version < 5)
28590                ? DEBUG_LTO_DWO_MACINFO_SECTION : DEBUG_LTO_DWO_MACRO_SECTION);
28591           debug_macinfo_section = get_section (debug_macinfo_section_name,
28592                                                SECTION_DEBUG | SECTION_EXCLUDE,
28593                                                NULL);
28594         }
28595       /* For macro info and the file table we have to refer to a
28596          debug_line section.  */
28597       debug_line_section = get_section (DEBUG_LTO_LINE_SECTION,
28598                                         SECTION_DEBUG | SECTION_EXCLUDE, NULL);
28599       ASM_GENERATE_INTERNAL_LABEL (debug_line_section_label,
28600                                    DEBUG_LINE_SECTION_LABEL, generation);
28601
28602       debug_str_section = get_section (DEBUG_LTO_STR_SECTION,
28603                                        DEBUG_STR_SECTION_FLAGS
28604                                        | SECTION_EXCLUDE, NULL);
28605       if (!dwarf_split_debug_info)
28606         debug_line_str_section
28607           = get_section (DEBUG_LTO_LINE_STR_SECTION,
28608                          DEBUG_STR_SECTION_FLAGS | SECTION_EXCLUDE, NULL);
28609     }
28610   else
28611     {
28612       if (!dwarf_split_debug_info)
28613         {
28614           debug_info_section = get_section (DEBUG_INFO_SECTION,
28615                                             SECTION_DEBUG, NULL);
28616           debug_abbrev_section = get_section (DEBUG_ABBREV_SECTION,
28617                                               SECTION_DEBUG, NULL);
28618           debug_loc_section = get_section (dwarf_version >= 5
28619                                            ? DEBUG_LOCLISTS_SECTION
28620                                            : DEBUG_LOC_SECTION,
28621                                            SECTION_DEBUG, NULL);
28622           debug_macinfo_section_name
28623             = ((dwarf_strict && dwarf_version < 5)
28624                ? DEBUG_MACINFO_SECTION : DEBUG_MACRO_SECTION);
28625           debug_macinfo_section = get_section (debug_macinfo_section_name,
28626                                                SECTION_DEBUG, NULL);
28627         }
28628       else
28629         {
28630           debug_info_section = get_section (DEBUG_DWO_INFO_SECTION,
28631                                             SECTION_DEBUG | SECTION_EXCLUDE,
28632                                             NULL);
28633           debug_abbrev_section = get_section (DEBUG_DWO_ABBREV_SECTION,
28634                                               SECTION_DEBUG | SECTION_EXCLUDE,
28635                                               NULL);
28636           debug_addr_section = get_section (DEBUG_ADDR_SECTION,
28637                                             SECTION_DEBUG, NULL);
28638           debug_skeleton_info_section = get_section (DEBUG_INFO_SECTION,
28639                                                      SECTION_DEBUG, NULL);
28640           debug_skeleton_abbrev_section = get_section (DEBUG_ABBREV_SECTION,
28641                                                        SECTION_DEBUG, NULL);
28642           ASM_GENERATE_INTERNAL_LABEL (debug_skeleton_abbrev_section_label,
28643                                        DEBUG_SKELETON_ABBREV_SECTION_LABEL,
28644                                        generation);
28645
28646           /* Somewhat confusing detail: The skeleton_[abbrev|info] sections
28647              stay in the main .o, but the skeleton_line goes into the
28648              split off dwo.  */
28649           debug_skeleton_line_section
28650               = get_section (DEBUG_DWO_LINE_SECTION,
28651                              SECTION_DEBUG | SECTION_EXCLUDE, NULL);
28652           ASM_GENERATE_INTERNAL_LABEL (debug_skeleton_line_section_label,
28653                                        DEBUG_SKELETON_LINE_SECTION_LABEL,
28654                                        generation);
28655           debug_str_offsets_section
28656             = get_section (DEBUG_DWO_STR_OFFSETS_SECTION,
28657                            SECTION_DEBUG | SECTION_EXCLUDE, NULL);
28658           ASM_GENERATE_INTERNAL_LABEL (debug_skeleton_info_section_label,
28659                                        DEBUG_SKELETON_INFO_SECTION_LABEL,
28660                                        generation);
28661           debug_loc_section = get_section (dwarf_version >= 5
28662                                            ? DEBUG_DWO_LOCLISTS_SECTION
28663                                            : DEBUG_DWO_LOC_SECTION,
28664                                            SECTION_DEBUG | SECTION_EXCLUDE,
28665                                            NULL);
28666           debug_str_dwo_section = get_section (DEBUG_STR_DWO_SECTION,
28667                                                DEBUG_STR_DWO_SECTION_FLAGS,
28668                                                NULL);
28669           debug_macinfo_section_name
28670             = ((dwarf_strict && dwarf_version < 5)
28671                ? DEBUG_DWO_MACINFO_SECTION : DEBUG_DWO_MACRO_SECTION);
28672           debug_macinfo_section = get_section (debug_macinfo_section_name,
28673                                                SECTION_DEBUG | SECTION_EXCLUDE,
28674                                                NULL);
28675         }
28676       debug_aranges_section = get_section (DEBUG_ARANGES_SECTION,
28677                                            SECTION_DEBUG, NULL);
28678       debug_line_section = get_section (DEBUG_LINE_SECTION,
28679                                         SECTION_DEBUG, NULL);
28680       debug_pubnames_section = get_section (DEBUG_PUBNAMES_SECTION,
28681                                             SECTION_DEBUG, NULL);
28682       debug_pubtypes_section = get_section (DEBUG_PUBTYPES_SECTION,
28683                                             SECTION_DEBUG, NULL);
28684       debug_str_section = get_section (DEBUG_STR_SECTION,
28685                                        DEBUG_STR_SECTION_FLAGS, NULL);
28686       if (!dwarf_split_debug_info && !output_asm_line_debug_info ())
28687         debug_line_str_section = get_section (DEBUG_LINE_STR_SECTION,
28688                                               DEBUG_STR_SECTION_FLAGS, NULL);
28689
28690       debug_ranges_section = get_section (dwarf_version >= 5
28691                                           ? DEBUG_RNGLISTS_SECTION
28692                                           : DEBUG_RANGES_SECTION,
28693                                           SECTION_DEBUG, NULL);
28694       debug_frame_section = get_section (DEBUG_FRAME_SECTION,
28695                                          SECTION_DEBUG, NULL);
28696     }
28697
28698   ASM_GENERATE_INTERNAL_LABEL (abbrev_section_label,
28699                                DEBUG_ABBREV_SECTION_LABEL, generation);
28700   ASM_GENERATE_INTERNAL_LABEL (debug_info_section_label,
28701                                DEBUG_INFO_SECTION_LABEL, generation);
28702   info_section_emitted = false;
28703   ASM_GENERATE_INTERNAL_LABEL (debug_line_section_label,
28704                                DEBUG_LINE_SECTION_LABEL, generation);
28705   /* There are up to 4 unique ranges labels per generation.
28706      See also output_rnglists.  */
28707   ASM_GENERATE_INTERNAL_LABEL (ranges_section_label,
28708                                DEBUG_RANGES_SECTION_LABEL, generation * 4);
28709   if (dwarf_version >= 5 && dwarf_split_debug_info)
28710     ASM_GENERATE_INTERNAL_LABEL (ranges_base_label,
28711                                  DEBUG_RANGES_SECTION_LABEL,
28712                                  1 + generation * 4);
28713   ASM_GENERATE_INTERNAL_LABEL (debug_addr_section_label,
28714                                DEBUG_ADDR_SECTION_LABEL, generation);
28715   ASM_GENERATE_INTERNAL_LABEL (macinfo_section_label,
28716                                (dwarf_strict && dwarf_version < 5)
28717                                ? DEBUG_MACINFO_SECTION_LABEL
28718                                : DEBUG_MACRO_SECTION_LABEL, generation);
28719   ASM_GENERATE_INTERNAL_LABEL (loc_section_label, DEBUG_LOC_SECTION_LABEL,
28720                                generation);
28721
28722   ++generation;
28723   return generation - 1;
28724 }
28725
28726 /* Set up for Dwarf output at the start of compilation.  */
28727
28728 static void
28729 dwarf2out_init (const char *filename ATTRIBUTE_UNUSED)
28730 {
28731   /* Allocate the file_table.  */
28732   file_table = hash_table<dwarf_file_hasher>::create_ggc (50);
28733
28734 #ifndef DWARF2_LINENO_DEBUGGING_INFO
28735   /* Allocate the decl_die_table.  */
28736   decl_die_table = hash_table<decl_die_hasher>::create_ggc (10);
28737
28738   /* Allocate the decl_loc_table.  */
28739   decl_loc_table = hash_table<decl_loc_hasher>::create_ggc (10);
28740
28741   /* Allocate the cached_dw_loc_list_table.  */
28742   cached_dw_loc_list_table = hash_table<dw_loc_list_hasher>::create_ggc (10);
28743
28744   /* Allocate the initial hunk of the decl_scope_table.  */
28745   vec_alloc (decl_scope_table, 256);
28746
28747   /* Allocate the initial hunk of the abbrev_die_table.  */
28748   vec_alloc (abbrev_die_table, 256);
28749   /* Zero-th entry is allocated, but unused.  */
28750   abbrev_die_table->quick_push (NULL);
28751
28752   /* Allocate the dwarf_proc_stack_usage_map.  */
28753   dwarf_proc_stack_usage_map = new hash_map<dw_die_ref, int>;
28754
28755   /* Allocate the pubtypes and pubnames vectors.  */
28756   vec_alloc (pubname_table, 32);
28757   vec_alloc (pubtype_table, 32);
28758
28759   vec_alloc (incomplete_types, 64);
28760
28761   vec_alloc (used_rtx_array, 32);
28762
28763   if (debug_info_level >= DINFO_LEVEL_VERBOSE)
28764     vec_alloc (macinfo_table, 64);
28765 #endif
28766
28767   /* If front-ends already registered a main translation unit but we were not
28768      ready to perform the association, do this now.  */
28769   if (main_translation_unit != NULL_TREE)
28770     equate_decl_number_to_die (main_translation_unit, comp_unit_die ());
28771 }
28772
28773 /* Called before compile () starts outputtting functions, variables
28774    and toplevel asms into assembly.  */
28775
28776 static void
28777 dwarf2out_assembly_start (void)
28778 {
28779   if (text_section_line_info)
28780     return;
28781
28782 #ifndef DWARF2_LINENO_DEBUGGING_INFO
28783   ASM_GENERATE_INTERNAL_LABEL (text_section_label, TEXT_SECTION_LABEL, 0);
28784   ASM_GENERATE_INTERNAL_LABEL (text_end_label, TEXT_END_LABEL, 0);
28785   ASM_GENERATE_INTERNAL_LABEL (cold_text_section_label,
28786                                COLD_TEXT_SECTION_LABEL, 0);
28787   ASM_GENERATE_INTERNAL_LABEL (cold_end_label, COLD_END_LABEL, 0);
28788
28789   switch_to_section (text_section);
28790   ASM_OUTPUT_LABEL (asm_out_file, text_section_label);
28791 #endif
28792
28793   /* Make sure the line number table for .text always exists.  */
28794   text_section_line_info = new_line_info_table ();
28795   text_section_line_info->end_label = text_end_label;
28796
28797 #ifdef DWARF2_LINENO_DEBUGGING_INFO
28798   cur_line_info_table = text_section_line_info;
28799 #endif
28800
28801   if (HAVE_GAS_CFI_SECTIONS_DIRECTIVE
28802       && dwarf2out_do_cfi_asm ()
28803       && !dwarf2out_do_eh_frame ())
28804     fprintf (asm_out_file, "\t.cfi_sections\t.debug_frame\n");
28805 }
28806
28807 /* A helper function for dwarf2out_finish called through
28808    htab_traverse.  Assign a string its index.  All strings must be
28809    collected into the table by the time index_string is called,
28810    because the indexing code relies on htab_traverse to traverse nodes
28811    in the same order for each run. */
28812
28813 int
28814 index_string (indirect_string_node **h, unsigned int *index)
28815 {
28816   indirect_string_node *node = *h;
28817
28818   find_string_form (node);
28819   if (node->form == DW_FORM_GNU_str_index && node->refcount > 0)
28820     {
28821       gcc_assert (node->index == NO_INDEX_ASSIGNED);
28822       node->index = *index;
28823       *index += 1;
28824     }
28825   return 1;
28826 }
28827
28828 /* A helper function for output_indirect_strings called through
28829    htab_traverse.  Output the offset to a string and update the
28830    current offset.  */
28831
28832 int
28833 output_index_string_offset (indirect_string_node **h, unsigned int *offset)
28834 {
28835   indirect_string_node *node = *h;
28836
28837   if (node->form == DW_FORM_GNU_str_index && node->refcount > 0)
28838     {
28839       /* Assert that this node has been assigned an index.  */
28840       gcc_assert (node->index != NO_INDEX_ASSIGNED
28841                   && node->index != NOT_INDEXED);
28842       dw2_asm_output_data (DWARF_OFFSET_SIZE, *offset,
28843                            "indexed string 0x%x: %s", node->index, node->str);
28844       *offset += strlen (node->str) + 1;
28845     }
28846   return 1;
28847 }
28848
28849 /* A helper function for dwarf2out_finish called through
28850    htab_traverse.  Output the indexed string.  */
28851
28852 int
28853 output_index_string (indirect_string_node **h, unsigned int *cur_idx)
28854 {
28855   struct indirect_string_node *node = *h;
28856
28857   if (node->form == DW_FORM_GNU_str_index && node->refcount > 0)
28858     {
28859       /* Assert that the strings are output in the same order as their
28860          indexes were assigned.  */
28861       gcc_assert (*cur_idx == node->index);
28862       assemble_string (node->str, strlen (node->str) + 1);
28863       *cur_idx += 1;
28864     }
28865   return 1;
28866 }
28867
28868 /* A helper function for dwarf2out_finish called through
28869    htab_traverse.  Emit one queued .debug_str string.  */
28870
28871 int
28872 output_indirect_string (indirect_string_node **h, enum dwarf_form form)
28873 {
28874   struct indirect_string_node *node = *h;
28875
28876   node->form = find_string_form (node);
28877   if (node->form == form && node->refcount > 0)
28878     {
28879       ASM_OUTPUT_LABEL (asm_out_file, node->label);
28880       assemble_string (node->str, strlen (node->str) + 1);
28881     }
28882
28883   return 1;
28884 }
28885
28886 /* Output the indexed string table.  */
28887
28888 static void
28889 output_indirect_strings (void)
28890 {
28891   switch_to_section (debug_str_section);
28892   if (!dwarf_split_debug_info)
28893     debug_str_hash->traverse<enum dwarf_form,
28894                              output_indirect_string> (DW_FORM_strp);
28895   else
28896     {
28897       unsigned int offset = 0;
28898       unsigned int cur_idx = 0;
28899
28900       if (skeleton_debug_str_hash)
28901         skeleton_debug_str_hash->traverse<enum dwarf_form,
28902                                           output_indirect_string> (DW_FORM_strp);
28903
28904       switch_to_section (debug_str_offsets_section);
28905       debug_str_hash->traverse_noresize
28906         <unsigned int *, output_index_string_offset> (&offset);
28907       switch_to_section (debug_str_dwo_section);
28908       debug_str_hash->traverse_noresize<unsigned int *, output_index_string>
28909         (&cur_idx);
28910     }
28911 }
28912
28913 /* Callback for htab_traverse to assign an index to an entry in the
28914    table, and to write that entry to the .debug_addr section.  */
28915
28916 int
28917 output_addr_table_entry (addr_table_entry **slot, unsigned int *cur_index)
28918 {
28919   addr_table_entry *entry = *slot;
28920
28921   if (entry->refcount == 0)
28922     {
28923       gcc_assert (entry->index == NO_INDEX_ASSIGNED
28924                   || entry->index == NOT_INDEXED);
28925       return 1;
28926     }
28927
28928   gcc_assert (entry->index == *cur_index);
28929   (*cur_index)++;
28930
28931   switch (entry->kind)
28932     {
28933       case ate_kind_rtx:
28934         dw2_asm_output_addr_rtx (DWARF2_ADDR_SIZE, entry->addr.rtl,
28935                                  "0x%x", entry->index);
28936         break;
28937       case ate_kind_rtx_dtprel:
28938         gcc_assert (targetm.asm_out.output_dwarf_dtprel);
28939         targetm.asm_out.output_dwarf_dtprel (asm_out_file,
28940                                              DWARF2_ADDR_SIZE,
28941                                              entry->addr.rtl);
28942         fputc ('\n', asm_out_file);
28943         break;
28944       case ate_kind_label:
28945         dw2_asm_output_addr (DWARF2_ADDR_SIZE, entry->addr.label,
28946                                  "0x%x", entry->index);
28947         break;
28948       default:
28949         gcc_unreachable ();
28950     }
28951   return 1;
28952 }
28953
28954 /* Produce the .debug_addr section.  */
28955
28956 static void
28957 output_addr_table (void)
28958 {
28959   unsigned int index = 0;
28960   if (addr_index_table == NULL || addr_index_table->size () == 0)
28961     return;
28962
28963   switch_to_section (debug_addr_section);
28964   addr_index_table
28965     ->traverse_noresize<unsigned int *, output_addr_table_entry> (&index);
28966 }
28967
28968 #if ENABLE_ASSERT_CHECKING
28969 /* Verify that all marks are clear.  */
28970
28971 static void
28972 verify_marks_clear (dw_die_ref die)
28973 {
28974   dw_die_ref c;
28975
28976   gcc_assert (! die->die_mark);
28977   FOR_EACH_CHILD (die, c, verify_marks_clear (c));
28978 }
28979 #endif /* ENABLE_ASSERT_CHECKING */
28980
28981 /* Clear the marks for a die and its children.
28982    Be cool if the mark isn't set.  */
28983
28984 static void
28985 prune_unmark_dies (dw_die_ref die)
28986 {
28987   dw_die_ref c;
28988
28989   if (die->die_mark)
28990     die->die_mark = 0;
28991   FOR_EACH_CHILD (die, c, prune_unmark_dies (c));
28992 }
28993
28994 /* Given LOC that is referenced by a DIE we're marking as used, find all
28995    referenced DWARF procedures it references and mark them as used.  */
28996
28997 static void
28998 prune_unused_types_walk_loc_descr (dw_loc_descr_ref loc)
28999 {
29000   for (; loc != NULL; loc = loc->dw_loc_next)
29001     switch (loc->dw_loc_opc)
29002       {
29003       case DW_OP_implicit_pointer:
29004       case DW_OP_convert:
29005       case DW_OP_reinterpret:
29006       case DW_OP_GNU_implicit_pointer:
29007       case DW_OP_GNU_convert:
29008       case DW_OP_GNU_reinterpret:
29009         if (loc->dw_loc_oprnd1.val_class == dw_val_class_die_ref)
29010           prune_unused_types_mark (loc->dw_loc_oprnd1.v.val_die_ref.die, 1);
29011         break;
29012       case DW_OP_GNU_variable_value:
29013         if (loc->dw_loc_oprnd1.val_class == dw_val_class_decl_ref)
29014           {
29015             dw_die_ref ref
29016               = lookup_decl_die (loc->dw_loc_oprnd1.v.val_decl_ref);
29017             if (ref == NULL)
29018               break;
29019             loc->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
29020             loc->dw_loc_oprnd1.v.val_die_ref.die = ref;
29021             loc->dw_loc_oprnd1.v.val_die_ref.external = 0;
29022           }
29023         /* FALLTHRU */
29024       case DW_OP_call2:
29025       case DW_OP_call4:
29026       case DW_OP_call_ref:
29027       case DW_OP_const_type:
29028       case DW_OP_GNU_const_type:
29029       case DW_OP_GNU_parameter_ref:
29030         gcc_assert (loc->dw_loc_oprnd1.val_class == dw_val_class_die_ref);
29031         prune_unused_types_mark (loc->dw_loc_oprnd1.v.val_die_ref.die, 1);
29032         break;
29033       case DW_OP_regval_type:
29034       case DW_OP_deref_type:
29035       case DW_OP_GNU_regval_type:
29036       case DW_OP_GNU_deref_type:
29037         gcc_assert (loc->dw_loc_oprnd2.val_class == dw_val_class_die_ref);
29038         prune_unused_types_mark (loc->dw_loc_oprnd2.v.val_die_ref.die, 1);
29039         break;
29040       case DW_OP_entry_value:
29041       case DW_OP_GNU_entry_value:
29042         gcc_assert (loc->dw_loc_oprnd1.val_class == dw_val_class_loc);
29043         prune_unused_types_walk_loc_descr (loc->dw_loc_oprnd1.v.val_loc);
29044         break;
29045       default:
29046         break;
29047       }
29048 }
29049
29050 /* Given DIE that we're marking as used, find any other dies
29051    it references as attributes and mark them as used.  */
29052
29053 static void
29054 prune_unused_types_walk_attribs (dw_die_ref die)
29055 {
29056   dw_attr_node *a;
29057   unsigned ix;
29058
29059   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
29060     {
29061       switch (AT_class (a))
29062         {
29063         /* Make sure DWARF procedures referenced by location descriptions will
29064            get emitted.  */
29065         case dw_val_class_loc:
29066           prune_unused_types_walk_loc_descr (AT_loc (a));
29067           break;
29068         case dw_val_class_loc_list:
29069           for (dw_loc_list_ref list = AT_loc_list (a);
29070                list != NULL;
29071                list = list->dw_loc_next)
29072             prune_unused_types_walk_loc_descr (list->expr);
29073           break;
29074
29075         case dw_val_class_view_list:
29076           /* This points to a loc_list in another attribute, so it's
29077              already covered.  */
29078           break;
29079
29080         case dw_val_class_die_ref:
29081           /* A reference to another DIE.
29082              Make sure that it will get emitted.
29083              If it was broken out into a comdat group, don't follow it.  */
29084           if (! AT_ref (a)->comdat_type_p
29085               || a->dw_attr == DW_AT_specification)
29086             prune_unused_types_mark (a->dw_attr_val.v.val_die_ref.die, 1);
29087           break;
29088
29089         case dw_val_class_str:
29090           /* Set the string's refcount to 0 so that prune_unused_types_mark
29091              accounts properly for it.  */
29092           a->dw_attr_val.v.val_str->refcount = 0;
29093           break;
29094
29095         default:
29096           break;
29097         }
29098     }
29099 }
29100
29101 /* Mark the generic parameters and arguments children DIEs of DIE.  */
29102
29103 static void
29104 prune_unused_types_mark_generic_parms_dies (dw_die_ref die)
29105 {
29106   dw_die_ref c;
29107
29108   if (die == NULL || die->die_child == NULL)
29109     return;
29110   c = die->die_child;
29111   do
29112     {
29113       if (is_template_parameter (c))
29114         prune_unused_types_mark (c, 1);
29115       c = c->die_sib;
29116     } while (c && c != die->die_child);
29117 }
29118
29119 /* Mark DIE as being used.  If DOKIDS is true, then walk down
29120    to DIE's children.  */
29121
29122 static void
29123 prune_unused_types_mark (dw_die_ref die, int dokids)
29124 {
29125   dw_die_ref c;
29126
29127   if (die->die_mark == 0)
29128     {
29129       /* We haven't done this node yet.  Mark it as used.  */
29130       die->die_mark = 1;
29131       /* If this is the DIE of a generic type instantiation,
29132          mark the children DIEs that describe its generic parms and
29133          args.  */
29134       prune_unused_types_mark_generic_parms_dies (die);
29135
29136       /* We also have to mark its parents as used.
29137          (But we don't want to mark our parent's kids due to this,
29138          unless it is a class.)  */
29139       if (die->die_parent)
29140         prune_unused_types_mark (die->die_parent,
29141                                  class_scope_p (die->die_parent));
29142
29143       /* Mark any referenced nodes.  */
29144       prune_unused_types_walk_attribs (die);
29145
29146       /* If this node is a specification,
29147          also mark the definition, if it exists.  */
29148       if (get_AT_flag (die, DW_AT_declaration) && die->die_definition)
29149         prune_unused_types_mark (die->die_definition, 1);
29150     }
29151
29152   if (dokids && die->die_mark != 2)
29153     {
29154       /* We need to walk the children, but haven't done so yet.
29155          Remember that we've walked the kids.  */
29156       die->die_mark = 2;
29157
29158       /* If this is an array type, we need to make sure our
29159          kids get marked, even if they're types.  If we're
29160          breaking out types into comdat sections, do this
29161          for all type definitions.  */
29162       if (die->die_tag == DW_TAG_array_type
29163           || (use_debug_types
29164               && is_type_die (die) && ! is_declaration_die (die)))
29165         FOR_EACH_CHILD (die, c, prune_unused_types_mark (c, 1));
29166       else
29167         FOR_EACH_CHILD (die, c, prune_unused_types_walk (c));
29168     }
29169 }
29170
29171 /* For local classes, look if any static member functions were emitted
29172    and if so, mark them.  */
29173
29174 static void
29175 prune_unused_types_walk_local_classes (dw_die_ref die)
29176 {
29177   dw_die_ref c;
29178
29179   if (die->die_mark == 2)
29180     return;
29181
29182   switch (die->die_tag)
29183     {
29184     case DW_TAG_structure_type:
29185     case DW_TAG_union_type:
29186     case DW_TAG_class_type:
29187       break;
29188
29189     case DW_TAG_subprogram:
29190       if (!get_AT_flag (die, DW_AT_declaration)
29191           || die->die_definition != NULL)
29192         prune_unused_types_mark (die, 1);
29193       return;
29194
29195     default:
29196       return;
29197     }
29198
29199   /* Mark children.  */
29200   FOR_EACH_CHILD (die, c, prune_unused_types_walk_local_classes (c));
29201 }
29202
29203 /* Walk the tree DIE and mark types that we actually use.  */
29204
29205 static void
29206 prune_unused_types_walk (dw_die_ref die)
29207 {
29208   dw_die_ref c;
29209
29210   /* Don't do anything if this node is already marked and
29211      children have been marked as well.  */
29212   if (die->die_mark == 2)
29213     return;
29214
29215   switch (die->die_tag)
29216     {
29217     case DW_TAG_structure_type:
29218     case DW_TAG_union_type:
29219     case DW_TAG_class_type:
29220       if (die->die_perennial_p)
29221         break;
29222
29223       for (c = die->die_parent; c; c = c->die_parent)
29224         if (c->die_tag == DW_TAG_subprogram)
29225           break;
29226
29227       /* Finding used static member functions inside of classes
29228          is needed just for local classes, because for other classes
29229          static member function DIEs with DW_AT_specification
29230          are emitted outside of the DW_TAG_*_type.  If we ever change
29231          it, we'd need to call this even for non-local classes.  */
29232       if (c)
29233         prune_unused_types_walk_local_classes (die);
29234
29235       /* It's a type node --- don't mark it.  */
29236       return;
29237
29238     case DW_TAG_const_type:
29239     case DW_TAG_packed_type:
29240     case DW_TAG_pointer_type:
29241     case DW_TAG_reference_type:
29242     case DW_TAG_rvalue_reference_type:
29243     case DW_TAG_volatile_type:
29244     case DW_TAG_typedef:
29245     case DW_TAG_array_type:
29246     case DW_TAG_interface_type:
29247     case DW_TAG_friend:
29248     case DW_TAG_enumeration_type:
29249     case DW_TAG_subroutine_type:
29250     case DW_TAG_string_type:
29251     case DW_TAG_set_type:
29252     case DW_TAG_subrange_type:
29253     case DW_TAG_ptr_to_member_type:
29254     case DW_TAG_file_type:
29255       /* Type nodes are useful only when other DIEs reference them --- don't
29256          mark them.  */
29257       /* FALLTHROUGH */
29258
29259     case DW_TAG_dwarf_procedure:
29260       /* Likewise for DWARF procedures.  */
29261
29262       if (die->die_perennial_p)
29263         break;
29264
29265       return;
29266
29267     default:
29268       /* Mark everything else.  */
29269       break;
29270   }
29271
29272   if (die->die_mark == 0)
29273     {
29274       die->die_mark = 1;
29275
29276       /* Now, mark any dies referenced from here.  */
29277       prune_unused_types_walk_attribs (die);
29278     }
29279
29280   die->die_mark = 2;
29281
29282   /* Mark children.  */
29283   FOR_EACH_CHILD (die, c, prune_unused_types_walk (c));
29284 }
29285
29286 /* Increment the string counts on strings referred to from DIE's
29287    attributes.  */
29288
29289 static void
29290 prune_unused_types_update_strings (dw_die_ref die)
29291 {
29292   dw_attr_node *a;
29293   unsigned ix;
29294
29295   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
29296     if (AT_class (a) == dw_val_class_str)
29297       {
29298         struct indirect_string_node *s = a->dw_attr_val.v.val_str;
29299         s->refcount++;
29300         /* Avoid unnecessarily putting strings that are used less than
29301            twice in the hash table.  */
29302         if (s->refcount
29303             == ((DEBUG_STR_SECTION_FLAGS & SECTION_MERGE) ? 1 : 2))
29304           {
29305             indirect_string_node **slot
29306               = debug_str_hash->find_slot_with_hash (s->str,
29307                                                      htab_hash_string (s->str),
29308                                                      INSERT);
29309             gcc_assert (*slot == NULL);
29310             *slot = s;
29311           }
29312       }
29313 }
29314
29315 /* Mark DIE and its children as removed.  */
29316
29317 static void
29318 mark_removed (dw_die_ref die)
29319 {
29320   dw_die_ref c;
29321   die->removed = true;
29322   FOR_EACH_CHILD (die, c, mark_removed (c));
29323 }
29324
29325 /* Remove from the tree DIE any dies that aren't marked.  */
29326
29327 static void
29328 prune_unused_types_prune (dw_die_ref die)
29329 {
29330   dw_die_ref c;
29331
29332   gcc_assert (die->die_mark);
29333   prune_unused_types_update_strings (die);
29334
29335   if (! die->die_child)
29336     return;
29337
29338   c = die->die_child;
29339   do {
29340     dw_die_ref prev = c, next;
29341     for (c = c->die_sib; ! c->die_mark; c = next)
29342       if (c == die->die_child)
29343         {
29344           /* No marked children between 'prev' and the end of the list.  */
29345           if (prev == c)
29346             /* No marked children at all.  */
29347             die->die_child = NULL;
29348           else
29349             {
29350               prev->die_sib = c->die_sib;
29351               die->die_child = prev;
29352             }
29353           c->die_sib = NULL;
29354           mark_removed (c);
29355           return;
29356         }
29357       else
29358         {
29359           next = c->die_sib;
29360           c->die_sib = NULL;
29361           mark_removed (c);
29362         }
29363
29364     if (c != prev->die_sib)
29365       prev->die_sib = c;
29366     prune_unused_types_prune (c);
29367   } while (c != die->die_child);
29368 }
29369
29370 /* Remove dies representing declarations that we never use.  */
29371
29372 static void
29373 prune_unused_types (void)
29374 {
29375   unsigned int i;
29376   limbo_die_node *node;
29377   comdat_type_node *ctnode;
29378   pubname_entry *pub;
29379   dw_die_ref base_type;
29380
29381 #if ENABLE_ASSERT_CHECKING
29382   /* All the marks should already be clear.  */
29383   verify_marks_clear (comp_unit_die ());
29384   for (node = limbo_die_list; node; node = node->next)
29385     verify_marks_clear (node->die);
29386   for (ctnode = comdat_type_list; ctnode; ctnode = ctnode->next)
29387     verify_marks_clear (ctnode->root_die);
29388 #endif /* ENABLE_ASSERT_CHECKING */
29389
29390   /* Mark types that are used in global variables.  */
29391   premark_types_used_by_global_vars ();
29392
29393   /* Set the mark on nodes that are actually used.  */
29394   prune_unused_types_walk (comp_unit_die ());
29395   for (node = limbo_die_list; node; node = node->next)
29396     prune_unused_types_walk (node->die);
29397   for (ctnode = comdat_type_list; ctnode; ctnode = ctnode->next)
29398     {
29399       prune_unused_types_walk (ctnode->root_die);
29400       prune_unused_types_mark (ctnode->type_die, 1);
29401     }
29402
29403   /* Also set the mark on nodes referenced from the pubname_table.  Enumerators
29404      are unusual in that they are pubnames that are the children of pubtypes.
29405      They should only be marked via their parent DW_TAG_enumeration_type die,
29406      not as roots in themselves.  */
29407   FOR_EACH_VEC_ELT (*pubname_table, i, pub)
29408     if (pub->die->die_tag != DW_TAG_enumerator)
29409       prune_unused_types_mark (pub->die, 1);
29410   for (i = 0; base_types.iterate (i, &base_type); i++)
29411     prune_unused_types_mark (base_type, 1);
29412
29413   /* For -fvar-tracking-assignments, also set the mark on nodes that could be
29414      referenced by DW_TAG_call_site DW_AT_call_origin (i.e. direct call
29415      callees).  */
29416   cgraph_node *cnode;
29417   FOR_EACH_FUNCTION (cnode)
29418     if (cnode->referred_to_p (false))
29419       {
29420         dw_die_ref die = lookup_decl_die (cnode->decl);
29421         if (die == NULL || die->die_mark)
29422           continue;
29423         for (cgraph_edge *e = cnode->callers; e; e = e->next_caller)
29424           if (e->caller != cnode
29425               && opt_for_fn (e->caller->decl, flag_var_tracking_assignments))
29426             {
29427               prune_unused_types_mark (die, 1);
29428               break;
29429             }
29430       }
29431
29432   if (debug_str_hash)
29433     debug_str_hash->empty ();
29434   if (skeleton_debug_str_hash)
29435     skeleton_debug_str_hash->empty ();
29436   prune_unused_types_prune (comp_unit_die ());
29437   for (limbo_die_node **pnode = &limbo_die_list; *pnode; )
29438     {
29439       node = *pnode;
29440       if (!node->die->die_mark)
29441         *pnode = node->next;
29442       else
29443         {
29444           prune_unused_types_prune (node->die);
29445           pnode = &node->next;
29446         }
29447     }
29448   for (ctnode = comdat_type_list; ctnode; ctnode = ctnode->next)
29449     prune_unused_types_prune (ctnode->root_die);
29450
29451   /* Leave the marks clear.  */
29452   prune_unmark_dies (comp_unit_die ());
29453   for (node = limbo_die_list; node; node = node->next)
29454     prune_unmark_dies (node->die);
29455   for (ctnode = comdat_type_list; ctnode; ctnode = ctnode->next)
29456     prune_unmark_dies (ctnode->root_die);
29457 }
29458
29459 /* Helpers to manipulate hash table of comdat type units.  */
29460
29461 struct comdat_type_hasher : nofree_ptr_hash <comdat_type_node>
29462 {
29463   static inline hashval_t hash (const comdat_type_node *);
29464   static inline bool equal (const comdat_type_node *, const comdat_type_node *);
29465 };
29466
29467 inline hashval_t
29468 comdat_type_hasher::hash (const comdat_type_node *type_node)
29469 {
29470   hashval_t h;
29471   memcpy (&h, type_node->signature, sizeof (h));
29472   return h;
29473 }
29474
29475 inline bool
29476 comdat_type_hasher::equal (const comdat_type_node *type_node_1,
29477                            const comdat_type_node *type_node_2)
29478 {
29479   return (! memcmp (type_node_1->signature, type_node_2->signature,
29480                     DWARF_TYPE_SIGNATURE_SIZE));
29481 }
29482
29483 /* Move a DW_AT_{,MIPS_}linkage_name attribute just added to dw_die_ref
29484    to the location it would have been added, should we know its
29485    DECL_ASSEMBLER_NAME when we added other attributes.  This will
29486    probably improve compactness of debug info, removing equivalent
29487    abbrevs, and hide any differences caused by deferring the
29488    computation of the assembler name, triggered by e.g. PCH.  */
29489
29490 static inline void
29491 move_linkage_attr (dw_die_ref die)
29492 {
29493   unsigned ix = vec_safe_length (die->die_attr);
29494   dw_attr_node linkage = (*die->die_attr)[ix - 1];
29495
29496   gcc_assert (linkage.dw_attr == DW_AT_linkage_name
29497               || linkage.dw_attr == DW_AT_MIPS_linkage_name);
29498
29499   while (--ix > 0)
29500     {
29501       dw_attr_node *prev = &(*die->die_attr)[ix - 1];
29502
29503       if (prev->dw_attr == DW_AT_decl_line
29504           || prev->dw_attr == DW_AT_decl_column
29505           || prev->dw_attr == DW_AT_name)
29506         break;
29507     }
29508
29509   if (ix != vec_safe_length (die->die_attr) - 1)
29510     {
29511       die->die_attr->pop ();
29512       die->die_attr->quick_insert (ix, linkage);
29513     }
29514 }
29515
29516 /* Helper function for resolve_addr, mark DW_TAG_base_type nodes
29517    referenced from typed stack ops and count how often they are used.  */
29518
29519 static void
29520 mark_base_types (dw_loc_descr_ref loc)
29521 {
29522   dw_die_ref base_type = NULL;
29523
29524   for (; loc; loc = loc->dw_loc_next)
29525     {
29526       switch (loc->dw_loc_opc)
29527         {
29528         case DW_OP_regval_type:
29529         case DW_OP_deref_type:
29530         case DW_OP_GNU_regval_type:
29531         case DW_OP_GNU_deref_type:
29532           base_type = loc->dw_loc_oprnd2.v.val_die_ref.die;
29533           break;
29534         case DW_OP_convert:
29535         case DW_OP_reinterpret:
29536         case DW_OP_GNU_convert:
29537         case DW_OP_GNU_reinterpret:
29538           if (loc->dw_loc_oprnd1.val_class == dw_val_class_unsigned_const)
29539             continue;
29540           /* FALLTHRU */
29541         case DW_OP_const_type:
29542         case DW_OP_GNU_const_type:
29543           base_type = loc->dw_loc_oprnd1.v.val_die_ref.die;
29544           break;
29545         case DW_OP_entry_value:
29546         case DW_OP_GNU_entry_value:
29547           mark_base_types (loc->dw_loc_oprnd1.v.val_loc);
29548           continue;
29549         default:
29550           continue;
29551         }
29552       gcc_assert (base_type->die_parent == comp_unit_die ());
29553       if (base_type->die_mark)
29554         base_type->die_mark++;
29555       else
29556         {
29557           base_types.safe_push (base_type);
29558           base_type->die_mark = 1;
29559         }
29560     }
29561 }
29562
29563 /* Comparison function for sorting marked base types.  */
29564
29565 static int
29566 base_type_cmp (const void *x, const void *y)
29567 {
29568   dw_die_ref dx = *(const dw_die_ref *) x;
29569   dw_die_ref dy = *(const dw_die_ref *) y;
29570   unsigned int byte_size1, byte_size2;
29571   unsigned int encoding1, encoding2;
29572   unsigned int align1, align2;
29573   if (dx->die_mark > dy->die_mark)
29574     return -1;
29575   if (dx->die_mark < dy->die_mark)
29576     return 1;
29577   byte_size1 = get_AT_unsigned (dx, DW_AT_byte_size);
29578   byte_size2 = get_AT_unsigned (dy, DW_AT_byte_size);
29579   if (byte_size1 < byte_size2)
29580     return 1;
29581   if (byte_size1 > byte_size2)
29582     return -1;
29583   encoding1 = get_AT_unsigned (dx, DW_AT_encoding);
29584   encoding2 = get_AT_unsigned (dy, DW_AT_encoding);
29585   if (encoding1 < encoding2)
29586     return 1;
29587   if (encoding1 > encoding2)
29588     return -1;
29589   align1 = get_AT_unsigned (dx, DW_AT_alignment);
29590   align2 = get_AT_unsigned (dy, DW_AT_alignment);
29591   if (align1 < align2)
29592     return 1;
29593   if (align1 > align2)
29594     return -1;
29595   return 0;
29596 }
29597
29598 /* Move base types marked by mark_base_types as early as possible
29599    in the CU, sorted by decreasing usage count both to make the
29600    uleb128 references as small as possible and to make sure they
29601    will have die_offset already computed by calc_die_sizes when
29602    sizes of typed stack loc ops is computed.  */
29603
29604 static void
29605 move_marked_base_types (void)
29606 {
29607   unsigned int i;
29608   dw_die_ref base_type, die, c;
29609
29610   if (base_types.is_empty ())
29611     return;
29612
29613   /* Sort by decreasing usage count, they will be added again in that
29614      order later on.  */
29615   base_types.qsort (base_type_cmp);
29616   die = comp_unit_die ();
29617   c = die->die_child;
29618   do
29619     {
29620       dw_die_ref prev = c;
29621       c = c->die_sib;
29622       while (c->die_mark)
29623         {
29624           remove_child_with_prev (c, prev);
29625           /* As base types got marked, there must be at least
29626              one node other than DW_TAG_base_type.  */
29627           gcc_assert (die->die_child != NULL);
29628           c = prev->die_sib;
29629         }
29630     }
29631   while (c != die->die_child);
29632   gcc_assert (die->die_child);
29633   c = die->die_child;
29634   for (i = 0; base_types.iterate (i, &base_type); i++)
29635     {
29636       base_type->die_mark = 0;
29637       base_type->die_sib = c->die_sib;
29638       c->die_sib = base_type;
29639       c = base_type;
29640     }
29641 }
29642
29643 /* Helper function for resolve_addr, attempt to resolve
29644    one CONST_STRING, return true if successful.  Similarly verify that
29645    SYMBOL_REFs refer to variables emitted in the current CU.  */
29646
29647 static bool
29648 resolve_one_addr (rtx *addr)
29649 {
29650   rtx rtl = *addr;
29651
29652   if (GET_CODE (rtl) == CONST_STRING)
29653     {
29654       size_t len = strlen (XSTR (rtl, 0)) + 1;
29655       tree t = build_string (len, XSTR (rtl, 0));
29656       tree tlen = size_int (len - 1);
29657       TREE_TYPE (t)
29658         = build_array_type (char_type_node, build_index_type (tlen));
29659       rtl = lookup_constant_def (t);
29660       if (!rtl || !MEM_P (rtl))
29661         return false;
29662       rtl = XEXP (rtl, 0);
29663       if (GET_CODE (rtl) == SYMBOL_REF
29664           && SYMBOL_REF_DECL (rtl)
29665           && !TREE_ASM_WRITTEN (SYMBOL_REF_DECL (rtl)))
29666         return false;
29667       vec_safe_push (used_rtx_array, rtl);
29668       *addr = rtl;
29669       return true;
29670     }
29671
29672   if (GET_CODE (rtl) == SYMBOL_REF
29673       && SYMBOL_REF_DECL (rtl))
29674     {
29675       if (TREE_CONSTANT_POOL_ADDRESS_P (rtl))
29676         {
29677           if (!TREE_ASM_WRITTEN (DECL_INITIAL (SYMBOL_REF_DECL (rtl))))
29678             return false;
29679         }
29680       else if (!TREE_ASM_WRITTEN (SYMBOL_REF_DECL (rtl)))
29681         return false;
29682     }
29683
29684   if (GET_CODE (rtl) == CONST)
29685     {
29686       subrtx_ptr_iterator::array_type array;
29687       FOR_EACH_SUBRTX_PTR (iter, array, &XEXP (rtl, 0), ALL)
29688         if (!resolve_one_addr (*iter))
29689           return false;
29690     }
29691
29692   return true;
29693 }
29694
29695 /* For STRING_CST, return SYMBOL_REF of its constant pool entry,
29696    if possible, and create DW_TAG_dwarf_procedure that can be referenced
29697    from DW_OP_implicit_pointer if the string hasn't been seen yet.  */
29698
29699 static rtx
29700 string_cst_pool_decl (tree t)
29701 {
29702   rtx rtl = output_constant_def (t, 1);
29703   unsigned char *array;
29704   dw_loc_descr_ref l;
29705   tree decl;
29706   size_t len;
29707   dw_die_ref ref;
29708
29709   if (!rtl || !MEM_P (rtl))
29710     return NULL_RTX;
29711   rtl = XEXP (rtl, 0);
29712   if (GET_CODE (rtl) != SYMBOL_REF
29713       || SYMBOL_REF_DECL (rtl) == NULL_TREE)
29714     return NULL_RTX;
29715
29716   decl = SYMBOL_REF_DECL (rtl);
29717   if (!lookup_decl_die (decl))
29718     {
29719       len = TREE_STRING_LENGTH (t);
29720       vec_safe_push (used_rtx_array, rtl);
29721       ref = new_die (DW_TAG_dwarf_procedure, comp_unit_die (), decl);
29722       array = ggc_vec_alloc<unsigned char> (len);
29723       memcpy (array, TREE_STRING_POINTER (t), len);
29724       l = new_loc_descr (DW_OP_implicit_value, len, 0);
29725       l->dw_loc_oprnd2.val_class = dw_val_class_vec;
29726       l->dw_loc_oprnd2.v.val_vec.length = len;
29727       l->dw_loc_oprnd2.v.val_vec.elt_size = 1;
29728       l->dw_loc_oprnd2.v.val_vec.array = array;
29729       add_AT_loc (ref, DW_AT_location, l);
29730       equate_decl_number_to_die (decl, ref);
29731     }
29732   return rtl;
29733 }
29734
29735 /* Helper function of resolve_addr_in_expr.  LOC is
29736    a DW_OP_addr followed by DW_OP_stack_value, either at the start
29737    of exprloc or after DW_OP_{,bit_}piece, and val_addr can't be
29738    resolved.  Replace it (both DW_OP_addr and DW_OP_stack_value)
29739    with DW_OP_implicit_pointer if possible
29740    and return true, if unsuccessful, return false.  */
29741
29742 static bool
29743 optimize_one_addr_into_implicit_ptr (dw_loc_descr_ref loc)
29744 {
29745   rtx rtl = loc->dw_loc_oprnd1.v.val_addr;
29746   HOST_WIDE_INT offset = 0;
29747   dw_die_ref ref = NULL;
29748   tree decl;
29749
29750   if (GET_CODE (rtl) == CONST
29751       && GET_CODE (XEXP (rtl, 0)) == PLUS
29752       && CONST_INT_P (XEXP (XEXP (rtl, 0), 1)))
29753     {
29754       offset = INTVAL (XEXP (XEXP (rtl, 0), 1));
29755       rtl = XEXP (XEXP (rtl, 0), 0);
29756     }
29757   if (GET_CODE (rtl) == CONST_STRING)
29758     {
29759       size_t len = strlen (XSTR (rtl, 0)) + 1;
29760       tree t = build_string (len, XSTR (rtl, 0));
29761       tree tlen = size_int (len - 1);
29762
29763       TREE_TYPE (t)
29764         = build_array_type (char_type_node, build_index_type (tlen));
29765       rtl = string_cst_pool_decl (t);
29766       if (!rtl)
29767         return false;
29768     }
29769   if (GET_CODE (rtl) == SYMBOL_REF && SYMBOL_REF_DECL (rtl))
29770     {
29771       decl = SYMBOL_REF_DECL (rtl);
29772       if (VAR_P (decl) && !DECL_EXTERNAL (decl))
29773         {
29774           ref = lookup_decl_die (decl);
29775           if (ref && (get_AT (ref, DW_AT_location)
29776                       || get_AT (ref, DW_AT_const_value)))
29777             {
29778               loc->dw_loc_opc = dwarf_OP (DW_OP_implicit_pointer);
29779               loc->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
29780               loc->dw_loc_oprnd1.val_entry = NULL;
29781               loc->dw_loc_oprnd1.v.val_die_ref.die = ref;
29782               loc->dw_loc_oprnd1.v.val_die_ref.external = 0;
29783               loc->dw_loc_next = loc->dw_loc_next->dw_loc_next;
29784               loc->dw_loc_oprnd2.v.val_int = offset;
29785               return true;
29786             }
29787         }
29788     }
29789   return false;
29790 }
29791
29792 /* Helper function for resolve_addr, handle one location
29793    expression, return false if at least one CONST_STRING or SYMBOL_REF in
29794    the location list couldn't be resolved.  */
29795
29796 static bool
29797 resolve_addr_in_expr (dw_attr_node *a, dw_loc_descr_ref loc)
29798 {
29799   dw_loc_descr_ref keep = NULL;
29800   for (dw_loc_descr_ref prev = NULL; loc; prev = loc, loc = loc->dw_loc_next)
29801     switch (loc->dw_loc_opc)
29802       {
29803       case DW_OP_addr:
29804         if (!resolve_one_addr (&loc->dw_loc_oprnd1.v.val_addr))
29805           {
29806             if ((prev == NULL
29807                  || prev->dw_loc_opc == DW_OP_piece
29808                  || prev->dw_loc_opc == DW_OP_bit_piece)
29809                 && loc->dw_loc_next
29810                 && loc->dw_loc_next->dw_loc_opc == DW_OP_stack_value
29811                 && (!dwarf_strict || dwarf_version >= 5)
29812                 && optimize_one_addr_into_implicit_ptr (loc))
29813               break;
29814             return false;
29815           }
29816         break;
29817       case DW_OP_GNU_addr_index:
29818       case DW_OP_GNU_const_index:
29819         if (loc->dw_loc_opc == DW_OP_GNU_addr_index
29820             || (loc->dw_loc_opc == DW_OP_GNU_const_index && loc->dtprel))
29821           {
29822             rtx rtl = loc->dw_loc_oprnd1.val_entry->addr.rtl;
29823             if (!resolve_one_addr (&rtl))
29824               return false;
29825             remove_addr_table_entry (loc->dw_loc_oprnd1.val_entry);
29826             loc->dw_loc_oprnd1.val_entry
29827               = add_addr_table_entry (rtl, ate_kind_rtx);
29828           }
29829         break;
29830       case DW_OP_const4u:
29831       case DW_OP_const8u:
29832         if (loc->dtprel
29833             && !resolve_one_addr (&loc->dw_loc_oprnd1.v.val_addr))
29834           return false;
29835         break;
29836       case DW_OP_plus_uconst:
29837         if (size_of_loc_descr (loc)
29838             > size_of_int_loc_descriptor (loc->dw_loc_oprnd1.v.val_unsigned)
29839               + 1
29840             && loc->dw_loc_oprnd1.v.val_unsigned > 0)
29841           {
29842             dw_loc_descr_ref repl
29843               = int_loc_descriptor (loc->dw_loc_oprnd1.v.val_unsigned);
29844             add_loc_descr (&repl, new_loc_descr (DW_OP_plus, 0, 0));
29845             add_loc_descr (&repl, loc->dw_loc_next);
29846             *loc = *repl;
29847           }
29848         break;
29849       case DW_OP_implicit_value:
29850         if (loc->dw_loc_oprnd2.val_class == dw_val_class_addr
29851             && !resolve_one_addr (&loc->dw_loc_oprnd2.v.val_addr))
29852           return false;
29853         break;
29854       case DW_OP_implicit_pointer:
29855       case DW_OP_GNU_implicit_pointer:
29856       case DW_OP_GNU_parameter_ref:
29857       case DW_OP_GNU_variable_value:
29858         if (loc->dw_loc_oprnd1.val_class == dw_val_class_decl_ref)
29859           {
29860             dw_die_ref ref
29861               = lookup_decl_die (loc->dw_loc_oprnd1.v.val_decl_ref);
29862             if (ref == NULL)
29863               return false;
29864             loc->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
29865             loc->dw_loc_oprnd1.v.val_die_ref.die = ref;
29866             loc->dw_loc_oprnd1.v.val_die_ref.external = 0;
29867           }
29868         if (loc->dw_loc_opc == DW_OP_GNU_variable_value)
29869           {
29870             if (prev == NULL
29871                 && loc->dw_loc_next == NULL
29872                 && AT_class (a) == dw_val_class_loc)
29873               switch (a->dw_attr)
29874                 {
29875                   /* Following attributes allow both exprloc and reference,
29876                      so if the whole expression is DW_OP_GNU_variable_value
29877                      alone we could transform it into reference.  */
29878                 case DW_AT_byte_size:
29879                 case DW_AT_bit_size:
29880                 case DW_AT_lower_bound:
29881                 case DW_AT_upper_bound:
29882                 case DW_AT_bit_stride:
29883                 case DW_AT_count:
29884                 case DW_AT_allocated:
29885                 case DW_AT_associated:
29886                 case DW_AT_byte_stride:
29887                   a->dw_attr_val.val_class = dw_val_class_die_ref;
29888                   a->dw_attr_val.val_entry = NULL;
29889                   a->dw_attr_val.v.val_die_ref.die
29890                     = loc->dw_loc_oprnd1.v.val_die_ref.die;
29891                   a->dw_attr_val.v.val_die_ref.external = 0;
29892                   return true;
29893                 default:
29894                   break;
29895                 }
29896             if (dwarf_strict)
29897               return false;
29898           }
29899         break;
29900       case DW_OP_const_type:
29901       case DW_OP_regval_type:
29902       case DW_OP_deref_type:
29903       case DW_OP_convert:
29904       case DW_OP_reinterpret:
29905       case DW_OP_GNU_const_type:
29906       case DW_OP_GNU_regval_type:
29907       case DW_OP_GNU_deref_type:
29908       case DW_OP_GNU_convert:
29909       case DW_OP_GNU_reinterpret:
29910         while (loc->dw_loc_next
29911                && (loc->dw_loc_next->dw_loc_opc == DW_OP_convert
29912                    || loc->dw_loc_next->dw_loc_opc == DW_OP_GNU_convert))
29913           {
29914             dw_die_ref base1, base2;
29915             unsigned enc1, enc2, size1, size2;
29916             if (loc->dw_loc_opc == DW_OP_regval_type
29917                 || loc->dw_loc_opc == DW_OP_deref_type
29918                 || loc->dw_loc_opc == DW_OP_GNU_regval_type
29919                 || loc->dw_loc_opc == DW_OP_GNU_deref_type)
29920               base1 = loc->dw_loc_oprnd2.v.val_die_ref.die;
29921             else if (loc->dw_loc_oprnd1.val_class
29922                      == dw_val_class_unsigned_const)
29923               break;
29924             else
29925               base1 = loc->dw_loc_oprnd1.v.val_die_ref.die;
29926             if (loc->dw_loc_next->dw_loc_oprnd1.val_class
29927                 == dw_val_class_unsigned_const)
29928               break;
29929             base2 = loc->dw_loc_next->dw_loc_oprnd1.v.val_die_ref.die;
29930             gcc_assert (base1->die_tag == DW_TAG_base_type
29931                         && base2->die_tag == DW_TAG_base_type);
29932             enc1 = get_AT_unsigned (base1, DW_AT_encoding);
29933             enc2 = get_AT_unsigned (base2, DW_AT_encoding);
29934             size1 = get_AT_unsigned (base1, DW_AT_byte_size);
29935             size2 = get_AT_unsigned (base2, DW_AT_byte_size);
29936             if (size1 == size2
29937                 && (((enc1 == DW_ATE_unsigned || enc1 == DW_ATE_signed)
29938                      && (enc2 == DW_ATE_unsigned || enc2 == DW_ATE_signed)
29939                      && loc != keep)
29940                     || enc1 == enc2))
29941               {
29942                 /* Optimize away next DW_OP_convert after
29943                    adjusting LOC's base type die reference.  */
29944                 if (loc->dw_loc_opc == DW_OP_regval_type
29945                     || loc->dw_loc_opc == DW_OP_deref_type
29946                     || loc->dw_loc_opc == DW_OP_GNU_regval_type
29947                     || loc->dw_loc_opc == DW_OP_GNU_deref_type)
29948                   loc->dw_loc_oprnd2.v.val_die_ref.die = base2;
29949                 else
29950                   loc->dw_loc_oprnd1.v.val_die_ref.die = base2;
29951                 loc->dw_loc_next = loc->dw_loc_next->dw_loc_next;
29952                 continue;
29953               }
29954             /* Don't change integer DW_OP_convert after e.g. floating
29955                point typed stack entry.  */
29956             else if (enc1 != DW_ATE_unsigned && enc1 != DW_ATE_signed)
29957               keep = loc->dw_loc_next;
29958             break;
29959           }
29960         break;
29961       default:
29962         break;
29963       }
29964   return true;
29965 }
29966
29967 /* Helper function of resolve_addr.  DIE had DW_AT_location of
29968    DW_OP_addr alone, which referred to DECL in DW_OP_addr's operand
29969    and DW_OP_addr couldn't be resolved.  resolve_addr has already
29970    removed the DW_AT_location attribute.  This function attempts to
29971    add a new DW_AT_location attribute with DW_OP_implicit_pointer
29972    to it or DW_AT_const_value attribute, if possible.  */
29973
29974 static void
29975 optimize_location_into_implicit_ptr (dw_die_ref die, tree decl)
29976 {
29977   if (!VAR_P (decl)
29978       || lookup_decl_die (decl) != die
29979       || DECL_EXTERNAL (decl)
29980       || !TREE_STATIC (decl)
29981       || DECL_INITIAL (decl) == NULL_TREE
29982       || DECL_P (DECL_INITIAL (decl))
29983       || get_AT (die, DW_AT_const_value))
29984     return;
29985
29986   tree init = DECL_INITIAL (decl);
29987   HOST_WIDE_INT offset = 0;
29988   /* For variables that have been optimized away and thus
29989      don't have a memory location, see if we can emit
29990      DW_AT_const_value instead.  */
29991   if (tree_add_const_value_attribute (die, init))
29992     return;
29993   if (dwarf_strict && dwarf_version < 5)
29994     return;
29995   /* If init is ADDR_EXPR or POINTER_PLUS_EXPR of ADDR_EXPR,
29996      and ADDR_EXPR refers to a decl that has DW_AT_location or
29997      DW_AT_const_value (but isn't addressable, otherwise
29998      resolving the original DW_OP_addr wouldn't fail), see if
29999      we can add DW_OP_implicit_pointer.  */
30000   STRIP_NOPS (init);
30001   if (TREE_CODE (init) == POINTER_PLUS_EXPR
30002       && tree_fits_shwi_p (TREE_OPERAND (init, 1)))
30003     {
30004       offset = tree_to_shwi (TREE_OPERAND (init, 1));
30005       init = TREE_OPERAND (init, 0);
30006       STRIP_NOPS (init);
30007     }
30008   if (TREE_CODE (init) != ADDR_EXPR)
30009     return;
30010   if ((TREE_CODE (TREE_OPERAND (init, 0)) == STRING_CST
30011        && !TREE_ASM_WRITTEN (TREE_OPERAND (init, 0)))
30012       || (TREE_CODE (TREE_OPERAND (init, 0)) == VAR_DECL
30013           && !DECL_EXTERNAL (TREE_OPERAND (init, 0))
30014           && TREE_OPERAND (init, 0) != decl))
30015     {
30016       dw_die_ref ref;
30017       dw_loc_descr_ref l;
30018
30019       if (TREE_CODE (TREE_OPERAND (init, 0)) == STRING_CST)
30020         {
30021           rtx rtl = string_cst_pool_decl (TREE_OPERAND (init, 0));
30022           if (!rtl)
30023             return;
30024           decl = SYMBOL_REF_DECL (rtl);
30025         }
30026       else
30027         decl = TREE_OPERAND (init, 0);
30028       ref = lookup_decl_die (decl);
30029       if (ref == NULL
30030           || (!get_AT (ref, DW_AT_location)
30031               && !get_AT (ref, DW_AT_const_value)))
30032         return;
30033       l = new_loc_descr (dwarf_OP (DW_OP_implicit_pointer), 0, offset);
30034       l->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
30035       l->dw_loc_oprnd1.v.val_die_ref.die = ref;
30036       l->dw_loc_oprnd1.v.val_die_ref.external = 0;
30037       add_AT_loc (die, DW_AT_location, l);
30038     }
30039 }
30040
30041 /* Return NULL if l is a DWARF expression, or first op that is not
30042    valid DWARF expression.  */
30043
30044 static dw_loc_descr_ref
30045 non_dwarf_expression (dw_loc_descr_ref l)
30046 {
30047   while (l)
30048     {
30049       if (l->dw_loc_opc >= DW_OP_reg0 && l->dw_loc_opc <= DW_OP_reg31)
30050         return l;
30051       switch (l->dw_loc_opc)
30052         {
30053         case DW_OP_regx:
30054         case DW_OP_implicit_value:
30055         case DW_OP_stack_value:
30056         case DW_OP_implicit_pointer:
30057         case DW_OP_GNU_implicit_pointer:
30058         case DW_OP_GNU_parameter_ref:
30059         case DW_OP_piece:
30060         case DW_OP_bit_piece:
30061           return l;
30062         default:
30063           break;
30064         }
30065       l = l->dw_loc_next;
30066     }
30067   return NULL;
30068 }
30069
30070 /* Return adjusted copy of EXPR:
30071    If it is empty DWARF expression, return it.
30072    If it is valid non-empty DWARF expression,
30073    return copy of EXPR with DW_OP_deref appended to it.
30074    If it is DWARF expression followed by DW_OP_reg{N,x}, return
30075    copy of the DWARF expression with DW_OP_breg{N,x} <0> appended.
30076    If it is DWARF expression followed by DW_OP_stack_value, return
30077    copy of the DWARF expression without anything appended.
30078    Otherwise, return NULL.  */
30079
30080 static dw_loc_descr_ref
30081 copy_deref_exprloc (dw_loc_descr_ref expr)
30082 {
30083   dw_loc_descr_ref tail = NULL;
30084
30085   if (expr == NULL)
30086     return NULL;
30087
30088   dw_loc_descr_ref l = non_dwarf_expression (expr);
30089   if (l && l->dw_loc_next)
30090     return NULL;
30091
30092   if (l)
30093     {
30094       if (l->dw_loc_opc >= DW_OP_reg0 && l->dw_loc_opc <= DW_OP_reg31)
30095         tail = new_loc_descr ((enum dwarf_location_atom)
30096                               (DW_OP_breg0 + (l->dw_loc_opc - DW_OP_reg0)),
30097                               0, 0);
30098       else
30099         switch (l->dw_loc_opc)
30100           {
30101           case DW_OP_regx:
30102             tail = new_loc_descr (DW_OP_bregx,
30103                                   l->dw_loc_oprnd1.v.val_unsigned, 0);
30104             break;
30105           case DW_OP_stack_value:
30106             break;
30107           default:
30108             return NULL;
30109           }
30110     }
30111   else
30112     tail = new_loc_descr (DW_OP_deref, 0, 0);
30113
30114   dw_loc_descr_ref ret = NULL, *p = &ret;
30115   while (expr != l)
30116     {
30117       *p = new_loc_descr (expr->dw_loc_opc, 0, 0);
30118       (*p)->dw_loc_oprnd1 = expr->dw_loc_oprnd1;
30119       (*p)->dw_loc_oprnd2 = expr->dw_loc_oprnd2;
30120       p = &(*p)->dw_loc_next;
30121       expr = expr->dw_loc_next;
30122     }
30123   *p = tail;
30124   return ret;
30125 }
30126
30127 /* For DW_AT_string_length attribute with DW_OP_GNU_variable_value
30128    reference to a variable or argument, adjust it if needed and return:
30129    -1 if the DW_AT_string_length attribute and DW_AT_{string_length_,}byte_size
30130       attribute if present should be removed
30131    0 keep the attribute perhaps with minor modifications, no need to rescan
30132    1 if the attribute has been successfully adjusted.  */
30133
30134 static int
30135 optimize_string_length (dw_attr_node *a)
30136 {
30137   dw_loc_descr_ref l = AT_loc (a), lv;
30138   dw_die_ref die;
30139   if (l->dw_loc_oprnd1.val_class == dw_val_class_decl_ref)
30140     {
30141       tree decl = l->dw_loc_oprnd1.v.val_decl_ref;
30142       die = lookup_decl_die (decl);
30143       if (die)
30144         {
30145           l->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
30146           l->dw_loc_oprnd1.v.val_die_ref.die = die;
30147           l->dw_loc_oprnd1.v.val_die_ref.external = 0;
30148         }
30149       else
30150         return -1;
30151     }
30152   else
30153     die = l->dw_loc_oprnd1.v.val_die_ref.die;
30154
30155   /* DWARF5 allows reference class, so we can then reference the DIE.
30156      Only do this for DW_OP_GNU_variable_value DW_OP_stack_value.  */
30157   if (l->dw_loc_next != NULL && dwarf_version >= 5)
30158     {
30159       a->dw_attr_val.val_class = dw_val_class_die_ref;
30160       a->dw_attr_val.val_entry = NULL;
30161       a->dw_attr_val.v.val_die_ref.die = die;
30162       a->dw_attr_val.v.val_die_ref.external = 0;
30163       return 0;
30164     }
30165
30166   dw_attr_node *av = get_AT (die, DW_AT_location);
30167   dw_loc_list_ref d;
30168   bool non_dwarf_expr = false;
30169
30170   if (av == NULL)
30171     return dwarf_strict ? -1 : 0;
30172   switch (AT_class (av))
30173     {
30174     case dw_val_class_loc_list:
30175       for (d = AT_loc_list (av); d != NULL; d = d->dw_loc_next)
30176         if (d->expr && non_dwarf_expression (d->expr))
30177           non_dwarf_expr = true;
30178       break;
30179     case dw_val_class_view_list:
30180       gcc_unreachable ();
30181     case dw_val_class_loc:
30182       lv = AT_loc (av);
30183       if (lv == NULL)
30184         return dwarf_strict ? -1 : 0;
30185       if (non_dwarf_expression (lv))
30186         non_dwarf_expr = true;
30187       break;
30188     default:
30189       return dwarf_strict ? -1 : 0;
30190     }
30191
30192   /* If it is safe to transform DW_OP_GNU_variable_value DW_OP_stack_value
30193      into DW_OP_call4  or DW_OP_GNU_variable_value into
30194      DW_OP_call4 DW_OP_deref, do so.  */
30195   if (!non_dwarf_expr
30196       && (l->dw_loc_next != NULL || AT_class (av) == dw_val_class_loc))
30197     {
30198       l->dw_loc_opc = DW_OP_call4;
30199       if (l->dw_loc_next)
30200         l->dw_loc_next = NULL;
30201       else
30202         l->dw_loc_next = new_loc_descr (DW_OP_deref, 0, 0);
30203       return 0;
30204     }
30205
30206   /* For DW_OP_GNU_variable_value DW_OP_stack_value, we can just
30207      copy over the DW_AT_location attribute from die to a.  */
30208   if (l->dw_loc_next != NULL)
30209     {
30210       a->dw_attr_val = av->dw_attr_val;
30211       return 1;
30212     }
30213
30214   dw_loc_list_ref list, *p;
30215   switch (AT_class (av))
30216     {
30217     case dw_val_class_loc_list:
30218       p = &list;
30219       list = NULL;
30220       for (d = AT_loc_list (av); d != NULL; d = d->dw_loc_next)
30221         {
30222           lv = copy_deref_exprloc (d->expr);
30223           if (lv)
30224             {
30225               *p = new_loc_list (lv, d->begin, d->vbegin, d->end, d->vend, d->section);
30226               p = &(*p)->dw_loc_next;
30227             }
30228           else if (!dwarf_strict && d->expr)
30229             return 0;
30230         }
30231       if (list == NULL)
30232         return dwarf_strict ? -1 : 0;
30233       a->dw_attr_val.val_class = dw_val_class_loc_list;
30234       gen_llsym (list);
30235       *AT_loc_list_ptr (a) = list;
30236       return 1;
30237     case dw_val_class_loc:
30238       lv = copy_deref_exprloc (AT_loc (av));
30239       if (lv == NULL)
30240         return dwarf_strict ? -1 : 0;
30241       a->dw_attr_val.v.val_loc = lv;
30242       return 1;
30243     default:
30244       gcc_unreachable ();
30245     }
30246 }
30247
30248 /* Resolve DW_OP_addr and DW_AT_const_value CONST_STRING arguments to
30249    an address in .rodata section if the string literal is emitted there,
30250    or remove the containing location list or replace DW_AT_const_value
30251    with DW_AT_location and empty location expression, if it isn't found
30252    in .rodata.  Similarly for SYMBOL_REFs, keep only those that refer
30253    to something that has been emitted in the current CU.  */
30254
30255 static void
30256 resolve_addr (dw_die_ref die)
30257 {
30258   dw_die_ref c;
30259   dw_attr_node *a;
30260   dw_loc_list_ref *curr, *start, loc;
30261   unsigned ix;
30262   bool remove_AT_byte_size = false;
30263
30264   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
30265     switch (AT_class (a))
30266       {
30267       case dw_val_class_loc_list:
30268         start = curr = AT_loc_list_ptr (a);
30269         loc = *curr;
30270         gcc_assert (loc);
30271         /* The same list can be referenced more than once.  See if we have
30272            already recorded the result from a previous pass.  */
30273         if (loc->replaced)
30274           *curr = loc->dw_loc_next;
30275         else if (!loc->resolved_addr)
30276           {
30277             /* As things stand, we do not expect or allow one die to
30278                reference a suffix of another die's location list chain.
30279                References must be identical or completely separate.
30280                There is therefore no need to cache the result of this
30281                pass on any list other than the first; doing so
30282                would lead to unnecessary writes.  */
30283             while (*curr)
30284               {
30285                 gcc_assert (!(*curr)->replaced && !(*curr)->resolved_addr);
30286                 if (!resolve_addr_in_expr (a, (*curr)->expr))
30287                   {
30288                     dw_loc_list_ref next = (*curr)->dw_loc_next;
30289                     dw_loc_descr_ref l = (*curr)->expr;
30290
30291                     if (next && (*curr)->ll_symbol)
30292                       {
30293                         gcc_assert (!next->ll_symbol);
30294                         next->ll_symbol = (*curr)->ll_symbol;
30295                         next->vl_symbol = (*curr)->vl_symbol;
30296                       }
30297                     if (dwarf_split_debug_info)
30298                       remove_loc_list_addr_table_entries (l);
30299                     *curr = next;
30300                   }
30301                 else
30302                   {
30303                     mark_base_types ((*curr)->expr);
30304                     curr = &(*curr)->dw_loc_next;
30305                   }
30306               }
30307             if (loc == *start)
30308               loc->resolved_addr = 1;
30309             else
30310               {
30311                 loc->replaced = 1;
30312                 loc->dw_loc_next = *start;
30313               }
30314           }
30315         if (!*start)
30316           {
30317             remove_AT (die, a->dw_attr);
30318             ix--;
30319           }
30320         break;
30321       case dw_val_class_view_list:
30322         {
30323           gcc_checking_assert (a->dw_attr == DW_AT_GNU_locviews);
30324           gcc_checking_assert (dwarf2out_locviews_in_attribute ());
30325           dw_val_node *llnode
30326             = view_list_to_loc_list_val_node (&a->dw_attr_val);
30327           /* If we no longer have a loclist, or it no longer needs
30328              views, drop this attribute.  */
30329           if (!llnode || !llnode->v.val_loc_list->vl_symbol)
30330             {
30331               remove_AT (die, a->dw_attr);
30332               ix--;
30333             }
30334           break;
30335         }
30336       case dw_val_class_loc:
30337         {
30338           dw_loc_descr_ref l = AT_loc (a);
30339           /* DW_OP_GNU_variable_value DW_OP_stack_value or
30340              DW_OP_GNU_variable_value in DW_AT_string_length can be converted
30341              into DW_OP_call4 or DW_OP_call4 DW_OP_deref, which is standard
30342              DWARF4 unlike DW_OP_GNU_variable_value.  Or for DWARF5
30343              DW_OP_GNU_variable_value DW_OP_stack_value can be replaced
30344              with DW_FORM_ref referencing the same DIE as
30345              DW_OP_GNU_variable_value used to reference.  */
30346           if (a->dw_attr == DW_AT_string_length
30347               && l
30348               && l->dw_loc_opc == DW_OP_GNU_variable_value
30349               && (l->dw_loc_next == NULL
30350                   || (l->dw_loc_next->dw_loc_next == NULL
30351                       && l->dw_loc_next->dw_loc_opc == DW_OP_stack_value)))
30352             {
30353               switch (optimize_string_length (a))
30354                 {
30355                 case -1:
30356                   remove_AT (die, a->dw_attr);
30357                   ix--;
30358                   /* If we drop DW_AT_string_length, we need to drop also
30359                      DW_AT_{string_length_,}byte_size.  */
30360                   remove_AT_byte_size = true;
30361                   continue;
30362                 default:
30363                   break;
30364                 case 1:
30365                   /* Even if we keep the optimized DW_AT_string_length,
30366                      it might have changed AT_class, so process it again.  */
30367                   ix--;
30368                   continue;
30369                 }
30370             }
30371           /* For -gdwarf-2 don't attempt to optimize
30372              DW_AT_data_member_location containing
30373              DW_OP_plus_uconst - older consumers might
30374              rely on it being that op instead of a more complex,
30375              but shorter, location description.  */
30376           if ((dwarf_version > 2
30377                || a->dw_attr != DW_AT_data_member_location
30378                || l == NULL
30379                || l->dw_loc_opc != DW_OP_plus_uconst
30380                || l->dw_loc_next != NULL)
30381               && !resolve_addr_in_expr (a, l))
30382             {
30383               if (dwarf_split_debug_info)
30384                 remove_loc_list_addr_table_entries (l);
30385               if (l != NULL
30386                   && l->dw_loc_next == NULL
30387                   && l->dw_loc_opc == DW_OP_addr
30388                   && GET_CODE (l->dw_loc_oprnd1.v.val_addr) == SYMBOL_REF
30389                   && SYMBOL_REF_DECL (l->dw_loc_oprnd1.v.val_addr)
30390                   && a->dw_attr == DW_AT_location)
30391                 {
30392                   tree decl = SYMBOL_REF_DECL (l->dw_loc_oprnd1.v.val_addr);
30393                   remove_AT (die, a->dw_attr);
30394                   ix--;
30395                   optimize_location_into_implicit_ptr (die, decl);
30396                   break;
30397                 }
30398               if (a->dw_attr == DW_AT_string_length)
30399                 /* If we drop DW_AT_string_length, we need to drop also
30400                    DW_AT_{string_length_,}byte_size.  */
30401                 remove_AT_byte_size = true;
30402               remove_AT (die, a->dw_attr);
30403               ix--;
30404             }
30405           else
30406             mark_base_types (l);
30407         }
30408         break;
30409       case dw_val_class_addr:
30410         if (a->dw_attr == DW_AT_const_value
30411             && !resolve_one_addr (&a->dw_attr_val.v.val_addr))
30412           {
30413             if (AT_index (a) != NOT_INDEXED)
30414               remove_addr_table_entry (a->dw_attr_val.val_entry);
30415             remove_AT (die, a->dw_attr);
30416             ix--;
30417           }
30418         if ((die->die_tag == DW_TAG_call_site
30419              && a->dw_attr == DW_AT_call_origin)
30420             || (die->die_tag == DW_TAG_GNU_call_site
30421                 && a->dw_attr == DW_AT_abstract_origin))
30422           {
30423             tree tdecl = SYMBOL_REF_DECL (a->dw_attr_val.v.val_addr);
30424             dw_die_ref tdie = lookup_decl_die (tdecl);
30425             dw_die_ref cdie;
30426             if (tdie == NULL
30427                 && DECL_EXTERNAL (tdecl)
30428                 && DECL_ABSTRACT_ORIGIN (tdecl) == NULL_TREE
30429                 && (cdie = lookup_context_die (DECL_CONTEXT (tdecl))))
30430               {
30431                 dw_die_ref pdie = cdie;
30432                 /* Make sure we don't add these DIEs into type units.
30433                    We could emit skeleton DIEs for context (namespaces,
30434                    outer structs/classes) and a skeleton DIE for the
30435                    innermost context with DW_AT_signature pointing to the
30436                    type unit.  See PR78835.  */
30437                 while (pdie && pdie->die_tag != DW_TAG_type_unit)
30438                   pdie = pdie->die_parent;
30439                 if (pdie == NULL)
30440                   {
30441                     /* Creating a full DIE for tdecl is overly expensive and
30442                        at this point even wrong when in the LTO phase
30443                        as it can end up generating new type DIEs we didn't
30444                        output and thus optimize_external_refs will crash.  */
30445                     tdie = new_die (DW_TAG_subprogram, cdie, NULL_TREE);
30446                     add_AT_flag (tdie, DW_AT_external, 1);
30447                     add_AT_flag (tdie, DW_AT_declaration, 1);
30448                     add_linkage_attr (tdie, tdecl);
30449                     add_name_and_src_coords_attributes (tdie, tdecl, true);
30450                     equate_decl_number_to_die (tdecl, tdie);
30451                   }
30452               }
30453             if (tdie)
30454               {
30455                 a->dw_attr_val.val_class = dw_val_class_die_ref;
30456                 a->dw_attr_val.v.val_die_ref.die = tdie;
30457                 a->dw_attr_val.v.val_die_ref.external = 0;
30458               }
30459             else
30460               {
30461                 if (AT_index (a) != NOT_INDEXED)
30462                   remove_addr_table_entry (a->dw_attr_val.val_entry);
30463                 remove_AT (die, a->dw_attr);
30464                 ix--;
30465               }
30466           }
30467         break;
30468       default:
30469         break;
30470       }
30471
30472   if (remove_AT_byte_size)
30473     remove_AT (die, dwarf_version >= 5
30474                     ? DW_AT_string_length_byte_size
30475                     : DW_AT_byte_size);
30476
30477   FOR_EACH_CHILD (die, c, resolve_addr (c));
30478 }
30479 \f
30480 /* Helper routines for optimize_location_lists.
30481    This pass tries to share identical local lists in .debug_loc
30482    section.  */
30483
30484 /* Iteratively hash operands of LOC opcode into HSTATE.  */
30485
30486 static void
30487 hash_loc_operands (dw_loc_descr_ref loc, inchash::hash &hstate)
30488 {
30489   dw_val_ref val1 = &loc->dw_loc_oprnd1;
30490   dw_val_ref val2 = &loc->dw_loc_oprnd2;
30491
30492   switch (loc->dw_loc_opc)
30493     {
30494     case DW_OP_const4u:
30495     case DW_OP_const8u:
30496       if (loc->dtprel)
30497         goto hash_addr;
30498       /* FALLTHRU */
30499     case DW_OP_const1u:
30500     case DW_OP_const1s:
30501     case DW_OP_const2u:
30502     case DW_OP_const2s:
30503     case DW_OP_const4s:
30504     case DW_OP_const8s:
30505     case DW_OP_constu:
30506     case DW_OP_consts:
30507     case DW_OP_pick:
30508     case DW_OP_plus_uconst:
30509     case DW_OP_breg0:
30510     case DW_OP_breg1:
30511     case DW_OP_breg2:
30512     case DW_OP_breg3:
30513     case DW_OP_breg4:
30514     case DW_OP_breg5:
30515     case DW_OP_breg6:
30516     case DW_OP_breg7:
30517     case DW_OP_breg8:
30518     case DW_OP_breg9:
30519     case DW_OP_breg10:
30520     case DW_OP_breg11:
30521     case DW_OP_breg12:
30522     case DW_OP_breg13:
30523     case DW_OP_breg14:
30524     case DW_OP_breg15:
30525     case DW_OP_breg16:
30526     case DW_OP_breg17:
30527     case DW_OP_breg18:
30528     case DW_OP_breg19:
30529     case DW_OP_breg20:
30530     case DW_OP_breg21:
30531     case DW_OP_breg22:
30532     case DW_OP_breg23:
30533     case DW_OP_breg24:
30534     case DW_OP_breg25:
30535     case DW_OP_breg26:
30536     case DW_OP_breg27:
30537     case DW_OP_breg28:
30538     case DW_OP_breg29:
30539     case DW_OP_breg30:
30540     case DW_OP_breg31:
30541     case DW_OP_regx:
30542     case DW_OP_fbreg:
30543     case DW_OP_piece:
30544     case DW_OP_deref_size:
30545     case DW_OP_xderef_size:
30546       hstate.add_object (val1->v.val_int);
30547       break;
30548     case DW_OP_skip:
30549     case DW_OP_bra:
30550       {
30551         int offset;
30552
30553         gcc_assert (val1->val_class == dw_val_class_loc);
30554         offset = val1->v.val_loc->dw_loc_addr - (loc->dw_loc_addr + 3);
30555         hstate.add_object (offset);
30556       }
30557       break;
30558     case DW_OP_implicit_value:
30559       hstate.add_object (val1->v.val_unsigned);
30560       switch (val2->val_class)
30561         {
30562         case dw_val_class_const:
30563           hstate.add_object (val2->v.val_int);
30564           break;
30565         case dw_val_class_vec:
30566           {
30567             unsigned int elt_size = val2->v.val_vec.elt_size;
30568             unsigned int len = val2->v.val_vec.length;
30569
30570             hstate.add_int (elt_size);
30571             hstate.add_int (len);
30572             hstate.add (val2->v.val_vec.array, len * elt_size);
30573           }
30574           break;
30575         case dw_val_class_const_double:
30576           hstate.add_object (val2->v.val_double.low);
30577           hstate.add_object (val2->v.val_double.high);
30578           break;
30579         case dw_val_class_wide_int:
30580           hstate.add (val2->v.val_wide->get_val (),
30581                       get_full_len (*val2->v.val_wide)
30582                       * HOST_BITS_PER_WIDE_INT / HOST_BITS_PER_CHAR);
30583           break;
30584         case dw_val_class_addr: 
30585           inchash::add_rtx (val2->v.val_addr, hstate);
30586           break;
30587         default:
30588           gcc_unreachable ();
30589         }
30590       break;
30591     case DW_OP_bregx:
30592     case DW_OP_bit_piece:
30593       hstate.add_object (val1->v.val_int);
30594       hstate.add_object (val2->v.val_int);
30595       break;
30596     case DW_OP_addr:
30597     hash_addr:
30598       if (loc->dtprel)
30599         {
30600           unsigned char dtprel = 0xd1;
30601           hstate.add_object (dtprel);
30602         }
30603       inchash::add_rtx (val1->v.val_addr, hstate);
30604       break;
30605     case DW_OP_GNU_addr_index:
30606     case DW_OP_GNU_const_index:
30607       {
30608         if (loc->dtprel)
30609           {
30610             unsigned char dtprel = 0xd1;
30611             hstate.add_object (dtprel);
30612           }
30613         inchash::add_rtx (val1->val_entry->addr.rtl, hstate);
30614       }
30615       break;
30616     case DW_OP_implicit_pointer:
30617     case DW_OP_GNU_implicit_pointer:
30618       hstate.add_int (val2->v.val_int);
30619       break;
30620     case DW_OP_entry_value:
30621     case DW_OP_GNU_entry_value:
30622       hstate.add_object (val1->v.val_loc);
30623       break;
30624     case DW_OP_regval_type:
30625     case DW_OP_deref_type:
30626     case DW_OP_GNU_regval_type:
30627     case DW_OP_GNU_deref_type:
30628       {
30629         unsigned int byte_size
30630           = get_AT_unsigned (val2->v.val_die_ref.die, DW_AT_byte_size);
30631         unsigned int encoding
30632           = get_AT_unsigned (val2->v.val_die_ref.die, DW_AT_encoding);
30633         hstate.add_object (val1->v.val_int);
30634         hstate.add_object (byte_size);
30635         hstate.add_object (encoding);
30636       }
30637       break;
30638     case DW_OP_convert:
30639     case DW_OP_reinterpret:
30640     case DW_OP_GNU_convert:
30641     case DW_OP_GNU_reinterpret:
30642       if (val1->val_class == dw_val_class_unsigned_const)
30643         {
30644           hstate.add_object (val1->v.val_unsigned);
30645           break;
30646         }
30647       /* FALLTHRU */
30648     case DW_OP_const_type:
30649     case DW_OP_GNU_const_type:
30650       {
30651         unsigned int byte_size
30652           = get_AT_unsigned (val1->v.val_die_ref.die, DW_AT_byte_size);
30653         unsigned int encoding
30654           = get_AT_unsigned (val1->v.val_die_ref.die, DW_AT_encoding);
30655         hstate.add_object (byte_size);
30656         hstate.add_object (encoding);
30657         if (loc->dw_loc_opc != DW_OP_const_type
30658             && loc->dw_loc_opc != DW_OP_GNU_const_type)
30659           break;
30660         hstate.add_object (val2->val_class);
30661         switch (val2->val_class)
30662           {
30663           case dw_val_class_const:
30664             hstate.add_object (val2->v.val_int);
30665             break;
30666           case dw_val_class_vec:
30667             {
30668               unsigned int elt_size = val2->v.val_vec.elt_size;
30669               unsigned int len = val2->v.val_vec.length;
30670
30671               hstate.add_object (elt_size);
30672               hstate.add_object (len);
30673               hstate.add (val2->v.val_vec.array, len * elt_size);
30674             }
30675             break;
30676           case dw_val_class_const_double:
30677             hstate.add_object (val2->v.val_double.low);
30678             hstate.add_object (val2->v.val_double.high);
30679             break;
30680           case dw_val_class_wide_int:
30681             hstate.add (val2->v.val_wide->get_val (),
30682                         get_full_len (*val2->v.val_wide)
30683                         * HOST_BITS_PER_WIDE_INT / HOST_BITS_PER_CHAR);
30684             break;
30685           default:
30686             gcc_unreachable ();
30687           }
30688       }
30689       break;
30690
30691     default:
30692       /* Other codes have no operands.  */
30693       break;
30694     }
30695 }
30696
30697 /* Iteratively hash the whole DWARF location expression LOC into HSTATE.  */
30698
30699 static inline void
30700 hash_locs (dw_loc_descr_ref loc, inchash::hash &hstate)
30701 {
30702   dw_loc_descr_ref l;
30703   bool sizes_computed = false;
30704   /* Compute sizes, so that DW_OP_skip/DW_OP_bra can be checksummed.  */
30705   size_of_locs (loc);
30706
30707   for (l = loc; l != NULL; l = l->dw_loc_next)
30708     {
30709       enum dwarf_location_atom opc = l->dw_loc_opc;
30710       hstate.add_object (opc);
30711       if ((opc == DW_OP_skip || opc == DW_OP_bra) && !sizes_computed)
30712         {
30713           size_of_locs (loc);
30714           sizes_computed = true;
30715         }
30716       hash_loc_operands (l, hstate);
30717     }
30718 }
30719
30720 /* Compute hash of the whole location list LIST_HEAD.  */
30721
30722 static inline void
30723 hash_loc_list (dw_loc_list_ref list_head)
30724 {
30725   dw_loc_list_ref curr = list_head;
30726   inchash::hash hstate;
30727
30728   for (curr = list_head; curr != NULL; curr = curr->dw_loc_next)
30729     {
30730       hstate.add (curr->begin, strlen (curr->begin) + 1);
30731       hstate.add (curr->end, strlen (curr->end) + 1);
30732       hstate.add_object (curr->vbegin);
30733       hstate.add_object (curr->vend);
30734       if (curr->section)
30735         hstate.add (curr->section, strlen (curr->section) + 1);
30736       hash_locs (curr->expr, hstate);
30737     }
30738   list_head->hash = hstate.end ();
30739 }
30740
30741 /* Return true if X and Y opcodes have the same operands.  */
30742
30743 static inline bool
30744 compare_loc_operands (dw_loc_descr_ref x, dw_loc_descr_ref y)
30745 {
30746   dw_val_ref valx1 = &x->dw_loc_oprnd1;
30747   dw_val_ref valx2 = &x->dw_loc_oprnd2;
30748   dw_val_ref valy1 = &y->dw_loc_oprnd1;
30749   dw_val_ref valy2 = &y->dw_loc_oprnd2;
30750
30751   switch (x->dw_loc_opc)
30752     {
30753     case DW_OP_const4u:
30754     case DW_OP_const8u:
30755       if (x->dtprel)
30756         goto hash_addr;
30757       /* FALLTHRU */
30758     case DW_OP_const1u:
30759     case DW_OP_const1s:
30760     case DW_OP_const2u:
30761     case DW_OP_const2s:
30762     case DW_OP_const4s:
30763     case DW_OP_const8s:
30764     case DW_OP_constu:
30765     case DW_OP_consts:
30766     case DW_OP_pick:
30767     case DW_OP_plus_uconst:
30768     case DW_OP_breg0:
30769     case DW_OP_breg1:
30770     case DW_OP_breg2:
30771     case DW_OP_breg3:
30772     case DW_OP_breg4:
30773     case DW_OP_breg5:
30774     case DW_OP_breg6:
30775     case DW_OP_breg7:
30776     case DW_OP_breg8:
30777     case DW_OP_breg9:
30778     case DW_OP_breg10:
30779     case DW_OP_breg11:
30780     case DW_OP_breg12:
30781     case DW_OP_breg13:
30782     case DW_OP_breg14:
30783     case DW_OP_breg15:
30784     case DW_OP_breg16:
30785     case DW_OP_breg17:
30786     case DW_OP_breg18:
30787     case DW_OP_breg19:
30788     case DW_OP_breg20:
30789     case DW_OP_breg21:
30790     case DW_OP_breg22:
30791     case DW_OP_breg23:
30792     case DW_OP_breg24:
30793     case DW_OP_breg25:
30794     case DW_OP_breg26:
30795     case DW_OP_breg27:
30796     case DW_OP_breg28:
30797     case DW_OP_breg29:
30798     case DW_OP_breg30:
30799     case DW_OP_breg31:
30800     case DW_OP_regx:
30801     case DW_OP_fbreg:
30802     case DW_OP_piece:
30803     case DW_OP_deref_size:
30804     case DW_OP_xderef_size:
30805       return valx1->v.val_int == valy1->v.val_int;
30806     case DW_OP_skip:
30807     case DW_OP_bra:
30808       /* If splitting debug info, the use of DW_OP_GNU_addr_index
30809         can cause irrelevant differences in dw_loc_addr.  */
30810       gcc_assert (valx1->val_class == dw_val_class_loc
30811                   && valy1->val_class == dw_val_class_loc
30812                   && (dwarf_split_debug_info
30813                       || x->dw_loc_addr == y->dw_loc_addr));
30814       return valx1->v.val_loc->dw_loc_addr == valy1->v.val_loc->dw_loc_addr;
30815     case DW_OP_implicit_value:
30816       if (valx1->v.val_unsigned != valy1->v.val_unsigned
30817           || valx2->val_class != valy2->val_class)
30818         return false;
30819       switch (valx2->val_class)
30820         {
30821         case dw_val_class_const:
30822           return valx2->v.val_int == valy2->v.val_int;
30823         case dw_val_class_vec:
30824           return valx2->v.val_vec.elt_size == valy2->v.val_vec.elt_size
30825                  && valx2->v.val_vec.length == valy2->v.val_vec.length
30826                  && memcmp (valx2->v.val_vec.array, valy2->v.val_vec.array,
30827                             valx2->v.val_vec.elt_size
30828                             * valx2->v.val_vec.length) == 0;
30829         case dw_val_class_const_double:
30830           return valx2->v.val_double.low == valy2->v.val_double.low
30831                  && valx2->v.val_double.high == valy2->v.val_double.high;
30832         case dw_val_class_wide_int:
30833           return *valx2->v.val_wide == *valy2->v.val_wide;
30834         case dw_val_class_addr:
30835           return rtx_equal_p (valx2->v.val_addr, valy2->v.val_addr);
30836         default:
30837           gcc_unreachable ();
30838         }
30839     case DW_OP_bregx:
30840     case DW_OP_bit_piece:
30841       return valx1->v.val_int == valy1->v.val_int
30842              && valx2->v.val_int == valy2->v.val_int;
30843     case DW_OP_addr:
30844     hash_addr:
30845       return rtx_equal_p (valx1->v.val_addr, valy1->v.val_addr);
30846     case DW_OP_GNU_addr_index:
30847     case DW_OP_GNU_const_index:
30848       {
30849         rtx ax1 = valx1->val_entry->addr.rtl;
30850         rtx ay1 = valy1->val_entry->addr.rtl;
30851         return rtx_equal_p (ax1, ay1);
30852       }
30853     case DW_OP_implicit_pointer:
30854     case DW_OP_GNU_implicit_pointer:
30855       return valx1->val_class == dw_val_class_die_ref
30856              && valx1->val_class == valy1->val_class
30857              && valx1->v.val_die_ref.die == valy1->v.val_die_ref.die
30858              && valx2->v.val_int == valy2->v.val_int;
30859     case DW_OP_entry_value:
30860     case DW_OP_GNU_entry_value:
30861       return compare_loc_operands (valx1->v.val_loc, valy1->v.val_loc);
30862     case DW_OP_const_type:
30863     case DW_OP_GNU_const_type:
30864       if (valx1->v.val_die_ref.die != valy1->v.val_die_ref.die
30865           || valx2->val_class != valy2->val_class)
30866         return false;
30867       switch (valx2->val_class)
30868         {
30869         case dw_val_class_const:
30870           return valx2->v.val_int == valy2->v.val_int;
30871         case dw_val_class_vec:
30872           return valx2->v.val_vec.elt_size == valy2->v.val_vec.elt_size
30873                  && valx2->v.val_vec.length == valy2->v.val_vec.length
30874                  && memcmp (valx2->v.val_vec.array, valy2->v.val_vec.array,
30875                             valx2->v.val_vec.elt_size
30876                             * valx2->v.val_vec.length) == 0;
30877         case dw_val_class_const_double:
30878           return valx2->v.val_double.low == valy2->v.val_double.low
30879                  && valx2->v.val_double.high == valy2->v.val_double.high;
30880         case dw_val_class_wide_int:
30881           return *valx2->v.val_wide == *valy2->v.val_wide;
30882         default:
30883           gcc_unreachable ();
30884         }
30885     case DW_OP_regval_type:
30886     case DW_OP_deref_type:
30887     case DW_OP_GNU_regval_type:
30888     case DW_OP_GNU_deref_type:
30889       return valx1->v.val_int == valy1->v.val_int
30890              && valx2->v.val_die_ref.die == valy2->v.val_die_ref.die;
30891     case DW_OP_convert:
30892     case DW_OP_reinterpret:
30893     case DW_OP_GNU_convert:
30894     case DW_OP_GNU_reinterpret:
30895       if (valx1->val_class != valy1->val_class)
30896         return false;
30897       if (valx1->val_class == dw_val_class_unsigned_const)
30898         return valx1->v.val_unsigned == valy1->v.val_unsigned;
30899       return valx1->v.val_die_ref.die == valy1->v.val_die_ref.die;
30900     case DW_OP_GNU_parameter_ref:
30901       return valx1->val_class == dw_val_class_die_ref
30902              && valx1->val_class == valy1->val_class
30903              && valx1->v.val_die_ref.die == valy1->v.val_die_ref.die;
30904     default:
30905       /* Other codes have no operands.  */
30906       return true;
30907     }
30908 }
30909
30910 /* Return true if DWARF location expressions X and Y are the same.  */
30911
30912 static inline bool
30913 compare_locs (dw_loc_descr_ref x, dw_loc_descr_ref y)
30914 {
30915   for (; x != NULL && y != NULL; x = x->dw_loc_next, y = y->dw_loc_next)
30916     if (x->dw_loc_opc != y->dw_loc_opc
30917         || x->dtprel != y->dtprel
30918         || !compare_loc_operands (x, y))
30919       break;
30920   return x == NULL && y == NULL;
30921 }
30922
30923 /* Hashtable helpers.  */
30924
30925 struct loc_list_hasher : nofree_ptr_hash <dw_loc_list_struct>
30926 {
30927   static inline hashval_t hash (const dw_loc_list_struct *);
30928   static inline bool equal (const dw_loc_list_struct *,
30929                             const dw_loc_list_struct *);
30930 };
30931
30932 /* Return precomputed hash of location list X.  */
30933
30934 inline hashval_t
30935 loc_list_hasher::hash (const dw_loc_list_struct *x)
30936 {
30937   return x->hash;
30938 }
30939
30940 /* Return true if location lists A and B are the same.  */
30941
30942 inline bool
30943 loc_list_hasher::equal (const dw_loc_list_struct *a,
30944                         const dw_loc_list_struct *b)
30945 {
30946   if (a == b)
30947     return 1;
30948   if (a->hash != b->hash)
30949     return 0;
30950   for (; a != NULL && b != NULL; a = a->dw_loc_next, b = b->dw_loc_next)
30951     if (strcmp (a->begin, b->begin) != 0
30952         || strcmp (a->end, b->end) != 0
30953         || (a->section == NULL) != (b->section == NULL)
30954         || (a->section && strcmp (a->section, b->section) != 0)
30955         || a->vbegin != b->vbegin || a->vend != b->vend
30956         || !compare_locs (a->expr, b->expr))
30957       break;
30958   return a == NULL && b == NULL;
30959 }
30960
30961 typedef hash_table<loc_list_hasher> loc_list_hash_type;
30962
30963
30964 /* Recursively optimize location lists referenced from DIE
30965    children and share them whenever possible.  */
30966
30967 static void
30968 optimize_location_lists_1 (dw_die_ref die, loc_list_hash_type *htab)
30969 {
30970   dw_die_ref c;
30971   dw_attr_node *a;
30972   unsigned ix;
30973   dw_loc_list_struct **slot;
30974   bool drop_locviews = false;
30975   bool has_locviews = false;
30976
30977   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
30978     if (AT_class (a) == dw_val_class_loc_list)
30979       {
30980         dw_loc_list_ref list = AT_loc_list (a);
30981         /* TODO: perform some optimizations here, before hashing
30982            it and storing into the hash table.  */
30983         hash_loc_list (list);
30984         slot = htab->find_slot_with_hash (list, list->hash, INSERT);
30985         if (*slot == NULL)
30986           {
30987             *slot = list;
30988             if (loc_list_has_views (list))
30989               gcc_assert (list->vl_symbol);
30990             else if (list->vl_symbol)
30991               {
30992                 drop_locviews = true;
30993                 list->vl_symbol = NULL;
30994               }
30995           }
30996         else
30997           {
30998             if (list->vl_symbol && !(*slot)->vl_symbol)
30999               drop_locviews = true;
31000             a->dw_attr_val.v.val_loc_list = *slot;
31001           }
31002       }
31003     else if (AT_class (a) == dw_val_class_view_list)
31004       {
31005         gcc_checking_assert (a->dw_attr == DW_AT_GNU_locviews);
31006         has_locviews = true;
31007       }
31008
31009
31010   if (drop_locviews && has_locviews)
31011     remove_AT (die, DW_AT_GNU_locviews);
31012
31013   FOR_EACH_CHILD (die, c, optimize_location_lists_1 (c, htab));
31014 }
31015
31016
31017 /* Recursively assign each location list a unique index into the debug_addr
31018    section.  */
31019
31020 static void
31021 index_location_lists (dw_die_ref die)
31022 {
31023   dw_die_ref c;
31024   dw_attr_node *a;
31025   unsigned ix;
31026
31027   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
31028     if (AT_class (a) == dw_val_class_loc_list)
31029       {
31030         dw_loc_list_ref list = AT_loc_list (a);
31031         dw_loc_list_ref curr;
31032         for (curr = list; curr != NULL; curr = curr->dw_loc_next)
31033           {
31034             /* Don't index an entry that has already been indexed
31035                or won't be output.  Make sure skip_loc_list_entry doesn't
31036                call size_of_locs, because that might cause circular dependency,
31037                index_location_lists requiring address table indexes to be
31038                computed, but adding new indexes through add_addr_table_entry
31039                and address table index computation requiring no new additions
31040                to the hash table.  In the rare case of DWARF[234] >= 64KB
31041                location expression, we'll just waste unused address table entry
31042                for it.  */
31043             if (curr->begin_entry != NULL
31044                 || skip_loc_list_entry (curr))
31045               continue;
31046
31047             curr->begin_entry
31048               = add_addr_table_entry (xstrdup (curr->begin), ate_kind_label);
31049           }
31050       }
31051
31052   FOR_EACH_CHILD (die, c, index_location_lists (c));
31053 }
31054
31055 /* Optimize location lists referenced from DIE
31056    children and share them whenever possible.  */
31057
31058 static void
31059 optimize_location_lists (dw_die_ref die)
31060 {
31061   loc_list_hash_type htab (500);
31062   optimize_location_lists_1 (die, &htab);
31063 }
31064 \f
31065 /* Traverse the limbo die list, and add parent/child links.  The only
31066    dies without parents that should be here are concrete instances of
31067    inline functions, and the comp_unit_die.  We can ignore the comp_unit_die.
31068    For concrete instances, we can get the parent die from the abstract
31069    instance.  */
31070
31071 static void
31072 flush_limbo_die_list (void)
31073 {
31074   limbo_die_node *node;
31075
31076   /* get_context_die calls force_decl_die, which can put new DIEs on the
31077      limbo list in LTO mode when nested functions are put in a different
31078      partition than that of their parent function.  */
31079   while ((node = limbo_die_list))
31080     {
31081       dw_die_ref die = node->die;
31082       limbo_die_list = node->next;
31083
31084       if (die->die_parent == NULL)
31085         {
31086           dw_die_ref origin = get_AT_ref (die, DW_AT_abstract_origin);
31087
31088           if (origin && origin->die_parent)
31089             add_child_die (origin->die_parent, die);
31090           else if (is_cu_die (die))
31091             ;
31092           else if (seen_error ())
31093             /* It's OK to be confused by errors in the input.  */
31094             add_child_die (comp_unit_die (), die);
31095           else
31096             {
31097               /* In certain situations, the lexical block containing a
31098                  nested function can be optimized away, which results
31099                  in the nested function die being orphaned.  Likewise
31100                  with the return type of that nested function.  Force
31101                  this to be a child of the containing function.
31102
31103                  It may happen that even the containing function got fully
31104                  inlined and optimized out.  In that case we are lost and
31105                  assign the empty child.  This should not be big issue as
31106                  the function is likely unreachable too.  */
31107               gcc_assert (node->created_for);
31108
31109               if (DECL_P (node->created_for))
31110                 origin = get_context_die (DECL_CONTEXT (node->created_for));
31111               else if (TYPE_P (node->created_for))
31112                 origin = scope_die_for (node->created_for, comp_unit_die ());
31113               else
31114                 origin = comp_unit_die ();
31115
31116               add_child_die (origin, die);
31117             }
31118         }
31119     }
31120 }
31121
31122 /* Reset DIEs so we can output them again.  */
31123
31124 static void
31125 reset_dies (dw_die_ref die)
31126 {
31127   dw_die_ref c;
31128
31129   /* Remove stuff we re-generate.  */
31130   die->die_mark = 0;
31131   die->die_offset = 0;
31132   die->die_abbrev = 0;
31133   remove_AT (die, DW_AT_sibling);
31134
31135   FOR_EACH_CHILD (die, c, reset_dies (c));
31136 }
31137
31138 /* Output stuff that dwarf requires at the end of every file,
31139    and generate the DWARF-2 debugging info.  */
31140
31141 static void
31142 dwarf2out_finish (const char *)
31143 {
31144   comdat_type_node *ctnode;
31145   dw_die_ref main_comp_unit_die;
31146   unsigned char checksum[16];
31147   char dl_section_ref[MAX_ARTIFICIAL_LABEL_BYTES];
31148
31149   /* Flush out any latecomers to the limbo party.  */
31150   flush_limbo_die_list ();
31151
31152   if (inline_entry_data_table)
31153     gcc_assert (inline_entry_data_table->elements () == 0);
31154
31155   if (flag_checking)
31156     {
31157       verify_die (comp_unit_die ());
31158       for (limbo_die_node *node = cu_die_list; node; node = node->next)
31159         verify_die (node->die);
31160     }
31161
31162   /* We shouldn't have any symbols with delayed asm names for
31163      DIEs generated after early finish.  */
31164   gcc_assert (deferred_asm_name == NULL);
31165
31166   gen_remaining_tmpl_value_param_die_attribute ();
31167
31168   if (flag_generate_lto || flag_generate_offload)
31169     {
31170       gcc_assert (flag_fat_lto_objects || flag_generate_offload);
31171
31172       /* Prune stuff so that dwarf2out_finish runs successfully
31173          for the fat part of the object.  */
31174       reset_dies (comp_unit_die ());
31175       for (limbo_die_node *node = cu_die_list; node; node = node->next)
31176         reset_dies (node->die);
31177
31178       hash_table<comdat_type_hasher> comdat_type_table (100);
31179       for (ctnode = comdat_type_list; ctnode != NULL; ctnode = ctnode->next)
31180         {
31181           comdat_type_node **slot
31182               = comdat_type_table.find_slot (ctnode, INSERT);
31183
31184           /* Don't reset types twice.  */
31185           if (*slot != HTAB_EMPTY_ENTRY)
31186             continue;
31187
31188           /* Remove the pointer to the line table.  */
31189           remove_AT (ctnode->root_die, DW_AT_stmt_list);
31190
31191           if (debug_info_level >= DINFO_LEVEL_TERSE)
31192             reset_dies (ctnode->root_die);
31193
31194           *slot = ctnode;
31195         }
31196
31197       /* Reset die CU symbol so we don't output it twice.  */
31198       comp_unit_die ()->die_id.die_symbol = NULL;
31199
31200       /* Remove DW_AT_macro and DW_AT_stmt_list from the early output.  */
31201       remove_AT (comp_unit_die (), DW_AT_stmt_list);
31202       if (have_macinfo)
31203         remove_AT (comp_unit_die (), DEBUG_MACRO_ATTRIBUTE);
31204
31205       /* Remove indirect string decisions.  */
31206       debug_str_hash->traverse<void *, reset_indirect_string> (NULL);
31207       if (debug_line_str_hash)
31208         {
31209           debug_line_str_hash->traverse<void *, reset_indirect_string> (NULL);
31210           debug_line_str_hash = NULL;
31211         }
31212     }
31213
31214 #if ENABLE_ASSERT_CHECKING
31215   {
31216     dw_die_ref die = comp_unit_die (), c;
31217     FOR_EACH_CHILD (die, c, gcc_assert (! c->die_mark));
31218   }
31219 #endif
31220   for (ctnode = comdat_type_list; ctnode != NULL; ctnode = ctnode->next)
31221     resolve_addr (ctnode->root_die);
31222   resolve_addr (comp_unit_die ());
31223   move_marked_base_types ();
31224
31225   /* Initialize sections and labels used for actual assembler output.  */
31226   unsigned generation = init_sections_and_labels (false);
31227
31228   /* Traverse the DIE's and add sibling attributes to those DIE's that
31229      have children.  */
31230   add_sibling_attributes (comp_unit_die ());
31231   limbo_die_node *node;
31232   for (node = cu_die_list; node; node = node->next)
31233     add_sibling_attributes (node->die);
31234   for (ctnode = comdat_type_list; ctnode != NULL; ctnode = ctnode->next)
31235     add_sibling_attributes (ctnode->root_die);
31236
31237   /* When splitting DWARF info, we put some attributes in the
31238      skeleton compile_unit DIE that remains in the .o, while
31239      most attributes go in the DWO compile_unit_die.  */
31240   if (dwarf_split_debug_info)
31241     {
31242       limbo_die_node *cu;
31243       main_comp_unit_die = gen_compile_unit_die (NULL);
31244       if (dwarf_version >= 5)
31245         main_comp_unit_die->die_tag = DW_TAG_skeleton_unit;
31246       cu = limbo_die_list;
31247       gcc_assert (cu->die == main_comp_unit_die);
31248       limbo_die_list = limbo_die_list->next;
31249       cu->next = cu_die_list;
31250       cu_die_list = cu;
31251     }
31252   else
31253     main_comp_unit_die = comp_unit_die ();
31254
31255   /* Output a terminator label for the .text section.  */
31256   switch_to_section (text_section);
31257   targetm.asm_out.internal_label (asm_out_file, TEXT_END_LABEL, 0);
31258   if (cold_text_section)
31259     {
31260       switch_to_section (cold_text_section);
31261       targetm.asm_out.internal_label (asm_out_file, COLD_END_LABEL, 0);
31262     }
31263
31264   /* We can only use the low/high_pc attributes if all of the code was
31265      in .text.  */
31266   if (!have_multiple_function_sections 
31267       || (dwarf_version < 3 && dwarf_strict))
31268     {
31269       /* Don't add if the CU has no associated code.  */
31270       if (text_section_used)
31271         add_AT_low_high_pc (main_comp_unit_die, text_section_label,
31272                             text_end_label, true);
31273     }
31274   else
31275     {
31276       unsigned fde_idx;
31277       dw_fde_ref fde;
31278       bool range_list_added = false;
31279
31280       if (text_section_used)
31281         add_ranges_by_labels (main_comp_unit_die, text_section_label,
31282                               text_end_label, &range_list_added, true);
31283       if (cold_text_section_used)
31284         add_ranges_by_labels (main_comp_unit_die, cold_text_section_label,
31285                               cold_end_label, &range_list_added, true);
31286
31287       FOR_EACH_VEC_ELT (*fde_vec, fde_idx, fde)
31288         {
31289           if (DECL_IGNORED_P (fde->decl))
31290             continue;
31291           if (!fde->in_std_section)
31292             add_ranges_by_labels (main_comp_unit_die, fde->dw_fde_begin,
31293                                   fde->dw_fde_end, &range_list_added,
31294                                   true);
31295           if (fde->dw_fde_second_begin && !fde->second_in_std_section)
31296             add_ranges_by_labels (main_comp_unit_die, fde->dw_fde_second_begin,
31297                                   fde->dw_fde_second_end, &range_list_added,
31298                                   true);
31299         }
31300
31301       if (range_list_added)
31302         {
31303           /* We need to give .debug_loc and .debug_ranges an appropriate
31304              "base address".  Use zero so that these addresses become
31305              absolute.  Historically, we've emitted the unexpected
31306              DW_AT_entry_pc instead of DW_AT_low_pc for this purpose.
31307              Emit both to give time for other tools to adapt.  */
31308           add_AT_addr (main_comp_unit_die, DW_AT_low_pc, const0_rtx, true);
31309           if (! dwarf_strict && dwarf_version < 4)
31310             add_AT_addr (main_comp_unit_die, DW_AT_entry_pc, const0_rtx, true);
31311
31312           add_ranges (NULL);
31313         }
31314     }
31315
31316   /* AIX Assembler inserts the length, so adjust the reference to match the
31317      offset expected by debuggers.  */
31318   strcpy (dl_section_ref, debug_line_section_label);
31319   if (XCOFF_DEBUGGING_INFO)
31320     strcat (dl_section_ref, DWARF_INITIAL_LENGTH_SIZE_STR);
31321
31322   if (debug_info_level >= DINFO_LEVEL_TERSE)
31323     add_AT_lineptr (main_comp_unit_die, DW_AT_stmt_list,
31324                     dl_section_ref);
31325
31326   if (have_macinfo)
31327     add_AT_macptr (comp_unit_die (), DEBUG_MACRO_ATTRIBUTE,
31328                    macinfo_section_label);
31329
31330   if (dwarf_split_debug_info)
31331     {
31332       if (have_location_lists)
31333         {
31334           if (dwarf_version >= 5)
31335             add_AT_loclistsptr (comp_unit_die (), DW_AT_loclists_base,
31336                                 loc_section_label);
31337           /* optimize_location_lists calculates the size of the lists,
31338              so index them first, and assign indices to the entries.
31339              Although optimize_location_lists will remove entries from
31340              the table, it only does so for duplicates, and therefore
31341              only reduces ref_counts to 1.  */
31342           index_location_lists (comp_unit_die ());
31343         }
31344
31345       if (addr_index_table != NULL)
31346         {
31347           unsigned int index = 0;
31348           addr_index_table
31349             ->traverse_noresize<unsigned int *, index_addr_table_entry>
31350             (&index);
31351         }
31352     }
31353
31354   loc_list_idx = 0;
31355   if (have_location_lists)
31356     {
31357       optimize_location_lists (comp_unit_die ());
31358       /* And finally assign indexes to the entries for -gsplit-dwarf.  */
31359       if (dwarf_version >= 5 && dwarf_split_debug_info)
31360         assign_location_list_indexes (comp_unit_die ());
31361     }
31362
31363   save_macinfo_strings ();
31364
31365   if (dwarf_split_debug_info)
31366     {
31367       unsigned int index = 0;
31368
31369       /* Add attributes common to skeleton compile_units and
31370          type_units.  Because these attributes include strings, it
31371          must be done before freezing the string table.  Top-level
31372          skeleton die attrs are added when the skeleton type unit is
31373          created, so ensure it is created by this point.  */
31374       add_top_level_skeleton_die_attrs (main_comp_unit_die);
31375       debug_str_hash->traverse_noresize<unsigned int *, index_string> (&index);
31376     }
31377
31378   /* Output all of the compilation units.  We put the main one last so that
31379      the offsets are available to output_pubnames.  */
31380   for (node = cu_die_list; node; node = node->next)
31381     output_comp_unit (node->die, 0, NULL);
31382
31383   hash_table<comdat_type_hasher> comdat_type_table (100);
31384   for (ctnode = comdat_type_list; ctnode != NULL; ctnode = ctnode->next)
31385     {
31386       comdat_type_node **slot = comdat_type_table.find_slot (ctnode, INSERT);
31387
31388       /* Don't output duplicate types.  */
31389       if (*slot != HTAB_EMPTY_ENTRY)
31390         continue;
31391
31392       /* Add a pointer to the line table for the main compilation unit
31393          so that the debugger can make sense of DW_AT_decl_file
31394          attributes.  */
31395       if (debug_info_level >= DINFO_LEVEL_TERSE)
31396         add_AT_lineptr (ctnode->root_die, DW_AT_stmt_list,
31397                         (!dwarf_split_debug_info
31398                          ? dl_section_ref
31399                          : debug_skeleton_line_section_label));
31400
31401       output_comdat_type_unit (ctnode);
31402       *slot = ctnode;
31403     }
31404
31405   if (dwarf_split_debug_info)
31406     {
31407       int mark;
31408       struct md5_ctx ctx;
31409
31410       if (dwarf_version >= 5 && !vec_safe_is_empty (ranges_table))
31411         index_rnglists ();
31412
31413       /* Compute a checksum of the comp_unit to use as the dwo_id.  */
31414       md5_init_ctx (&ctx);
31415       mark = 0;
31416       die_checksum (comp_unit_die (), &ctx, &mark);
31417       unmark_all_dies (comp_unit_die ());
31418       md5_finish_ctx (&ctx, checksum);
31419
31420       if (dwarf_version < 5)
31421         {
31422           /* Use the first 8 bytes of the checksum as the dwo_id,
31423              and add it to both comp-unit DIEs.  */
31424           add_AT_data8 (main_comp_unit_die, DW_AT_GNU_dwo_id, checksum);
31425           add_AT_data8 (comp_unit_die (), DW_AT_GNU_dwo_id, checksum);
31426         }
31427
31428       /* Add the base offset of the ranges table to the skeleton
31429         comp-unit DIE.  */
31430       if (!vec_safe_is_empty (ranges_table))
31431         {
31432           if (dwarf_version >= 5)
31433             add_AT_lineptr (main_comp_unit_die, DW_AT_rnglists_base,
31434                             ranges_base_label);
31435           else
31436             add_AT_lineptr (main_comp_unit_die, DW_AT_GNU_ranges_base,
31437                             ranges_section_label);
31438         }
31439
31440       switch_to_section (debug_addr_section);
31441       ASM_OUTPUT_LABEL (asm_out_file, debug_addr_section_label);
31442       output_addr_table ();
31443     }
31444
31445   /* Output the main compilation unit if non-empty or if .debug_macinfo
31446      or .debug_macro will be emitted.  */
31447   output_comp_unit (comp_unit_die (), have_macinfo,
31448                     dwarf_split_debug_info ? checksum : NULL);
31449
31450   if (dwarf_split_debug_info && info_section_emitted)
31451     output_skeleton_debug_sections (main_comp_unit_die, checksum);
31452
31453   /* Output the abbreviation table.  */
31454   if (vec_safe_length (abbrev_die_table) != 1)
31455     {
31456       switch_to_section (debug_abbrev_section);
31457       ASM_OUTPUT_LABEL (asm_out_file, abbrev_section_label);
31458       output_abbrev_section ();
31459     }
31460
31461   /* Output location list section if necessary.  */
31462   if (have_location_lists)
31463     {
31464       char l1[MAX_ARTIFICIAL_LABEL_BYTES];
31465       char l2[MAX_ARTIFICIAL_LABEL_BYTES];
31466       /* Output the location lists info.  */
31467       switch_to_section (debug_loc_section);
31468       if (dwarf_version >= 5)
31469         {
31470           ASM_GENERATE_INTERNAL_LABEL (l1, DEBUG_LOC_SECTION_LABEL, 2);
31471           ASM_GENERATE_INTERNAL_LABEL (l2, DEBUG_LOC_SECTION_LABEL, 3);
31472           if (DWARF_INITIAL_LENGTH_SIZE - DWARF_OFFSET_SIZE == 4)
31473             dw2_asm_output_data (4, 0xffffffff,
31474                                  "Initial length escape value indicating "
31475                                  "64-bit DWARF extension");
31476           dw2_asm_output_delta (DWARF_OFFSET_SIZE, l2, l1,
31477                             "Length of Location Lists");
31478           ASM_OUTPUT_LABEL (asm_out_file, l1);
31479           output_dwarf_version ();
31480           dw2_asm_output_data (1, DWARF2_ADDR_SIZE, "Address Size");
31481           dw2_asm_output_data (1, 0, "Segment Size");
31482           dw2_asm_output_data (4, dwarf_split_debug_info ? loc_list_idx : 0,
31483                                "Offset Entry Count");
31484         }
31485       ASM_OUTPUT_LABEL (asm_out_file, loc_section_label);
31486       if (dwarf_version >= 5 && dwarf_split_debug_info)
31487         {
31488           unsigned int save_loc_list_idx = loc_list_idx;
31489           loc_list_idx = 0;
31490           output_loclists_offsets (comp_unit_die ());
31491           gcc_assert (save_loc_list_idx == loc_list_idx);
31492         }
31493       output_location_lists (comp_unit_die ());
31494       if (dwarf_version >= 5)
31495         ASM_OUTPUT_LABEL (asm_out_file, l2);
31496     }
31497
31498   output_pubtables ();
31499
31500   /* Output the address range information if a CU (.debug_info section)
31501      was emitted.  We output an empty table even if we had no functions
31502      to put in it.  This because the consumer has no way to tell the
31503      difference between an empty table that we omitted and failure to
31504      generate a table that would have contained data.  */
31505   if (info_section_emitted)
31506     {
31507       switch_to_section (debug_aranges_section);
31508       output_aranges ();
31509     }
31510
31511   /* Output ranges section if necessary.  */
31512   if (!vec_safe_is_empty (ranges_table))
31513     {
31514       if (dwarf_version >= 5)
31515         output_rnglists (generation);
31516       else
31517         output_ranges ();
31518     }
31519
31520   /* Have to end the macro section.  */
31521   if (have_macinfo)
31522     {
31523       switch_to_section (debug_macinfo_section);
31524       ASM_OUTPUT_LABEL (asm_out_file, macinfo_section_label);
31525       output_macinfo (!dwarf_split_debug_info ? debug_line_section_label
31526                       : debug_skeleton_line_section_label, false);
31527       dw2_asm_output_data (1, 0, "End compilation unit");
31528     }
31529
31530   /* Output the source line correspondence table.  We must do this
31531      even if there is no line information.  Otherwise, on an empty
31532      translation unit, we will generate a present, but empty,
31533      .debug_info section.  IRIX 6.5 `nm' will then complain when
31534      examining the file.  This is done late so that any filenames
31535      used by the debug_info section are marked as 'used'.  */
31536   switch_to_section (debug_line_section);
31537   ASM_OUTPUT_LABEL (asm_out_file, debug_line_section_label);
31538   if (! output_asm_line_debug_info ())
31539     output_line_info (false);
31540
31541   if (dwarf_split_debug_info && info_section_emitted)
31542     {
31543       switch_to_section (debug_skeleton_line_section);
31544       ASM_OUTPUT_LABEL (asm_out_file, debug_skeleton_line_section_label);
31545       output_line_info (true);
31546     }
31547
31548   /* If we emitted any indirect strings, output the string table too.  */
31549   if (debug_str_hash || skeleton_debug_str_hash)
31550     output_indirect_strings ();
31551   if (debug_line_str_hash)
31552     {
31553       switch_to_section (debug_line_str_section);
31554       const enum dwarf_form form = DW_FORM_line_strp;
31555       debug_line_str_hash->traverse<enum dwarf_form,
31556                                     output_indirect_string> (form);
31557     }
31558
31559   /* ??? Move lvugid out of dwarf2out_source_line and reset it too?  */
31560   symview_upper_bound = 0;
31561   if (zero_view_p)
31562     bitmap_clear (zero_view_p);
31563 }
31564
31565 /* Returns a hash value for X (which really is a variable_value_struct).  */
31566
31567 inline hashval_t
31568 variable_value_hasher::hash (variable_value_struct *x)
31569 {
31570   return (hashval_t) x->decl_id;
31571 }
31572
31573 /* Return nonzero if decl_id of variable_value_struct X is the same as
31574    UID of decl Y.  */
31575
31576 inline bool
31577 variable_value_hasher::equal (variable_value_struct *x, tree y)
31578 {
31579   return x->decl_id == DECL_UID (y);
31580 }
31581
31582 /* Helper function for resolve_variable_value, handle
31583    DW_OP_GNU_variable_value in one location expression.
31584    Return true if exprloc has been changed into loclist.  */
31585
31586 static bool
31587 resolve_variable_value_in_expr (dw_attr_node *a, dw_loc_descr_ref loc)
31588 {
31589   dw_loc_descr_ref next;
31590   for (dw_loc_descr_ref prev = NULL; loc; prev = loc, loc = next)
31591     {
31592       next = loc->dw_loc_next;
31593       if (loc->dw_loc_opc != DW_OP_GNU_variable_value
31594           || loc->dw_loc_oprnd1.val_class != dw_val_class_decl_ref)
31595         continue;
31596
31597       tree decl = loc->dw_loc_oprnd1.v.val_decl_ref;
31598       if (DECL_CONTEXT (decl) != current_function_decl)
31599         continue;
31600
31601       dw_die_ref ref = lookup_decl_die (decl);
31602       if (ref)
31603         {
31604           loc->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
31605           loc->dw_loc_oprnd1.v.val_die_ref.die = ref;
31606           loc->dw_loc_oprnd1.v.val_die_ref.external = 0;
31607           continue;
31608         }
31609       dw_loc_list_ref l = loc_list_from_tree (decl, 0, NULL);
31610       if (l == NULL)
31611         continue;
31612       if (l->dw_loc_next)
31613         {
31614           if (AT_class (a) != dw_val_class_loc)
31615             continue;
31616           switch (a->dw_attr)
31617             {
31618             /* Following attributes allow both exprloc and loclist
31619                classes, so we can change them into a loclist.  */
31620             case DW_AT_location:
31621             case DW_AT_string_length:
31622             case DW_AT_return_addr:
31623             case DW_AT_data_member_location:
31624             case DW_AT_frame_base:
31625             case DW_AT_segment:
31626             case DW_AT_static_link:
31627             case DW_AT_use_location:
31628             case DW_AT_vtable_elem_location:
31629               if (prev)
31630                 {
31631                   prev->dw_loc_next = NULL;
31632                   prepend_loc_descr_to_each (l, AT_loc (a));
31633                 }
31634               if (next)
31635                 add_loc_descr_to_each (l, next);
31636               a->dw_attr_val.val_class = dw_val_class_loc_list;
31637               a->dw_attr_val.val_entry = NULL;
31638               a->dw_attr_val.v.val_loc_list = l;
31639               have_location_lists = true;
31640               return true;
31641             /* Following attributes allow both exprloc and reference,
31642                so if the whole expression is DW_OP_GNU_variable_value alone
31643                we could transform it into reference.  */
31644             case DW_AT_byte_size:
31645             case DW_AT_bit_size:
31646             case DW_AT_lower_bound:
31647             case DW_AT_upper_bound:
31648             case DW_AT_bit_stride:
31649             case DW_AT_count:
31650             case DW_AT_allocated:
31651             case DW_AT_associated:
31652             case DW_AT_byte_stride:
31653               if (prev == NULL && next == NULL)
31654                 break;
31655               /* FALLTHRU */
31656             default:
31657               if (dwarf_strict)
31658                 continue;
31659               break;
31660             }
31661           /* Create DW_TAG_variable that we can refer to.  */
31662           gen_decl_die (decl, NULL_TREE, NULL,
31663                         lookup_decl_die (current_function_decl));
31664           ref = lookup_decl_die (decl);
31665           if (ref)
31666             {
31667               loc->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
31668               loc->dw_loc_oprnd1.v.val_die_ref.die = ref;
31669               loc->dw_loc_oprnd1.v.val_die_ref.external = 0;
31670             }
31671           continue;
31672         }
31673       if (prev)
31674         {
31675           prev->dw_loc_next = l->expr;
31676           add_loc_descr (&prev->dw_loc_next, next);
31677           free_loc_descr (loc, NULL);
31678           next = prev->dw_loc_next;
31679         }
31680       else
31681         {
31682           memcpy (loc, l->expr, sizeof (dw_loc_descr_node));
31683           add_loc_descr (&loc, next);
31684           next = loc;
31685         }
31686       loc = prev;
31687     }
31688   return false;
31689 }
31690
31691 /* Attempt to resolve DW_OP_GNU_variable_value using loc_list_from_tree.  */
31692
31693 static void
31694 resolve_variable_value (dw_die_ref die)
31695 {
31696   dw_attr_node *a;
31697   dw_loc_list_ref loc;
31698   unsigned ix;
31699
31700   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
31701     switch (AT_class (a))
31702       {
31703       case dw_val_class_loc:
31704         if (!resolve_variable_value_in_expr (a, AT_loc (a)))
31705           break;
31706         /* FALLTHRU */
31707       case dw_val_class_loc_list:
31708         loc = AT_loc_list (a);
31709         gcc_assert (loc);
31710         for (; loc; loc = loc->dw_loc_next)
31711           resolve_variable_value_in_expr (a, loc->expr);
31712         break;
31713       default:
31714         break;
31715       }
31716 }
31717
31718 /* Attempt to optimize DW_OP_GNU_variable_value refering to
31719    temporaries in the current function.  */
31720
31721 static void
31722 resolve_variable_values (void)
31723 {
31724   if (!variable_value_hash || !current_function_decl)
31725     return;
31726
31727   struct variable_value_struct *node
31728     = variable_value_hash->find_with_hash (current_function_decl,
31729                                            DECL_UID (current_function_decl));
31730
31731   if (node == NULL)
31732     return;
31733
31734   unsigned int i;
31735   dw_die_ref die;
31736   FOR_EACH_VEC_SAFE_ELT (node->dies, i, die)
31737     resolve_variable_value (die);
31738 }
31739
31740 /* Helper function for note_variable_value, handle one location
31741    expression.  */
31742
31743 static void
31744 note_variable_value_in_expr (dw_die_ref die, dw_loc_descr_ref loc)
31745 {
31746   for (; loc; loc = loc->dw_loc_next)
31747     if (loc->dw_loc_opc == DW_OP_GNU_variable_value
31748         && loc->dw_loc_oprnd1.val_class == dw_val_class_decl_ref)
31749       {
31750         tree decl = loc->dw_loc_oprnd1.v.val_decl_ref;
31751         dw_die_ref ref = lookup_decl_die (decl);
31752         if (! ref && (flag_generate_lto || flag_generate_offload))
31753           {
31754             /* ???  This is somewhat a hack because we do not create DIEs
31755                for variables not in BLOCK trees early but when generating
31756                early LTO output we need the dw_val_class_decl_ref to be
31757                fully resolved.  For fat LTO objects we'd also like to
31758                undo this after LTO dwarf output.  */
31759             gcc_assert (DECL_CONTEXT (decl));
31760             dw_die_ref ctx = lookup_decl_die (DECL_CONTEXT (decl));
31761             gcc_assert (ctx != NULL);
31762             gen_decl_die (decl, NULL_TREE, NULL, ctx);
31763             ref = lookup_decl_die (decl);
31764             gcc_assert (ref != NULL);
31765           }
31766         if (ref)
31767           {
31768             loc->dw_loc_oprnd1.val_class = dw_val_class_die_ref;
31769             loc->dw_loc_oprnd1.v.val_die_ref.die = ref;
31770             loc->dw_loc_oprnd1.v.val_die_ref.external = 0;
31771             continue;
31772           }
31773         if (VAR_P (decl)
31774             && DECL_CONTEXT (decl)
31775             && TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL
31776             && lookup_decl_die (DECL_CONTEXT (decl)))
31777           {
31778             if (!variable_value_hash)
31779               variable_value_hash
31780                 = hash_table<variable_value_hasher>::create_ggc (10);
31781
31782             tree fndecl = DECL_CONTEXT (decl);
31783             struct variable_value_struct *node;
31784             struct variable_value_struct **slot
31785               = variable_value_hash->find_slot_with_hash (fndecl,
31786                                                           DECL_UID (fndecl),
31787                                                           INSERT);
31788             if (*slot == NULL)
31789               {
31790                 node = ggc_cleared_alloc<variable_value_struct> ();
31791                 node->decl_id = DECL_UID (fndecl);
31792                 *slot = node;
31793               }
31794             else
31795               node = *slot;
31796
31797             vec_safe_push (node->dies, die);
31798           }
31799       }
31800 }
31801
31802 /* Walk the tree DIE and note DIEs with DW_OP_GNU_variable_value still
31803    with dw_val_class_decl_ref operand.  */
31804
31805 static void
31806 note_variable_value (dw_die_ref die)
31807 {
31808   dw_die_ref c;
31809   dw_attr_node *a;
31810   dw_loc_list_ref loc;
31811   unsigned ix;
31812
31813   FOR_EACH_VEC_SAFE_ELT (die->die_attr, ix, a)
31814     switch (AT_class (a))
31815       {
31816       case dw_val_class_loc_list:
31817         loc = AT_loc_list (a);
31818         gcc_assert (loc);
31819         if (!loc->noted_variable_value)
31820           {
31821             loc->noted_variable_value = 1;
31822             for (; loc; loc = loc->dw_loc_next)
31823               note_variable_value_in_expr (die, loc->expr);
31824           }
31825         break;
31826       case dw_val_class_loc:
31827         note_variable_value_in_expr (die, AT_loc (a));
31828         break;
31829       default:
31830         break;
31831       }
31832
31833   /* Mark children.  */
31834   FOR_EACH_CHILD (die, c, note_variable_value (c));
31835 }
31836
31837 /* Perform any cleanups needed after the early debug generation pass
31838    has run.  */
31839
31840 static void
31841 dwarf2out_early_finish (const char *filename)
31842 {
31843   set_early_dwarf s;
31844   char dl_section_ref[MAX_ARTIFICIAL_LABEL_BYTES];
31845
31846   /* PCH might result in DW_AT_producer string being restored from the
31847      header compilation, so always fill it with empty string initially
31848      and overwrite only here.  */
31849   dw_attr_node *producer = get_AT (comp_unit_die (), DW_AT_producer);
31850   producer_string = gen_producer_string ();
31851   producer->dw_attr_val.v.val_str->refcount--;
31852   producer->dw_attr_val.v.val_str = find_AT_string (producer_string);
31853
31854   /* Add the name for the main input file now.  We delayed this from
31855      dwarf2out_init to avoid complications with PCH.  */
31856   add_name_attribute (comp_unit_die (), remap_debug_filename (filename));
31857   add_comp_dir_attribute (comp_unit_die ());
31858
31859   /* When emitting DWARF5 .debug_line_str, move DW_AT_name and
31860      DW_AT_comp_dir into .debug_line_str section.  */
31861   if (!output_asm_line_debug_info ()
31862       && dwarf_version >= 5
31863       && DWARF5_USE_DEBUG_LINE_STR)
31864     {
31865       for (int i = 0; i < 2; i++)
31866         {
31867           dw_attr_node *a = get_AT (comp_unit_die (),
31868                                     i ? DW_AT_comp_dir : DW_AT_name);
31869           if (a == NULL
31870               || AT_class (a) != dw_val_class_str
31871               || strlen (AT_string (a)) + 1 <= DWARF_OFFSET_SIZE)
31872             continue;
31873
31874           if (! debug_line_str_hash)
31875             debug_line_str_hash
31876               = hash_table<indirect_string_hasher>::create_ggc (10);
31877
31878           struct indirect_string_node *node
31879             = find_AT_string_in_table (AT_string (a), debug_line_str_hash);
31880           set_indirect_string (node);
31881           node->form = DW_FORM_line_strp;
31882           a->dw_attr_val.v.val_str->refcount--;
31883           a->dw_attr_val.v.val_str = node;
31884         }
31885     }
31886
31887   /* With LTO early dwarf was really finished at compile-time, so make
31888      sure to adjust the phase after annotating the LTRANS CU DIE.  */
31889   if (in_lto_p)
31890     {
31891       early_dwarf_finished = true;
31892       return;
31893     }
31894
31895   /* Walk through the list of incomplete types again, trying once more to
31896      emit full debugging info for them.  */
31897   retry_incomplete_types ();
31898
31899   /* The point here is to flush out the limbo list so that it is empty
31900      and we don't need to stream it for LTO.  */
31901   flush_limbo_die_list ();
31902
31903   gen_scheduled_generic_parms_dies ();
31904   gen_remaining_tmpl_value_param_die_attribute ();
31905
31906   /* Add DW_AT_linkage_name for all deferred DIEs.  */
31907   for (limbo_die_node *node = deferred_asm_name; node; node = node->next)
31908     {
31909       tree decl = node->created_for;
31910       if (DECL_ASSEMBLER_NAME (decl) != DECL_NAME (decl)
31911           /* A missing DECL_ASSEMBLER_NAME can be a constant DIE that
31912              ended up in deferred_asm_name before we knew it was
31913              constant and never written to disk.  */
31914           && DECL_ASSEMBLER_NAME (decl))
31915         {
31916           add_linkage_attr (node->die, decl);
31917           move_linkage_attr (node->die);
31918         }
31919     }
31920   deferred_asm_name = NULL;
31921
31922   if (flag_eliminate_unused_debug_types)
31923     prune_unused_types ();
31924
31925   /* Generate separate COMDAT sections for type DIEs. */
31926   if (use_debug_types)
31927     {
31928       break_out_comdat_types (comp_unit_die ());
31929
31930       /* Each new type_unit DIE was added to the limbo die list when created.
31931          Since these have all been added to comdat_type_list, clear the
31932          limbo die list.  */
31933       limbo_die_list = NULL;
31934
31935       /* For each new comdat type unit, copy declarations for incomplete
31936          types to make the new unit self-contained (i.e., no direct
31937          references to the main compile unit).  */
31938       for (comdat_type_node *ctnode = comdat_type_list;
31939            ctnode != NULL; ctnode = ctnode->next)
31940         copy_decls_for_unworthy_types (ctnode->root_die);
31941       copy_decls_for_unworthy_types (comp_unit_die ());
31942
31943       /* In the process of copying declarations from one unit to another,
31944          we may have left some declarations behind that are no longer
31945          referenced.  Prune them.  */
31946       prune_unused_types ();
31947     }
31948
31949   /* Traverse the DIE's and note DIEs with DW_OP_GNU_variable_value still
31950      with dw_val_class_decl_ref operand.  */
31951   note_variable_value (comp_unit_die ());
31952   for (limbo_die_node *node = cu_die_list; node; node = node->next)
31953     note_variable_value (node->die);
31954   for (comdat_type_node *ctnode = comdat_type_list; ctnode != NULL;
31955        ctnode = ctnode->next)
31956     note_variable_value (ctnode->root_die);
31957   for (limbo_die_node *node = limbo_die_list; node; node = node->next)
31958     note_variable_value (node->die);
31959
31960   /* The AT_pubnames attribute needs to go in all skeleton dies, including
31961      both the main_cu and all skeleton TUs.  Making this call unconditional
31962      would end up either adding a second copy of the AT_pubnames attribute, or
31963      requiring a special case in add_top_level_skeleton_die_attrs.  */
31964   if (!dwarf_split_debug_info)
31965     add_AT_pubnames (comp_unit_die ());
31966
31967   /* The early debug phase is now finished.  */
31968   early_dwarf_finished = true;
31969
31970   /* Do not generate DWARF assembler now when not producing LTO bytecode.  */
31971   if ((!flag_generate_lto && !flag_generate_offload)
31972       /* FIXME: Disable debug info generation for (PE-)COFF targets since the
31973          copy_lto_debug_sections operation of the simple object support in
31974          libiberty is not implemented for them yet.  */
31975       || TARGET_PECOFF || TARGET_COFF)
31976     return;
31977
31978   /* Now as we are going to output for LTO initialize sections and labels
31979      to the LTO variants.  We don't need a random-seed postfix as other
31980      LTO sections as linking the LTO debug sections into one in a partial
31981      link is fine.  */
31982   init_sections_and_labels (true);
31983
31984   /* The output below is modeled after dwarf2out_finish with all
31985      location related output removed and some LTO specific changes.
31986      Some refactoring might make both smaller and easier to match up.  */
31987
31988   /* Traverse the DIE's and add add sibling attributes to those DIE's
31989      that have children.  */
31990   add_sibling_attributes (comp_unit_die ());
31991   for (limbo_die_node *node = limbo_die_list; node; node = node->next)
31992     add_sibling_attributes (node->die);
31993   for (comdat_type_node *ctnode = comdat_type_list;
31994        ctnode != NULL; ctnode = ctnode->next)
31995     add_sibling_attributes (ctnode->root_die);
31996
31997   /* AIX Assembler inserts the length, so adjust the reference to match the
31998      offset expected by debuggers.  */
31999   strcpy (dl_section_ref, debug_line_section_label);
32000   if (XCOFF_DEBUGGING_INFO)
32001     strcat (dl_section_ref, DWARF_INITIAL_LENGTH_SIZE_STR);
32002
32003   if (debug_info_level >= DINFO_LEVEL_TERSE)
32004     add_AT_lineptr (comp_unit_die (), DW_AT_stmt_list, dl_section_ref);
32005
32006   if (have_macinfo)
32007     add_AT_macptr (comp_unit_die (), DEBUG_MACRO_ATTRIBUTE,
32008                    macinfo_section_label);
32009
32010   save_macinfo_strings ();
32011
32012   if (dwarf_split_debug_info)
32013     {
32014       unsigned int index = 0;
32015       debug_str_hash->traverse_noresize<unsigned int *, index_string> (&index);
32016     }
32017
32018   /* Output all of the compilation units.  We put the main one last so that
32019      the offsets are available to output_pubnames.  */
32020   for (limbo_die_node *node = limbo_die_list; node; node = node->next)
32021     output_comp_unit (node->die, 0, NULL);
32022
32023   hash_table<comdat_type_hasher> comdat_type_table (100);
32024   for (comdat_type_node *ctnode = comdat_type_list;
32025        ctnode != NULL; ctnode = ctnode->next)
32026     {
32027       comdat_type_node **slot = comdat_type_table.find_slot (ctnode, INSERT);
32028
32029       /* Don't output duplicate types.  */
32030       if (*slot != HTAB_EMPTY_ENTRY)
32031         continue;
32032
32033       /* Add a pointer to the line table for the main compilation unit
32034          so that the debugger can make sense of DW_AT_decl_file
32035          attributes.  */
32036       if (debug_info_level >= DINFO_LEVEL_TERSE)
32037         add_AT_lineptr (ctnode->root_die, DW_AT_stmt_list,
32038                         (!dwarf_split_debug_info
32039                          ? debug_line_section_label
32040                          : debug_skeleton_line_section_label));
32041
32042       output_comdat_type_unit (ctnode);
32043       *slot = ctnode;
32044     }
32045
32046   /* Stick a unique symbol to the main debuginfo section.  */
32047   compute_comp_unit_symbol (comp_unit_die ());
32048
32049   /* Output the main compilation unit.  We always need it if only for
32050      the CU symbol.  */
32051   output_comp_unit (comp_unit_die (), true, NULL);
32052
32053   /* Output the abbreviation table.  */
32054   if (vec_safe_length (abbrev_die_table) != 1)
32055     {
32056       switch_to_section (debug_abbrev_section);
32057       ASM_OUTPUT_LABEL (asm_out_file, abbrev_section_label);
32058       output_abbrev_section ();
32059     }
32060
32061   /* Have to end the macro section.  */
32062   if (have_macinfo)
32063     {
32064       /* We have to save macinfo state if we need to output it again
32065          for the FAT part of the object.  */
32066       vec<macinfo_entry, va_gc> *saved_macinfo_table = macinfo_table;
32067       if (flag_fat_lto_objects)
32068         macinfo_table = macinfo_table->copy ();
32069
32070       switch_to_section (debug_macinfo_section);
32071       ASM_OUTPUT_LABEL (asm_out_file, macinfo_section_label);
32072       output_macinfo (debug_line_section_label, true);
32073       dw2_asm_output_data (1, 0, "End compilation unit");
32074
32075       if (flag_fat_lto_objects)
32076         {
32077           vec_free (macinfo_table);
32078           macinfo_table = saved_macinfo_table;
32079         }
32080     }
32081
32082   /* Emit a skeleton debug_line section.  */
32083   switch_to_section (debug_line_section);
32084   ASM_OUTPUT_LABEL (asm_out_file, debug_line_section_label);
32085   output_line_info (true);
32086
32087   /* If we emitted any indirect strings, output the string table too.  */
32088   if (debug_str_hash || skeleton_debug_str_hash)
32089     output_indirect_strings ();
32090   if (debug_line_str_hash)
32091     {
32092       switch_to_section (debug_line_str_section);
32093       const enum dwarf_form form = DW_FORM_line_strp;
32094       debug_line_str_hash->traverse<enum dwarf_form,
32095                                     output_indirect_string> (form);
32096     }
32097
32098   /* Switch back to the text section.  */
32099   switch_to_section (text_section);
32100 }
32101
32102 /* Reset all state within dwarf2out.c so that we can rerun the compiler
32103    within the same process.  For use by toplev::finalize.  */
32104
32105 void
32106 dwarf2out_c_finalize (void)
32107 {
32108   last_var_location_insn = NULL;
32109   cached_next_real_insn = NULL;
32110   used_rtx_array = NULL;
32111   incomplete_types = NULL;
32112   decl_scope_table = NULL;
32113   debug_info_section = NULL;
32114   debug_skeleton_info_section = NULL;
32115   debug_abbrev_section = NULL;
32116   debug_skeleton_abbrev_section = NULL;
32117   debug_aranges_section = NULL;
32118   debug_addr_section = NULL;
32119   debug_macinfo_section = NULL;
32120   debug_line_section = NULL;
32121   debug_skeleton_line_section = NULL;
32122   debug_loc_section = NULL;
32123   debug_pubnames_section = NULL;
32124   debug_pubtypes_section = NULL;
32125   debug_str_section = NULL;
32126   debug_line_str_section = NULL;
32127   debug_str_dwo_section = NULL;
32128   debug_str_offsets_section = NULL;
32129   debug_ranges_section = NULL;
32130   debug_frame_section = NULL;
32131   fde_vec = NULL;
32132   debug_str_hash = NULL;
32133   debug_line_str_hash = NULL;
32134   skeleton_debug_str_hash = NULL;
32135   dw2_string_counter = 0;
32136   have_multiple_function_sections = false;
32137   text_section_used = false;
32138   cold_text_section_used = false;
32139   cold_text_section = NULL;
32140   current_unit_personality = NULL;
32141
32142   early_dwarf = false;
32143   early_dwarf_finished = false;
32144
32145   next_die_offset = 0;
32146   single_comp_unit_die = NULL;
32147   comdat_type_list = NULL;
32148   limbo_die_list = NULL;
32149   file_table = NULL;
32150   decl_die_table = NULL;
32151   common_block_die_table = NULL;
32152   decl_loc_table = NULL;
32153   call_arg_locations = NULL;
32154   call_arg_loc_last = NULL;
32155   call_site_count = -1;
32156   tail_call_site_count = -1;
32157   cached_dw_loc_list_table = NULL;
32158   abbrev_die_table = NULL;
32159   delete dwarf_proc_stack_usage_map;
32160   dwarf_proc_stack_usage_map = NULL;
32161   line_info_label_num = 0;
32162   cur_line_info_table = NULL;
32163   text_section_line_info = NULL;
32164   cold_text_section_line_info = NULL;
32165   separate_line_info = NULL;
32166   info_section_emitted = false;
32167   pubname_table = NULL;
32168   pubtype_table = NULL;
32169   macinfo_table = NULL;
32170   ranges_table = NULL;
32171   ranges_by_label = NULL;
32172   rnglist_idx = 0;
32173   have_location_lists = false;
32174   loclabel_num = 0;
32175   poc_label_num = 0;
32176   last_emitted_file = NULL;
32177   label_num = 0;
32178   tmpl_value_parm_die_table = NULL;
32179   generic_type_instances = NULL;
32180   frame_pointer_fb_offset = 0;
32181   frame_pointer_fb_offset_valid = false;
32182   base_types.release ();
32183   XDELETEVEC (producer_string);
32184   producer_string = NULL;
32185 }
32186
32187 #include "gt-dwarf2out.h"