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