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