Port c++/78252 from GCC
[external/binutils.git] / libiberty / cp-demangle.c
1 /* Demangler for g++ V3 ABI.
2    Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2014
3    Free Software Foundation, Inc.
4    Written by Ian Lance Taylor <ian@wasabisystems.com>.
5
6    This file is part of the libiberty library, which is part of GCC.
7
8    This file is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12
13    In addition to the permissions in the GNU General Public License, the
14    Free Software Foundation gives you unlimited permission to link the
15    compiled version of this file into combinations with other programs,
16    and to distribute those combinations without any restriction coming
17    from the use of this file.  (The General Public License restrictions
18    do apply in other respects; for example, they cover modification of
19    the file, and distribution when not linked into a combined
20    executable.)
21
22    This program is distributed in the hope that it will be useful,
23    but WITHOUT ANY WARRANTY; without even the implied warranty of
24    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25    GNU General Public License for more details.
26
27    You should have received a copy of the GNU General Public License
28    along with this program; if not, write to the Free Software
29    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. 
30 */
31
32 /* This code implements a demangler for the g++ V3 ABI.  The ABI is
33    described on this web page:
34        http://www.codesourcery.com/cxx-abi/abi.html#mangling
35
36    This code was written while looking at the demangler written by
37    Alex Samuel <samuel@codesourcery.com>.
38
39    This code first pulls the mangled name apart into a list of
40    components, and then walks the list generating the demangled
41    name.
42
43    This file will normally define the following functions, q.v.:
44       char *cplus_demangle_v3(const char *mangled, int options)
45       char *java_demangle_v3(const char *mangled)
46       int cplus_demangle_v3_callback(const char *mangled, int options,
47                                      demangle_callbackref callback)
48       int java_demangle_v3_callback(const char *mangled,
49                                     demangle_callbackref callback)
50       enum gnu_v3_ctor_kinds is_gnu_v3_mangled_ctor (const char *name)
51       enum gnu_v3_dtor_kinds is_gnu_v3_mangled_dtor (const char *name)
52
53    Also, the interface to the component list is public, and defined in
54    demangle.h.  The interface consists of these types, which are
55    defined in demangle.h:
56       enum demangle_component_type
57       struct demangle_component
58       demangle_callbackref
59    and these functions defined in this file:
60       cplus_demangle_fill_name
61       cplus_demangle_fill_extended_operator
62       cplus_demangle_fill_ctor
63       cplus_demangle_fill_dtor
64       cplus_demangle_print
65       cplus_demangle_print_callback
66    and other functions defined in the file cp-demint.c.
67
68    This file also defines some other functions and variables which are
69    only to be used by the file cp-demint.c.
70
71    Preprocessor macros you can define while compiling this file:
72
73    IN_LIBGCC2
74       If defined, this file defines the following functions, q.v.:
75          char *__cxa_demangle (const char *mangled, char *buf, size_t *len,
76                                int *status)
77          int __gcclibcxx_demangle_callback (const char *,
78                                             void (*)
79                                               (const char *, size_t, void *),
80                                             void *)
81       instead of cplus_demangle_v3[_callback]() and
82       java_demangle_v3[_callback]().
83
84    IN_GLIBCPP_V3
85       If defined, this file defines only __cxa_demangle() and
86       __gcclibcxx_demangle_callback(), and no other publically visible
87       functions or variables.
88
89    STANDALONE_DEMANGLER
90       If defined, this file defines a main() function which demangles
91       any arguments, or, if none, demangles stdin.
92
93    CP_DEMANGLE_DEBUG
94       If defined, turns on debugging mode, which prints information on
95       stdout about the mangled string.  This is not generally useful.
96
97    CHECK_DEMANGLER
98       If defined, additional sanity checks will be performed.  It will
99       cause some slowdown, but will allow to catch out-of-bound access
100       errors earlier.  This macro is intended for testing and debugging.  */
101
102 #if defined (_AIX) && !defined (__GNUC__)
103  #pragma alloca
104 #endif
105
106 #ifdef HAVE_CONFIG_H
107 #include "config.h"
108 #endif
109
110 #include <stdio.h>
111
112 #ifdef HAVE_STDLIB_H
113 #include <stdlib.h>
114 #endif
115 #ifdef HAVE_STRING_H
116 #include <string.h>
117 #endif
118
119 #ifdef HAVE_ALLOCA_H
120 # include <alloca.h>
121 #else
122 # ifndef alloca
123 #  ifdef __GNUC__
124 #   define alloca __builtin_alloca
125 #  else
126 extern char *alloca ();
127 #  endif /* __GNUC__ */
128 # endif /* alloca */
129 #endif /* HAVE_ALLOCA_H */
130
131 #ifdef HAVE_LIMITS_H
132 #include <limits.h>
133 #endif
134 #ifndef INT_MAX
135 # define INT_MAX       (int)(((unsigned int) ~0) >> 1)          /* 0x7FFFFFFF */ 
136 #endif
137
138 #include "ansidecl.h"
139 #include "libiberty.h"
140 #include "demangle.h"
141 #include "cp-demangle.h"
142
143 /* If IN_GLIBCPP_V3 is defined, some functions are made static.  We
144    also rename them via #define to avoid compiler errors when the
145    static definition conflicts with the extern declaration in a header
146    file.  */
147 #ifdef IN_GLIBCPP_V3
148
149 #define CP_STATIC_IF_GLIBCPP_V3 static
150
151 #define cplus_demangle_fill_name d_fill_name
152 static int d_fill_name (struct demangle_component *, const char *, int);
153
154 #define cplus_demangle_fill_extended_operator d_fill_extended_operator
155 static int
156 d_fill_extended_operator (struct demangle_component *, int,
157                           struct demangle_component *);
158
159 #define cplus_demangle_fill_ctor d_fill_ctor
160 static int
161 d_fill_ctor (struct demangle_component *, enum gnu_v3_ctor_kinds,
162              struct demangle_component *);
163
164 #define cplus_demangle_fill_dtor d_fill_dtor
165 static int
166 d_fill_dtor (struct demangle_component *, enum gnu_v3_dtor_kinds,
167              struct demangle_component *);
168
169 #define cplus_demangle_mangled_name d_mangled_name
170 static struct demangle_component *d_mangled_name (struct d_info *, int);
171
172 #define cplus_demangle_type d_type
173 static struct demangle_component *d_type (struct d_info *);
174
175 #define cplus_demangle_print d_print
176 static char *d_print (int, const struct demangle_component *, int, size_t *);
177
178 #define cplus_demangle_print_callback d_print_callback
179 static int d_print_callback (int, const struct demangle_component *,
180                              demangle_callbackref, void *);
181
182 #define cplus_demangle_init_info d_init_info
183 static void d_init_info (const char *, int, size_t, struct d_info *);
184
185 #else /* ! defined(IN_GLIBCPP_V3) */
186 #define CP_STATIC_IF_GLIBCPP_V3
187 #endif /* ! defined(IN_GLIBCPP_V3) */
188
189 /* See if the compiler supports dynamic arrays.  */
190
191 #ifdef __GNUC__
192 #define CP_DYNAMIC_ARRAYS
193 #else
194 #ifdef __STDC__
195 #ifdef __STDC_VERSION__
196 #if __STDC_VERSION__ >= 199901L
197 #define CP_DYNAMIC_ARRAYS
198 #endif /* __STDC__VERSION >= 199901L */
199 #endif /* defined (__STDC_VERSION__) */
200 #endif /* defined (__STDC__) */
201 #endif /* ! defined (__GNUC__) */
202
203 /* We avoid pulling in the ctype tables, to prevent pulling in
204    additional unresolved symbols when this code is used in a library.
205    FIXME: Is this really a valid reason?  This comes from the original
206    V3 demangler code.
207
208    As of this writing this file has the following undefined references
209    when compiled with -DIN_GLIBCPP_V3: realloc, free, memcpy, strcpy,
210    strcat, strlen.  */
211
212 #define IS_DIGIT(c) ((c) >= '0' && (c) <= '9')
213 #define IS_UPPER(c) ((c) >= 'A' && (c) <= 'Z')
214 #define IS_LOWER(c) ((c) >= 'a' && (c) <= 'z')
215
216 /* The prefix prepended by GCC to an identifier represnting the
217    anonymous namespace.  */
218 #define ANONYMOUS_NAMESPACE_PREFIX "_GLOBAL_"
219 #define ANONYMOUS_NAMESPACE_PREFIX_LEN \
220   (sizeof (ANONYMOUS_NAMESPACE_PREFIX) - 1)
221
222 /* Information we keep for the standard substitutions.  */
223
224 struct d_standard_sub_info
225 {
226   /* The code for this substitution.  */
227   char code;
228   /* The simple string it expands to.  */
229   const char *simple_expansion;
230   /* The length of the simple expansion.  */
231   int simple_len;
232   /* The results of a full, verbose, expansion.  This is used when
233      qualifying a constructor/destructor, or when in verbose mode.  */
234   const char *full_expansion;
235   /* The length of the full expansion.  */
236   int full_len;
237   /* What to set the last_name field of d_info to; NULL if we should
238      not set it.  This is only relevant when qualifying a
239      constructor/destructor.  */
240   const char *set_last_name;
241   /* The length of set_last_name.  */
242   int set_last_name_len;
243 };
244
245 /* Accessors for subtrees of struct demangle_component.  */
246
247 #define d_left(dc) ((dc)->u.s_binary.left)
248 #define d_right(dc) ((dc)->u.s_binary.right)
249
250 /* A list of templates.  This is used while printing.  */
251
252 struct d_print_template
253 {
254   /* Next template on the list.  */
255   struct d_print_template *next;
256   /* This template.  */
257   const struct demangle_component *template_decl;
258 };
259
260 /* A list of type modifiers.  This is used while printing.  */
261
262 struct d_print_mod
263 {
264   /* Next modifier on the list.  These are in the reverse of the order
265      in which they appeared in the mangled string.  */
266   struct d_print_mod *next;
267   /* The modifier.  */
268   const struct demangle_component *mod;
269   /* Whether this modifier was printed.  */
270   int printed;
271   /* The list of templates which applies to this modifier.  */
272   struct d_print_template *templates;
273 };
274
275 /* We use these structures to hold information during printing.  */
276
277 struct d_growable_string
278 {
279   /* Buffer holding the result.  */
280   char *buf;
281   /* Current length of data in buffer.  */
282   size_t len;
283   /* Allocated size of buffer.  */
284   size_t alc;
285   /* Set to 1 if we had a memory allocation failure.  */
286   int allocation_failure;
287 };
288
289 /* Stack of components, innermost first, used to avoid loops.  */
290
291 struct d_component_stack
292 {
293   /* This component.  */
294   const struct demangle_component *dc;
295   /* This component's parent.  */
296   const struct d_component_stack *parent;
297 };
298
299 /* A demangle component and some scope captured when it was first
300    traversed.  */
301
302 struct d_saved_scope
303 {
304   /* The component whose scope this is.  */
305   const struct demangle_component *container;
306   /* The list of templates, if any, that was current when this
307      scope was captured.  */
308   struct d_print_template *templates;
309 };
310
311 /* Checkpoint structure to allow backtracking.  This holds copies
312    of the fields of struct d_info that need to be restored
313    if a trial parse needs to be backtracked over.  */
314
315 struct d_info_checkpoint
316 {
317   const char *n;
318   int next_comp;
319   int next_sub;
320   int did_subs;
321   int expansion;
322 };
323
324 enum { D_PRINT_BUFFER_LENGTH = 256 };
325 struct d_print_info
326 {
327   /* Fixed-length allocated buffer for demangled data, flushed to the
328      callback with a NUL termination once full.  */
329   char buf[D_PRINT_BUFFER_LENGTH];
330   /* Current length of data in buffer.  */
331   size_t len;
332   /* The last character printed, saved individually so that it survives
333      any buffer flush.  */
334   char last_char;
335   /* Callback function to handle demangled buffer flush.  */
336   demangle_callbackref callback;
337   /* Opaque callback argument.  */
338   void *opaque;
339   /* The current list of templates, if any.  */
340   struct d_print_template *templates;
341   /* The current list of modifiers (e.g., pointer, reference, etc.),
342      if any.  */
343   struct d_print_mod *modifiers;
344   /* Set to 1 if we saw a demangling error.  */
345   int demangle_failure;
346   /* Non-zero if we're printing a lambda argument.  A template
347      parameter reference actually means 'auto'.  */
348   int is_lambda_arg;
349   /* The current index into any template argument packs we are using
350      for printing, or -1 to print the whole pack.  */
351   int pack_index;
352   /* Number of d_print_flush calls so far.  */
353   unsigned long int flush_count;
354   /* Stack of components, innermost first, used to avoid loops.  */
355   const struct d_component_stack *component_stack;
356   /* Array of saved scopes for evaluating substitutions.  */
357   struct d_saved_scope *saved_scopes;
358   /* Index of the next unused saved scope in the above array.  */
359   int next_saved_scope;
360   /* Number of saved scopes in the above array.  */
361   int num_saved_scopes;
362   /* Array of templates for saving into scopes.  */
363   struct d_print_template *copy_templates;
364   /* Index of the next unused copy template in the above array.  */
365   int next_copy_template;
366   /* Number of copy templates in the above array.  */
367   int num_copy_templates;
368   /* The nearest enclosing template, if any.  */
369   const struct demangle_component *current_template;
370 };
371
372 #ifdef CP_DEMANGLE_DEBUG
373 static void d_dump (struct demangle_component *, int);
374 #endif
375
376 static struct demangle_component *
377 d_make_empty (struct d_info *);
378
379 static struct demangle_component *
380 d_make_comp (struct d_info *, enum demangle_component_type,
381              struct demangle_component *,
382              struct demangle_component *);
383
384 static struct demangle_component *
385 d_make_name (struct d_info *, const char *, int);
386
387 static struct demangle_component *
388 d_make_demangle_mangled_name (struct d_info *, const char *);
389
390 static struct demangle_component *
391 d_make_builtin_type (struct d_info *,
392                      const struct demangle_builtin_type_info *);
393
394 static struct demangle_component *
395 d_make_operator (struct d_info *,
396                  const struct demangle_operator_info *);
397
398 static struct demangle_component *
399 d_make_extended_operator (struct d_info *, int,
400                           struct demangle_component *);
401
402 static struct demangle_component *
403 d_make_ctor (struct d_info *, enum gnu_v3_ctor_kinds,
404              struct demangle_component *);
405
406 static struct demangle_component *
407 d_make_dtor (struct d_info *, enum gnu_v3_dtor_kinds,
408              struct demangle_component *);
409
410 static struct demangle_component *
411 d_make_template_param (struct d_info *, int);
412
413 static struct demangle_component *
414 d_make_sub (struct d_info *, const char *, int);
415
416 static int
417 has_return_type (struct demangle_component *);
418
419 static int
420 is_ctor_dtor_or_conversion (struct demangle_component *);
421
422 static struct demangle_component *d_encoding (struct d_info *, int);
423
424 static struct demangle_component *d_name (struct d_info *);
425
426 static struct demangle_component *d_nested_name (struct d_info *);
427
428 static struct demangle_component *d_prefix (struct d_info *);
429
430 static struct demangle_component *d_unqualified_name (struct d_info *);
431
432 static struct demangle_component *d_source_name (struct d_info *);
433
434 static int d_number (struct d_info *);
435
436 static struct demangle_component *d_identifier (struct d_info *, int);
437
438 static struct demangle_component *d_operator_name (struct d_info *);
439
440 static struct demangle_component *d_special_name (struct d_info *);
441
442 static struct demangle_component *d_parmlist (struct d_info *);
443
444 static int d_call_offset (struct d_info *, int);
445
446 static struct demangle_component *d_ctor_dtor_name (struct d_info *);
447
448 static struct demangle_component **
449 d_cv_qualifiers (struct d_info *, struct demangle_component **, int);
450
451 static struct demangle_component *
452 d_ref_qualifier (struct d_info *, struct demangle_component *);
453
454 static struct demangle_component *
455 d_function_type (struct d_info *);
456
457 static struct demangle_component *
458 d_bare_function_type (struct d_info *, int);
459
460 static struct demangle_component *
461 d_class_enum_type (struct d_info *);
462
463 static struct demangle_component *d_array_type (struct d_info *);
464
465 static struct demangle_component *d_vector_type (struct d_info *);
466
467 static struct demangle_component *
468 d_pointer_to_member_type (struct d_info *);
469
470 static struct demangle_component *
471 d_template_param (struct d_info *);
472
473 static struct demangle_component *d_template_args (struct d_info *);
474 static struct demangle_component *d_template_args_1 (struct d_info *);
475
476 static struct demangle_component *
477 d_template_arg (struct d_info *);
478
479 static struct demangle_component *d_expression (struct d_info *);
480
481 static struct demangle_component *d_expr_primary (struct d_info *);
482
483 static struct demangle_component *d_local_name (struct d_info *);
484
485 static int d_discriminator (struct d_info *);
486
487 static struct demangle_component *d_lambda (struct d_info *);
488
489 static struct demangle_component *d_unnamed_type (struct d_info *);
490
491 static struct demangle_component *
492 d_clone_suffix (struct d_info *, struct demangle_component *);
493
494 static int
495 d_add_substitution (struct d_info *, struct demangle_component *);
496
497 static struct demangle_component *d_substitution (struct d_info *, int);
498
499 static void d_checkpoint (struct d_info *, struct d_info_checkpoint *);
500
501 static void d_backtrack (struct d_info *, struct d_info_checkpoint *);
502
503 static void d_growable_string_init (struct d_growable_string *, size_t);
504
505 static inline void
506 d_growable_string_resize (struct d_growable_string *, size_t);
507
508 static inline void
509 d_growable_string_append_buffer (struct d_growable_string *,
510                                  const char *, size_t);
511 static void
512 d_growable_string_callback_adapter (const char *, size_t, void *);
513
514 static void
515 d_print_init (struct d_print_info *, demangle_callbackref, void *,
516               const struct demangle_component *);
517
518 static inline void d_print_error (struct d_print_info *);
519
520 static inline int d_print_saw_error (struct d_print_info *);
521
522 static inline void d_print_flush (struct d_print_info *);
523
524 static inline void d_append_char (struct d_print_info *, char);
525
526 static inline void d_append_buffer (struct d_print_info *,
527                                     const char *, size_t);
528
529 static inline void d_append_string (struct d_print_info *, const char *);
530
531 static inline char d_last_char (struct d_print_info *);
532
533 static void
534 d_print_comp (struct d_print_info *, int, const struct demangle_component *);
535
536 static void
537 d_print_java_identifier (struct d_print_info *, const char *, int);
538
539 static void
540 d_print_mod_list (struct d_print_info *, int, struct d_print_mod *, int);
541
542 static void
543 d_print_mod (struct d_print_info *, int, const struct demangle_component *);
544
545 static void
546 d_print_function_type (struct d_print_info *, int,
547                        const struct demangle_component *,
548                        struct d_print_mod *);
549
550 static void
551 d_print_array_type (struct d_print_info *, int,
552                     const struct demangle_component *,
553                     struct d_print_mod *);
554
555 static void
556 d_print_expr_op (struct d_print_info *, int, const struct demangle_component *);
557
558 static void d_print_cast (struct d_print_info *, int,
559                           const struct demangle_component *);
560 static void d_print_conversion (struct d_print_info *, int,
561                                 const struct demangle_component *);
562
563 static int d_demangle_callback (const char *, int,
564                                 demangle_callbackref, void *);
565 static char *d_demangle (const char *, int, size_t *);
566
567 /* True iff TYPE is a demangling component representing a
568    function-type-qualifier.  */
569
570 static int
571 is_fnqual_component_type (enum demangle_component_type type)
572 {
573   return (type == DEMANGLE_COMPONENT_RESTRICT_THIS
574           || type == DEMANGLE_COMPONENT_VOLATILE_THIS
575           || type == DEMANGLE_COMPONENT_CONST_THIS
576           || type == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS
577           || type == DEMANGLE_COMPONENT_TRANSACTION_SAFE
578           || type == DEMANGLE_COMPONENT_NOEXCEPT
579           || type == DEMANGLE_COMPONENT_THROW_SPEC
580           || type == DEMANGLE_COMPONENT_REFERENCE_THIS);
581 }
582
583 #define FNQUAL_COMPONENT_CASE                           \
584     case DEMANGLE_COMPONENT_RESTRICT_THIS:              \
585     case DEMANGLE_COMPONENT_VOLATILE_THIS:              \
586     case DEMANGLE_COMPONENT_CONST_THIS:                 \
587     case DEMANGLE_COMPONENT_REFERENCE_THIS:             \
588     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:      \
589     case DEMANGLE_COMPONENT_TRANSACTION_SAFE:           \
590     case DEMANGLE_COMPONENT_NOEXCEPT:                   \
591     case DEMANGLE_COMPONENT_THROW_SPEC
592
593 #ifdef CP_DEMANGLE_DEBUG
594
595 static void
596 d_dump (struct demangle_component *dc, int indent)
597 {
598   int i;
599
600   if (dc == NULL)
601     {
602       if (indent == 0)
603         printf ("failed demangling\n");
604       return;
605     }
606
607   for (i = 0; i < indent; ++i)
608     putchar (' ');
609
610   switch (dc->type)
611     {
612     case DEMANGLE_COMPONENT_NAME:
613       printf ("name '%.*s'\n", dc->u.s_name.len, dc->u.s_name.s);
614       return;
615     case DEMANGLE_COMPONENT_TAGGED_NAME:
616       printf ("tagged name\n");
617       d_dump (dc->u.s_binary.left, indent + 2);
618       d_dump (dc->u.s_binary.right, indent + 2);
619       return;
620     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
621       printf ("template parameter %ld\n", dc->u.s_number.number);
622       return;
623     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
624       printf ("function parameter %ld\n", dc->u.s_number.number);
625       return;
626     case DEMANGLE_COMPONENT_CTOR:
627       printf ("constructor %d\n", (int) dc->u.s_ctor.kind);
628       d_dump (dc->u.s_ctor.name, indent + 2);
629       return;
630     case DEMANGLE_COMPONENT_DTOR:
631       printf ("destructor %d\n", (int) dc->u.s_dtor.kind);
632       d_dump (dc->u.s_dtor.name, indent + 2);
633       return;
634     case DEMANGLE_COMPONENT_SUB_STD:
635       printf ("standard substitution %s\n", dc->u.s_string.string);
636       return;
637     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
638       printf ("builtin type %s\n", dc->u.s_builtin.type->name);
639       return;
640     case DEMANGLE_COMPONENT_OPERATOR:
641       printf ("operator %s\n", dc->u.s_operator.op->name);
642       return;
643     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
644       printf ("extended operator with %d args\n",
645               dc->u.s_extended_operator.args);
646       d_dump (dc->u.s_extended_operator.name, indent + 2);
647       return;
648
649     case DEMANGLE_COMPONENT_QUAL_NAME:
650       printf ("qualified name\n");
651       break;
652     case DEMANGLE_COMPONENT_LOCAL_NAME:
653       printf ("local name\n");
654       break;
655     case DEMANGLE_COMPONENT_TYPED_NAME:
656       printf ("typed name\n");
657       break;
658     case DEMANGLE_COMPONENT_TEMPLATE:
659       printf ("template\n");
660       break;
661     case DEMANGLE_COMPONENT_VTABLE:
662       printf ("vtable\n");
663       break;
664     case DEMANGLE_COMPONENT_VTT:
665       printf ("VTT\n");
666       break;
667     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
668       printf ("construction vtable\n");
669       break;
670     case DEMANGLE_COMPONENT_TYPEINFO:
671       printf ("typeinfo\n");
672       break;
673     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
674       printf ("typeinfo name\n");
675       break;
676     case DEMANGLE_COMPONENT_TYPEINFO_FN:
677       printf ("typeinfo function\n");
678       break;
679     case DEMANGLE_COMPONENT_THUNK:
680       printf ("thunk\n");
681       break;
682     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
683       printf ("virtual thunk\n");
684       break;
685     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
686       printf ("covariant thunk\n");
687       break;
688     case DEMANGLE_COMPONENT_JAVA_CLASS:
689       printf ("java class\n");
690       break;
691     case DEMANGLE_COMPONENT_GUARD:
692       printf ("guard\n");
693       break;
694     case DEMANGLE_COMPONENT_REFTEMP:
695       printf ("reference temporary\n");
696       break;
697     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
698       printf ("hidden alias\n");
699       break;
700     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
701       printf ("transaction clone\n");
702       break;
703     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
704       printf ("non-transaction clone\n");
705       break;
706     case DEMANGLE_COMPONENT_RESTRICT:
707       printf ("restrict\n");
708       break;
709     case DEMANGLE_COMPONENT_VOLATILE:
710       printf ("volatile\n");
711       break;
712     case DEMANGLE_COMPONENT_CONST:
713       printf ("const\n");
714       break;
715     case DEMANGLE_COMPONENT_RESTRICT_THIS:
716       printf ("restrict this\n");
717       break;
718     case DEMANGLE_COMPONENT_VOLATILE_THIS:
719       printf ("volatile this\n");
720       break;
721     case DEMANGLE_COMPONENT_CONST_THIS:
722       printf ("const this\n");
723       break;
724     case DEMANGLE_COMPONENT_REFERENCE_THIS:
725       printf ("reference this\n");
726       break;
727     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
728       printf ("rvalue reference this\n");
729       break;
730     case DEMANGLE_COMPONENT_TRANSACTION_SAFE:
731       printf ("transaction_safe this\n");
732       break;
733     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
734       printf ("vendor type qualifier\n");
735       break;
736     case DEMANGLE_COMPONENT_POINTER:
737       printf ("pointer\n");
738       break;
739     case DEMANGLE_COMPONENT_REFERENCE:
740       printf ("reference\n");
741       break;
742     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
743       printf ("rvalue reference\n");
744       break;
745     case DEMANGLE_COMPONENT_COMPLEX:
746       printf ("complex\n");
747       break;
748     case DEMANGLE_COMPONENT_IMAGINARY:
749       printf ("imaginary\n");
750       break;
751     case DEMANGLE_COMPONENT_VENDOR_TYPE:
752       printf ("vendor type\n");
753       break;
754     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
755       printf ("function type\n");
756       break;
757     case DEMANGLE_COMPONENT_ARRAY_TYPE:
758       printf ("array type\n");
759       break;
760     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
761       printf ("pointer to member type\n");
762       break;
763     case DEMANGLE_COMPONENT_FIXED_TYPE:
764       printf ("fixed-point type, accum? %d, sat? %d\n",
765               dc->u.s_fixed.accum, dc->u.s_fixed.sat);
766       d_dump (dc->u.s_fixed.length, indent + 2);
767       break;
768     case DEMANGLE_COMPONENT_ARGLIST:
769       printf ("argument list\n");
770       break;
771     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
772       printf ("template argument list\n");
773       break;
774     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
775       printf ("initializer list\n");
776       break;
777     case DEMANGLE_COMPONENT_CAST:
778       printf ("cast\n");
779       break;
780     case DEMANGLE_COMPONENT_CONVERSION:
781       printf ("conversion operator\n");
782       break;
783     case DEMANGLE_COMPONENT_NULLARY:
784       printf ("nullary operator\n");
785       break;
786     case DEMANGLE_COMPONENT_UNARY:
787       printf ("unary operator\n");
788       break;
789     case DEMANGLE_COMPONENT_BINARY:
790       printf ("binary operator\n");
791       break;
792     case DEMANGLE_COMPONENT_BINARY_ARGS:
793       printf ("binary operator arguments\n");
794       break;
795     case DEMANGLE_COMPONENT_TRINARY:
796       printf ("trinary operator\n");
797       break;
798     case DEMANGLE_COMPONENT_TRINARY_ARG1:
799       printf ("trinary operator arguments 1\n");
800       break;
801     case DEMANGLE_COMPONENT_TRINARY_ARG2:
802       printf ("trinary operator arguments 1\n");
803       break;
804     case DEMANGLE_COMPONENT_LITERAL:
805       printf ("literal\n");
806       break;
807     case DEMANGLE_COMPONENT_LITERAL_NEG:
808       printf ("negative literal\n");
809       break;
810     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
811       printf ("java resource\n");
812       break;
813     case DEMANGLE_COMPONENT_COMPOUND_NAME:
814       printf ("compound name\n");
815       break;
816     case DEMANGLE_COMPONENT_CHARACTER:
817       printf ("character '%c'\n",  dc->u.s_character.character);
818       return;
819     case DEMANGLE_COMPONENT_NUMBER:
820       printf ("number %ld\n", dc->u.s_number.number);
821       return;
822     case DEMANGLE_COMPONENT_DECLTYPE:
823       printf ("decltype\n");
824       break;
825     case DEMANGLE_COMPONENT_PACK_EXPANSION:
826       printf ("pack expansion\n");
827       break;
828     case DEMANGLE_COMPONENT_TLS_INIT:
829       printf ("tls init function\n");
830       break;
831     case DEMANGLE_COMPONENT_TLS_WRAPPER:
832       printf ("tls wrapper function\n");
833       break;
834     case DEMANGLE_COMPONENT_DEFAULT_ARG:
835       printf ("default argument %d\n", dc->u.s_unary_num.num);
836       d_dump (dc->u.s_unary_num.sub, indent+2);
837       return;
838     case DEMANGLE_COMPONENT_LAMBDA:
839       printf ("lambda %d\n", dc->u.s_unary_num.num);
840       d_dump (dc->u.s_unary_num.sub, indent+2);
841       return;
842     }
843
844   d_dump (d_left (dc), indent + 2);
845   d_dump (d_right (dc), indent + 2);
846 }
847
848 #endif /* CP_DEMANGLE_DEBUG */
849
850 /* Fill in a DEMANGLE_COMPONENT_NAME.  */
851
852 CP_STATIC_IF_GLIBCPP_V3
853 int
854 cplus_demangle_fill_name (struct demangle_component *p, const char *s, int len)
855 {
856   if (p == NULL || s == NULL || len == 0)
857     return 0;
858   p->type = DEMANGLE_COMPONENT_NAME;
859   p->u.s_name.s = s;
860   p->u.s_name.len = len;
861   return 1;
862 }
863
864 /* Fill in a DEMANGLE_COMPONENT_EXTENDED_OPERATOR.  */
865
866 CP_STATIC_IF_GLIBCPP_V3
867 int
868 cplus_demangle_fill_extended_operator (struct demangle_component *p, int args,
869                                        struct demangle_component *name)
870 {
871   if (p == NULL || args < 0 || name == NULL)
872     return 0;
873   p->type = DEMANGLE_COMPONENT_EXTENDED_OPERATOR;
874   p->u.s_extended_operator.args = args;
875   p->u.s_extended_operator.name = name;
876   return 1;
877 }
878
879 /* Fill in a DEMANGLE_COMPONENT_CTOR.  */
880
881 CP_STATIC_IF_GLIBCPP_V3
882 int
883 cplus_demangle_fill_ctor (struct demangle_component *p,
884                           enum gnu_v3_ctor_kinds kind,
885                           struct demangle_component *name)
886 {
887   if (p == NULL
888       || name == NULL
889       || (int) kind < gnu_v3_complete_object_ctor
890       || (int) kind > gnu_v3_object_ctor_group)
891     return 0;
892   p->type = DEMANGLE_COMPONENT_CTOR;
893   p->u.s_ctor.kind = kind;
894   p->u.s_ctor.name = name;
895   return 1;
896 }
897
898 /* Fill in a DEMANGLE_COMPONENT_DTOR.  */
899
900 CP_STATIC_IF_GLIBCPP_V3
901 int
902 cplus_demangle_fill_dtor (struct demangle_component *p,
903                           enum gnu_v3_dtor_kinds kind,
904                           struct demangle_component *name)
905 {
906   if (p == NULL
907       || name == NULL
908       || (int) kind < gnu_v3_deleting_dtor
909       || (int) kind > gnu_v3_object_dtor_group)
910     return 0;
911   p->type = DEMANGLE_COMPONENT_DTOR;
912   p->u.s_dtor.kind = kind;
913   p->u.s_dtor.name = name;
914   return 1;
915 }
916
917 /* Add a new component.  */
918
919 static struct demangle_component *
920 d_make_empty (struct d_info *di)
921 {
922   struct demangle_component *p;
923
924   if (di->next_comp >= di->num_comps)
925     return NULL;
926   p = &di->comps[di->next_comp];
927   ++di->next_comp;
928   return p;
929 }
930
931 /* Add a new generic component.  */
932
933 static struct demangle_component *
934 d_make_comp (struct d_info *di, enum demangle_component_type type,
935              struct demangle_component *left,
936              struct demangle_component *right)
937 {
938   struct demangle_component *p;
939
940   /* We check for errors here.  A typical error would be a NULL return
941      from a subroutine.  We catch those here, and return NULL
942      upward.  */
943   switch (type)
944     {
945       /* These types require two parameters.  */
946     case DEMANGLE_COMPONENT_QUAL_NAME:
947     case DEMANGLE_COMPONENT_LOCAL_NAME:
948     case DEMANGLE_COMPONENT_TYPED_NAME:
949     case DEMANGLE_COMPONENT_TAGGED_NAME:
950     case DEMANGLE_COMPONENT_TEMPLATE:
951     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
952     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
953     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
954     case DEMANGLE_COMPONENT_UNARY:
955     case DEMANGLE_COMPONENT_BINARY:
956     case DEMANGLE_COMPONENT_BINARY_ARGS:
957     case DEMANGLE_COMPONENT_TRINARY:
958     case DEMANGLE_COMPONENT_TRINARY_ARG1:
959     case DEMANGLE_COMPONENT_LITERAL:
960     case DEMANGLE_COMPONENT_LITERAL_NEG:
961     case DEMANGLE_COMPONENT_COMPOUND_NAME:
962     case DEMANGLE_COMPONENT_VECTOR_TYPE:
963     case DEMANGLE_COMPONENT_CLONE:
964       if (left == NULL || right == NULL)
965         return NULL;
966       break;
967
968       /* These types only require one parameter.  */
969     case DEMANGLE_COMPONENT_VTABLE:
970     case DEMANGLE_COMPONENT_VTT:
971     case DEMANGLE_COMPONENT_TYPEINFO:
972     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
973     case DEMANGLE_COMPONENT_TYPEINFO_FN:
974     case DEMANGLE_COMPONENT_THUNK:
975     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
976     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
977     case DEMANGLE_COMPONENT_JAVA_CLASS:
978     case DEMANGLE_COMPONENT_GUARD:
979     case DEMANGLE_COMPONENT_TLS_INIT:
980     case DEMANGLE_COMPONENT_TLS_WRAPPER:
981     case DEMANGLE_COMPONENT_REFTEMP:
982     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
983     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
984     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
985     case DEMANGLE_COMPONENT_POINTER:
986     case DEMANGLE_COMPONENT_REFERENCE:
987     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
988     case DEMANGLE_COMPONENT_COMPLEX:
989     case DEMANGLE_COMPONENT_IMAGINARY:
990     case DEMANGLE_COMPONENT_VENDOR_TYPE:
991     case DEMANGLE_COMPONENT_CAST:
992     case DEMANGLE_COMPONENT_CONVERSION:
993     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
994     case DEMANGLE_COMPONENT_DECLTYPE:
995     case DEMANGLE_COMPONENT_PACK_EXPANSION:
996     case DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS:
997     case DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS:
998     case DEMANGLE_COMPONENT_NULLARY:
999     case DEMANGLE_COMPONENT_TRINARY_ARG2:
1000       if (left == NULL)
1001         return NULL;
1002       break;
1003
1004       /* This needs a right parameter, but the left parameter can be
1005          empty.  */
1006     case DEMANGLE_COMPONENT_ARRAY_TYPE:
1007     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
1008       if (right == NULL)
1009         return NULL;
1010       break;
1011
1012       /* These are allowed to have no parameters--in some cases they
1013          will be filled in later.  */
1014     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
1015     case DEMANGLE_COMPONENT_RESTRICT:
1016     case DEMANGLE_COMPONENT_VOLATILE:
1017     case DEMANGLE_COMPONENT_CONST:
1018     case DEMANGLE_COMPONENT_ARGLIST:
1019     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
1020     FNQUAL_COMPONENT_CASE:
1021       break;
1022
1023       /* Other types should not be seen here.  */
1024     default:
1025       return NULL;
1026     }
1027
1028   p = d_make_empty (di);
1029   if (p != NULL)
1030     {
1031       p->type = type;
1032       p->u.s_binary.left = left;
1033       p->u.s_binary.right = right;
1034     }
1035   return p;
1036 }
1037
1038 /* Add a new demangle mangled name component.  */
1039
1040 static struct demangle_component *
1041 d_make_demangle_mangled_name (struct d_info *di, const char *s)
1042 {
1043   if (d_peek_char (di) != '_' || d_peek_next_char (di) != 'Z')
1044     return d_make_name (di, s, strlen (s));
1045   d_advance (di, 2);
1046   return d_encoding (di, 0);
1047 }
1048
1049 /* Add a new name component.  */
1050
1051 static struct demangle_component *
1052 d_make_name (struct d_info *di, const char *s, int len)
1053 {
1054   struct demangle_component *p;
1055
1056   p = d_make_empty (di);
1057   if (! cplus_demangle_fill_name (p, s, len))
1058     return NULL;
1059   return p;
1060 }
1061
1062 /* Add a new builtin type component.  */
1063
1064 static struct demangle_component *
1065 d_make_builtin_type (struct d_info *di,
1066                      const struct demangle_builtin_type_info *type)
1067 {
1068   struct demangle_component *p;
1069
1070   if (type == NULL)
1071     return NULL;
1072   p = d_make_empty (di);
1073   if (p != NULL)
1074     {
1075       p->type = DEMANGLE_COMPONENT_BUILTIN_TYPE;
1076       p->u.s_builtin.type = type;
1077     }
1078   return p;
1079 }
1080
1081 /* Add a new operator component.  */
1082
1083 static struct demangle_component *
1084 d_make_operator (struct d_info *di, const struct demangle_operator_info *op)
1085 {
1086   struct demangle_component *p;
1087
1088   p = d_make_empty (di);
1089   if (p != NULL)
1090     {
1091       p->type = DEMANGLE_COMPONENT_OPERATOR;
1092       p->u.s_operator.op = op;
1093     }
1094   return p;
1095 }
1096
1097 /* Add a new extended operator component.  */
1098
1099 static struct demangle_component *
1100 d_make_extended_operator (struct d_info *di, int args,
1101                           struct demangle_component *name)
1102 {
1103   struct demangle_component *p;
1104
1105   p = d_make_empty (di);
1106   if (! cplus_demangle_fill_extended_operator (p, args, name))
1107     return NULL;
1108   return p;
1109 }
1110
1111 static struct demangle_component *
1112 d_make_default_arg (struct d_info *di, int num,
1113                     struct demangle_component *sub)
1114 {
1115   struct demangle_component *p = d_make_empty (di);
1116   if (p)
1117     {
1118       p->type = DEMANGLE_COMPONENT_DEFAULT_ARG;
1119       p->u.s_unary_num.num = num;
1120       p->u.s_unary_num.sub = sub;
1121     }
1122   return p;
1123 }
1124
1125 /* Add a new constructor component.  */
1126
1127 static struct demangle_component *
1128 d_make_ctor (struct d_info *di, enum gnu_v3_ctor_kinds kind,
1129              struct demangle_component *name)
1130 {
1131   struct demangle_component *p;
1132
1133   p = d_make_empty (di);
1134   if (! cplus_demangle_fill_ctor (p, kind, name))
1135     return NULL;
1136   return p;
1137 }
1138
1139 /* Add a new destructor component.  */
1140
1141 static struct demangle_component *
1142 d_make_dtor (struct d_info *di, enum gnu_v3_dtor_kinds kind,
1143              struct demangle_component *name)
1144 {
1145   struct demangle_component *p;
1146
1147   p = d_make_empty (di);
1148   if (! cplus_demangle_fill_dtor (p, kind, name))
1149     return NULL;
1150   return p;
1151 }
1152
1153 /* Add a new template parameter.  */
1154
1155 static struct demangle_component *
1156 d_make_template_param (struct d_info *di, int i)
1157 {
1158   struct demangle_component *p;
1159
1160   p = d_make_empty (di);
1161   if (p != NULL)
1162     {
1163       p->type = DEMANGLE_COMPONENT_TEMPLATE_PARAM;
1164       p->u.s_number.number = i;
1165     }
1166   return p;
1167 }
1168
1169 /* Add a new function parameter.  */
1170
1171 static struct demangle_component *
1172 d_make_function_param (struct d_info *di, int i)
1173 {
1174   struct demangle_component *p;
1175
1176   p = d_make_empty (di);
1177   if (p != NULL)
1178     {
1179       p->type = DEMANGLE_COMPONENT_FUNCTION_PARAM;
1180       p->u.s_number.number = i;
1181     }
1182   return p;
1183 }
1184
1185 /* Add a new standard substitution component.  */
1186
1187 static struct demangle_component *
1188 d_make_sub (struct d_info *di, const char *name, int len)
1189 {
1190   struct demangle_component *p;
1191
1192   p = d_make_empty (di);
1193   if (p != NULL)
1194     {
1195       p->type = DEMANGLE_COMPONENT_SUB_STD;
1196       p->u.s_string.string = name;
1197       p->u.s_string.len = len;
1198     }
1199   return p;
1200 }
1201
1202 /* <mangled-name> ::= _Z <encoding> [<clone-suffix>]*
1203
1204    TOP_LEVEL is non-zero when called at the top level.  */
1205
1206 CP_STATIC_IF_GLIBCPP_V3
1207 struct demangle_component *
1208 cplus_demangle_mangled_name (struct d_info *di, int top_level)
1209 {
1210   struct demangle_component *p;
1211
1212   if (! d_check_char (di, '_')
1213       /* Allow missing _ if not at toplevel to work around a
1214          bug in G++ abi-version=2 mangling; see the comment in
1215          write_template_arg.  */
1216       && top_level)
1217     return NULL;
1218   if (! d_check_char (di, 'Z'))
1219     return NULL;
1220   p = d_encoding (di, top_level);
1221
1222   /* If at top level and parsing parameters, check for a clone
1223      suffix.  */
1224   if (top_level && (di->options & DMGL_PARAMS) != 0)
1225     while (d_peek_char (di) == '.'
1226            && (IS_LOWER (d_peek_next_char (di))
1227                || d_peek_next_char (di) == '_'
1228                || IS_DIGIT (d_peek_next_char (di))))
1229       p = d_clone_suffix (di, p);
1230
1231   return p;
1232 }
1233
1234 /* Return whether a function should have a return type.  The argument
1235    is the function name, which may be qualified in various ways.  The
1236    rules are that template functions have return types with some
1237    exceptions, function types which are not part of a function name
1238    mangling have return types with some exceptions, and non-template
1239    function names do not have return types.  The exceptions are that
1240    constructors, destructors, and conversion operators do not have
1241    return types.  */
1242
1243 static int
1244 has_return_type (struct demangle_component *dc)
1245 {
1246   if (dc == NULL)
1247     return 0;
1248   switch (dc->type)
1249     {
1250     default:
1251       return 0;
1252     case DEMANGLE_COMPONENT_TEMPLATE:
1253       return ! is_ctor_dtor_or_conversion (d_left (dc));
1254     FNQUAL_COMPONENT_CASE:
1255       return has_return_type (d_left (dc));
1256     }
1257 }
1258
1259 /* Return whether a name is a constructor, a destructor, or a
1260    conversion operator.  */
1261
1262 static int
1263 is_ctor_dtor_or_conversion (struct demangle_component *dc)
1264 {
1265   if (dc == NULL)
1266     return 0;
1267   switch (dc->type)
1268     {
1269     default:
1270       return 0;
1271     case DEMANGLE_COMPONENT_QUAL_NAME:
1272     case DEMANGLE_COMPONENT_LOCAL_NAME:
1273       return is_ctor_dtor_or_conversion (d_right (dc));
1274     case DEMANGLE_COMPONENT_CTOR:
1275     case DEMANGLE_COMPONENT_DTOR:
1276     case DEMANGLE_COMPONENT_CONVERSION:
1277       return 1;
1278     }
1279 }
1280
1281 /* <encoding> ::= <(function) name> <bare-function-type>
1282               ::= <(data) name>
1283               ::= <special-name>
1284
1285    TOP_LEVEL is non-zero when called at the top level, in which case
1286    if DMGL_PARAMS is not set we do not demangle the function
1287    parameters.  We only set this at the top level, because otherwise
1288    we would not correctly demangle names in local scopes.  */
1289
1290 static struct demangle_component *
1291 d_encoding (struct d_info *di, int top_level)
1292 {
1293   char peek = d_peek_char (di);
1294
1295   if (peek == 'G' || peek == 'T')
1296     return d_special_name (di);
1297   else
1298     {
1299       struct demangle_component *dc;
1300
1301       dc = d_name (di);
1302
1303       if (dc != NULL && top_level && (di->options & DMGL_PARAMS) == 0)
1304         {
1305           /* Strip off any initial CV-qualifiers, as they really apply
1306              to the `this' parameter, and they were not output by the
1307              v2 demangler without DMGL_PARAMS.  */
1308           while (dc->type == DEMANGLE_COMPONENT_RESTRICT_THIS
1309                  || dc->type == DEMANGLE_COMPONENT_VOLATILE_THIS
1310                  || dc->type == DEMANGLE_COMPONENT_CONST_THIS
1311                  || dc->type == DEMANGLE_COMPONENT_REFERENCE_THIS
1312                  || dc->type == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS)
1313             dc = d_left (dc);
1314
1315           /* If the top level is a DEMANGLE_COMPONENT_LOCAL_NAME, then
1316              there may be function-qualifiers on its right argument which
1317              really apply here; this happens when parsing a class
1318              which is local to a function.  */
1319           if (dc->type == DEMANGLE_COMPONENT_LOCAL_NAME)
1320             {
1321               struct demangle_component *dcr;
1322
1323               dcr = d_right (dc);
1324               while (is_fnqual_component_type (dcr->type))
1325                 dcr = d_left (dcr);
1326               dc->u.s_binary.right = dcr;
1327             }
1328
1329           return dc;
1330         }
1331
1332       peek = d_peek_char (di);
1333       if (dc == NULL || peek == '\0' || peek == 'E')
1334         return dc;
1335       return d_make_comp (di, DEMANGLE_COMPONENT_TYPED_NAME, dc,
1336                           d_bare_function_type (di, has_return_type (dc)));
1337     }
1338 }
1339
1340 /* <tagged-name> ::= <name> B <source-name> */
1341
1342 static struct demangle_component *
1343 d_abi_tags (struct d_info *di, struct demangle_component *dc)
1344 {
1345   struct demangle_component *hold_last_name;
1346   char peek;
1347
1348   /* Preserve the last name, so the ABI tag doesn't clobber it.  */
1349   hold_last_name = di->last_name;
1350
1351   while (peek = d_peek_char (di),
1352          peek == 'B')
1353     {
1354       struct demangle_component *tag;
1355       d_advance (di, 1);
1356       tag = d_source_name (di);
1357       dc = d_make_comp (di, DEMANGLE_COMPONENT_TAGGED_NAME, dc, tag);
1358     }
1359
1360   di->last_name = hold_last_name;
1361
1362   return dc;
1363 }
1364
1365 /* <name> ::= <nested-name>
1366           ::= <unscoped-name>
1367           ::= <unscoped-template-name> <template-args>
1368           ::= <local-name>
1369
1370    <unscoped-name> ::= <unqualified-name>
1371                    ::= St <unqualified-name>
1372
1373    <unscoped-template-name> ::= <unscoped-name>
1374                             ::= <substitution>
1375 */
1376
1377 static struct demangle_component *
1378 d_name (struct d_info *di)
1379 {
1380   char peek = d_peek_char (di);
1381   struct demangle_component *dc;
1382
1383   switch (peek)
1384     {
1385     case 'N':
1386       return d_nested_name (di);
1387
1388     case 'Z':
1389       return d_local_name (di);
1390
1391     case 'U':
1392       return d_unqualified_name (di);
1393
1394     case 'S':
1395       {
1396         int subst;
1397
1398         if (d_peek_next_char (di) != 't')
1399           {
1400             dc = d_substitution (di, 0);
1401             subst = 1;
1402           }
1403         else
1404           {
1405             d_advance (di, 2);
1406             dc = d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME,
1407                               d_make_name (di, "std", 3),
1408                               d_unqualified_name (di));
1409             di->expansion += 3;
1410             subst = 0;
1411           }
1412
1413         if (d_peek_char (di) != 'I')
1414           {
1415             /* The grammar does not permit this case to occur if we
1416                called d_substitution() above (i.e., subst == 1).  We
1417                don't bother to check.  */
1418           }
1419         else
1420           {
1421             /* This is <template-args>, which means that we just saw
1422                <unscoped-template-name>, which is a substitution
1423                candidate if we didn't just get it from a
1424                substitution.  */
1425             if (! subst)
1426               {
1427                 if (! d_add_substitution (di, dc))
1428                   return NULL;
1429               }
1430             dc = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, dc,
1431                               d_template_args (di));
1432           }
1433
1434         return dc;
1435       }
1436
1437     case 'L':
1438     default:
1439       dc = d_unqualified_name (di);
1440       if (d_peek_char (di) == 'I')
1441         {
1442           /* This is <template-args>, which means that we just saw
1443              <unscoped-template-name>, which is a substitution
1444              candidate.  */
1445           if (! d_add_substitution (di, dc))
1446             return NULL;
1447           dc = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, dc,
1448                             d_template_args (di));
1449         }
1450       return dc;
1451     }
1452 }
1453
1454 /* <nested-name> ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1455                  ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E
1456 */
1457
1458 static struct demangle_component *
1459 d_nested_name (struct d_info *di)
1460 {
1461   struct demangle_component *ret;
1462   struct demangle_component **pret;
1463   struct demangle_component *rqual;
1464
1465   if (! d_check_char (di, 'N'))
1466     return NULL;
1467
1468   pret = d_cv_qualifiers (di, &ret, 1);
1469   if (pret == NULL)
1470     return NULL;
1471
1472   /* Parse the ref-qualifier now and then attach it
1473      once we have something to attach it to.  */
1474   rqual = d_ref_qualifier (di, NULL);
1475
1476   *pret = d_prefix (di);
1477   if (*pret == NULL)
1478     return NULL;
1479
1480   if (rqual)
1481     {
1482       d_left (rqual) = ret;
1483       ret = rqual;
1484     }
1485
1486   if (! d_check_char (di, 'E'))
1487     return NULL;
1488
1489   return ret;
1490 }
1491
1492 /* <prefix> ::= <prefix> <unqualified-name>
1493             ::= <template-prefix> <template-args>
1494             ::= <template-param>
1495             ::= <decltype>
1496             ::=
1497             ::= <substitution>
1498
1499    <template-prefix> ::= <prefix> <(template) unqualified-name>
1500                      ::= <template-param>
1501                      ::= <substitution>
1502 */
1503
1504 static struct demangle_component *
1505 d_prefix (struct d_info *di)
1506 {
1507   struct demangle_component *ret = NULL;
1508
1509   while (1)
1510     {
1511       char peek;
1512       enum demangle_component_type comb_type;
1513       struct demangle_component *dc;
1514
1515       peek = d_peek_char (di);
1516       if (peek == '\0')
1517         return NULL;
1518
1519       /* The older code accepts a <local-name> here, but I don't see
1520          that in the grammar.  The older code does not accept a
1521          <template-param> here.  */
1522
1523       comb_type = DEMANGLE_COMPONENT_QUAL_NAME;
1524       if (peek == 'D')
1525         {
1526           char peek2 = d_peek_next_char (di);
1527           if (peek2 == 'T' || peek2 == 't')
1528             /* Decltype.  */
1529             dc = cplus_demangle_type (di);
1530           else
1531             /* Destructor name.  */
1532             dc = d_unqualified_name (di);
1533         }
1534       else if (IS_DIGIT (peek)
1535           || IS_LOWER (peek)
1536           || peek == 'C'
1537           || peek == 'U'
1538           || peek == 'L')
1539         dc = d_unqualified_name (di);
1540       else if (peek == 'S')
1541         dc = d_substitution (di, 1);
1542       else if (peek == 'I')
1543         {
1544           if (ret == NULL)
1545             return NULL;
1546           comb_type = DEMANGLE_COMPONENT_TEMPLATE;
1547           dc = d_template_args (di);
1548         }
1549       else if (peek == 'T')
1550         dc = d_template_param (di);
1551       else if (peek == 'E')
1552         return ret;
1553       else if (peek == 'M')
1554         {
1555           /* Initializer scope for a lambda.  We don't need to represent
1556              this; the normal code will just treat the variable as a type
1557              scope, which gives appropriate output.  */
1558           if (ret == NULL)
1559             return NULL;
1560           d_advance (di, 1);
1561           continue;
1562         }
1563       else
1564         return NULL;
1565
1566       if (ret == NULL)
1567         ret = dc;
1568       else
1569         ret = d_make_comp (di, comb_type, ret, dc);
1570
1571       if (peek != 'S' && d_peek_char (di) != 'E')
1572         {
1573           if (! d_add_substitution (di, ret))
1574             return NULL;
1575         }
1576     }
1577 }
1578
1579 /* <unqualified-name> ::= <operator-name>
1580                       ::= <ctor-dtor-name>
1581                       ::= <source-name>
1582                       ::= <local-source-name> 
1583
1584     <local-source-name> ::= L <source-name> <discriminator>
1585 */
1586
1587 static struct demangle_component *
1588 d_unqualified_name (struct d_info *di)
1589 {
1590   struct demangle_component *ret;
1591   char peek;
1592
1593   peek = d_peek_char (di);
1594   if (IS_DIGIT (peek))
1595     ret = d_source_name (di);
1596   else if (IS_LOWER (peek))
1597     {
1598       ret = d_operator_name (di);
1599       if (ret != NULL && ret->type == DEMANGLE_COMPONENT_OPERATOR)
1600         {
1601           di->expansion += sizeof "operator" + ret->u.s_operator.op->len - 2;
1602           if (!strcmp (ret->u.s_operator.op->code, "li"))
1603             ret = d_make_comp (di, DEMANGLE_COMPONENT_UNARY, ret,
1604                                d_source_name (di));
1605         }
1606     }
1607   else if (peek == 'C' || peek == 'D')
1608     ret = d_ctor_dtor_name (di);
1609   else if (peek == 'L')
1610     {
1611       d_advance (di, 1);
1612
1613       ret = d_source_name (di);
1614       if (ret == NULL)
1615         return NULL;
1616       if (! d_discriminator (di))
1617         return NULL;
1618     }
1619   else if (peek == 'U')
1620     {
1621       switch (d_peek_next_char (di))
1622         {
1623         case 'l':
1624           ret = d_lambda (di);
1625           break;
1626         case 't':
1627           ret = d_unnamed_type (di);
1628           break;
1629         default:
1630           return NULL;
1631         }
1632     }
1633   else
1634     return NULL;
1635
1636   if (d_peek_char (di) == 'B')
1637     ret = d_abi_tags (di, ret);
1638   return ret;
1639 }
1640
1641 /* <source-name> ::= <(positive length) number> <identifier>  */
1642
1643 static struct demangle_component *
1644 d_source_name (struct d_info *di)
1645 {
1646   int len;
1647   struct demangle_component *ret;
1648
1649   len = d_number (di);
1650   if (len <= 0)
1651     return NULL;
1652   ret = d_identifier (di, len);
1653   di->last_name = ret;
1654   return ret;
1655 }
1656
1657 /* number ::= [n] <(non-negative decimal integer)>  */
1658
1659 static int
1660 d_number (struct d_info *di)
1661 {
1662   int negative;
1663   char peek;
1664   int ret;
1665
1666   negative = 0;
1667   peek = d_peek_char (di);
1668   if (peek == 'n')
1669     {
1670       negative = 1;
1671       d_advance (di, 1);
1672       peek = d_peek_char (di);
1673     }
1674
1675   ret = 0;
1676   while (1)
1677     {
1678       if (! IS_DIGIT (peek))
1679         {
1680           if (negative)
1681             ret = - ret;
1682           return ret;
1683         }
1684       ret = ret * 10 + peek - '0';
1685       d_advance (di, 1);
1686       peek = d_peek_char (di);
1687     }
1688 }
1689
1690 /* Like d_number, but returns a demangle_component.  */
1691
1692 static struct demangle_component *
1693 d_number_component (struct d_info *di)
1694 {
1695   struct demangle_component *ret = d_make_empty (di);
1696   if (ret)
1697     {
1698       ret->type = DEMANGLE_COMPONENT_NUMBER;
1699       ret->u.s_number.number = d_number (di);
1700     }
1701   return ret;
1702 }
1703
1704 /* identifier ::= <(unqualified source code identifier)>  */
1705
1706 static struct demangle_component *
1707 d_identifier (struct d_info *di, int len)
1708 {
1709   const char *name;
1710
1711   name = d_str (di);
1712
1713   if (di->send - name < len)
1714     return NULL;
1715
1716   d_advance (di, len);
1717
1718   /* A Java mangled name may have a trailing '$' if it is a C++
1719      keyword.  This '$' is not included in the length count.  We just
1720      ignore the '$'.  */
1721   if ((di->options & DMGL_JAVA) != 0
1722       && d_peek_char (di) == '$')
1723     d_advance (di, 1);
1724
1725   /* Look for something which looks like a gcc encoding of an
1726      anonymous namespace, and replace it with a more user friendly
1727      name.  */
1728   if (len >= (int) ANONYMOUS_NAMESPACE_PREFIX_LEN + 2
1729       && memcmp (name, ANONYMOUS_NAMESPACE_PREFIX,
1730                  ANONYMOUS_NAMESPACE_PREFIX_LEN) == 0)
1731     {
1732       const char *s;
1733
1734       s = name + ANONYMOUS_NAMESPACE_PREFIX_LEN;
1735       if ((*s == '.' || *s == '_' || *s == '$')
1736           && s[1] == 'N')
1737         {
1738           di->expansion -= len - sizeof "(anonymous namespace)";
1739           return d_make_name (di, "(anonymous namespace)",
1740                               sizeof "(anonymous namespace)" - 1);
1741         }
1742     }
1743
1744   return d_make_name (di, name, len);
1745 }
1746
1747 /* operator_name ::= many different two character encodings.
1748                  ::= cv <type>
1749                  ::= v <digit> <source-name>
1750
1751    This list is sorted for binary search.  */
1752
1753 #define NL(s) s, (sizeof s) - 1
1754
1755 CP_STATIC_IF_GLIBCPP_V3
1756 const struct demangle_operator_info cplus_demangle_operators[] =
1757 {
1758   { "aN", NL ("&="),        2 },
1759   { "aS", NL ("="),         2 },
1760   { "aa", NL ("&&"),        2 },
1761   { "ad", NL ("&"),         1 },
1762   { "an", NL ("&"),         2 },
1763   { "at", NL ("alignof "),   1 },
1764   { "az", NL ("alignof "),   1 },
1765   { "cc", NL ("const_cast"), 2 },
1766   { "cl", NL ("()"),        2 },
1767   { "cm", NL (","),         2 },
1768   { "co", NL ("~"),         1 },
1769   { "dV", NL ("/="),        2 },
1770   { "da", NL ("delete[] "), 1 },
1771   { "dc", NL ("dynamic_cast"), 2 },
1772   { "de", NL ("*"),         1 },
1773   { "dl", NL ("delete "),   1 },
1774   { "ds", NL (".*"),        2 },
1775   { "dt", NL ("."),         2 },
1776   { "dv", NL ("/"),         2 },
1777   { "eO", NL ("^="),        2 },
1778   { "eo", NL ("^"),         2 },
1779   { "eq", NL ("=="),        2 },
1780   { "fL", NL ("..."),       3 },
1781   { "fR", NL ("..."),       3 },
1782   { "fl", NL ("..."),       2 },
1783   { "fr", NL ("..."),       2 },
1784   { "ge", NL (">="),        2 },
1785   { "gs", NL ("::"),        1 },
1786   { "gt", NL (">"),         2 },
1787   { "ix", NL ("[]"),        2 },
1788   { "lS", NL ("<<="),       2 },
1789   { "le", NL ("<="),        2 },
1790   { "li", NL ("operator\"\" "), 1 },
1791   { "ls", NL ("<<"),        2 },
1792   { "lt", NL ("<"),         2 },
1793   { "mI", NL ("-="),        2 },
1794   { "mL", NL ("*="),        2 },
1795   { "mi", NL ("-"),         2 },
1796   { "ml", NL ("*"),         2 },
1797   { "mm", NL ("--"),        1 },
1798   { "na", NL ("new[]"),     3 },
1799   { "ne", NL ("!="),        2 },
1800   { "ng", NL ("-"),         1 },
1801   { "nt", NL ("!"),         1 },
1802   { "nw", NL ("new"),       3 },
1803   { "oR", NL ("|="),        2 },
1804   { "oo", NL ("||"),        2 },
1805   { "or", NL ("|"),         2 },
1806   { "pL", NL ("+="),        2 },
1807   { "pl", NL ("+"),         2 },
1808   { "pm", NL ("->*"),       2 },
1809   { "pp", NL ("++"),        1 },
1810   { "ps", NL ("+"),         1 },
1811   { "pt", NL ("->"),        2 },
1812   { "qu", NL ("?"),         3 },
1813   { "rM", NL ("%="),        2 },
1814   { "rS", NL (">>="),       2 },
1815   { "rc", NL ("reinterpret_cast"), 2 },
1816   { "rm", NL ("%"),         2 },
1817   { "rs", NL (">>"),        2 },
1818   { "sP", NL ("sizeof..."), 1 },
1819   { "sZ", NL ("sizeof..."), 1 },
1820   { "sc", NL ("static_cast"), 2 },
1821   { "st", NL ("sizeof "),   1 },
1822   { "sz", NL ("sizeof "),   1 },
1823   { "tr", NL ("throw"),     0 },
1824   { "tw", NL ("throw "),    1 },
1825   { NULL, NULL, 0,          0 }
1826 };
1827
1828 static struct demangle_component *
1829 d_operator_name (struct d_info *di)
1830 {
1831   char c1;
1832   char c2;
1833
1834   c1 = d_next_char (di);
1835   c2 = d_next_char (di);
1836   if (c1 == 'v' && IS_DIGIT (c2))
1837     return d_make_extended_operator (di, c2 - '0', d_source_name (di));
1838   else if (c1 == 'c' && c2 == 'v')
1839     {
1840       struct demangle_component *type;
1841       int was_conversion = di->is_conversion;
1842       struct demangle_component *res;
1843
1844       di->is_conversion = ! di->is_expression;
1845       type = cplus_demangle_type (di);
1846       if (di->is_conversion)
1847         res = d_make_comp (di, DEMANGLE_COMPONENT_CONVERSION, type, NULL);
1848       else
1849         res = d_make_comp (di, DEMANGLE_COMPONENT_CAST, type, NULL);
1850       di->is_conversion = was_conversion;
1851       return res;
1852     }
1853   else
1854     {
1855       /* LOW is the inclusive lower bound.  */
1856       int low = 0;
1857       /* HIGH is the exclusive upper bound.  We subtract one to ignore
1858          the sentinel at the end of the array.  */
1859       int high = ((sizeof (cplus_demangle_operators)
1860                    / sizeof (cplus_demangle_operators[0]))
1861                   - 1);
1862
1863       while (1)
1864         {
1865           int i;
1866           const struct demangle_operator_info *p;
1867
1868           i = low + (high - low) / 2;
1869           p = cplus_demangle_operators + i;
1870
1871           if (c1 == p->code[0] && c2 == p->code[1])
1872             return d_make_operator (di, p);
1873
1874           if (c1 < p->code[0] || (c1 == p->code[0] && c2 < p->code[1]))
1875             high = i;
1876           else
1877             low = i + 1;
1878           if (low == high)
1879             return NULL;
1880         }
1881     }
1882 }
1883
1884 static struct demangle_component *
1885 d_make_character (struct d_info *di, int c)
1886 {
1887   struct demangle_component *p;
1888   p = d_make_empty (di);
1889   if (p != NULL)
1890     {
1891       p->type = DEMANGLE_COMPONENT_CHARACTER;
1892       p->u.s_character.character = c;
1893     }
1894   return p;
1895 }
1896
1897 static struct demangle_component *
1898 d_java_resource (struct d_info *di)
1899 {
1900   struct demangle_component *p = NULL;
1901   struct demangle_component *next = NULL;
1902   int len, i;
1903   char c;
1904   const char *str;
1905
1906   len = d_number (di);
1907   if (len <= 1)
1908     return NULL;
1909
1910   /* Eat the leading '_'.  */
1911   if (d_next_char (di) != '_')
1912     return NULL;
1913   len--;
1914
1915   str = d_str (di);
1916   i = 0;
1917
1918   while (len > 0)
1919     {
1920       c = str[i];
1921       if (!c)
1922         return NULL;
1923
1924       /* Each chunk is either a '$' escape...  */
1925       if (c == '$')
1926         {
1927           i++;
1928           switch (str[i++])
1929             {
1930             case 'S':
1931               c = '/';
1932               break;
1933             case '_':
1934               c = '.';
1935               break;
1936             case '$':
1937               c = '$';
1938               break;
1939             default:
1940               return NULL;
1941             }
1942           next = d_make_character (di, c);
1943           d_advance (di, i);
1944           str = d_str (di);
1945           len -= i;
1946           i = 0;
1947           if (next == NULL)
1948             return NULL;
1949         }
1950       /* ... or a sequence of characters.  */
1951       else
1952         {
1953           while (i < len && str[i] && str[i] != '$')
1954             i++;
1955
1956           next = d_make_name (di, str, i);
1957           d_advance (di, i);
1958           str = d_str (di);
1959           len -= i;
1960           i = 0;
1961           if (next == NULL)
1962             return NULL;
1963         }
1964
1965       if (p == NULL)
1966         p = next;
1967       else
1968         {
1969           p = d_make_comp (di, DEMANGLE_COMPONENT_COMPOUND_NAME, p, next);
1970           if (p == NULL)
1971             return NULL;
1972         }
1973     }
1974
1975   p = d_make_comp (di, DEMANGLE_COMPONENT_JAVA_RESOURCE, p, NULL);
1976
1977   return p;
1978 }
1979
1980 /* <special-name> ::= TV <type>
1981                   ::= TT <type>
1982                   ::= TI <type>
1983                   ::= TS <type>
1984                   ::= GV <(object) name>
1985                   ::= T <call-offset> <(base) encoding>
1986                   ::= Tc <call-offset> <call-offset> <(base) encoding>
1987    Also g++ extensions:
1988                   ::= TC <type> <(offset) number> _ <(base) type>
1989                   ::= TF <type>
1990                   ::= TJ <type>
1991                   ::= GR <name>
1992                   ::= GA <encoding>
1993                   ::= Gr <resource name>
1994                   ::= GTt <encoding>
1995                   ::= GTn <encoding>
1996 */
1997
1998 static struct demangle_component *
1999 d_special_name (struct d_info *di)
2000 {
2001   di->expansion += 20;
2002   if (d_check_char (di, 'T'))
2003     {
2004       switch (d_next_char (di))
2005         {
2006         case 'V':
2007           di->expansion -= 5;
2008           return d_make_comp (di, DEMANGLE_COMPONENT_VTABLE,
2009                               cplus_demangle_type (di), NULL);
2010         case 'T':
2011           di->expansion -= 10;
2012           return d_make_comp (di, DEMANGLE_COMPONENT_VTT,
2013                               cplus_demangle_type (di), NULL);
2014         case 'I':
2015           return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO,
2016                               cplus_demangle_type (di), NULL);
2017         case 'S':
2018           return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO_NAME,
2019                               cplus_demangle_type (di), NULL);
2020
2021         case 'h':
2022           if (! d_call_offset (di, 'h'))
2023             return NULL;
2024           return d_make_comp (di, DEMANGLE_COMPONENT_THUNK,
2025                               d_encoding (di, 0), NULL);
2026
2027         case 'v':
2028           if (! d_call_offset (di, 'v'))
2029             return NULL;
2030           return d_make_comp (di, DEMANGLE_COMPONENT_VIRTUAL_THUNK,
2031                               d_encoding (di, 0), NULL);
2032
2033         case 'c':
2034           if (! d_call_offset (di, '\0'))
2035             return NULL;
2036           if (! d_call_offset (di, '\0'))
2037             return NULL;
2038           return d_make_comp (di, DEMANGLE_COMPONENT_COVARIANT_THUNK,
2039                               d_encoding (di, 0), NULL);
2040
2041         case 'C':
2042           {
2043             struct demangle_component *derived_type;
2044             int offset;
2045             struct demangle_component *base_type;
2046
2047             derived_type = cplus_demangle_type (di);
2048             offset = d_number (di);
2049             if (offset < 0)
2050               return NULL;
2051             if (! d_check_char (di, '_'))
2052               return NULL;
2053             base_type = cplus_demangle_type (di);
2054             /* We don't display the offset.  FIXME: We should display
2055                it in verbose mode.  */
2056             di->expansion += 5;
2057             return d_make_comp (di, DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE,
2058                                 base_type, derived_type);
2059           }
2060
2061         case 'F':
2062           return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO_FN,
2063                               cplus_demangle_type (di), NULL);
2064         case 'J':
2065           return d_make_comp (di, DEMANGLE_COMPONENT_JAVA_CLASS,
2066                               cplus_demangle_type (di), NULL);
2067
2068         case 'H':
2069           return d_make_comp (di, DEMANGLE_COMPONENT_TLS_INIT,
2070                               d_name (di), NULL);
2071
2072         case 'W':
2073           return d_make_comp (di, DEMANGLE_COMPONENT_TLS_WRAPPER,
2074                               d_name (di), NULL);
2075
2076         default:
2077           return NULL;
2078         }
2079     }
2080   else if (d_check_char (di, 'G'))
2081     {
2082       switch (d_next_char (di))
2083         {
2084         case 'V':
2085           return d_make_comp (di, DEMANGLE_COMPONENT_GUARD, d_name (di), NULL);
2086
2087         case 'R':
2088           {
2089             struct demangle_component *name = d_name (di);
2090             return d_make_comp (di, DEMANGLE_COMPONENT_REFTEMP, name,
2091                                 d_number_component (di));
2092           }
2093
2094         case 'A':
2095           return d_make_comp (di, DEMANGLE_COMPONENT_HIDDEN_ALIAS,
2096                               d_encoding (di, 0), NULL);
2097
2098         case 'T':
2099           switch (d_next_char (di))
2100             {
2101             case 'n':
2102               return d_make_comp (di, DEMANGLE_COMPONENT_NONTRANSACTION_CLONE,
2103                                   d_encoding (di, 0), NULL);
2104             default:
2105               /* ??? The proposal is that other letters (such as 'h') stand
2106                  for different variants of transaction cloning, such as
2107                  compiling directly for hardware transaction support.  But
2108                  they still should all be transactional clones of some sort
2109                  so go ahead and call them that.  */
2110             case 't':
2111               return d_make_comp (di, DEMANGLE_COMPONENT_TRANSACTION_CLONE,
2112                                   d_encoding (di, 0), NULL);
2113             }
2114
2115         case 'r':
2116           return d_java_resource (di);
2117
2118         default:
2119           return NULL;
2120         }
2121     }
2122   else
2123     return NULL;
2124 }
2125
2126 /* <call-offset> ::= h <nv-offset> _
2127                  ::= v <v-offset> _
2128
2129    <nv-offset> ::= <(offset) number>
2130
2131    <v-offset> ::= <(offset) number> _ <(virtual offset) number>
2132
2133    The C parameter, if not '\0', is a character we just read which is
2134    the start of the <call-offset>.
2135
2136    We don't display the offset information anywhere.  FIXME: We should
2137    display it in verbose mode.  */
2138
2139 static int
2140 d_call_offset (struct d_info *di, int c)
2141 {
2142   if (c == '\0')
2143     c = d_next_char (di);
2144
2145   if (c == 'h')
2146     d_number (di);
2147   else if (c == 'v')
2148     {
2149       d_number (di);
2150       if (! d_check_char (di, '_'))
2151         return 0;
2152       d_number (di);
2153     }
2154   else
2155     return 0;
2156
2157   if (! d_check_char (di, '_'))
2158     return 0;
2159
2160   return 1;
2161 }
2162
2163 /* <ctor-dtor-name> ::= C1
2164                     ::= C2
2165                     ::= C3
2166                     ::= D0
2167                     ::= D1
2168                     ::= D2
2169 */
2170
2171 static struct demangle_component *
2172 d_ctor_dtor_name (struct d_info *di)
2173 {
2174   if (di->last_name != NULL)
2175     {
2176       if (di->last_name->type == DEMANGLE_COMPONENT_NAME)
2177         di->expansion += di->last_name->u.s_name.len;
2178       else if (di->last_name->type == DEMANGLE_COMPONENT_SUB_STD)
2179         di->expansion += di->last_name->u.s_string.len;
2180     }
2181   switch (d_peek_char (di))
2182     {
2183     case 'C':
2184       {
2185         enum gnu_v3_ctor_kinds kind;
2186         int inheriting = 0;
2187
2188         if (d_peek_next_char (di) == 'I')
2189           {
2190             inheriting = 1;
2191             d_advance (di, 1);
2192           }
2193
2194         switch (d_peek_next_char (di))
2195           {
2196           case '1':
2197             kind = gnu_v3_complete_object_ctor;
2198             break;
2199           case '2':
2200             kind = gnu_v3_base_object_ctor;
2201             break;
2202           case '3':
2203             kind = gnu_v3_complete_object_allocating_ctor;
2204             break;
2205           case '4':
2206             kind = gnu_v3_unified_ctor;
2207             break;
2208           case '5':
2209             kind = gnu_v3_object_ctor_group;
2210             break;
2211           default:
2212             return NULL;
2213           }
2214
2215         d_advance (di, 2);
2216
2217         if (inheriting)
2218           cplus_demangle_type (di);
2219
2220         return d_make_ctor (di, kind, di->last_name);
2221       }
2222
2223     case 'D':
2224       {
2225         enum gnu_v3_dtor_kinds kind;
2226
2227         switch (d_peek_next_char (di))
2228           {
2229           case '0':
2230             kind = gnu_v3_deleting_dtor;
2231             break;
2232           case '1':
2233             kind = gnu_v3_complete_object_dtor;
2234             break;
2235           case '2':
2236             kind = gnu_v3_base_object_dtor;
2237             break;
2238           /*  digit '3' is not used */
2239           case '4':
2240             kind = gnu_v3_unified_dtor;
2241             break;
2242           case '5':
2243             kind = gnu_v3_object_dtor_group;
2244             break;
2245           default:
2246             return NULL;
2247           }
2248         d_advance (di, 2);
2249         return d_make_dtor (di, kind, di->last_name);
2250       }
2251
2252     default:
2253       return NULL;
2254     }
2255 }
2256
2257 /* True iff we're looking at an order-insensitive type-qualifier, including
2258    function-type-qualifiers.  */
2259
2260 static int
2261 next_is_type_qual (struct d_info *di)
2262 {
2263   char peek = d_peek_char (di);
2264   if (peek == 'r' || peek == 'V' || peek == 'K')
2265     return 1;
2266   if (peek == 'D')
2267     {
2268       peek = d_peek_next_char (di);
2269       if (peek == 'x' || peek == 'o' || peek == 'O' || peek == 'w')
2270         return 1;
2271     }
2272   return 0;
2273 }
2274
2275 /* <type> ::= <builtin-type>
2276           ::= <function-type>
2277           ::= <class-enum-type>
2278           ::= <array-type>
2279           ::= <pointer-to-member-type>
2280           ::= <template-param>
2281           ::= <template-template-param> <template-args>
2282           ::= <substitution>
2283           ::= <CV-qualifiers> <type>
2284           ::= P <type>
2285           ::= R <type>
2286           ::= O <type> (C++0x)
2287           ::= C <type>
2288           ::= G <type>
2289           ::= U <source-name> <type>
2290
2291    <builtin-type> ::= various one letter codes
2292                   ::= u <source-name>
2293 */
2294
2295 CP_STATIC_IF_GLIBCPP_V3
2296 const struct demangle_builtin_type_info
2297 cplus_demangle_builtin_types[D_BUILTIN_TYPE_COUNT] =
2298 {
2299   /* a */ { NL ("signed char"), NL ("signed char"),     D_PRINT_DEFAULT },
2300   /* b */ { NL ("bool"),        NL ("boolean"),         D_PRINT_BOOL },
2301   /* c */ { NL ("char"),        NL ("byte"),            D_PRINT_DEFAULT },
2302   /* d */ { NL ("double"),      NL ("double"),          D_PRINT_FLOAT },
2303   /* e */ { NL ("long double"), NL ("long double"),     D_PRINT_FLOAT },
2304   /* f */ { NL ("float"),       NL ("float"),           D_PRINT_FLOAT },
2305   /* g */ { NL ("__float128"),  NL ("__float128"),      D_PRINT_FLOAT },
2306   /* h */ { NL ("unsigned char"), NL ("unsigned char"), D_PRINT_DEFAULT },
2307   /* i */ { NL ("int"),         NL ("int"),             D_PRINT_INT },
2308   /* j */ { NL ("unsigned int"), NL ("unsigned"),       D_PRINT_UNSIGNED },
2309   /* k */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
2310   /* l */ { NL ("long"),        NL ("long"),            D_PRINT_LONG },
2311   /* m */ { NL ("unsigned long"), NL ("unsigned long"), D_PRINT_UNSIGNED_LONG },
2312   /* n */ { NL ("__int128"),    NL ("__int128"),        D_PRINT_DEFAULT },
2313   /* o */ { NL ("unsigned __int128"), NL ("unsigned __int128"),
2314             D_PRINT_DEFAULT },
2315   /* p */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
2316   /* q */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
2317   /* r */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
2318   /* s */ { NL ("short"),       NL ("short"),           D_PRINT_DEFAULT },
2319   /* t */ { NL ("unsigned short"), NL ("unsigned short"), D_PRINT_DEFAULT },
2320   /* u */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
2321   /* v */ { NL ("void"),        NL ("void"),            D_PRINT_VOID },
2322   /* w */ { NL ("wchar_t"),     NL ("char"),            D_PRINT_DEFAULT },
2323   /* x */ { NL ("long long"),   NL ("long"),            D_PRINT_LONG_LONG },
2324   /* y */ { NL ("unsigned long long"), NL ("unsigned long long"),
2325             D_PRINT_UNSIGNED_LONG_LONG },
2326   /* z */ { NL ("..."),         NL ("..."),             D_PRINT_DEFAULT },
2327   /* 26 */ { NL ("decimal32"),  NL ("decimal32"),       D_PRINT_DEFAULT },
2328   /* 27 */ { NL ("decimal64"),  NL ("decimal64"),       D_PRINT_DEFAULT },
2329   /* 28 */ { NL ("decimal128"), NL ("decimal128"),      D_PRINT_DEFAULT },
2330   /* 29 */ { NL ("half"),       NL ("half"),            D_PRINT_FLOAT },
2331   /* 30 */ { NL ("char16_t"),   NL ("char16_t"),        D_PRINT_DEFAULT },
2332   /* 31 */ { NL ("char32_t"),   NL ("char32_t"),        D_PRINT_DEFAULT },
2333   /* 32 */ { NL ("decltype(nullptr)"),  NL ("decltype(nullptr)"),
2334              D_PRINT_DEFAULT },
2335 };
2336
2337 CP_STATIC_IF_GLIBCPP_V3
2338 struct demangle_component *
2339 cplus_demangle_type (struct d_info *di)
2340 {
2341   char peek;
2342   struct demangle_component *ret;
2343   int can_subst;
2344
2345   /* The ABI specifies that when CV-qualifiers are used, the base type
2346      is substitutable, and the fully qualified type is substitutable,
2347      but the base type with a strict subset of the CV-qualifiers is
2348      not substitutable.  The natural recursive implementation of the
2349      CV-qualifiers would cause subsets to be substitutable, so instead
2350      we pull them all off now.
2351
2352      FIXME: The ABI says that order-insensitive vendor qualifiers
2353      should be handled in the same way, but we have no way to tell
2354      which vendor qualifiers are order-insensitive and which are
2355      order-sensitive.  So we just assume that they are all
2356      order-sensitive.  g++ 3.4 supports only one vendor qualifier,
2357      __vector, and it treats it as order-sensitive when mangling
2358      names.  */
2359
2360   if (next_is_type_qual (di))
2361     {
2362       struct demangle_component **pret;
2363
2364       pret = d_cv_qualifiers (di, &ret, 0);
2365       if (pret == NULL)
2366         return NULL;
2367       if (d_peek_char (di) == 'F')
2368         {
2369           /* cv-qualifiers before a function type apply to 'this',
2370              so avoid adding the unqualified function type to
2371              the substitution list.  */
2372           *pret = d_function_type (di);
2373         }
2374       else
2375         *pret = cplus_demangle_type (di);
2376       if (!*pret)
2377         return NULL;
2378       if ((*pret)->type == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS
2379           || (*pret)->type == DEMANGLE_COMPONENT_REFERENCE_THIS)
2380         {
2381           /* Move the ref-qualifier outside the cv-qualifiers so that
2382              they are printed in the right order.  */
2383           struct demangle_component *fn = d_left (*pret);
2384           d_left (*pret) = ret;
2385           ret = *pret;
2386           *pret = fn;
2387         }
2388       if (! d_add_substitution (di, ret))
2389         return NULL;
2390       return ret;
2391     }
2392
2393   can_subst = 1;
2394
2395   peek = d_peek_char (di);
2396   switch (peek)
2397     {
2398     case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2399     case 'h': case 'i': case 'j':           case 'l': case 'm': case 'n':
2400     case 'o':                               case 's': case 't':
2401     case 'v': case 'w': case 'x': case 'y': case 'z':
2402       ret = d_make_builtin_type (di,
2403                                  &cplus_demangle_builtin_types[peek - 'a']);
2404       di->expansion += ret->u.s_builtin.type->len;
2405       can_subst = 0;
2406       d_advance (di, 1);
2407       break;
2408
2409     case 'u':
2410       d_advance (di, 1);
2411       ret = d_make_comp (di, DEMANGLE_COMPONENT_VENDOR_TYPE,
2412                          d_source_name (di), NULL);
2413       break;
2414
2415     case 'F':
2416       ret = d_function_type (di);
2417       break;
2418
2419     case '0': case '1': case '2': case '3': case '4':
2420     case '5': case '6': case '7': case '8': case '9':
2421     case 'N':
2422     case 'Z':
2423       ret = d_class_enum_type (di);
2424       break;
2425
2426     case 'A':
2427       ret = d_array_type (di);
2428       break;
2429
2430     case 'M':
2431       ret = d_pointer_to_member_type (di);
2432       break;
2433
2434     case 'T':
2435       ret = d_template_param (di);
2436       if (d_peek_char (di) == 'I')
2437         {
2438           /* This may be <template-template-param> <template-args>.
2439              If this is the type for a conversion operator, we can
2440              have a <template-template-param> here only by following
2441              a derivation like this:
2442
2443              <nested-name>
2444              -> <template-prefix> <template-args>
2445              -> <prefix> <template-unqualified-name> <template-args>
2446              -> <unqualified-name> <template-unqualified-name> <template-args>
2447              -> <source-name> <template-unqualified-name> <template-args>
2448              -> <source-name> <operator-name> <template-args>
2449              -> <source-name> cv <type> <template-args>
2450              -> <source-name> cv <template-template-param> <template-args> <template-args>
2451
2452              where the <template-args> is followed by another.
2453              Otherwise, we must have a derivation like this:
2454
2455              <nested-name>
2456              -> <template-prefix> <template-args>
2457              -> <prefix> <template-unqualified-name> <template-args>
2458              -> <unqualified-name> <template-unqualified-name> <template-args>
2459              -> <source-name> <template-unqualified-name> <template-args>
2460              -> <source-name> <operator-name> <template-args>
2461              -> <source-name> cv <type> <template-args>
2462              -> <source-name> cv <template-param> <template-args>
2463
2464              where we need to leave the <template-args> to be processed
2465              by d_prefix (following the <template-prefix>).
2466
2467              The <template-template-param> part is a substitution
2468              candidate.  */
2469           if (! di->is_conversion)
2470             {
2471               if (! d_add_substitution (di, ret))
2472                 return NULL;
2473               ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
2474                                  d_template_args (di));
2475             }
2476           else
2477             {
2478               struct demangle_component *args;
2479               struct d_info_checkpoint checkpoint;
2480
2481               d_checkpoint (di, &checkpoint);
2482               args = d_template_args (di);
2483               if (d_peek_char (di) == 'I')
2484                 {
2485                   if (! d_add_substitution (di, ret))
2486                     return NULL;
2487                   ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
2488                                      args);
2489                 }
2490               else
2491                 d_backtrack (di, &checkpoint);
2492             }
2493         }
2494       break;
2495
2496     case 'S':
2497       /* If this is a special substitution, then it is the start of
2498          <class-enum-type>.  */
2499       {
2500         char peek_next;
2501
2502         peek_next = d_peek_next_char (di);
2503         if (IS_DIGIT (peek_next)
2504             || peek_next == '_'
2505             || IS_UPPER (peek_next))
2506           {
2507             ret = d_substitution (di, 0);
2508             /* The substituted name may have been a template name and
2509                may be followed by tepmlate args.  */
2510             if (d_peek_char (di) == 'I')
2511               ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
2512                                  d_template_args (di));
2513             else
2514               can_subst = 0;
2515           }
2516         else
2517           {
2518             ret = d_class_enum_type (di);
2519             /* If the substitution was a complete type, then it is not
2520                a new substitution candidate.  However, if the
2521                substitution was followed by template arguments, then
2522                the whole thing is a substitution candidate.  */
2523             if (ret != NULL && ret->type == DEMANGLE_COMPONENT_SUB_STD)
2524               can_subst = 0;
2525           }
2526       }
2527       break;
2528
2529     case 'O':
2530       d_advance (di, 1);
2531       ret = d_make_comp (di, DEMANGLE_COMPONENT_RVALUE_REFERENCE,
2532                          cplus_demangle_type (di), NULL);
2533       break;
2534
2535     case 'P':
2536       d_advance (di, 1);
2537       ret = d_make_comp (di, DEMANGLE_COMPONENT_POINTER,
2538                          cplus_demangle_type (di), NULL);
2539       break;
2540
2541     case 'R':
2542       d_advance (di, 1);
2543       ret = d_make_comp (di, DEMANGLE_COMPONENT_REFERENCE,
2544                          cplus_demangle_type (di), NULL);
2545       break;
2546
2547     case 'C':
2548       d_advance (di, 1);
2549       ret = d_make_comp (di, DEMANGLE_COMPONENT_COMPLEX,
2550                          cplus_demangle_type (di), NULL);
2551       break;
2552
2553     case 'G':
2554       d_advance (di, 1);
2555       ret = d_make_comp (di, DEMANGLE_COMPONENT_IMAGINARY,
2556                          cplus_demangle_type (di), NULL);
2557       break;
2558
2559     case 'U':
2560       d_advance (di, 1);
2561       ret = d_source_name (di);
2562       if (d_peek_char (di) == 'I')
2563         ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
2564                            d_template_args (di));
2565       ret = d_make_comp (di, DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL,
2566                          cplus_demangle_type (di), ret);
2567       break;
2568
2569     case 'D':
2570       can_subst = 0;
2571       d_advance (di, 1);
2572       peek = d_next_char (di);
2573       switch (peek)
2574         {
2575         case 'T':
2576         case 't':
2577           /* decltype (expression) */
2578           ret = d_make_comp (di, DEMANGLE_COMPONENT_DECLTYPE,
2579                              d_expression (di), NULL);
2580           if (ret && d_next_char (di) != 'E')
2581             ret = NULL;
2582           can_subst = 1;
2583           break;
2584           
2585         case 'p':
2586           /* Pack expansion.  */
2587           ret = d_make_comp (di, DEMANGLE_COMPONENT_PACK_EXPANSION,
2588                              cplus_demangle_type (di), NULL);
2589           can_subst = 1;
2590           break;
2591
2592         case 'a':
2593           /* auto */
2594           ret = d_make_name (di, "auto", 4);
2595           break;
2596           
2597         case 'f':
2598           /* 32-bit decimal floating point */
2599           ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[26]);
2600           di->expansion += ret->u.s_builtin.type->len;
2601           break;
2602         case 'd':
2603           /* 64-bit DFP */
2604           ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[27]);
2605           di->expansion += ret->u.s_builtin.type->len;
2606           break;
2607         case 'e':
2608           /* 128-bit DFP */
2609           ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[28]);
2610           di->expansion += ret->u.s_builtin.type->len;
2611           break;
2612         case 'h':
2613           /* 16-bit half-precision FP */
2614           ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[29]);
2615           di->expansion += ret->u.s_builtin.type->len;
2616           break;
2617         case 's':
2618           /* char16_t */
2619           ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[30]);
2620           di->expansion += ret->u.s_builtin.type->len;
2621           break;
2622         case 'i':
2623           /* char32_t */
2624           ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[31]);
2625           di->expansion += ret->u.s_builtin.type->len;
2626           break;
2627
2628         case 'F':
2629           /* Fixed point types. DF<int bits><length><fract bits><sat>  */
2630           ret = d_make_empty (di);
2631           ret->type = DEMANGLE_COMPONENT_FIXED_TYPE;
2632           if ((ret->u.s_fixed.accum = IS_DIGIT (d_peek_char (di))))
2633             /* For demangling we don't care about the bits.  */
2634             d_number (di);
2635           ret->u.s_fixed.length = cplus_demangle_type (di);
2636           if (ret->u.s_fixed.length == NULL)
2637             return NULL;
2638           d_number (di);
2639           peek = d_next_char (di);
2640           ret->u.s_fixed.sat = (peek == 's');
2641           break;
2642
2643         case 'v':
2644           ret = d_vector_type (di);
2645           can_subst = 1;
2646           break;
2647
2648         case 'n':
2649           /* decltype(nullptr) */
2650           ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[32]);
2651           di->expansion += ret->u.s_builtin.type->len;
2652           break;
2653
2654         default:
2655           return NULL;
2656         }
2657       break;
2658
2659     default:
2660       return NULL;
2661     }
2662
2663   if (can_subst)
2664     {
2665       if (! d_add_substitution (di, ret))
2666         return NULL;
2667     }
2668
2669   return ret;
2670 }
2671
2672 /* <CV-qualifiers> ::= [r] [V] [K] [Dx] */
2673
2674 static struct demangle_component **
2675 d_cv_qualifiers (struct d_info *di,
2676                  struct demangle_component **pret, int member_fn)
2677 {
2678   struct demangle_component **pstart;
2679   char peek;
2680
2681   pstart = pret;
2682   peek = d_peek_char (di);
2683   while (next_is_type_qual (di))
2684     {
2685       enum demangle_component_type t;
2686       struct demangle_component *right = NULL;
2687
2688       d_advance (di, 1);
2689       if (peek == 'r')
2690         {
2691           t = (member_fn
2692                ? DEMANGLE_COMPONENT_RESTRICT_THIS
2693                : DEMANGLE_COMPONENT_RESTRICT);
2694           di->expansion += sizeof "restrict";
2695         }
2696       else if (peek == 'V')
2697         {
2698           t = (member_fn
2699                ? DEMANGLE_COMPONENT_VOLATILE_THIS
2700                : DEMANGLE_COMPONENT_VOLATILE);
2701           di->expansion += sizeof "volatile";
2702         }
2703       else if (peek == 'K')
2704         {
2705           t = (member_fn
2706                ? DEMANGLE_COMPONENT_CONST_THIS
2707                : DEMANGLE_COMPONENT_CONST);
2708           di->expansion += sizeof "const";
2709         }
2710       else
2711         {
2712           peek = d_next_char (di);
2713           if (peek == 'x')
2714             {
2715               t = DEMANGLE_COMPONENT_TRANSACTION_SAFE;
2716               di->expansion += sizeof "transaction_safe";
2717             }
2718           else if (peek == 'o'
2719                    || peek == 'O')
2720             {
2721               t = DEMANGLE_COMPONENT_NOEXCEPT;
2722               di->expansion += sizeof "noexcept";
2723               if (peek == 'O')
2724                 {
2725                   right = d_expression (di);
2726                   if (right == NULL)
2727                     return NULL;
2728                   if (! d_check_char (di, 'E'))
2729                     return NULL;
2730                 }
2731             }
2732           else if (peek == 'w')
2733             {
2734               t = DEMANGLE_COMPONENT_THROW_SPEC;
2735               di->expansion += sizeof "throw";
2736               right = d_parmlist (di);
2737               if (right == NULL)
2738                 return NULL;
2739               if (! d_check_char (di, 'E'))
2740                 return NULL;
2741             }
2742           else
2743             return NULL;
2744         }
2745
2746       *pret = d_make_comp (di, t, NULL, right);
2747       if (*pret == NULL)
2748         return NULL;
2749       pret = &d_left (*pret);
2750
2751       peek = d_peek_char (di);
2752     }
2753
2754   if (!member_fn && peek == 'F')
2755     {
2756       while (pstart != pret)
2757         {
2758           switch ((*pstart)->type)
2759             {
2760             case DEMANGLE_COMPONENT_RESTRICT:
2761               (*pstart)->type = DEMANGLE_COMPONENT_RESTRICT_THIS;
2762               break;
2763             case DEMANGLE_COMPONENT_VOLATILE:
2764               (*pstart)->type = DEMANGLE_COMPONENT_VOLATILE_THIS;
2765               break;
2766             case DEMANGLE_COMPONENT_CONST:
2767               (*pstart)->type = DEMANGLE_COMPONENT_CONST_THIS;
2768               break;
2769             default:
2770               break;
2771             }
2772           pstart = &d_left (*pstart);
2773         }
2774     }
2775
2776   return pret;
2777 }
2778
2779 /* <ref-qualifier> ::= R
2780                    ::= O */
2781
2782 static struct demangle_component *
2783 d_ref_qualifier (struct d_info *di, struct demangle_component *sub)
2784 {
2785   struct demangle_component *ret = sub;
2786   char peek;
2787
2788   peek = d_peek_char (di);
2789   if (peek == 'R' || peek == 'O')
2790     {
2791       enum demangle_component_type t;
2792       if (peek == 'R')
2793         {
2794           t = DEMANGLE_COMPONENT_REFERENCE_THIS;
2795           di->expansion += sizeof "&";
2796         }
2797       else
2798         {
2799           t = DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS;
2800           di->expansion += sizeof "&&";
2801         }
2802       d_advance (di, 1);
2803
2804       ret = d_make_comp (di, t, ret, NULL);
2805     }
2806
2807   return ret;
2808 }
2809
2810 /* <function-type> ::= F [Y] <bare-function-type> [<ref-qualifier>] [T] E  */
2811
2812 static struct demangle_component *
2813 d_function_type (struct d_info *di)
2814 {
2815   struct demangle_component *ret;
2816
2817   if (! d_check_char (di, 'F'))
2818     return NULL;
2819   if (d_peek_char (di) == 'Y')
2820     {
2821       /* Function has C linkage.  We don't print this information.
2822          FIXME: We should print it in verbose mode.  */
2823       d_advance (di, 1);
2824     }
2825   ret = d_bare_function_type (di, 1);
2826   ret = d_ref_qualifier (di, ret);
2827
2828   if (! d_check_char (di, 'E'))
2829     return NULL;
2830   return ret;
2831 }
2832
2833 /* <type>+ */
2834
2835 static struct demangle_component *
2836 d_parmlist (struct d_info *di)
2837 {
2838   struct demangle_component *tl;
2839   struct demangle_component **ptl;
2840
2841   tl = NULL;
2842   ptl = &tl;
2843   while (1)
2844     {
2845       struct demangle_component *type;
2846
2847       char peek = d_peek_char (di);
2848       if (peek == '\0' || peek == 'E' || peek == '.')
2849         break;
2850       if ((peek == 'R' || peek == 'O')
2851           && d_peek_next_char (di) == 'E')
2852         /* Function ref-qualifier, not a ref prefix for a parameter type.  */
2853         break;
2854       type = cplus_demangle_type (di);
2855       if (type == NULL)
2856         return NULL;
2857       *ptl = d_make_comp (di, DEMANGLE_COMPONENT_ARGLIST, type, NULL);
2858       if (*ptl == NULL)
2859         return NULL;
2860       ptl = &d_right (*ptl);
2861     }
2862
2863   /* There should be at least one parameter type besides the optional
2864      return type.  A function which takes no arguments will have a
2865      single parameter type void.  */
2866   if (tl == NULL)
2867     return NULL;
2868
2869   /* If we have a single parameter type void, omit it.  */
2870   if (d_right (tl) == NULL
2871       && d_left (tl)->type == DEMANGLE_COMPONENT_BUILTIN_TYPE
2872       && d_left (tl)->u.s_builtin.type->print == D_PRINT_VOID)
2873     {
2874       di->expansion -= d_left (tl)->u.s_builtin.type->len;
2875       d_left (tl) = NULL;
2876     }
2877
2878   return tl;
2879 }
2880
2881 /* <bare-function-type> ::= [J]<type>+  */
2882
2883 static struct demangle_component *
2884 d_bare_function_type (struct d_info *di, int has_return_type)
2885 {
2886   struct demangle_component *return_type;
2887   struct demangle_component *tl;
2888   char peek;
2889
2890   /* Detect special qualifier indicating that the first argument
2891      is the return type.  */
2892   peek = d_peek_char (di);
2893   if (peek == 'J')
2894     {
2895       d_advance (di, 1);
2896       has_return_type = 1;
2897     }
2898
2899   if (has_return_type)
2900     {
2901       return_type = cplus_demangle_type (di);
2902       if (return_type == NULL)
2903         return NULL;
2904     }
2905   else
2906     return_type = NULL;
2907
2908   tl = d_parmlist (di);
2909   if (tl == NULL)
2910     return NULL;
2911
2912   return d_make_comp (di, DEMANGLE_COMPONENT_FUNCTION_TYPE,
2913                       return_type, tl);
2914 }
2915
2916 /* <class-enum-type> ::= <name>  */
2917
2918 static struct demangle_component *
2919 d_class_enum_type (struct d_info *di)
2920 {
2921   return d_name (di);
2922 }
2923
2924 /* <array-type> ::= A <(positive dimension) number> _ <(element) type>
2925                 ::= A [<(dimension) expression>] _ <(element) type>
2926 */
2927
2928 static struct demangle_component *
2929 d_array_type (struct d_info *di)
2930 {
2931   char peek;
2932   struct demangle_component *dim;
2933
2934   if (! d_check_char (di, 'A'))
2935     return NULL;
2936
2937   peek = d_peek_char (di);
2938   if (peek == '_')
2939     dim = NULL;
2940   else if (IS_DIGIT (peek))
2941     {
2942       const char *s;
2943
2944       s = d_str (di);
2945       do
2946         {
2947           d_advance (di, 1);
2948           peek = d_peek_char (di);
2949         }
2950       while (IS_DIGIT (peek));
2951       dim = d_make_name (di, s, d_str (di) - s);
2952       if (dim == NULL)
2953         return NULL;
2954     }
2955   else
2956     {
2957       dim = d_expression (di);
2958       if (dim == NULL)
2959         return NULL;
2960     }
2961
2962   if (! d_check_char (di, '_'))
2963     return NULL;
2964
2965   return d_make_comp (di, DEMANGLE_COMPONENT_ARRAY_TYPE, dim,
2966                       cplus_demangle_type (di));
2967 }
2968
2969 /* <vector-type> ::= Dv <number> _ <type>
2970                  ::= Dv _ <expression> _ <type> */
2971
2972 static struct demangle_component *
2973 d_vector_type (struct d_info *di)
2974 {
2975   char peek;
2976   struct demangle_component *dim;
2977
2978   peek = d_peek_char (di);
2979   if (peek == '_')
2980     {
2981       d_advance (di, 1);
2982       dim = d_expression (di);
2983     }
2984   else
2985     dim = d_number_component (di);
2986
2987   if (dim == NULL)
2988     return NULL;
2989
2990   if (! d_check_char (di, '_'))
2991     return NULL;
2992
2993   return d_make_comp (di, DEMANGLE_COMPONENT_VECTOR_TYPE, dim,
2994                       cplus_demangle_type (di));
2995 }
2996
2997 /* <pointer-to-member-type> ::= M <(class) type> <(member) type>  */
2998
2999 static struct demangle_component *
3000 d_pointer_to_member_type (struct d_info *di)
3001 {
3002   struct demangle_component *cl;
3003   struct demangle_component *mem;
3004
3005   if (! d_check_char (di, 'M'))
3006     return NULL;
3007
3008   cl = cplus_demangle_type (di);
3009   if (cl == NULL)
3010     return NULL;
3011
3012   /* The ABI says, "The type of a non-static member function is considered
3013      to be different, for the purposes of substitution, from the type of a
3014      namespace-scope or static member function whose type appears
3015      similar. The types of two non-static member functions are considered
3016      to be different, for the purposes of substitution, if the functions
3017      are members of different classes. In other words, for the purposes of
3018      substitution, the class of which the function is a member is
3019      considered part of the type of function."
3020
3021      For a pointer to member function, this call to cplus_demangle_type
3022      will end up adding a (possibly qualified) non-member function type to
3023      the substitution table, which is not correct; however, the member
3024      function type will never be used in a substitution, so putting the
3025      wrong type in the substitution table is harmless.  */
3026
3027   mem = cplus_demangle_type (di);
3028   if (mem == NULL)
3029     return NULL;
3030
3031   return d_make_comp (di, DEMANGLE_COMPONENT_PTRMEM_TYPE, cl, mem);
3032 }
3033
3034 /* <non-negative number> _ */
3035
3036 static int
3037 d_compact_number (struct d_info *di)
3038 {
3039   int num;
3040   if (d_peek_char (di) == '_')
3041     num = 0;
3042   else if (d_peek_char (di) == 'n')
3043     return -1;
3044   else
3045     num = d_number (di) + 1;
3046
3047   if (num < 0 || ! d_check_char (di, '_'))
3048     return -1;
3049   return num;
3050 }
3051
3052 /* <template-param> ::= T_
3053                     ::= T <(parameter-2 non-negative) number> _
3054 */
3055
3056 static struct demangle_component *
3057 d_template_param (struct d_info *di)
3058 {
3059   int param;
3060
3061   if (! d_check_char (di, 'T'))
3062     return NULL;
3063
3064   param = d_compact_number (di);
3065   if (param < 0)
3066     return NULL;
3067
3068   ++di->did_subs;
3069
3070   return d_make_template_param (di, param);
3071 }
3072
3073 /* <template-args> ::= I <template-arg>+ E  */
3074
3075 static struct demangle_component *
3076 d_template_args (struct d_info *di)
3077 {
3078   if (d_peek_char (di) != 'I'
3079       && d_peek_char (di) != 'J')
3080     return NULL;
3081   d_advance (di, 1);
3082
3083   return d_template_args_1 (di);
3084 }
3085
3086 /* <template-arg>* E  */
3087
3088 static struct demangle_component *
3089 d_template_args_1 (struct d_info *di)
3090 {
3091   struct demangle_component *hold_last_name;
3092   struct demangle_component *al;
3093   struct demangle_component **pal;
3094
3095   /* Preserve the last name we saw--don't let the template arguments
3096      clobber it, as that would give us the wrong name for a subsequent
3097      constructor or destructor.  */
3098   hold_last_name = di->last_name;
3099
3100   if (d_peek_char (di) == 'E')
3101     {
3102       /* An argument pack can be empty.  */
3103       d_advance (di, 1);
3104       return d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE_ARGLIST, NULL, NULL);
3105     }
3106
3107   al = NULL;
3108   pal = &al;
3109   while (1)
3110     {
3111       struct demangle_component *a;
3112
3113       a = d_template_arg (di);
3114       if (a == NULL)
3115         return NULL;
3116
3117       *pal = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE_ARGLIST, a, NULL);
3118       if (*pal == NULL)
3119         return NULL;
3120       pal = &d_right (*pal);
3121
3122       if (d_peek_char (di) == 'E')
3123         {
3124           d_advance (di, 1);
3125           break;
3126         }
3127     }
3128
3129   di->last_name = hold_last_name;
3130
3131   return al;
3132 }
3133
3134 /* <template-arg> ::= <type>
3135                   ::= X <expression> E
3136                   ::= <expr-primary>
3137 */
3138
3139 static struct demangle_component *
3140 d_template_arg (struct d_info *di)
3141 {
3142   struct demangle_component *ret;
3143
3144   switch (d_peek_char (di))
3145     {
3146     case 'X':
3147       d_advance (di, 1);
3148       ret = d_expression (di);
3149       if (! d_check_char (di, 'E'))
3150         return NULL;
3151       return ret;
3152
3153     case 'L':
3154       return d_expr_primary (di);
3155
3156     case 'I':
3157     case 'J':
3158       /* An argument pack.  */
3159       return d_template_args (di);
3160
3161     default:
3162       return cplus_demangle_type (di);
3163     }
3164 }
3165
3166 /* Parse a sequence of expressions until we hit the terminator
3167    character.  */
3168
3169 static struct demangle_component *
3170 d_exprlist (struct d_info *di, char terminator)
3171 {
3172   struct demangle_component *list = NULL;
3173   struct demangle_component **p = &list;
3174
3175   if (d_peek_char (di) == terminator)
3176     {
3177       d_advance (di, 1);
3178       return d_make_comp (di, DEMANGLE_COMPONENT_ARGLIST, NULL, NULL);
3179     }
3180
3181   while (1)
3182     {
3183       struct demangle_component *arg = d_expression (di);
3184       if (arg == NULL)
3185         return NULL;
3186
3187       *p = d_make_comp (di, DEMANGLE_COMPONENT_ARGLIST, arg, NULL);
3188       if (*p == NULL)
3189         return NULL;
3190       p = &d_right (*p);
3191
3192       if (d_peek_char (di) == terminator)
3193         {
3194           d_advance (di, 1);
3195           break;
3196         }
3197     }
3198
3199   return list;
3200 }
3201
3202 /* Returns nonzero iff OP is an operator for a C++ cast: const_cast,
3203    dynamic_cast, static_cast or reinterpret_cast.  */
3204
3205 static int
3206 op_is_new_cast (struct demangle_component *op)
3207 {
3208   const char *code = op->u.s_operator.op->code;
3209   return (code[1] == 'c'
3210           && (code[0] == 's' || code[0] == 'd'
3211               || code[0] == 'c' || code[0] == 'r'));
3212 }
3213
3214 /* <expression> ::= <(unary) operator-name> <expression>
3215                 ::= <(binary) operator-name> <expression> <expression>
3216                 ::= <(trinary) operator-name> <expression> <expression> <expression>
3217                 ::= cl <expression>+ E
3218                 ::= st <type>
3219                 ::= <template-param>
3220                 ::= sr <type> <unqualified-name>
3221                 ::= sr <type> <unqualified-name> <template-args>
3222                 ::= <expr-primary>
3223 */
3224
3225 static inline struct demangle_component *
3226 d_expression_1 (struct d_info *di)
3227 {
3228   char peek;
3229
3230   peek = d_peek_char (di);
3231   if (peek == 'L')
3232     return d_expr_primary (di);
3233   else if (peek == 'T')
3234     return d_template_param (di);
3235   else if (peek == 's' && d_peek_next_char (di) == 'r')
3236     {
3237       struct demangle_component *type;
3238       struct demangle_component *name;
3239
3240       d_advance (di, 2);
3241       type = cplus_demangle_type (di);
3242       name = d_unqualified_name (di);
3243       if (d_peek_char (di) != 'I')
3244         return d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME, type, name);
3245       else
3246         return d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME, type,
3247                             d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, name,
3248                                          d_template_args (di)));
3249     }
3250   else if (peek == 's' && d_peek_next_char (di) == 'p')
3251     {
3252       d_advance (di, 2);
3253       return d_make_comp (di, DEMANGLE_COMPONENT_PACK_EXPANSION,
3254                           d_expression_1 (di), NULL);
3255     }
3256   else if (peek == 'f' && d_peek_next_char (di) == 'p')
3257     {
3258       /* Function parameter used in a late-specified return type.  */
3259       int index;
3260       d_advance (di, 2);
3261       if (d_peek_char (di) == 'T')
3262         {
3263           /* 'this' parameter.  */
3264           d_advance (di, 1);
3265           index = 0;
3266         }
3267       else
3268         {
3269           index = d_compact_number (di);
3270           if (index == INT_MAX || index == -1)
3271             return NULL;
3272           index++;
3273         }
3274       return d_make_function_param (di, index);
3275     }
3276   else if (IS_DIGIT (peek)
3277            || (peek == 'o' && d_peek_next_char (di) == 'n'))
3278     {
3279       /* We can get an unqualified name as an expression in the case of
3280          a dependent function call, i.e. decltype(f(t)).  */
3281       struct demangle_component *name;
3282
3283       if (peek == 'o')
3284         /* operator-function-id, i.e. operator+(t).  */
3285         d_advance (di, 2);
3286
3287       name = d_unqualified_name (di);
3288       if (name == NULL)
3289         return NULL;
3290       if (d_peek_char (di) == 'I')
3291         return d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, name,
3292                             d_template_args (di));
3293       else
3294         return name;
3295     }
3296   else if ((peek == 'i' || peek == 't')
3297            && d_peek_next_char (di) == 'l')
3298     {
3299       /* Brace-enclosed initializer list, untyped or typed.  */
3300       struct demangle_component *type = NULL;
3301       if (peek == 't')
3302         type = cplus_demangle_type (di);
3303       if (!d_peek_next_char (di))
3304         return NULL;
3305       d_advance (di, 2);
3306       return d_make_comp (di, DEMANGLE_COMPONENT_INITIALIZER_LIST,
3307                           type, d_exprlist (di, 'E'));
3308     }
3309   else
3310     {
3311       struct demangle_component *op;
3312       const char *code = NULL;
3313       int args;
3314
3315       op = d_operator_name (di);
3316       if (op == NULL)
3317         return NULL;
3318
3319       if (op->type == DEMANGLE_COMPONENT_OPERATOR)
3320         {
3321           code = op->u.s_operator.op->code;
3322           di->expansion += op->u.s_operator.op->len - 2;
3323           if (strcmp (code, "st") == 0)
3324             return d_make_comp (di, DEMANGLE_COMPONENT_UNARY, op,
3325                                 cplus_demangle_type (di));
3326         }
3327
3328       switch (op->type)
3329         {
3330         default:
3331           return NULL;
3332         case DEMANGLE_COMPONENT_OPERATOR:
3333           args = op->u.s_operator.op->args;
3334           break;
3335         case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
3336           args = op->u.s_extended_operator.args;
3337           break;
3338         case DEMANGLE_COMPONENT_CAST:
3339           args = 1;
3340           break;
3341         }
3342
3343       switch (args)
3344         {
3345         case 0:
3346           return d_make_comp (di, DEMANGLE_COMPONENT_NULLARY, op, NULL);
3347
3348         case 1:
3349           {
3350             struct demangle_component *operand;
3351             int suffix = 0;
3352
3353             if (code && (code[0] == 'p' || code[0] == 'm')
3354                 && code[1] == code[0])
3355               /* pp_ and mm_ are the prefix variants.  */
3356               suffix = !d_check_char (di, '_');
3357
3358             if (op->type == DEMANGLE_COMPONENT_CAST
3359                 && d_check_char (di, '_'))
3360               operand = d_exprlist (di, 'E');
3361             else if (code && !strcmp (code, "sP"))
3362               operand = d_template_args_1 (di);
3363             else
3364               operand = d_expression_1 (di);
3365
3366             if (suffix)
3367               /* Indicate the suffix variant for d_print_comp.  */
3368               return d_make_comp (di, DEMANGLE_COMPONENT_UNARY, op,
3369                                   d_make_comp (di,
3370                                                DEMANGLE_COMPONENT_BINARY_ARGS,
3371                                                operand, operand));
3372             else
3373               return d_make_comp (di, DEMANGLE_COMPONENT_UNARY, op,
3374                                   operand);
3375           }
3376         case 2:
3377           {
3378             struct demangle_component *left;
3379             struct demangle_component *right;
3380
3381             if (code == NULL)
3382               return NULL;
3383             if (op_is_new_cast (op))
3384               left = cplus_demangle_type (di);
3385             else if (code[0] == 'f')
3386               /* fold-expression.  */
3387               left = d_operator_name (di);
3388             else
3389               left = d_expression_1 (di);
3390             if (!strcmp (code, "cl"))
3391               right = d_exprlist (di, 'E');
3392             else if (!strcmp (code, "dt") || !strcmp (code, "pt"))
3393               {
3394                 right = d_unqualified_name (di);
3395                 if (d_peek_char (di) == 'I')
3396                   right = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE,
3397                                        right, d_template_args (di));
3398               }
3399             else
3400               right = d_expression_1 (di);
3401
3402             return d_make_comp (di, DEMANGLE_COMPONENT_BINARY, op,
3403                                 d_make_comp (di,
3404                                              DEMANGLE_COMPONENT_BINARY_ARGS,
3405                                              left, right));
3406           }
3407         case 3:
3408           {
3409             struct demangle_component *first;
3410             struct demangle_component *second;
3411             struct demangle_component *third;
3412
3413             if (code == NULL)
3414               return NULL;
3415             else if (!strcmp (code, "qu"))
3416               {
3417                 /* ?: expression.  */
3418                 first = d_expression_1 (di);
3419                 second = d_expression_1 (di);
3420                 third = d_expression_1 (di);
3421                 if (third == NULL)
3422                   return NULL;
3423               }
3424             else if (code[0] == 'f')
3425               {
3426                 /* fold-expression.  */
3427                 first = d_operator_name (di);
3428                 second = d_expression_1 (di);
3429                 third = d_expression_1 (di);
3430                 if (third == NULL)
3431                   return NULL;
3432               }
3433             else if (code[0] == 'n')
3434               {
3435                 /* new-expression.  */
3436                 if (code[1] != 'w' && code[1] != 'a')
3437                   return NULL;
3438                 first = d_exprlist (di, '_');
3439                 second = cplus_demangle_type (di);
3440                 if (d_peek_char (di) == 'E')
3441                   {
3442                     d_advance (di, 1);
3443                     third = NULL;
3444                   }
3445                 else if (d_peek_char (di) == 'p'
3446                          && d_peek_next_char (di) == 'i')
3447                   {
3448                     /* Parenthesized initializer.  */
3449                     d_advance (di, 2);
3450                     third = d_exprlist (di, 'E');
3451                   }
3452                 else if (d_peek_char (di) == 'i'
3453                          && d_peek_next_char (di) == 'l')
3454                   /* initializer-list.  */
3455                   third = d_expression_1 (di);
3456                 else
3457                   return NULL;
3458               }
3459             else
3460               return NULL;
3461             return d_make_comp (di, DEMANGLE_COMPONENT_TRINARY, op,
3462                                 d_make_comp (di,
3463                                              DEMANGLE_COMPONENT_TRINARY_ARG1,
3464                                              first,
3465                                              d_make_comp (di,
3466                                                           DEMANGLE_COMPONENT_TRINARY_ARG2,
3467                                                           second, third)));
3468           }
3469         default:
3470           return NULL;
3471         }
3472     }
3473 }
3474
3475 static struct demangle_component *
3476 d_expression (struct d_info *di)
3477 {
3478   struct demangle_component *ret;
3479   int was_expression = di->is_expression;
3480
3481   di->is_expression = 1;
3482   ret = d_expression_1 (di);
3483   di->is_expression = was_expression;
3484   return ret;
3485 }
3486
3487 /* <expr-primary> ::= L <type> <(value) number> E
3488                   ::= L <type> <(value) float> E
3489                   ::= L <mangled-name> E
3490 */
3491
3492 static struct demangle_component *
3493 d_expr_primary (struct d_info *di)
3494 {
3495   struct demangle_component *ret;
3496
3497   if (! d_check_char (di, 'L'))
3498     return NULL;
3499   if (d_peek_char (di) == '_'
3500       /* Workaround for G++ bug; see comment in write_template_arg.  */
3501       || d_peek_char (di) == 'Z')
3502     ret = cplus_demangle_mangled_name (di, 0);
3503   else
3504     {
3505       struct demangle_component *type;
3506       enum demangle_component_type t;
3507       const char *s;
3508
3509       type = cplus_demangle_type (di);
3510       if (type == NULL)
3511         return NULL;
3512
3513       /* If we have a type we know how to print, we aren't going to
3514          print the type name itself.  */
3515       if (type->type == DEMANGLE_COMPONENT_BUILTIN_TYPE
3516           && type->u.s_builtin.type->print != D_PRINT_DEFAULT)
3517         di->expansion -= type->u.s_builtin.type->len;
3518
3519       /* Rather than try to interpret the literal value, we just
3520          collect it as a string.  Note that it's possible to have a
3521          floating point literal here.  The ABI specifies that the
3522          format of such literals is machine independent.  That's fine,
3523          but what's not fine is that versions of g++ up to 3.2 with
3524          -fabi-version=1 used upper case letters in the hex constant,
3525          and dumped out gcc's internal representation.  That makes it
3526          hard to tell where the constant ends, and hard to dump the
3527          constant in any readable form anyhow.  We don't attempt to
3528          handle these cases.  */
3529
3530       t = DEMANGLE_COMPONENT_LITERAL;
3531       if (d_peek_char (di) == 'n')
3532         {
3533           t = DEMANGLE_COMPONENT_LITERAL_NEG;
3534           d_advance (di, 1);
3535         }
3536       s = d_str (di);
3537       while (d_peek_char (di) != 'E')
3538         {
3539           if (d_peek_char (di) == '\0')
3540             return NULL;
3541           d_advance (di, 1);
3542         }
3543       ret = d_make_comp (di, t, type, d_make_name (di, s, d_str (di) - s));
3544     }
3545   if (! d_check_char (di, 'E'))
3546     return NULL;
3547   return ret;
3548 }
3549
3550 /* <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
3551                 ::= Z <(function) encoding> E s [<discriminator>]
3552                 ::= Z <(function) encoding> E d [<parameter> number>] _ <entity name>
3553 */
3554
3555 static struct demangle_component *
3556 d_local_name (struct d_info *di)
3557 {
3558   struct demangle_component *function;
3559
3560   if (! d_check_char (di, 'Z'))
3561     return NULL;
3562
3563   function = d_encoding (di, 0);
3564
3565   if (! d_check_char (di, 'E'))
3566     return NULL;
3567
3568   if (d_peek_char (di) == 's')
3569     {
3570       d_advance (di, 1);
3571       if (! d_discriminator (di))
3572         return NULL;
3573       return d_make_comp (di, DEMANGLE_COMPONENT_LOCAL_NAME, function,
3574                           d_make_name (di, "string literal",
3575                                        sizeof "string literal" - 1));
3576     }
3577   else
3578     {
3579       struct demangle_component *name;
3580       int num = -1;
3581
3582       if (d_peek_char (di) == 'd')
3583         {
3584           /* Default argument scope: d <number> _.  */
3585           d_advance (di, 1);
3586           num = d_compact_number (di);
3587           if (num < 0)
3588             return NULL;
3589         }
3590
3591       name = d_name (di);
3592       if (name)
3593         switch (name->type)
3594           {
3595             /* Lambdas and unnamed types have internal discriminators.  */
3596           case DEMANGLE_COMPONENT_LAMBDA:
3597           case DEMANGLE_COMPONENT_UNNAMED_TYPE:
3598             break;
3599           default:
3600             if (! d_discriminator (di))
3601               return NULL;
3602           }
3603       if (num >= 0)
3604         name = d_make_default_arg (di, num, name);
3605       return d_make_comp (di, DEMANGLE_COMPONENT_LOCAL_NAME, function, name);
3606     }
3607 }
3608
3609 /* <discriminator> ::= _ <(non-negative) number>
3610
3611    We demangle the discriminator, but we don't print it out.  FIXME:
3612    We should print it out in verbose mode.  */
3613
3614 static int
3615 d_discriminator (struct d_info *di)
3616 {
3617   int discrim;
3618
3619   if (d_peek_char (di) != '_')
3620     return 1;
3621   d_advance (di, 1);
3622   discrim = d_number (di);
3623   if (discrim < 0)
3624     return 0;
3625   return 1;
3626 }
3627
3628 /* <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _ */
3629
3630 static struct demangle_component *
3631 d_lambda (struct d_info *di)
3632 {
3633   struct demangle_component *tl;
3634   struct demangle_component *ret;
3635   int num;
3636
3637   if (! d_check_char (di, 'U'))
3638     return NULL;
3639   if (! d_check_char (di, 'l'))
3640     return NULL;
3641
3642   tl = d_parmlist (di);
3643   if (tl == NULL)
3644     return NULL;
3645
3646   if (! d_check_char (di, 'E'))
3647     return NULL;
3648
3649   num = d_compact_number (di);
3650   if (num < 0)
3651     return NULL;
3652
3653   ret = d_make_empty (di);
3654   if (ret)
3655     {
3656       ret->type = DEMANGLE_COMPONENT_LAMBDA;
3657       ret->u.s_unary_num.sub = tl;
3658       ret->u.s_unary_num.num = num;
3659     }
3660
3661   if (! d_add_substitution (di, ret))
3662     return NULL;
3663
3664   return ret;
3665 }
3666
3667 /* <unnamed-type-name> ::= Ut [ <nonnegative number> ] _ */
3668
3669 static struct demangle_component *
3670 d_unnamed_type (struct d_info *di)
3671 {
3672   struct demangle_component *ret;
3673   int num;
3674
3675   if (! d_check_char (di, 'U'))
3676     return NULL;
3677   if (! d_check_char (di, 't'))
3678     return NULL;
3679
3680   num = d_compact_number (di);
3681   if (num < 0)
3682     return NULL;
3683
3684   ret = d_make_empty (di);
3685   if (ret)
3686     {
3687       ret->type = DEMANGLE_COMPONENT_UNNAMED_TYPE;
3688       ret->u.s_number.number = num;
3689     }
3690
3691   if (! d_add_substitution (di, ret))
3692     return NULL;
3693
3694   return ret;
3695 }
3696
3697 /* <clone-suffix> ::= [ . <clone-type-identifier> ] [ . <nonnegative number> ]*
3698 */
3699
3700 static struct demangle_component *
3701 d_clone_suffix (struct d_info *di, struct demangle_component *encoding)
3702 {
3703   const char *suffix = d_str (di);
3704   const char *pend = suffix;
3705   struct demangle_component *n;
3706
3707   if (*pend == '.' && (IS_LOWER (pend[1]) || pend[1] == '_'))
3708     {
3709       pend += 2;
3710       while (IS_LOWER (*pend) || *pend == '_')
3711         ++pend;
3712     }
3713   while (*pend == '.' && IS_DIGIT (pend[1]))
3714     {
3715       pend += 2;
3716       while (IS_DIGIT (*pend))
3717         ++pend;
3718     }
3719   d_advance (di, pend - suffix);
3720   n = d_make_name (di, suffix, pend - suffix);
3721   return d_make_comp (di, DEMANGLE_COMPONENT_CLONE, encoding, n);
3722 }
3723
3724 /* Add a new substitution.  */
3725
3726 static int
3727 d_add_substitution (struct d_info *di, struct demangle_component *dc)
3728 {
3729   if (dc == NULL)
3730     return 0;
3731   if (di->next_sub >= di->num_subs)
3732     return 0;
3733   di->subs[di->next_sub] = dc;
3734   ++di->next_sub;
3735   return 1;
3736 }
3737
3738 /* <substitution> ::= S <seq-id> _
3739                   ::= S_
3740                   ::= St
3741                   ::= Sa
3742                   ::= Sb
3743                   ::= Ss
3744                   ::= Si
3745                   ::= So
3746                   ::= Sd
3747
3748    If PREFIX is non-zero, then this type is being used as a prefix in
3749    a qualified name.  In this case, for the standard substitutions, we
3750    need to check whether we are being used as a prefix for a
3751    constructor or destructor, and return a full template name.
3752    Otherwise we will get something like std::iostream::~iostream()
3753    which does not correspond particularly well to any function which
3754    actually appears in the source.
3755 */
3756
3757 static const struct d_standard_sub_info standard_subs[] =
3758 {
3759   { 't', NL ("std"),
3760     NL ("std"),
3761     NULL, 0 },
3762   { 'a', NL ("std::allocator"),
3763     NL ("std::allocator"),
3764     NL ("allocator") },
3765   { 'b', NL ("std::basic_string"),
3766     NL ("std::basic_string"),
3767     NL ("basic_string") },
3768   { 's', NL ("std::string"),
3769     NL ("std::basic_string<char, std::char_traits<char>, std::allocator<char> >"),
3770     NL ("basic_string") },
3771   { 'i', NL ("std::istream"),
3772     NL ("std::basic_istream<char, std::char_traits<char> >"),
3773     NL ("basic_istream") },
3774   { 'o', NL ("std::ostream"),
3775     NL ("std::basic_ostream<char, std::char_traits<char> >"),
3776     NL ("basic_ostream") },
3777   { 'd', NL ("std::iostream"),
3778     NL ("std::basic_iostream<char, std::char_traits<char> >"),
3779     NL ("basic_iostream") }
3780 };
3781
3782 static struct demangle_component *
3783 d_substitution (struct d_info *di, int prefix)
3784 {
3785   char c;
3786
3787   if (! d_check_char (di, 'S'))
3788     return NULL;
3789
3790   c = d_next_char (di);
3791   if (c == '_' || IS_DIGIT (c) || IS_UPPER (c))
3792     {
3793       unsigned int id;
3794
3795       id = 0;
3796       if (c != '_')
3797         {
3798           do
3799             {
3800               unsigned int new_id;
3801
3802               if (IS_DIGIT (c))
3803                 new_id = id * 36 + c - '0';
3804               else if (IS_UPPER (c))
3805                 new_id = id * 36 + c - 'A' + 10;
3806               else
3807                 return NULL;
3808               if (new_id < id)
3809                 return NULL;
3810               id = new_id;
3811               c = d_next_char (di);
3812             }
3813           while (c != '_');
3814
3815           ++id;
3816         }
3817
3818       if (id >= (unsigned int) di->next_sub)
3819         return NULL;
3820
3821       ++di->did_subs;
3822
3823       return di->subs[id];
3824     }
3825   else
3826     {
3827       int verbose;
3828       const struct d_standard_sub_info *p;
3829       const struct d_standard_sub_info *pend;
3830
3831       verbose = (di->options & DMGL_VERBOSE) != 0;
3832       if (! verbose && prefix)
3833         {
3834           char peek;
3835
3836           peek = d_peek_char (di);
3837           if (peek == 'C' || peek == 'D')
3838             verbose = 1;
3839         }
3840
3841       pend = (&standard_subs[0]
3842               + sizeof standard_subs / sizeof standard_subs[0]);
3843       for (p = &standard_subs[0]; p < pend; ++p)
3844         {
3845           if (c == p->code)
3846             {
3847               const char *s;
3848               int len;
3849               struct demangle_component *dc;
3850
3851               if (p->set_last_name != NULL)
3852                 di->last_name = d_make_sub (di, p->set_last_name,
3853                                             p->set_last_name_len);
3854               if (verbose)
3855                 {
3856                   s = p->full_expansion;
3857                   len = p->full_len;
3858                 }
3859               else
3860                 {
3861                   s = p->simple_expansion;
3862                   len = p->simple_len;
3863                 }
3864               di->expansion += len;
3865               dc = d_make_sub (di, s, len);
3866               if (d_peek_char (di) == 'B')
3867                 {
3868                   /* If there are ABI tags on the abbreviation, it becomes
3869                      a substitution candidate.  */
3870                   dc = d_abi_tags (di, dc);
3871                   d_add_substitution (di, dc);
3872                 }
3873               return dc;
3874             }
3875         }
3876
3877       return NULL;
3878     }
3879 }
3880
3881 static void
3882 d_checkpoint (struct d_info *di, struct d_info_checkpoint *checkpoint)
3883 {
3884   checkpoint->n = di->n;
3885   checkpoint->next_comp = di->next_comp;
3886   checkpoint->next_sub = di->next_sub;
3887   checkpoint->did_subs = di->did_subs;
3888   checkpoint->expansion = di->expansion;
3889 }
3890
3891 static void
3892 d_backtrack (struct d_info *di, struct d_info_checkpoint *checkpoint)
3893 {
3894   di->n = checkpoint->n;
3895   di->next_comp = checkpoint->next_comp;
3896   di->next_sub = checkpoint->next_sub;
3897   di->did_subs = checkpoint->did_subs;
3898   di->expansion = checkpoint->expansion;
3899 }
3900
3901 /* Initialize a growable string.  */
3902
3903 static void
3904 d_growable_string_init (struct d_growable_string *dgs, size_t estimate)
3905 {
3906   dgs->buf = NULL;
3907   dgs->len = 0;
3908   dgs->alc = 0;
3909   dgs->allocation_failure = 0;
3910
3911   if (estimate > 0)
3912     d_growable_string_resize (dgs, estimate);
3913 }
3914
3915 /* Grow a growable string to a given size.  */
3916
3917 static inline void
3918 d_growable_string_resize (struct d_growable_string *dgs, size_t need)
3919 {
3920   size_t newalc;
3921   char *newbuf;
3922
3923   if (dgs->allocation_failure)
3924     return;
3925
3926   /* Start allocation at two bytes to avoid any possibility of confusion
3927      with the special value of 1 used as a return in *palc to indicate
3928      allocation failures.  */
3929   newalc = dgs->alc > 0 ? dgs->alc : 2;
3930   while (newalc < need)
3931     newalc <<= 1;
3932
3933   newbuf = (char *) realloc (dgs->buf, newalc);
3934   if (newbuf == NULL)
3935     {
3936       free (dgs->buf);
3937       dgs->buf = NULL;
3938       dgs->len = 0;
3939       dgs->alc = 0;
3940       dgs->allocation_failure = 1;
3941       return;
3942     }
3943   dgs->buf = newbuf;
3944   dgs->alc = newalc;
3945 }
3946
3947 /* Append a buffer to a growable string.  */
3948
3949 static inline void
3950 d_growable_string_append_buffer (struct d_growable_string *dgs,
3951                                  const char *s, size_t l)
3952 {
3953   size_t need;
3954
3955   need = dgs->len + l + 1;
3956   if (need > dgs->alc)
3957     d_growable_string_resize (dgs, need);
3958
3959   if (dgs->allocation_failure)
3960     return;
3961
3962   memcpy (dgs->buf + dgs->len, s, l);
3963   dgs->buf[dgs->len + l] = '\0';
3964   dgs->len += l;
3965 }
3966
3967 /* Bridge growable strings to the callback mechanism.  */
3968
3969 static void
3970 d_growable_string_callback_adapter (const char *s, size_t l, void *opaque)
3971 {
3972   struct d_growable_string *dgs = (struct d_growable_string*) opaque;
3973
3974   d_growable_string_append_buffer (dgs, s, l);
3975 }
3976
3977 /* Walk the tree, counting the number of templates encountered, and
3978    the number of times a scope might be saved.  These counts will be
3979    used to allocate data structures for d_print_comp, so the logic
3980    here must mirror the logic d_print_comp will use.  It is not
3981    important that the resulting numbers are exact, so long as they
3982    are larger than the actual numbers encountered.  */
3983
3984 static void
3985 d_count_templates_scopes (int *num_templates, int *num_scopes,
3986                           const struct demangle_component *dc)
3987 {
3988   if (dc == NULL)
3989     return;
3990
3991   switch (dc->type)
3992     {
3993     case DEMANGLE_COMPONENT_NAME:
3994     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
3995     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
3996     case DEMANGLE_COMPONENT_SUB_STD:
3997     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
3998     case DEMANGLE_COMPONENT_OPERATOR:
3999     case DEMANGLE_COMPONENT_CHARACTER:
4000     case DEMANGLE_COMPONENT_NUMBER:
4001     case DEMANGLE_COMPONENT_UNNAMED_TYPE:
4002       break;
4003
4004     case DEMANGLE_COMPONENT_TEMPLATE:
4005       (*num_templates)++;
4006       goto recurse_left_right;
4007
4008     case DEMANGLE_COMPONENT_REFERENCE:
4009     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
4010       if (d_left (dc)->type == DEMANGLE_COMPONENT_TEMPLATE_PARAM)
4011         (*num_scopes)++;
4012       goto recurse_left_right;
4013
4014     case DEMANGLE_COMPONENT_QUAL_NAME:
4015     case DEMANGLE_COMPONENT_LOCAL_NAME:
4016     case DEMANGLE_COMPONENT_TYPED_NAME:
4017     case DEMANGLE_COMPONENT_VTABLE:
4018     case DEMANGLE_COMPONENT_VTT:
4019     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
4020     case DEMANGLE_COMPONENT_TYPEINFO:
4021     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
4022     case DEMANGLE_COMPONENT_TYPEINFO_FN:
4023     case DEMANGLE_COMPONENT_THUNK:
4024     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
4025     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
4026     case DEMANGLE_COMPONENT_JAVA_CLASS:
4027     case DEMANGLE_COMPONENT_GUARD:
4028     case DEMANGLE_COMPONENT_TLS_INIT:
4029     case DEMANGLE_COMPONENT_TLS_WRAPPER:
4030     case DEMANGLE_COMPONENT_REFTEMP:
4031     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
4032     case DEMANGLE_COMPONENT_RESTRICT:
4033     case DEMANGLE_COMPONENT_VOLATILE:
4034     case DEMANGLE_COMPONENT_CONST:
4035     case DEMANGLE_COMPONENT_RESTRICT_THIS:
4036     case DEMANGLE_COMPONENT_VOLATILE_THIS:
4037     case DEMANGLE_COMPONENT_CONST_THIS:
4038     case DEMANGLE_COMPONENT_REFERENCE_THIS:
4039     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
4040     case DEMANGLE_COMPONENT_TRANSACTION_SAFE:
4041     case DEMANGLE_COMPONENT_NOEXCEPT:
4042     case DEMANGLE_COMPONENT_THROW_SPEC:
4043     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
4044     case DEMANGLE_COMPONENT_POINTER:
4045     case DEMANGLE_COMPONENT_COMPLEX:
4046     case DEMANGLE_COMPONENT_IMAGINARY:
4047     case DEMANGLE_COMPONENT_VENDOR_TYPE:
4048     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
4049     case DEMANGLE_COMPONENT_ARRAY_TYPE:
4050     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
4051     case DEMANGLE_COMPONENT_VECTOR_TYPE:
4052     case DEMANGLE_COMPONENT_ARGLIST:
4053     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
4054     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
4055     case DEMANGLE_COMPONENT_CAST:
4056     case DEMANGLE_COMPONENT_CONVERSION:
4057     case DEMANGLE_COMPONENT_NULLARY:
4058     case DEMANGLE_COMPONENT_UNARY:
4059     case DEMANGLE_COMPONENT_BINARY:
4060     case DEMANGLE_COMPONENT_BINARY_ARGS:
4061     case DEMANGLE_COMPONENT_TRINARY:
4062     case DEMANGLE_COMPONENT_TRINARY_ARG1:
4063     case DEMANGLE_COMPONENT_TRINARY_ARG2:
4064     case DEMANGLE_COMPONENT_LITERAL:
4065     case DEMANGLE_COMPONENT_LITERAL_NEG:
4066     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
4067     case DEMANGLE_COMPONENT_COMPOUND_NAME:
4068     case DEMANGLE_COMPONENT_DECLTYPE:
4069     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
4070     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
4071     case DEMANGLE_COMPONENT_PACK_EXPANSION:
4072     case DEMANGLE_COMPONENT_TAGGED_NAME:
4073     case DEMANGLE_COMPONENT_CLONE:
4074     recurse_left_right:
4075       d_count_templates_scopes (num_templates, num_scopes,
4076                                 d_left (dc));
4077       d_count_templates_scopes (num_templates, num_scopes,
4078                                 d_right (dc));
4079       break;
4080
4081     case DEMANGLE_COMPONENT_CTOR:
4082       d_count_templates_scopes (num_templates, num_scopes,
4083                                 dc->u.s_ctor.name);
4084       break;
4085
4086     case DEMANGLE_COMPONENT_DTOR:
4087       d_count_templates_scopes (num_templates, num_scopes,
4088                                 dc->u.s_dtor.name);
4089       break;
4090
4091     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
4092       d_count_templates_scopes (num_templates, num_scopes,
4093                                 dc->u.s_extended_operator.name);
4094       break;
4095
4096     case DEMANGLE_COMPONENT_FIXED_TYPE:
4097       d_count_templates_scopes (num_templates, num_scopes,
4098                                 dc->u.s_fixed.length);
4099       break;
4100
4101     case DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS:
4102     case DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS:
4103       d_count_templates_scopes (num_templates, num_scopes,
4104                                 d_left (dc));
4105       break;
4106
4107     case DEMANGLE_COMPONENT_LAMBDA:
4108     case DEMANGLE_COMPONENT_DEFAULT_ARG:
4109       d_count_templates_scopes (num_templates, num_scopes,
4110                                 dc->u.s_unary_num.sub);
4111       break;
4112     }
4113 }
4114
4115 /* Initialize a print information structure.  */
4116
4117 static void
4118 d_print_init (struct d_print_info *dpi, demangle_callbackref callback,
4119               void *opaque, const struct demangle_component *dc)
4120 {
4121   dpi->len = 0;
4122   dpi->last_char = '\0';
4123   dpi->templates = NULL;
4124   dpi->modifiers = NULL;
4125   dpi->pack_index = 0;
4126   dpi->flush_count = 0;
4127
4128   dpi->callback = callback;
4129   dpi->opaque = opaque;
4130
4131   dpi->demangle_failure = 0;
4132   dpi->is_lambda_arg = 0;
4133
4134   dpi->component_stack = NULL;
4135
4136   dpi->saved_scopes = NULL;
4137   dpi->next_saved_scope = 0;
4138   dpi->num_saved_scopes = 0;
4139
4140   dpi->copy_templates = NULL;
4141   dpi->next_copy_template = 0;
4142   dpi->num_copy_templates = 0;
4143
4144   d_count_templates_scopes (&dpi->num_copy_templates,
4145                             &dpi->num_saved_scopes, dc);
4146   dpi->num_copy_templates *= dpi->num_saved_scopes;
4147
4148   dpi->current_template = NULL;
4149 }
4150
4151 /* Indicate that an error occurred during printing, and test for error.  */
4152
4153 static inline void
4154 d_print_error (struct d_print_info *dpi)
4155 {
4156   dpi->demangle_failure = 1;
4157 }
4158
4159 static inline int
4160 d_print_saw_error (struct d_print_info *dpi)
4161 {
4162   return dpi->demangle_failure != 0;
4163 }
4164
4165 /* Flush buffered characters to the callback.  */
4166
4167 static inline void
4168 d_print_flush (struct d_print_info *dpi)
4169 {
4170   dpi->buf[dpi->len] = '\0';
4171   dpi->callback (dpi->buf, dpi->len, dpi->opaque);
4172   dpi->len = 0;
4173   dpi->flush_count++;
4174 }
4175
4176 /* Append characters and buffers for printing.  */
4177
4178 static inline void
4179 d_append_char (struct d_print_info *dpi, char c)
4180 {
4181   if (dpi->len == sizeof (dpi->buf) - 1)
4182     d_print_flush (dpi);
4183
4184   dpi->buf[dpi->len++] = c;
4185   dpi->last_char = c;
4186 }
4187
4188 static inline void
4189 d_append_buffer (struct d_print_info *dpi, const char *s, size_t l)
4190 {
4191   size_t i;
4192
4193   for (i = 0; i < l; i++)
4194     d_append_char (dpi, s[i]);
4195 }
4196
4197 static inline void
4198 d_append_string (struct d_print_info *dpi, const char *s)
4199 {
4200   d_append_buffer (dpi, s, strlen (s));
4201 }
4202
4203 static inline void
4204 d_append_num (struct d_print_info *dpi, int l)
4205 {
4206   char buf[25];
4207   sprintf (buf,"%d", l);
4208   d_append_string (dpi, buf);
4209 }
4210
4211 static inline char
4212 d_last_char (struct d_print_info *dpi)
4213 {
4214   return dpi->last_char;
4215 }
4216
4217 /* Turn components into a human readable string.  OPTIONS is the
4218    options bits passed to the demangler.  DC is the tree to print.
4219    CALLBACK is a function to call to flush demangled string segments
4220    as they fill the intermediate buffer, and OPAQUE is a generalized
4221    callback argument.  On success, this returns 1.  On failure,
4222    it returns 0, indicating a bad parse.  It does not use heap
4223    memory to build an output string, so cannot encounter memory
4224    allocation failure.  */
4225
4226 CP_STATIC_IF_GLIBCPP_V3
4227 int
4228 cplus_demangle_print_callback (int options,
4229                                const struct demangle_component *dc,
4230                                demangle_callbackref callback, void *opaque)
4231 {
4232   struct d_print_info dpi;
4233
4234   d_print_init (&dpi, callback, opaque, dc);
4235
4236   {
4237 #ifdef CP_DYNAMIC_ARRAYS
4238     /* Avoid zero-length VLAs, which are prohibited by the C99 standard
4239        and flagged as errors by Address Sanitizer.  */
4240     __extension__ struct d_saved_scope scopes[(dpi.num_saved_scopes > 0)
4241                                               ? dpi.num_saved_scopes : 1];
4242     __extension__ struct d_print_template temps[(dpi.num_copy_templates > 0)
4243                                                 ? dpi.num_copy_templates : 1];
4244
4245     dpi.saved_scopes = scopes;
4246     dpi.copy_templates = temps;
4247 #else
4248     dpi.saved_scopes = alloca (dpi.num_saved_scopes
4249                                * sizeof (*dpi.saved_scopes));
4250     dpi.copy_templates = alloca (dpi.num_copy_templates
4251                                  * sizeof (*dpi.copy_templates));
4252 #endif
4253
4254     d_print_comp (&dpi, options, dc);
4255   }
4256
4257   d_print_flush (&dpi);
4258
4259   return ! d_print_saw_error (&dpi);
4260 }
4261
4262 /* Turn components into a human readable string.  OPTIONS is the
4263    options bits passed to the demangler.  DC is the tree to print.
4264    ESTIMATE is a guess at the length of the result.  This returns a
4265    string allocated by malloc, or NULL on error.  On success, this
4266    sets *PALC to the size of the allocated buffer.  On failure, this
4267    sets *PALC to 0 for a bad parse, or to 1 for a memory allocation
4268    failure.  */
4269
4270 CP_STATIC_IF_GLIBCPP_V3
4271 char *
4272 cplus_demangle_print (int options, const struct demangle_component *dc,
4273                       int estimate, size_t *palc)
4274 {
4275   struct d_growable_string dgs;
4276
4277   d_growable_string_init (&dgs, estimate);
4278
4279   if (! cplus_demangle_print_callback (options, dc,
4280                                        d_growable_string_callback_adapter,
4281                                        &dgs))
4282     {
4283       free (dgs.buf);
4284       *palc = 0;
4285       return NULL;
4286     }
4287
4288   *palc = dgs.allocation_failure ? 1 : dgs.alc;
4289   return dgs.buf;
4290 }
4291
4292 /* Returns the I'th element of the template arglist ARGS, or NULL on
4293    failure.  If I is negative, return the entire arglist.  */
4294
4295 static struct demangle_component *
4296 d_index_template_argument (struct demangle_component *args, int i)
4297 {
4298   struct demangle_component *a;
4299
4300   if (i < 0)
4301     /* Print the whole argument pack.  */
4302     return args;
4303
4304   for (a = args;
4305        a != NULL;
4306        a = d_right (a))
4307     {
4308       if (a->type != DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
4309         return NULL;
4310       if (i <= 0)
4311         break;
4312       --i;
4313     }
4314   if (i != 0 || a == NULL)
4315     return NULL;
4316
4317   return d_left (a);
4318 }
4319
4320 /* Returns the template argument from the current context indicated by DC,
4321    which is a DEMANGLE_COMPONENT_TEMPLATE_PARAM, or NULL.  */
4322
4323 static struct demangle_component *
4324 d_lookup_template_argument (struct d_print_info *dpi,
4325                             const struct demangle_component *dc)
4326 {
4327   if (dpi->templates == NULL)
4328     {
4329       d_print_error (dpi);
4330       return NULL;
4331     }
4332         
4333   return d_index_template_argument
4334     (d_right (dpi->templates->template_decl),
4335      dc->u.s_number.number);
4336 }
4337
4338 /* Returns a template argument pack used in DC (any will do), or NULL.  */
4339
4340 static struct demangle_component *
4341 d_find_pack (struct d_print_info *dpi,
4342              const struct demangle_component *dc)
4343 {
4344   struct demangle_component *a;
4345   if (dc == NULL)
4346     return NULL;
4347
4348   switch (dc->type)
4349     {
4350     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
4351       a = d_lookup_template_argument (dpi, dc);
4352       if (a && a->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
4353         return a;
4354       return NULL;
4355
4356     case DEMANGLE_COMPONENT_PACK_EXPANSION:
4357       return NULL;
4358       
4359     case DEMANGLE_COMPONENT_LAMBDA:
4360     case DEMANGLE_COMPONENT_NAME:
4361     case DEMANGLE_COMPONENT_TAGGED_NAME:
4362     case DEMANGLE_COMPONENT_OPERATOR:
4363     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
4364     case DEMANGLE_COMPONENT_SUB_STD:
4365     case DEMANGLE_COMPONENT_CHARACTER:
4366     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
4367     case DEMANGLE_COMPONENT_UNNAMED_TYPE:
4368     case DEMANGLE_COMPONENT_FIXED_TYPE:
4369     case DEMANGLE_COMPONENT_DEFAULT_ARG:
4370     case DEMANGLE_COMPONENT_NUMBER:
4371       return NULL;
4372
4373     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
4374       return d_find_pack (dpi, dc->u.s_extended_operator.name);
4375     case DEMANGLE_COMPONENT_CTOR:
4376       return d_find_pack (dpi, dc->u.s_ctor.name);
4377     case DEMANGLE_COMPONENT_DTOR:
4378       return d_find_pack (dpi, dc->u.s_dtor.name);
4379
4380     default:
4381       a = d_find_pack (dpi, d_left (dc));
4382       if (a)
4383         return a;
4384       return d_find_pack (dpi, d_right (dc));
4385     }
4386 }
4387
4388 /* Returns the length of the template argument pack DC.  */
4389
4390 static int
4391 d_pack_length (const struct demangle_component *dc)
4392 {
4393   int count = 0;
4394   while (dc && dc->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST
4395          && d_left (dc) != NULL)
4396     {
4397       ++count;
4398       dc = d_right (dc);
4399     }
4400   return count;
4401 }
4402
4403 /* Returns the number of template args in DC, expanding any pack expansions
4404    found there.  */
4405
4406 static int
4407 d_args_length (struct d_print_info *dpi, const struct demangle_component *dc)
4408 {
4409   int count = 0;
4410   for (; dc && dc->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST;
4411        dc = d_right (dc))
4412     {
4413       struct demangle_component *elt = d_left (dc);
4414       if (elt == NULL)
4415         break;
4416       if (elt->type == DEMANGLE_COMPONENT_PACK_EXPANSION)
4417         {
4418           struct demangle_component *a = d_find_pack (dpi, d_left (elt));
4419           count += d_pack_length (a);
4420         }
4421       else
4422         ++count;
4423     }
4424   return count;
4425 }
4426
4427 /* DC is a component of a mangled expression.  Print it, wrapped in parens
4428    if needed.  */
4429
4430 static void
4431 d_print_subexpr (struct d_print_info *dpi, int options,
4432                  const struct demangle_component *dc)
4433 {
4434   int simple = 0;
4435   if (dc->type == DEMANGLE_COMPONENT_NAME
4436       || dc->type == DEMANGLE_COMPONENT_QUAL_NAME
4437       || dc->type == DEMANGLE_COMPONENT_INITIALIZER_LIST
4438       || dc->type == DEMANGLE_COMPONENT_FUNCTION_PARAM)
4439     simple = 1;
4440   if (!simple)
4441     d_append_char (dpi, '(');
4442   d_print_comp (dpi, options, dc);
4443   if (!simple)
4444     d_append_char (dpi, ')');
4445 }
4446
4447 /* Save the current scope.  */
4448
4449 static void
4450 d_save_scope (struct d_print_info *dpi,
4451               const struct demangle_component *container)
4452 {
4453   struct d_saved_scope *scope;
4454   struct d_print_template *src, **link;
4455
4456   if (dpi->next_saved_scope >= dpi->num_saved_scopes)
4457     {
4458       d_print_error (dpi);
4459       return;
4460     }
4461   scope = &dpi->saved_scopes[dpi->next_saved_scope];
4462   dpi->next_saved_scope++;
4463
4464   scope->container = container;
4465   link = &scope->templates;
4466
4467   for (src = dpi->templates; src != NULL; src = src->next)
4468     {
4469       struct d_print_template *dst;
4470
4471       if (dpi->next_copy_template >= dpi->num_copy_templates)
4472         {
4473           d_print_error (dpi);
4474           return;
4475         }
4476       dst = &dpi->copy_templates[dpi->next_copy_template];
4477       dpi->next_copy_template++;
4478
4479       dst->template_decl = src->template_decl;
4480       *link = dst;
4481       link = &dst->next;
4482     }
4483
4484   *link = NULL;
4485 }
4486
4487 /* Attempt to locate a previously saved scope.  Returns NULL if no
4488    corresponding saved scope was found.  */
4489
4490 static struct d_saved_scope *
4491 d_get_saved_scope (struct d_print_info *dpi,
4492                    const struct demangle_component *container)
4493 {
4494   int i;
4495
4496   for (i = 0; i < dpi->next_saved_scope; i++)
4497     if (dpi->saved_scopes[i].container == container)
4498       return &dpi->saved_scopes[i];
4499
4500   return NULL;
4501 }
4502
4503 /* If DC is a C++17 fold-expression, print it and return true; otherwise
4504    return false.  */
4505
4506 static int
4507 d_maybe_print_fold_expression (struct d_print_info *dpi, int options,
4508                                const struct demangle_component *dc)
4509 {
4510   const struct demangle_component *ops, *operator_, *op1, *op2;
4511   int save_idx;
4512
4513   const char *fold_code = d_left (dc)->u.s_operator.op->code;
4514   if (fold_code[0] != 'f')
4515     return 0;
4516
4517   ops = d_right (dc);
4518   operator_ = d_left (ops);
4519   op1 = d_right (ops);
4520   op2 = 0;
4521   if (op1->type == DEMANGLE_COMPONENT_TRINARY_ARG2)
4522     {
4523       op2 = d_right (op1);
4524       op1 = d_left (op1);
4525     }
4526
4527   /* Print the whole pack.  */
4528   save_idx = dpi->pack_index;
4529   dpi->pack_index = -1;
4530
4531   switch (fold_code[1])
4532     {
4533       /* Unary left fold, (... + X).  */
4534     case 'l':
4535       d_append_string (dpi, "(...");
4536       d_print_expr_op (dpi, options, operator_);
4537       d_print_subexpr (dpi, options, op1);
4538       d_append_char (dpi, ')');
4539       break;
4540
4541       /* Unary right fold, (X + ...).  */
4542     case 'r':
4543       d_append_char (dpi, '(');
4544       d_print_subexpr (dpi, options, op1);
4545       d_print_expr_op (dpi, options, operator_);
4546       d_append_string (dpi, "...)");
4547       break;
4548
4549       /* Binary left fold, (42 + ... + X).  */
4550     case 'L':
4551       /* Binary right fold, (X + ... + 42).  */
4552     case 'R':
4553       d_append_char (dpi, '(');
4554       d_print_subexpr (dpi, options, op1);
4555       d_print_expr_op (dpi, options, operator_);
4556       d_append_string (dpi, "...");
4557       d_print_expr_op (dpi, options, operator_);
4558       d_print_subexpr (dpi, options, op2);
4559       d_append_char (dpi, ')');
4560       break;
4561     }
4562
4563   dpi->pack_index = save_idx;
4564   return 1;
4565 }
4566
4567 /* Subroutine to handle components.  */
4568
4569 static void
4570 d_print_comp_inner (struct d_print_info *dpi, int options,
4571                   const struct demangle_component *dc)
4572 {
4573   /* Magic variable to let reference smashing skip over the next modifier
4574      without needing to modify *dc.  */
4575   const struct demangle_component *mod_inner = NULL;
4576
4577   /* Variable used to store the current templates while a previously
4578      captured scope is used.  */
4579   struct d_print_template *saved_templates;
4580
4581   /* Nonzero if templates have been stored in the above variable.  */
4582   int need_template_restore = 0;
4583
4584   if (dc == NULL)
4585     {
4586       d_print_error (dpi);
4587       return;
4588     }
4589   if (d_print_saw_error (dpi))
4590     return;
4591
4592   switch (dc->type)
4593     {
4594     case DEMANGLE_COMPONENT_NAME:
4595       if ((options & DMGL_JAVA) == 0)
4596         d_append_buffer (dpi, dc->u.s_name.s, dc->u.s_name.len);
4597       else
4598         d_print_java_identifier (dpi, dc->u.s_name.s, dc->u.s_name.len);
4599       return;
4600
4601     case DEMANGLE_COMPONENT_TAGGED_NAME:
4602       d_print_comp (dpi, options, d_left (dc));
4603       d_append_string (dpi, "[abi:");
4604       d_print_comp (dpi, options, d_right (dc));
4605       d_append_char (dpi, ']');
4606       return;
4607
4608     case DEMANGLE_COMPONENT_QUAL_NAME:
4609     case DEMANGLE_COMPONENT_LOCAL_NAME:
4610       d_print_comp (dpi, options, d_left (dc));
4611       if ((options & DMGL_JAVA) == 0)
4612         d_append_string (dpi, "::");
4613       else
4614         d_append_char (dpi, '.');
4615       {
4616         struct demangle_component *local_name = d_right (dc);
4617         if (local_name->type == DEMANGLE_COMPONENT_DEFAULT_ARG)
4618           {
4619             d_append_string (dpi, "{default arg#");
4620             d_append_num (dpi, local_name->u.s_unary_num.num + 1);
4621             d_append_string (dpi, "}::");
4622             local_name = local_name->u.s_unary_num.sub;
4623           }
4624         d_print_comp (dpi, options, local_name);
4625       }
4626       return;
4627
4628     case DEMANGLE_COMPONENT_TYPED_NAME:
4629       {
4630         struct d_print_mod *hold_modifiers;
4631         struct demangle_component *typed_name;
4632         struct d_print_mod adpm[4];
4633         unsigned int i;
4634         struct d_print_template dpt;
4635
4636         /* Pass the name down to the type so that it can be printed in
4637            the right place for the type.  We also have to pass down
4638            any CV-qualifiers, which apply to the this parameter.  */
4639         hold_modifiers = dpi->modifiers;
4640         dpi->modifiers = 0;
4641         i = 0;
4642         typed_name = d_left (dc);
4643         while (typed_name != NULL)
4644           {
4645             if (i >= sizeof adpm / sizeof adpm[0])
4646               {
4647                 d_print_error (dpi);
4648                 return;
4649               }
4650
4651             adpm[i].next = dpi->modifiers;
4652             dpi->modifiers = &adpm[i];
4653             adpm[i].mod = typed_name;
4654             adpm[i].printed = 0;
4655             adpm[i].templates = dpi->templates;
4656             ++i;
4657
4658             if (!is_fnqual_component_type (typed_name->type))
4659               break;
4660
4661             typed_name = d_left (typed_name);
4662           }
4663
4664         if (typed_name == NULL)
4665           {
4666             d_print_error (dpi);
4667             return;
4668           }
4669
4670         /* If typed_name is a template, then it applies to the
4671            function type as well.  */
4672         if (typed_name->type == DEMANGLE_COMPONENT_TEMPLATE)
4673           {
4674             dpt.next = dpi->templates;
4675             dpi->templates = &dpt;
4676             dpt.template_decl = typed_name;
4677           }
4678
4679         /* If typed_name is a DEMANGLE_COMPONENT_LOCAL_NAME, then
4680            there may be CV-qualifiers on its right argument which
4681            really apply here; this happens when parsing a class which
4682            is local to a function.  */
4683         if (typed_name->type == DEMANGLE_COMPONENT_LOCAL_NAME)
4684           {
4685             struct demangle_component *local_name;
4686
4687             local_name = d_right (typed_name);
4688             if (local_name->type == DEMANGLE_COMPONENT_DEFAULT_ARG)
4689               local_name = local_name->u.s_unary_num.sub;
4690             if (local_name == NULL)
4691               {
4692                 d_print_error (dpi);
4693                 return;
4694               }
4695             while (is_fnqual_component_type (local_name->type))
4696               {
4697                 if (i >= sizeof adpm / sizeof adpm[0])
4698                   {
4699                     d_print_error (dpi);
4700                     return;
4701                   }
4702
4703                 adpm[i] = adpm[i - 1];
4704                 adpm[i].next = &adpm[i - 1];
4705                 dpi->modifiers = &adpm[i];
4706
4707                 adpm[i - 1].mod = local_name;
4708                 adpm[i - 1].printed = 0;
4709                 adpm[i - 1].templates = dpi->templates;
4710                 ++i;
4711
4712                 local_name = d_left (local_name);
4713               }
4714           }
4715
4716         d_print_comp (dpi, options, d_right (dc));
4717
4718         if (typed_name->type == DEMANGLE_COMPONENT_TEMPLATE)
4719           dpi->templates = dpt.next;
4720
4721         /* If the modifiers didn't get printed by the type, print them
4722            now.  */
4723         while (i > 0)
4724           {
4725             --i;
4726             if (! adpm[i].printed)
4727               {
4728                 d_append_char (dpi, ' ');
4729                 d_print_mod (dpi, options, adpm[i].mod);
4730               }
4731           }
4732
4733         dpi->modifiers = hold_modifiers;
4734
4735         return;
4736       }
4737
4738     case DEMANGLE_COMPONENT_TEMPLATE:
4739       {
4740         struct d_print_mod *hold_dpm;
4741         struct demangle_component *dcl;
4742         const struct demangle_component *hold_current;
4743
4744         /* This template may need to be referenced by a cast operator
4745            contained in its subtree.  */
4746         hold_current = dpi->current_template;
4747         dpi->current_template = dc;
4748
4749         /* Don't push modifiers into a template definition.  Doing so
4750            could give the wrong definition for a template argument.
4751            Instead, treat the template essentially as a name.  */
4752
4753         hold_dpm = dpi->modifiers;
4754         dpi->modifiers = NULL;
4755
4756         dcl = d_left (dc);
4757
4758         if ((options & DMGL_JAVA) != 0
4759             && dcl->type == DEMANGLE_COMPONENT_NAME
4760             && dcl->u.s_name.len == 6
4761             && strncmp (dcl->u.s_name.s, "JArray", 6) == 0)
4762           {
4763             /* Special-case Java arrays, so that JArray<TYPE> appears
4764                instead as TYPE[].  */
4765
4766             d_print_comp (dpi, options, d_right (dc));
4767             d_append_string (dpi, "[]");
4768           }
4769         else
4770           {
4771             d_print_comp (dpi, options, dcl);
4772             if (d_last_char (dpi) == '<')
4773               d_append_char (dpi, ' ');
4774             d_append_char (dpi, '<');
4775             d_print_comp (dpi, options, d_right (dc));
4776             /* Avoid generating two consecutive '>' characters, to avoid
4777                the C++ syntactic ambiguity.  */
4778             if (d_last_char (dpi) == '>')
4779               d_append_char (dpi, ' ');
4780             d_append_char (dpi, '>');
4781           }
4782
4783         dpi->modifiers = hold_dpm;
4784         dpi->current_template = hold_current;
4785
4786         return;
4787       }
4788
4789     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
4790       if (dpi->is_lambda_arg)
4791         {
4792           /* Show the template parm index, as that's how g++ displays
4793              these, and future proofs us against potential
4794              '[]<typename T> (T *a, T *b) {...}'.  */
4795           d_append_buffer (dpi, "auto:", 5);
4796           d_append_num (dpi, dc->u.s_number.number + 1);
4797         }
4798       else
4799         {
4800           struct d_print_template *hold_dpt;
4801           struct demangle_component *a = d_lookup_template_argument (dpi, dc);
4802
4803           if (a && a->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
4804             a = d_index_template_argument (a, dpi->pack_index);
4805
4806           if (a == NULL)
4807             {
4808               d_print_error (dpi);
4809               return;
4810             }
4811
4812           /* While processing this parameter, we need to pop the list
4813              of templates.  This is because the template parameter may
4814              itself be a reference to a parameter of an outer
4815              template.  */
4816
4817           hold_dpt = dpi->templates;
4818           dpi->templates = hold_dpt->next;
4819
4820           d_print_comp (dpi, options, a);
4821
4822           dpi->templates = hold_dpt;
4823         }
4824       return;
4825
4826     case DEMANGLE_COMPONENT_CTOR:
4827       d_print_comp (dpi, options, dc->u.s_ctor.name);
4828       return;
4829
4830     case DEMANGLE_COMPONENT_DTOR:
4831       d_append_char (dpi, '~');
4832       d_print_comp (dpi, options, dc->u.s_dtor.name);
4833       return;
4834
4835     case DEMANGLE_COMPONENT_VTABLE:
4836       d_append_string (dpi, "vtable for ");
4837       d_print_comp (dpi, options, d_left (dc));
4838       return;
4839
4840     case DEMANGLE_COMPONENT_VTT:
4841       d_append_string (dpi, "VTT for ");
4842       d_print_comp (dpi, options, d_left (dc));
4843       return;
4844
4845     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
4846       d_append_string (dpi, "construction vtable for ");
4847       d_print_comp (dpi, options, d_left (dc));
4848       d_append_string (dpi, "-in-");
4849       d_print_comp (dpi, options, d_right (dc));
4850       return;
4851
4852     case DEMANGLE_COMPONENT_TYPEINFO:
4853       d_append_string (dpi, "typeinfo for ");
4854       d_print_comp (dpi, options, d_left (dc));
4855       return;
4856
4857     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
4858       d_append_string (dpi, "typeinfo name for ");
4859       d_print_comp (dpi, options, d_left (dc));
4860       return;
4861
4862     case DEMANGLE_COMPONENT_TYPEINFO_FN:
4863       d_append_string (dpi, "typeinfo fn for ");
4864       d_print_comp (dpi, options, d_left (dc));
4865       return;
4866
4867     case DEMANGLE_COMPONENT_THUNK:
4868       d_append_string (dpi, "non-virtual thunk to ");
4869       d_print_comp (dpi, options, d_left (dc));
4870       return;
4871
4872     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
4873       d_append_string (dpi, "virtual thunk to ");
4874       d_print_comp (dpi, options, d_left (dc));
4875       return;
4876
4877     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
4878       d_append_string (dpi, "covariant return thunk to ");
4879       d_print_comp (dpi, options, d_left (dc));
4880       return;
4881
4882     case DEMANGLE_COMPONENT_JAVA_CLASS:
4883       d_append_string (dpi, "java Class for ");
4884       d_print_comp (dpi, options, d_left (dc));
4885       return;
4886
4887     case DEMANGLE_COMPONENT_GUARD:
4888       d_append_string (dpi, "guard variable for ");
4889       d_print_comp (dpi, options, d_left (dc));
4890       return;
4891
4892     case DEMANGLE_COMPONENT_TLS_INIT:
4893       d_append_string (dpi, "TLS init function for ");
4894       d_print_comp (dpi, options, d_left (dc));
4895       return;
4896
4897     case DEMANGLE_COMPONENT_TLS_WRAPPER:
4898       d_append_string (dpi, "TLS wrapper function for ");
4899       d_print_comp (dpi, options, d_left (dc));
4900       return;
4901
4902     case DEMANGLE_COMPONENT_REFTEMP:
4903       d_append_string (dpi, "reference temporary #");
4904       d_print_comp (dpi, options, d_right (dc));
4905       d_append_string (dpi, " for ");
4906       d_print_comp (dpi, options, d_left (dc));
4907       return;
4908
4909     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
4910       d_append_string (dpi, "hidden alias for ");
4911       d_print_comp (dpi, options, d_left (dc));
4912       return;
4913
4914     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
4915       d_append_string (dpi, "transaction clone for ");
4916       d_print_comp (dpi, options, d_left (dc));
4917       return;
4918
4919     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
4920       d_append_string (dpi, "non-transaction clone for ");
4921       d_print_comp (dpi, options, d_left (dc));
4922       return;
4923
4924     case DEMANGLE_COMPONENT_SUB_STD:
4925       d_append_buffer (dpi, dc->u.s_string.string, dc->u.s_string.len);
4926       return;
4927
4928     case DEMANGLE_COMPONENT_RESTRICT:
4929     case DEMANGLE_COMPONENT_VOLATILE:
4930     case DEMANGLE_COMPONENT_CONST:
4931       {
4932         struct d_print_mod *pdpm;
4933
4934         /* When printing arrays, it's possible to have cases where the
4935            same CV-qualifier gets pushed on the stack multiple times.
4936            We only need to print it once.  */
4937
4938         for (pdpm = dpi->modifiers; pdpm != NULL; pdpm = pdpm->next)
4939           {
4940             if (! pdpm->printed)
4941               {
4942                 if (pdpm->mod->type != DEMANGLE_COMPONENT_RESTRICT
4943                     && pdpm->mod->type != DEMANGLE_COMPONENT_VOLATILE
4944                     && pdpm->mod->type != DEMANGLE_COMPONENT_CONST)
4945                   break;
4946                 if (pdpm->mod->type == dc->type)
4947                   {
4948                     d_print_comp (dpi, options, d_left (dc));
4949                     return;
4950                   }
4951               }
4952           }
4953       }
4954       goto modifier;
4955
4956     case DEMANGLE_COMPONENT_REFERENCE:
4957     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
4958       {
4959         /* Handle reference smashing: & + && = &.  */
4960         const struct demangle_component *sub = d_left (dc);
4961         if (!dpi->is_lambda_arg
4962             && sub->type == DEMANGLE_COMPONENT_TEMPLATE_PARAM)
4963           {
4964             struct d_saved_scope *scope = d_get_saved_scope (dpi, sub);
4965             struct demangle_component *a;
4966
4967             if (scope == NULL)
4968               {
4969                 /* This is the first time SUB has been traversed.
4970                    We need to capture the current templates so
4971                    they can be restored if SUB is reentered as a
4972                    substitution.  */
4973                 d_save_scope (dpi, sub);
4974                 if (d_print_saw_error (dpi))
4975                   return;
4976               }
4977             else
4978               {
4979                 const struct d_component_stack *dcse;
4980                 int found_self_or_parent = 0;
4981
4982                 /* This traversal is reentering SUB as a substition.
4983                    If we are not beneath SUB or DC in the tree then we
4984                    need to restore SUB's template stack temporarily.  */
4985                 for (dcse = dpi->component_stack; dcse != NULL;
4986                      dcse = dcse->parent)
4987                   {
4988                     if (dcse->dc == sub
4989                         || (dcse->dc == dc
4990                             && dcse != dpi->component_stack))
4991                       {
4992                         found_self_or_parent = 1;
4993                         break;
4994                       }
4995                   }
4996
4997                 if (!found_self_or_parent)
4998                   {
4999                     saved_templates = dpi->templates;
5000                     dpi->templates = scope->templates;
5001                     need_template_restore = 1;
5002                   }
5003               }
5004
5005             a = d_lookup_template_argument (dpi, sub);
5006             if (a && a->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
5007               a = d_index_template_argument (a, dpi->pack_index);
5008
5009             if (a == NULL)
5010               {
5011                 if (need_template_restore)
5012                   dpi->templates = saved_templates;
5013
5014                 d_print_error (dpi);
5015                 return;
5016               }
5017
5018             sub = a;
5019           }
5020
5021         if (sub->type == DEMANGLE_COMPONENT_REFERENCE
5022             || sub->type == dc->type)
5023           dc = sub;
5024         else if (sub->type == DEMANGLE_COMPONENT_RVALUE_REFERENCE)
5025           mod_inner = d_left (sub);
5026       }
5027       /* Fall through.  */
5028
5029     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
5030     case DEMANGLE_COMPONENT_POINTER:
5031     case DEMANGLE_COMPONENT_COMPLEX:
5032     case DEMANGLE_COMPONENT_IMAGINARY:
5033     FNQUAL_COMPONENT_CASE:
5034     modifier:
5035       {
5036         /* We keep a list of modifiers on the stack.  */
5037         struct d_print_mod dpm;
5038
5039         dpm.next = dpi->modifiers;
5040         dpi->modifiers = &dpm;
5041         dpm.mod = dc;
5042         dpm.printed = 0;
5043         dpm.templates = dpi->templates;
5044
5045         if (!mod_inner)
5046           mod_inner = d_left (dc);
5047
5048         d_print_comp (dpi, options, mod_inner);
5049
5050         /* If the modifier didn't get printed by the type, print it
5051            now.  */
5052         if (! dpm.printed)
5053           d_print_mod (dpi, options, dc);
5054
5055         dpi->modifiers = dpm.next;
5056
5057         if (need_template_restore)
5058           dpi->templates = saved_templates;
5059
5060         return;
5061       }
5062
5063     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
5064       if ((options & DMGL_JAVA) == 0)
5065         d_append_buffer (dpi, dc->u.s_builtin.type->name,
5066                          dc->u.s_builtin.type->len);
5067       else
5068         d_append_buffer (dpi, dc->u.s_builtin.type->java_name,
5069                          dc->u.s_builtin.type->java_len);
5070       return;
5071
5072     case DEMANGLE_COMPONENT_VENDOR_TYPE:
5073       d_print_comp (dpi, options, d_left (dc));
5074       return;
5075
5076     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
5077       {
5078         if ((options & DMGL_RET_POSTFIX) != 0)
5079           d_print_function_type (dpi,
5080                                  options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
5081                                  dc, dpi->modifiers);
5082
5083         /* Print return type if present */
5084         if (d_left (dc) != NULL && (options & DMGL_RET_POSTFIX) != 0)
5085           d_print_comp (dpi, options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
5086                         d_left (dc));
5087         else if (d_left (dc) != NULL && (options & DMGL_RET_DROP) == 0)
5088           {
5089             struct d_print_mod dpm;
5090
5091             /* We must pass this type down as a modifier in order to
5092                print it in the right location.  */
5093             dpm.next = dpi->modifiers;
5094             dpi->modifiers = &dpm;
5095             dpm.mod = dc;
5096             dpm.printed = 0;
5097             dpm.templates = dpi->templates;
5098
5099             d_print_comp (dpi, options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
5100                           d_left (dc));
5101
5102             dpi->modifiers = dpm.next;
5103
5104             if (dpm.printed)
5105               return;
5106
5107             /* In standard prefix notation, there is a space between the
5108                return type and the function signature.  */
5109             if ((options & DMGL_RET_POSTFIX) == 0)
5110               d_append_char (dpi, ' ');
5111           }
5112
5113         if ((options & DMGL_RET_POSTFIX) == 0)
5114           d_print_function_type (dpi,
5115                                  options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
5116                                  dc, dpi->modifiers);
5117
5118         return;
5119       }
5120
5121     case DEMANGLE_COMPONENT_ARRAY_TYPE:
5122       {
5123         struct d_print_mod *hold_modifiers;
5124         struct d_print_mod adpm[4];
5125         unsigned int i;
5126         struct d_print_mod *pdpm;
5127
5128         /* We must pass this type down as a modifier in order to print
5129            multi-dimensional arrays correctly.  If the array itself is
5130            CV-qualified, we act as though the element type were
5131            CV-qualified.  We do this by copying the modifiers down
5132            rather than fiddling pointers, so that we don't wind up
5133            with a d_print_mod higher on the stack pointing into our
5134            stack frame after we return.  */
5135
5136         hold_modifiers = dpi->modifiers;
5137
5138         adpm[0].next = hold_modifiers;
5139         dpi->modifiers = &adpm[0];
5140         adpm[0].mod = dc;
5141         adpm[0].printed = 0;
5142         adpm[0].templates = dpi->templates;
5143
5144         i = 1;
5145         pdpm = hold_modifiers;
5146         while (pdpm != NULL
5147                && (pdpm->mod->type == DEMANGLE_COMPONENT_RESTRICT
5148                    || pdpm->mod->type == DEMANGLE_COMPONENT_VOLATILE
5149                    || pdpm->mod->type == DEMANGLE_COMPONENT_CONST))
5150           {
5151             if (! pdpm->printed)
5152               {
5153                 if (i >= sizeof adpm / sizeof adpm[0])
5154                   {
5155                     d_print_error (dpi);
5156                     return;
5157                   }
5158
5159                 adpm[i] = *pdpm;
5160                 adpm[i].next = dpi->modifiers;
5161                 dpi->modifiers = &adpm[i];
5162                 pdpm->printed = 1;
5163                 ++i;
5164               }
5165
5166             pdpm = pdpm->next;
5167           }
5168
5169         d_print_comp (dpi, options, d_right (dc));
5170
5171         dpi->modifiers = hold_modifiers;
5172
5173         if (adpm[0].printed)
5174           return;
5175
5176         while (i > 1)
5177           {
5178             --i;
5179             d_print_mod (dpi, options, adpm[i].mod);
5180           }
5181
5182         d_print_array_type (dpi, options, dc, dpi->modifiers);
5183
5184         return;
5185       }
5186
5187     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
5188     case DEMANGLE_COMPONENT_VECTOR_TYPE:
5189       {
5190         struct d_print_mod dpm;
5191
5192         dpm.next = dpi->modifiers;
5193         dpi->modifiers = &dpm;
5194         dpm.mod = dc;
5195         dpm.printed = 0;
5196         dpm.templates = dpi->templates;
5197
5198         d_print_comp (dpi, options, d_right (dc));
5199
5200         /* If the modifier didn't get printed by the type, print it
5201            now.  */
5202         if (! dpm.printed)
5203           d_print_mod (dpi, options, dc);
5204
5205         dpi->modifiers = dpm.next;
5206
5207         return;
5208       }
5209
5210     case DEMANGLE_COMPONENT_FIXED_TYPE:
5211       if (dc->u.s_fixed.sat)
5212         d_append_string (dpi, "_Sat ");
5213       /* Don't print "int _Accum".  */
5214       if (dc->u.s_fixed.length->u.s_builtin.type
5215           != &cplus_demangle_builtin_types['i'-'a'])
5216         {
5217           d_print_comp (dpi, options, dc->u.s_fixed.length);
5218           d_append_char (dpi, ' ');
5219         }
5220       if (dc->u.s_fixed.accum)
5221         d_append_string (dpi, "_Accum");
5222       else
5223         d_append_string (dpi, "_Fract");
5224       return;
5225
5226     case DEMANGLE_COMPONENT_ARGLIST:
5227     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
5228       if (d_left (dc) != NULL)
5229         d_print_comp (dpi, options, d_left (dc));
5230       if (d_right (dc) != NULL)
5231         {
5232           size_t len;
5233           unsigned long int flush_count;
5234           /* Make sure ", " isn't flushed by d_append_string, otherwise
5235              dpi->len -= 2 wouldn't work.  */
5236           if (dpi->len >= sizeof (dpi->buf) - 2)
5237             d_print_flush (dpi);
5238           d_append_string (dpi, ", ");
5239           len = dpi->len;
5240           flush_count = dpi->flush_count;
5241           d_print_comp (dpi, options, d_right (dc));
5242           /* If that didn't print anything (which can happen with empty
5243              template argument packs), remove the comma and space.  */
5244           if (dpi->flush_count == flush_count && dpi->len == len)
5245             dpi->len -= 2;
5246         }
5247       return;
5248
5249     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
5250       {
5251         struct demangle_component *type = d_left (dc);
5252         struct demangle_component *list = d_right (dc);
5253
5254         if (type)
5255           d_print_comp (dpi, options, type);
5256         d_append_char (dpi, '{');
5257         d_print_comp (dpi, options, list);
5258         d_append_char (dpi, '}');
5259       }
5260       return;
5261
5262     case DEMANGLE_COMPONENT_OPERATOR:
5263       {
5264         const struct demangle_operator_info *op = dc->u.s_operator.op;
5265         int len = op->len;
5266
5267         d_append_string (dpi, "operator");
5268         /* Add a space before new/delete.  */
5269         if (IS_LOWER (op->name[0]))
5270           d_append_char (dpi, ' ');
5271         /* Omit a trailing space.  */
5272         if (op->name[len-1] == ' ')
5273           --len;
5274         d_append_buffer (dpi, op->name, len);
5275         return;
5276       }
5277
5278     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
5279       d_append_string (dpi, "operator ");
5280       d_print_comp (dpi, options, dc->u.s_extended_operator.name);
5281       return;
5282
5283     case DEMANGLE_COMPONENT_CONVERSION:
5284       d_append_string (dpi, "operator ");
5285       d_print_conversion (dpi, options, dc);
5286       return;
5287
5288     case DEMANGLE_COMPONENT_NULLARY:
5289       d_print_expr_op (dpi, options, d_left (dc));
5290       return;
5291
5292     case DEMANGLE_COMPONENT_UNARY:
5293       {
5294         struct demangle_component *op = d_left (dc);
5295         struct demangle_component *operand = d_right (dc);
5296         const char *code = NULL;
5297
5298         if (op->type == DEMANGLE_COMPONENT_OPERATOR)
5299           {
5300             code = op->u.s_operator.op->code;
5301             if (!strcmp (code, "ad"))
5302               {
5303                 /* Don't print the argument list for the address of a
5304                    function.  */
5305                 if (operand->type == DEMANGLE_COMPONENT_TYPED_NAME
5306                     && d_left (operand)->type == DEMANGLE_COMPONENT_QUAL_NAME
5307                     && d_right (operand)->type == DEMANGLE_COMPONENT_FUNCTION_TYPE)
5308                   operand = d_left (operand);
5309               }
5310             if (operand->type == DEMANGLE_COMPONENT_BINARY_ARGS)
5311               {
5312                 /* This indicates a suffix operator.  */
5313                 operand = d_left (operand);
5314                 d_print_subexpr (dpi, options, operand);
5315                 d_print_expr_op (dpi, options, op);
5316                 return;
5317               }
5318           }
5319
5320         /* For sizeof..., just print the pack length.  */
5321         if (code && !strcmp (code, "sZ"))
5322           {
5323             struct demangle_component *a = d_find_pack (dpi, operand);
5324             int len = d_pack_length (a);
5325             d_append_num (dpi, len);
5326             return;
5327           }
5328         else if (code && !strcmp (code, "sP"))
5329           {
5330             int len = d_args_length (dpi, operand);
5331             d_append_num (dpi, len);
5332             return;
5333           }
5334
5335         if (op->type != DEMANGLE_COMPONENT_CAST)
5336           d_print_expr_op (dpi, options, op);
5337         else
5338           {
5339             d_append_char (dpi, '(');
5340             d_print_cast (dpi, options, op);
5341             d_append_char (dpi, ')');
5342           }
5343         if (code && !strcmp (code, "gs"))
5344           /* Avoid parens after '::'.  */
5345           d_print_comp (dpi, options, operand);
5346         else if (code && !strcmp (code, "st"))
5347           /* Always print parens for sizeof (type).  */
5348           {
5349             d_append_char (dpi, '(');
5350             d_print_comp (dpi, options, operand);
5351             d_append_char (dpi, ')');
5352           }
5353         else
5354           d_print_subexpr (dpi, options, operand);
5355       }
5356       return;
5357
5358     case DEMANGLE_COMPONENT_BINARY:
5359       if (d_right (dc)->type != DEMANGLE_COMPONENT_BINARY_ARGS)
5360         {
5361           d_print_error (dpi);
5362           return;
5363         }
5364
5365       if (op_is_new_cast (d_left (dc)))
5366         {
5367           d_print_expr_op (dpi, options, d_left (dc));
5368           d_append_char (dpi, '<');
5369           d_print_comp (dpi, options, d_left (d_right (dc)));
5370           d_append_string (dpi, ">(");
5371           d_print_comp (dpi, options, d_right (d_right (dc)));
5372           d_append_char (dpi, ')');
5373           return;
5374         }
5375
5376       if (d_maybe_print_fold_expression (dpi, options, dc))
5377         return;
5378
5379       /* We wrap an expression which uses the greater-than operator in
5380          an extra layer of parens so that it does not get confused
5381          with the '>' which ends the template parameters.  */
5382       if (d_left (dc)->type == DEMANGLE_COMPONENT_OPERATOR
5383           && d_left (dc)->u.s_operator.op->len == 1
5384           && d_left (dc)->u.s_operator.op->name[0] == '>')
5385         d_append_char (dpi, '(');
5386
5387       if (strcmp (d_left (dc)->u.s_operator.op->code, "cl") == 0
5388           && d_left (d_right (dc))->type == DEMANGLE_COMPONENT_TYPED_NAME)
5389         {
5390           /* Function call used in an expression should not have printed types
5391              of the function arguments.  Values of the function arguments still
5392              get printed below.  */
5393
5394           const struct demangle_component *func = d_left (d_right (dc));
5395
5396           if (d_right (func)->type != DEMANGLE_COMPONENT_FUNCTION_TYPE)
5397             d_print_error (dpi);
5398           d_print_subexpr (dpi, options, d_left (func));
5399         }
5400       else
5401         d_print_subexpr (dpi, options, d_left (d_right (dc)));
5402       if (strcmp (d_left (dc)->u.s_operator.op->code, "ix") == 0)
5403         {
5404           d_append_char (dpi, '[');
5405           d_print_comp (dpi, options, d_right (d_right (dc)));
5406           d_append_char (dpi, ']');
5407         }
5408       else
5409         {
5410           if (strcmp (d_left (dc)->u.s_operator.op->code, "cl") != 0)
5411             d_print_expr_op (dpi, options, d_left (dc));
5412           d_print_subexpr (dpi, options, d_right (d_right (dc)));
5413         }
5414
5415       if (d_left (dc)->type == DEMANGLE_COMPONENT_OPERATOR
5416           && d_left (dc)->u.s_operator.op->len == 1
5417           && d_left (dc)->u.s_operator.op->name[0] == '>')
5418         d_append_char (dpi, ')');
5419
5420       return;
5421
5422     case DEMANGLE_COMPONENT_BINARY_ARGS:
5423       /* We should only see this as part of DEMANGLE_COMPONENT_BINARY.  */
5424       d_print_error (dpi);
5425       return;
5426
5427     case DEMANGLE_COMPONENT_TRINARY:
5428       if (d_right (dc)->type != DEMANGLE_COMPONENT_TRINARY_ARG1
5429           || d_right (d_right (dc))->type != DEMANGLE_COMPONENT_TRINARY_ARG2)
5430         {
5431           d_print_error (dpi);
5432           return;
5433         }
5434       if (d_maybe_print_fold_expression (dpi, options, dc))
5435         return;
5436       {
5437         struct demangle_component *op = d_left (dc);
5438         struct demangle_component *first = d_left (d_right (dc));
5439         struct demangle_component *second = d_left (d_right (d_right (dc)));
5440         struct demangle_component *third = d_right (d_right (d_right (dc)));
5441
5442         if (!strcmp (op->u.s_operator.op->code, "qu"))
5443           {
5444             d_print_subexpr (dpi, options, first);
5445             d_print_expr_op (dpi, options, op);
5446             d_print_subexpr (dpi, options, second);
5447             d_append_string (dpi, " : ");
5448             d_print_subexpr (dpi, options, third);
5449           }
5450         else
5451           {
5452             d_append_string (dpi, "new ");
5453             if (d_left (first) != NULL)
5454               {
5455                 d_print_subexpr (dpi, options, first);
5456                 d_append_char (dpi, ' ');
5457               }
5458             d_print_comp (dpi, options, second);
5459             if (third)
5460               d_print_subexpr (dpi, options, third);
5461           }
5462       }
5463       return;
5464
5465     case DEMANGLE_COMPONENT_TRINARY_ARG1:
5466     case DEMANGLE_COMPONENT_TRINARY_ARG2:
5467       /* We should only see these are part of DEMANGLE_COMPONENT_TRINARY.  */
5468       d_print_error (dpi);
5469       return;
5470
5471     case DEMANGLE_COMPONENT_LITERAL:
5472     case DEMANGLE_COMPONENT_LITERAL_NEG:
5473       {
5474         enum d_builtin_type_print tp;
5475
5476         /* For some builtin types, produce simpler output.  */
5477         tp = D_PRINT_DEFAULT;
5478         if (d_left (dc)->type == DEMANGLE_COMPONENT_BUILTIN_TYPE)
5479           {
5480             tp = d_left (dc)->u.s_builtin.type->print;
5481             switch (tp)
5482               {
5483               case D_PRINT_INT:
5484               case D_PRINT_UNSIGNED:
5485               case D_PRINT_LONG:
5486               case D_PRINT_UNSIGNED_LONG:
5487               case D_PRINT_LONG_LONG:
5488               case D_PRINT_UNSIGNED_LONG_LONG:
5489                 if (d_right (dc)->type == DEMANGLE_COMPONENT_NAME)
5490                   {
5491                     if (dc->type == DEMANGLE_COMPONENT_LITERAL_NEG)
5492                       d_append_char (dpi, '-');
5493                     d_print_comp (dpi, options, d_right (dc));
5494                     switch (tp)
5495                       {
5496                       default:
5497                         break;
5498                       case D_PRINT_UNSIGNED:
5499                         d_append_char (dpi, 'u');
5500                         break;
5501                       case D_PRINT_LONG:
5502                         d_append_char (dpi, 'l');
5503                         break;
5504                       case D_PRINT_UNSIGNED_LONG:
5505                         d_append_string (dpi, "ul");
5506                         break;
5507                       case D_PRINT_LONG_LONG:
5508                         d_append_string (dpi, "ll");
5509                         break;
5510                       case D_PRINT_UNSIGNED_LONG_LONG:
5511                         d_append_string (dpi, "ull");
5512                         break;
5513                       }
5514                     return;
5515                   }
5516                 break;
5517
5518               case D_PRINT_BOOL:
5519                 if (d_right (dc)->type == DEMANGLE_COMPONENT_NAME
5520                     && d_right (dc)->u.s_name.len == 1
5521                     && dc->type == DEMANGLE_COMPONENT_LITERAL)
5522                   {
5523                     switch (d_right (dc)->u.s_name.s[0])
5524                       {
5525                       case '0':
5526                         d_append_string (dpi, "false");
5527                         return;
5528                       case '1':
5529                         d_append_string (dpi, "true");
5530                         return;
5531                       default:
5532                         break;
5533                       }
5534                   }
5535                 break;
5536
5537               default:
5538                 break;
5539               }
5540           }
5541
5542         d_append_char (dpi, '(');
5543         d_print_comp (dpi, options, d_left (dc));
5544         d_append_char (dpi, ')');
5545         if (dc->type == DEMANGLE_COMPONENT_LITERAL_NEG)
5546           d_append_char (dpi, '-');
5547         if (tp == D_PRINT_FLOAT)
5548           d_append_char (dpi, '[');
5549         d_print_comp (dpi, options, d_right (dc));
5550         if (tp == D_PRINT_FLOAT)
5551           d_append_char (dpi, ']');
5552       }
5553       return;
5554
5555     case DEMANGLE_COMPONENT_NUMBER:
5556       d_append_num (dpi, dc->u.s_number.number);
5557       return;
5558
5559     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
5560       d_append_string (dpi, "java resource ");
5561       d_print_comp (dpi, options, d_left (dc));
5562       return;
5563
5564     case DEMANGLE_COMPONENT_COMPOUND_NAME:
5565       d_print_comp (dpi, options, d_left (dc));
5566       d_print_comp (dpi, options, d_right (dc));
5567       return;
5568
5569     case DEMANGLE_COMPONENT_CHARACTER:
5570       d_append_char (dpi, dc->u.s_character.character);
5571       return;
5572
5573     case DEMANGLE_COMPONENT_DECLTYPE:
5574       d_append_string (dpi, "decltype (");
5575       d_print_comp (dpi, options, d_left (dc));
5576       d_append_char (dpi, ')');
5577       return;
5578
5579     case DEMANGLE_COMPONENT_PACK_EXPANSION:
5580       {
5581         int len;
5582         int i;
5583         struct demangle_component *a = d_find_pack (dpi, d_left (dc));
5584         if (a == NULL)
5585           {
5586             /* d_find_pack won't find anything if the only packs involved
5587                in this expansion are function parameter packs; in that
5588                case, just print the pattern and "...".  */
5589             d_print_subexpr (dpi, options, d_left (dc));
5590             d_append_string (dpi, "...");
5591             return;
5592           }
5593
5594         len = d_pack_length (a);
5595         dc = d_left (dc);
5596         for (i = 0; i < len; ++i)
5597           {
5598             dpi->pack_index = i;
5599             d_print_comp (dpi, options, dc);
5600             if (i < len-1)
5601               d_append_string (dpi, ", ");
5602           }
5603       }
5604       return;
5605
5606     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
5607       {
5608         long num = dc->u.s_number.number;
5609         if (num == 0)
5610           d_append_string (dpi, "this");
5611         else
5612           {
5613             d_append_string (dpi, "{parm#");
5614             d_append_num (dpi, num);
5615             d_append_char (dpi, '}');
5616           }
5617       }
5618       return;
5619
5620     case DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS:
5621       d_append_string (dpi, "global constructors keyed to ");
5622       d_print_comp (dpi, options, dc->u.s_binary.left);
5623       return;
5624
5625     case DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS:
5626       d_append_string (dpi, "global destructors keyed to ");
5627       d_print_comp (dpi, options, dc->u.s_binary.left);
5628       return;
5629
5630     case DEMANGLE_COMPONENT_LAMBDA:
5631       d_append_string (dpi, "{lambda(");
5632       /* Generic lambda auto parms are mangled as the template type
5633          parm they are.  */
5634       dpi->is_lambda_arg++;
5635       d_print_comp (dpi, options, dc->u.s_unary_num.sub);
5636       dpi->is_lambda_arg--;
5637       d_append_string (dpi, ")#");
5638       d_append_num (dpi, dc->u.s_unary_num.num + 1);
5639       d_append_char (dpi, '}');
5640       return;
5641
5642     case DEMANGLE_COMPONENT_UNNAMED_TYPE:
5643       d_append_string (dpi, "{unnamed type#");
5644       d_append_num (dpi, dc->u.s_number.number + 1);
5645       d_append_char (dpi, '}');
5646       return;
5647
5648     case DEMANGLE_COMPONENT_CLONE:
5649       d_print_comp (dpi, options, d_left (dc));
5650       d_append_string (dpi, " [clone ");
5651       d_print_comp (dpi, options, d_right (dc));
5652       d_append_char (dpi, ']');
5653       return;
5654
5655     default:
5656       d_print_error (dpi);
5657       return;
5658     }
5659 }
5660
5661 static void
5662 d_print_comp (struct d_print_info *dpi, int options,
5663               const struct demangle_component *dc)
5664 {
5665   struct d_component_stack self;
5666
5667   self.dc = dc;
5668   self.parent = dpi->component_stack;
5669   dpi->component_stack = &self;
5670
5671   d_print_comp_inner (dpi, options, dc);
5672
5673   dpi->component_stack = self.parent;
5674 }
5675
5676 /* Print a Java dentifier.  For Java we try to handle encoded extended
5677    Unicode characters.  The C++ ABI doesn't mention Unicode encoding,
5678    so we don't it for C++.  Characters are encoded as
5679    __U<hex-char>+_.  */
5680
5681 static void
5682 d_print_java_identifier (struct d_print_info *dpi, const char *name, int len)
5683 {
5684   const char *p;
5685   const char *end;
5686
5687   end = name + len;
5688   for (p = name; p < end; ++p)
5689     {
5690       if (end - p > 3
5691           && p[0] == '_'
5692           && p[1] == '_'
5693           && p[2] == 'U')
5694         {
5695           unsigned long c;
5696           const char *q;
5697
5698           c = 0;
5699           for (q = p + 3; q < end; ++q)
5700             {
5701               int dig;
5702
5703               if (IS_DIGIT (*q))
5704                 dig = *q - '0';
5705               else if (*q >= 'A' && *q <= 'F')
5706                 dig = *q - 'A' + 10;
5707               else if (*q >= 'a' && *q <= 'f')
5708                 dig = *q - 'a' + 10;
5709               else
5710                 break;
5711
5712               c = c * 16 + dig;
5713             }
5714           /* If the Unicode character is larger than 256, we don't try
5715              to deal with it here.  FIXME.  */
5716           if (q < end && *q == '_' && c < 256)
5717             {
5718               d_append_char (dpi, c);
5719               p = q;
5720               continue;
5721             }
5722         }
5723
5724       d_append_char (dpi, *p);
5725     }
5726 }
5727
5728 /* Print a list of modifiers.  SUFFIX is 1 if we are printing
5729    qualifiers on this after printing a function.  */
5730
5731 static void
5732 d_print_mod_list (struct d_print_info *dpi, int options,
5733                   struct d_print_mod *mods, int suffix)
5734 {
5735   struct d_print_template *hold_dpt;
5736
5737   if (mods == NULL || d_print_saw_error (dpi))
5738     return;
5739
5740   if (mods->printed
5741       || (! suffix
5742           && (is_fnqual_component_type (mods->mod->type))))
5743     {
5744       d_print_mod_list (dpi, options, mods->next, suffix);
5745       return;
5746     }
5747
5748   mods->printed = 1;
5749
5750   hold_dpt = dpi->templates;
5751   dpi->templates = mods->templates;
5752
5753   if (mods->mod->type == DEMANGLE_COMPONENT_FUNCTION_TYPE)
5754     {
5755       d_print_function_type (dpi, options, mods->mod, mods->next);
5756       dpi->templates = hold_dpt;
5757       return;
5758     }
5759   else if (mods->mod->type == DEMANGLE_COMPONENT_ARRAY_TYPE)
5760     {
5761       d_print_array_type (dpi, options, mods->mod, mods->next);
5762       dpi->templates = hold_dpt;
5763       return;
5764     }
5765   else if (mods->mod->type == DEMANGLE_COMPONENT_LOCAL_NAME)
5766     {
5767       struct d_print_mod *hold_modifiers;
5768       struct demangle_component *dc;
5769
5770       /* When this is on the modifier stack, we have pulled any
5771          qualifiers off the right argument already.  Otherwise, we
5772          print it as usual, but don't let the left argument see any
5773          modifiers.  */
5774
5775       hold_modifiers = dpi->modifiers;
5776       dpi->modifiers = NULL;
5777       d_print_comp (dpi, options, d_left (mods->mod));
5778       dpi->modifiers = hold_modifiers;
5779
5780       if ((options & DMGL_JAVA) == 0)
5781         d_append_string (dpi, "::");
5782       else
5783         d_append_char (dpi, '.');
5784
5785       dc = d_right (mods->mod);
5786
5787       if (dc->type == DEMANGLE_COMPONENT_DEFAULT_ARG)
5788         {
5789           d_append_string (dpi, "{default arg#");
5790           d_append_num (dpi, dc->u.s_unary_num.num + 1);
5791           d_append_string (dpi, "}::");
5792           dc = dc->u.s_unary_num.sub;
5793         }
5794
5795       while (is_fnqual_component_type (dc->type))
5796         dc = d_left (dc);
5797
5798       d_print_comp (dpi, options, dc);
5799
5800       dpi->templates = hold_dpt;
5801       return;
5802     }
5803
5804   d_print_mod (dpi, options, mods->mod);
5805
5806   dpi->templates = hold_dpt;
5807
5808   d_print_mod_list (dpi, options, mods->next, suffix);
5809 }
5810
5811 /* Print a modifier.  */
5812
5813 static void
5814 d_print_mod (struct d_print_info *dpi, int options,
5815              const struct demangle_component *mod)
5816 {
5817   switch (mod->type)
5818     {
5819     case DEMANGLE_COMPONENT_RESTRICT:
5820     case DEMANGLE_COMPONENT_RESTRICT_THIS:
5821       d_append_string (dpi, " restrict");
5822       return;
5823     case DEMANGLE_COMPONENT_VOLATILE:
5824     case DEMANGLE_COMPONENT_VOLATILE_THIS:
5825       d_append_string (dpi, " volatile");
5826       return;
5827     case DEMANGLE_COMPONENT_CONST:
5828     case DEMANGLE_COMPONENT_CONST_THIS:
5829       d_append_string (dpi, " const");
5830       return;
5831     case DEMANGLE_COMPONENT_TRANSACTION_SAFE:
5832       d_append_string (dpi, " transaction_safe");
5833       return;
5834     case DEMANGLE_COMPONENT_NOEXCEPT:
5835       d_append_string (dpi, " noexcept");
5836       if (d_right (mod))
5837         {
5838           d_append_char (dpi, '(');
5839           d_print_comp (dpi, options, d_right (mod));
5840           d_append_char (dpi, ')');
5841         }
5842       return;
5843     case DEMANGLE_COMPONENT_THROW_SPEC:
5844       d_append_string (dpi, " throw");
5845       if (d_right (mod))
5846         {
5847           d_append_char (dpi, '(');
5848           d_print_comp (dpi, options, d_right (mod));
5849           d_append_char (dpi, ')');
5850         }
5851       return;
5852     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
5853       d_append_char (dpi, ' ');
5854       d_print_comp (dpi, options, d_right (mod));
5855       return;
5856     case DEMANGLE_COMPONENT_POINTER:
5857       /* There is no pointer symbol in Java.  */
5858       if ((options & DMGL_JAVA) == 0)
5859         d_append_char (dpi, '*');
5860       return;
5861     case DEMANGLE_COMPONENT_REFERENCE_THIS:
5862       /* For the ref-qualifier, put a space before the &.  */
5863       d_append_char (dpi, ' ');
5864       /* FALLTHRU */
5865     case DEMANGLE_COMPONENT_REFERENCE:
5866       d_append_char (dpi, '&');
5867       return;
5868     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
5869       d_append_char (dpi, ' ');
5870       /* FALLTHRU */
5871     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
5872       d_append_string (dpi, "&&");
5873       return;
5874     case DEMANGLE_COMPONENT_COMPLEX:
5875       d_append_string (dpi, "complex ");
5876       return;
5877     case DEMANGLE_COMPONENT_IMAGINARY:
5878       d_append_string (dpi, "imaginary ");
5879       return;
5880     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
5881       if (d_last_char (dpi) != '(')
5882         d_append_char (dpi, ' ');
5883       d_print_comp (dpi, options, d_left (mod));
5884       d_append_string (dpi, "::*");
5885       return;
5886     case DEMANGLE_COMPONENT_TYPED_NAME:
5887       d_print_comp (dpi, options, d_left (mod));
5888       return;
5889     case DEMANGLE_COMPONENT_VECTOR_TYPE:
5890       d_append_string (dpi, " __vector(");
5891       d_print_comp (dpi, options, d_left (mod));
5892       d_append_char (dpi, ')');
5893       return;
5894
5895     default:
5896       /* Otherwise, we have something that won't go back on the
5897          modifier stack, so we can just print it.  */
5898       d_print_comp (dpi, options, mod);
5899       return;
5900     }
5901 }
5902
5903 /* Print a function type, except for the return type.  */
5904
5905 static void
5906 d_print_function_type (struct d_print_info *dpi, int options,
5907                        const struct demangle_component *dc,
5908                        struct d_print_mod *mods)
5909 {
5910   int need_paren;
5911   int need_space;
5912   struct d_print_mod *p;
5913   struct d_print_mod *hold_modifiers;
5914
5915   need_paren = 0;
5916   need_space = 0;
5917   for (p = mods; p != NULL; p = p->next)
5918     {
5919       if (p->printed)
5920         break;
5921
5922       switch (p->mod->type)
5923         {
5924         case DEMANGLE_COMPONENT_POINTER:
5925         case DEMANGLE_COMPONENT_REFERENCE:
5926         case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
5927           need_paren = 1;
5928           break;
5929         case DEMANGLE_COMPONENT_RESTRICT:
5930         case DEMANGLE_COMPONENT_VOLATILE:
5931         case DEMANGLE_COMPONENT_CONST:
5932         case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
5933         case DEMANGLE_COMPONENT_COMPLEX:
5934         case DEMANGLE_COMPONENT_IMAGINARY:
5935         case DEMANGLE_COMPONENT_PTRMEM_TYPE:
5936           need_space = 1;
5937           need_paren = 1;
5938           break;
5939         FNQUAL_COMPONENT_CASE:
5940           break;
5941         default:
5942           break;
5943         }
5944       if (need_paren)
5945         break;
5946     }
5947
5948   if (need_paren)
5949     {
5950       if (! need_space)
5951         {
5952           if (d_last_char (dpi) != '('
5953               && d_last_char (dpi) != '*')
5954             need_space = 1;
5955         }
5956       if (need_space && d_last_char (dpi) != ' ')
5957         d_append_char (dpi, ' ');
5958       d_append_char (dpi, '(');
5959     }
5960
5961   hold_modifiers = dpi->modifiers;
5962   dpi->modifiers = NULL;
5963
5964   d_print_mod_list (dpi, options, mods, 0);
5965
5966   if (need_paren)
5967     d_append_char (dpi, ')');
5968
5969   d_append_char (dpi, '(');
5970
5971   if (d_right (dc) != NULL)
5972     d_print_comp (dpi, options, d_right (dc));
5973
5974   d_append_char (dpi, ')');
5975
5976   d_print_mod_list (dpi, options, mods, 1);
5977
5978   dpi->modifiers = hold_modifiers;
5979 }
5980
5981 /* Print an array type, except for the element type.  */
5982
5983 static void
5984 d_print_array_type (struct d_print_info *dpi, int options,
5985                     const struct demangle_component *dc,
5986                     struct d_print_mod *mods)
5987 {
5988   int need_space;
5989
5990   need_space = 1;
5991   if (mods != NULL)
5992     {
5993       int need_paren;
5994       struct d_print_mod *p;
5995
5996       need_paren = 0;
5997       for (p = mods; p != NULL; p = p->next)
5998         {
5999           if (! p->printed)
6000             {
6001               if (p->mod->type == DEMANGLE_COMPONENT_ARRAY_TYPE)
6002                 {
6003                   need_space = 0;
6004                   break;
6005                 }
6006               else
6007                 {
6008                   need_paren = 1;
6009                   need_space = 1;
6010                   break;
6011                 }
6012             }
6013         }
6014
6015       if (need_paren)
6016         d_append_string (dpi, " (");
6017
6018       d_print_mod_list (dpi, options, mods, 0);
6019
6020       if (need_paren)
6021         d_append_char (dpi, ')');
6022     }
6023
6024   if (need_space)
6025     d_append_char (dpi, ' ');
6026
6027   d_append_char (dpi, '[');
6028
6029   if (d_left (dc) != NULL)
6030     d_print_comp (dpi, options, d_left (dc));
6031
6032   d_append_char (dpi, ']');
6033 }
6034
6035 /* Print an operator in an expression.  */
6036
6037 static void
6038 d_print_expr_op (struct d_print_info *dpi, int options,
6039                  const struct demangle_component *dc)
6040 {
6041   if (dc->type == DEMANGLE_COMPONENT_OPERATOR)
6042     d_append_buffer (dpi, dc->u.s_operator.op->name,
6043                      dc->u.s_operator.op->len);
6044   else
6045     d_print_comp (dpi, options, dc);
6046 }
6047
6048 /* Print a cast.  */
6049
6050 static void
6051 d_print_cast (struct d_print_info *dpi, int options,
6052                     const struct demangle_component *dc)
6053 {
6054   d_print_comp (dpi, options, d_left (dc));
6055 }
6056
6057 /* Print a conversion operator.  */
6058
6059 static void
6060 d_print_conversion (struct d_print_info *dpi, int options,
6061                     const struct demangle_component *dc)
6062 {
6063   struct d_print_template dpt;
6064
6065   /* For a conversion operator, we need the template parameters from
6066      the enclosing template in scope for processing the type.  */
6067   if (dpi->current_template != NULL)
6068     {
6069       dpt.next = dpi->templates;
6070       dpi->templates = &dpt;
6071       dpt.template_decl = dpi->current_template;
6072     }
6073
6074   if (d_left (dc)->type != DEMANGLE_COMPONENT_TEMPLATE)
6075     {
6076       d_print_comp (dpi, options, d_left (dc));
6077       if (dpi->current_template != NULL)
6078         dpi->templates = dpt.next;
6079     }
6080   else
6081     {
6082       d_print_comp (dpi, options, d_left (d_left (dc)));
6083
6084       /* For a templated cast operator, we need to remove the template
6085          parameters from scope after printing the operator name,
6086          so we need to handle the template printing here.  */
6087       if (dpi->current_template != NULL)
6088         dpi->templates = dpt.next;
6089
6090       if (d_last_char (dpi) == '<')
6091         d_append_char (dpi, ' ');
6092       d_append_char (dpi, '<');
6093       d_print_comp (dpi, options, d_right (d_left (dc)));
6094       /* Avoid generating two consecutive '>' characters, to avoid
6095          the C++ syntactic ambiguity.  */
6096       if (d_last_char (dpi) == '>')
6097         d_append_char (dpi, ' ');
6098       d_append_char (dpi, '>');
6099     }
6100 }
6101
6102 /* Initialize the information structure we use to pass around
6103    information.  */
6104
6105 CP_STATIC_IF_GLIBCPP_V3
6106 void
6107 cplus_demangle_init_info (const char *mangled, int options, size_t len,
6108                           struct d_info *di)
6109 {
6110   di->s = mangled;
6111   di->send = mangled + len;
6112   di->options = options;
6113
6114   di->n = mangled;
6115
6116   /* We can not need more components than twice the number of chars in
6117      the mangled string.  Most components correspond directly to
6118      chars, but the ARGLIST types are exceptions.  */
6119   di->num_comps = 2 * len;
6120   di->next_comp = 0;
6121
6122   /* Similarly, we can not need more substitutions than there are
6123      chars in the mangled string.  */
6124   di->num_subs = len;
6125   di->next_sub = 0;
6126   di->did_subs = 0;
6127
6128   di->last_name = NULL;
6129
6130   di->expansion = 0;
6131   di->is_expression = 0;
6132   di->is_conversion = 0;
6133 }
6134
6135 /* Internal implementation for the demangler.  If MANGLED is a g++ v3 ABI
6136    mangled name, return strings in repeated callback giving the demangled
6137    name.  OPTIONS is the usual libiberty demangler options.  On success,
6138    this returns 1.  On failure, returns 0.  */
6139
6140 static int
6141 d_demangle_callback (const char *mangled, int options,
6142                      demangle_callbackref callback, void *opaque)
6143 {
6144   enum
6145     {
6146       DCT_TYPE,
6147       DCT_MANGLED,
6148       DCT_GLOBAL_CTORS,
6149       DCT_GLOBAL_DTORS
6150     }
6151   type;
6152   struct d_info di;
6153   struct demangle_component *dc;
6154   int status;
6155
6156   if (mangled[0] == '_' && mangled[1] == 'Z')
6157     type = DCT_MANGLED;
6158   else if (strncmp (mangled, "_GLOBAL_", 8) == 0
6159            && (mangled[8] == '.' || mangled[8] == '_' || mangled[8] == '$')
6160            && (mangled[9] == 'D' || mangled[9] == 'I')
6161            && mangled[10] == '_')
6162     type = mangled[9] == 'I' ? DCT_GLOBAL_CTORS : DCT_GLOBAL_DTORS;
6163   else
6164     {
6165       if ((options & DMGL_TYPES) == 0)
6166         return 0;
6167       type = DCT_TYPE;
6168     }
6169
6170   cplus_demangle_init_info (mangled, options, strlen (mangled), &di);
6171
6172   {
6173 #ifdef CP_DYNAMIC_ARRAYS
6174     __extension__ struct demangle_component comps[di.num_comps];
6175     __extension__ struct demangle_component *subs[di.num_subs];
6176
6177     di.comps = comps;
6178     di.subs = subs;
6179 #else
6180     di.comps = alloca (di.num_comps * sizeof (*di.comps));
6181     di.subs = alloca (di.num_subs * sizeof (*di.subs));
6182 #endif
6183
6184     switch (type)
6185       {
6186       case DCT_TYPE:
6187         dc = cplus_demangle_type (&di);
6188         break;
6189       case DCT_MANGLED:
6190         dc = cplus_demangle_mangled_name (&di, 1);
6191         break;
6192       case DCT_GLOBAL_CTORS:
6193       case DCT_GLOBAL_DTORS:
6194         d_advance (&di, 11);
6195         dc = d_make_comp (&di,
6196                           (type == DCT_GLOBAL_CTORS
6197                            ? DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS
6198                            : DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS),
6199                           d_make_demangle_mangled_name (&di, d_str (&di)),
6200                           NULL);
6201         d_advance (&di, strlen (d_str (&di)));
6202         break;
6203       default:
6204         abort (); /* We have listed all the cases.  */
6205       }
6206
6207     /* If DMGL_PARAMS is set, then if we didn't consume the entire
6208        mangled string, then we didn't successfully demangle it.  If
6209        DMGL_PARAMS is not set, we didn't look at the trailing
6210        parameters.  */
6211     if (((options & DMGL_PARAMS) != 0) && d_peek_char (&di) != '\0')
6212       dc = NULL;
6213
6214 #ifdef CP_DEMANGLE_DEBUG
6215     d_dump (dc, 0);
6216 #endif
6217
6218     status = (dc != NULL)
6219              ? cplus_demangle_print_callback (options, dc, callback, opaque)
6220              : 0;
6221   }
6222
6223   return status;
6224 }
6225
6226 /* Entry point for the demangler.  If MANGLED is a g++ v3 ABI mangled
6227    name, return a buffer allocated with malloc holding the demangled
6228    name.  OPTIONS is the usual libiberty demangler options.  On
6229    success, this sets *PALC to the allocated size of the returned
6230    buffer.  On failure, this sets *PALC to 0 for a bad name, or 1 for
6231    a memory allocation failure, and returns NULL.  */
6232
6233 static char *
6234 d_demangle (const char *mangled, int options, size_t *palc)
6235 {
6236   struct d_growable_string dgs;
6237   int status;
6238
6239   d_growable_string_init (&dgs, 0);
6240
6241   status = d_demangle_callback (mangled, options,
6242                                 d_growable_string_callback_adapter, &dgs);
6243   if (status == 0)
6244     {
6245       free (dgs.buf);
6246       *palc = 0;
6247       return NULL;
6248     }
6249
6250   *palc = dgs.allocation_failure ? 1 : dgs.alc;
6251   return dgs.buf;
6252 }
6253
6254 #if defined(IN_LIBGCC2) || defined(IN_GLIBCPP_V3)
6255
6256 extern char *__cxa_demangle (const char *, char *, size_t *, int *);
6257
6258 /* ia64 ABI-mandated entry point in the C++ runtime library for
6259    performing demangling.  MANGLED_NAME is a NUL-terminated character
6260    string containing the name to be demangled.
6261
6262    OUTPUT_BUFFER is a region of memory, allocated with malloc, of
6263    *LENGTH bytes, into which the demangled name is stored.  If
6264    OUTPUT_BUFFER is not long enough, it is expanded using realloc.
6265    OUTPUT_BUFFER may instead be NULL; in that case, the demangled name
6266    is placed in a region of memory allocated with malloc.
6267
6268    If LENGTH is non-NULL, the length of the buffer containing the
6269    demangled name, is placed in *LENGTH.
6270
6271    The return value is a pointer to the start of the NUL-terminated
6272    demangled name, or NULL if the demangling fails.  The caller is
6273    responsible for deallocating this memory using free.
6274
6275    *STATUS is set to one of the following values:
6276       0: The demangling operation succeeded.
6277      -1: A memory allocation failure occurred.
6278      -2: MANGLED_NAME is not a valid name under the C++ ABI mangling rules.
6279      -3: One of the arguments is invalid.
6280
6281    The demangling is performed using the C++ ABI mangling rules, with
6282    GNU extensions.  */
6283
6284 char *
6285 __cxa_demangle (const char *mangled_name, char *output_buffer,
6286                 size_t *length, int *status)
6287 {
6288   char *demangled;
6289   size_t alc;
6290
6291   if (mangled_name == NULL)
6292     {
6293       if (status != NULL)
6294         *status = -3;
6295       return NULL;
6296     }
6297
6298   if (output_buffer != NULL && length == NULL)
6299     {
6300       if (status != NULL)
6301         *status = -3;
6302       return NULL;
6303     }
6304
6305   demangled = d_demangle (mangled_name, DMGL_PARAMS | DMGL_TYPES, &alc);
6306
6307   if (demangled == NULL)
6308     {
6309       if (status != NULL)
6310         {
6311           if (alc == 1)
6312             *status = -1;
6313           else
6314             *status = -2;
6315         }
6316       return NULL;
6317     }
6318
6319   if (output_buffer == NULL)
6320     {
6321       if (length != NULL)
6322         *length = alc;
6323     }
6324   else
6325     {
6326       if (strlen (demangled) < *length)
6327         {
6328           strcpy (output_buffer, demangled);
6329           free (demangled);
6330           demangled = output_buffer;
6331         }
6332       else
6333         {
6334           free (output_buffer);
6335           *length = alc;
6336         }
6337     }
6338
6339   if (status != NULL)
6340     *status = 0;
6341
6342   return demangled;
6343 }
6344
6345 extern int __gcclibcxx_demangle_callback (const char *,
6346                                           void (*)
6347                                             (const char *, size_t, void *),
6348                                           void *);
6349
6350 /* Alternative, allocationless entry point in the C++ runtime library
6351    for performing demangling.  MANGLED_NAME is a NUL-terminated character
6352    string containing the name to be demangled.
6353
6354    CALLBACK is a callback function, called with demangled string
6355    segments as demangling progresses; it is called at least once,
6356    but may be called more than once.  OPAQUE is a generalized pointer
6357    used as a callback argument.
6358
6359    The return code is one of the following values, equivalent to
6360    the STATUS values of __cxa_demangle() (excluding -1, since this
6361    function performs no memory allocations):
6362       0: The demangling operation succeeded.
6363      -2: MANGLED_NAME is not a valid name under the C++ ABI mangling rules.
6364      -3: One of the arguments is invalid.
6365
6366    The demangling is performed using the C++ ABI mangling rules, with
6367    GNU extensions.  */
6368
6369 int
6370 __gcclibcxx_demangle_callback (const char *mangled_name,
6371                                void (*callback) (const char *, size_t, void *),
6372                                void *opaque)
6373 {
6374   int status;
6375
6376   if (mangled_name == NULL || callback == NULL)
6377     return -3;
6378
6379   status = d_demangle_callback (mangled_name, DMGL_PARAMS | DMGL_TYPES,
6380                                 callback, opaque);
6381   if (status == 0)
6382     return -2;
6383
6384   return 0;
6385 }
6386
6387 #else /* ! (IN_LIBGCC2 || IN_GLIBCPP_V3) */
6388
6389 /* Entry point for libiberty demangler.  If MANGLED is a g++ v3 ABI
6390    mangled name, return a buffer allocated with malloc holding the
6391    demangled name.  Otherwise, return NULL.  */
6392
6393 char *
6394 cplus_demangle_v3 (const char *mangled, int options)
6395 {
6396   size_t alc;
6397
6398   return d_demangle (mangled, options, &alc);
6399 }
6400
6401 int
6402 cplus_demangle_v3_callback (const char *mangled, int options,
6403                             demangle_callbackref callback, void *opaque)
6404 {
6405   return d_demangle_callback (mangled, options, callback, opaque);
6406 }
6407
6408 /* Demangle a Java symbol.  Java uses a subset of the V3 ABI C++ mangling 
6409    conventions, but the output formatting is a little different.
6410    This instructs the C++ demangler not to emit pointer characters ("*"), to
6411    use Java's namespace separator symbol ("." instead of "::"), and to output
6412    JArray<TYPE> as TYPE[].  */
6413
6414 char *
6415 java_demangle_v3 (const char *mangled)
6416 {
6417   size_t alc;
6418
6419   return d_demangle (mangled, DMGL_JAVA | DMGL_PARAMS | DMGL_RET_POSTFIX, &alc);
6420 }
6421
6422 int
6423 java_demangle_v3_callback (const char *mangled,
6424                            demangle_callbackref callback, void *opaque)
6425 {
6426   return d_demangle_callback (mangled,
6427                               DMGL_JAVA | DMGL_PARAMS | DMGL_RET_POSTFIX,
6428                               callback, opaque);
6429 }
6430
6431 #endif /* IN_LIBGCC2 || IN_GLIBCPP_V3 */
6432
6433 #ifndef IN_GLIBCPP_V3
6434
6435 /* Demangle a string in order to find out whether it is a constructor
6436    or destructor.  Return non-zero on success.  Set *CTOR_KIND and
6437    *DTOR_KIND appropriately.  */
6438
6439 static int
6440 is_ctor_or_dtor (const char *mangled,
6441                  enum gnu_v3_ctor_kinds *ctor_kind,
6442                  enum gnu_v3_dtor_kinds *dtor_kind)
6443 {
6444   struct d_info di;
6445   struct demangle_component *dc;
6446   int ret;
6447
6448   *ctor_kind = (enum gnu_v3_ctor_kinds) 0;
6449   *dtor_kind = (enum gnu_v3_dtor_kinds) 0;
6450
6451   cplus_demangle_init_info (mangled, DMGL_GNU_V3, strlen (mangled), &di);
6452
6453   {
6454 #ifdef CP_DYNAMIC_ARRAYS
6455     __extension__ struct demangle_component comps[di.num_comps];
6456     __extension__ struct demangle_component *subs[di.num_subs];
6457
6458     di.comps = comps;
6459     di.subs = subs;
6460 #else
6461     di.comps = alloca (di.num_comps * sizeof (*di.comps));
6462     di.subs = alloca (di.num_subs * sizeof (*di.subs));
6463 #endif
6464
6465     dc = cplus_demangle_mangled_name (&di, 1);
6466
6467     /* Note that because we did not pass DMGL_PARAMS, we don't expect
6468        to demangle the entire string.  */
6469
6470     ret = 0;
6471     while (dc != NULL)
6472       {
6473         switch (dc->type)
6474           {
6475             /* These cannot appear on a constructor or destructor.  */
6476           case DEMANGLE_COMPONENT_RESTRICT_THIS:
6477           case DEMANGLE_COMPONENT_VOLATILE_THIS:
6478           case DEMANGLE_COMPONENT_CONST_THIS:
6479           case DEMANGLE_COMPONENT_REFERENCE_THIS:
6480           case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
6481           default:
6482             dc = NULL;
6483             break;
6484           case DEMANGLE_COMPONENT_TYPED_NAME:
6485           case DEMANGLE_COMPONENT_TEMPLATE:
6486             dc = d_left (dc);
6487             break;
6488           case DEMANGLE_COMPONENT_QUAL_NAME:
6489           case DEMANGLE_COMPONENT_LOCAL_NAME:
6490             dc = d_right (dc);
6491             break;
6492           case DEMANGLE_COMPONENT_CTOR:
6493             *ctor_kind = dc->u.s_ctor.kind;
6494             ret = 1;
6495             dc = NULL;
6496             break;
6497           case DEMANGLE_COMPONENT_DTOR:
6498             *dtor_kind = dc->u.s_dtor.kind;
6499             ret = 1;
6500             dc = NULL;
6501             break;
6502           }
6503       }
6504   }
6505
6506   return ret;
6507 }
6508
6509 /* Return whether NAME is the mangled form of a g++ V3 ABI constructor
6510    name.  A non-zero return indicates the type of constructor.  */
6511
6512 enum gnu_v3_ctor_kinds
6513 is_gnu_v3_mangled_ctor (const char *name)
6514 {
6515   enum gnu_v3_ctor_kinds ctor_kind;
6516   enum gnu_v3_dtor_kinds dtor_kind;
6517
6518   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
6519     return (enum gnu_v3_ctor_kinds) 0;
6520   return ctor_kind;
6521 }
6522
6523
6524 /* Return whether NAME is the mangled form of a g++ V3 ABI destructor
6525    name.  A non-zero return indicates the type of destructor.  */
6526
6527 enum gnu_v3_dtor_kinds
6528 is_gnu_v3_mangled_dtor (const char *name)
6529 {
6530   enum gnu_v3_ctor_kinds ctor_kind;
6531   enum gnu_v3_dtor_kinds dtor_kind;
6532
6533   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
6534     return (enum gnu_v3_dtor_kinds) 0;
6535   return dtor_kind;
6536 }
6537
6538 #endif /* IN_GLIBCPP_V3 */
6539
6540 #ifdef STANDALONE_DEMANGLER
6541
6542 #include "getopt.h"
6543 #include "dyn-string.h"
6544
6545 static void print_usage (FILE* fp, int exit_value);
6546
6547 #define IS_ALPHA(CHAR)                                                  \
6548   (((CHAR) >= 'a' && (CHAR) <= 'z')                                     \
6549    || ((CHAR) >= 'A' && (CHAR) <= 'Z'))
6550
6551 /* Non-zero if CHAR is a character than can occur in a mangled name.  */
6552 #define is_mangled_char(CHAR)                                           \
6553   (IS_ALPHA (CHAR) || IS_DIGIT (CHAR)                                   \
6554    || (CHAR) == '_' || (CHAR) == '.' || (CHAR) == '$')
6555
6556 /* The name of this program, as invoked.  */
6557 const char* program_name;
6558
6559 /* Prints usage summary to FP and then exits with EXIT_VALUE.  */
6560
6561 static void
6562 print_usage (FILE* fp, int exit_value)
6563 {
6564   fprintf (fp, "Usage: %s [options] [names ...]\n", program_name);
6565   fprintf (fp, "Options:\n");
6566   fprintf (fp, "  -h,--help       Display this message.\n");
6567   fprintf (fp, "  -p,--no-params  Don't display function parameters\n");
6568   fprintf (fp, "  -v,--verbose    Produce verbose demanglings.\n");
6569   fprintf (fp, "If names are provided, they are demangled.  Otherwise filters standard input.\n");
6570
6571   exit (exit_value);
6572 }
6573
6574 /* Option specification for getopt_long.  */
6575 static const struct option long_options[] = 
6576 {
6577   { "help",      no_argument, NULL, 'h' },
6578   { "no-params", no_argument, NULL, 'p' },
6579   { "verbose",   no_argument, NULL, 'v' },
6580   { NULL,        no_argument, NULL, 0   },
6581 };
6582
6583 /* Main entry for a demangling filter executable.  It will demangle
6584    its command line arguments, if any.  If none are provided, it will
6585    filter stdin to stdout, replacing any recognized mangled C++ names
6586    with their demangled equivalents.  */
6587
6588 int
6589 main (int argc, char *argv[])
6590 {
6591   int i;
6592   int opt_char;
6593   int options = DMGL_PARAMS | DMGL_ANSI | DMGL_TYPES;
6594
6595   /* Use the program name of this program, as invoked.  */
6596   program_name = argv[0];
6597
6598   /* Parse options.  */
6599   do 
6600     {
6601       opt_char = getopt_long (argc, argv, "hpv", long_options, NULL);
6602       switch (opt_char)
6603         {
6604         case '?':  /* Unrecognized option.  */
6605           print_usage (stderr, 1);
6606           break;
6607
6608         case 'h':
6609           print_usage (stdout, 0);
6610           break;
6611
6612         case 'p':
6613           options &= ~ DMGL_PARAMS;
6614           break;
6615
6616         case 'v':
6617           options |= DMGL_VERBOSE;
6618           break;
6619         }
6620     }
6621   while (opt_char != -1);
6622
6623   if (optind == argc) 
6624     /* No command line arguments were provided.  Filter stdin.  */
6625     {
6626       dyn_string_t mangled = dyn_string_new (3);
6627       char *s;
6628
6629       /* Read all of input.  */
6630       while (!feof (stdin))
6631         {
6632           char c;
6633
6634           /* Pile characters into mangled until we hit one that can't
6635              occur in a mangled name.  */
6636           c = getchar ();
6637           while (!feof (stdin) && is_mangled_char (c))
6638             {
6639               dyn_string_append_char (mangled, c);
6640               if (feof (stdin))
6641                 break;
6642               c = getchar ();
6643             }
6644
6645           if (dyn_string_length (mangled) > 0)
6646             {
6647 #ifdef IN_GLIBCPP_V3
6648               s = __cxa_demangle (dyn_string_buf (mangled), NULL, NULL, NULL);
6649 #else
6650               s = cplus_demangle_v3 (dyn_string_buf (mangled), options);
6651 #endif
6652
6653               if (s != NULL)
6654                 {
6655                   fputs (s, stdout);
6656                   free (s);
6657                 }
6658               else
6659                 {
6660                   /* It might not have been a mangled name.  Print the
6661                      original text.  */
6662                   fputs (dyn_string_buf (mangled), stdout);
6663                 }
6664
6665               dyn_string_clear (mangled);
6666             }
6667
6668           /* If we haven't hit EOF yet, we've read one character that
6669              can't occur in a mangled name, so print it out.  */
6670           if (!feof (stdin))
6671             putchar (c);
6672         }
6673
6674       dyn_string_delete (mangled);
6675     }
6676   else
6677     /* Demangle command line arguments.  */
6678     {
6679       /* Loop over command line arguments.  */
6680       for (i = optind; i < argc; ++i)
6681         {
6682           char *s;
6683 #ifdef IN_GLIBCPP_V3
6684           int status;
6685 #endif
6686
6687           /* Attempt to demangle.  */
6688 #ifdef IN_GLIBCPP_V3
6689           s = __cxa_demangle (argv[i], NULL, NULL, &status);
6690 #else
6691           s = cplus_demangle_v3 (argv[i], options);
6692 #endif
6693
6694           /* If it worked, print the demangled name.  */
6695           if (s != NULL)
6696             {
6697               printf ("%s\n", s);
6698               free (s);
6699             }
6700           else
6701             {
6702 #ifdef IN_GLIBCPP_V3
6703               fprintf (stderr, "Failed: %s (status %d)\n", argv[i], status);
6704 #else
6705               fprintf (stderr, "Failed: %s\n", argv[i]);
6706 #endif
6707             }
6708         }
6709     }
6710
6711   return 0;
6712 }
6713
6714 #endif /* STANDALONE_DEMANGLER */