]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/gcc/cp/mangle.c
Merge FreeBSD modifications into gcc 3.2.1-prerelease:
[FreeBSD/FreeBSD.git] / contrib / gcc / cp / mangle.c
1 /* Name mangling for the 3.0 C++ ABI.
2    Copyright (C) 2000, 2001, 2002 Free Software Foundation, Inc.
3    Written by Alex Samuel <sameul@codesourcery.com>
4
5    This file is part of GNU CC.
6
7    GNU CC is free software; you can redistribute it and/or modify it
8    under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2, or (at your option)
10    any later version.
11
12    GNU CC is distributed in the hope that it will be useful, but
13    WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15    General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GNU CC; see the file COPYING.  If not, write to the Free
19    Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20    02111-1307, USA.  */
21
22 /* This file implements mangling of C++ names according to the IA64
23    C++ ABI specification.  A mangled name encodes a function or
24    variable's name, scope, type, and/or template arguments into a text
25    identifier.  This identifier is used as the function's or
26    variable's linkage name, to preserve compatibility between C++'s
27    language features (templates, scoping, and overloading) and C
28    linkers.
29
30    Additionally, g++ uses mangled names internally.  To support this,
31    mangling of types is allowed, even though the mangled name of a
32    type should not appear by itself as an exported name.  Ditto for
33    uninstantiated templates.
34
35    The primary entry point for this module is mangle_decl, which
36    returns an identifier containing the mangled name for a decl.
37    Additional entry points are provided to build mangled names of
38    particular constructs when the appropriate decl for that construct
39    is not available.  These are:
40
41      mangle_typeinfo_for_type:        typeinfo data
42      mangle_typeinfo_string_for_type: typeinfo type name
43      mangle_vtbl_for_type:            virtual table data
44      mangle_vtt_for_type:             VTT data
45      mangle_ctor_vtbl_for_type:       `C-in-B' constructor virtual table data
46      mangle_thunk:                    thunk function or entry
47
48 */
49
50 #include "config.h"
51 #include "system.h"
52 #include "tree.h"
53 #include "cp-tree.h"
54 #include "obstack.h"
55 #include "toplev.h"
56 #include "varray.h"
57
58 /* Debugging support.  */
59
60 /* Define DEBUG_MANGLE to enable very verbose trace messages.  */
61 #ifndef DEBUG_MANGLE
62 #define DEBUG_MANGLE 0
63 #endif
64
65 /* Macros for tracing the write_* functions.  */
66 #if DEBUG_MANGLE
67 # define MANGLE_TRACE(FN, INPUT) \
68   fprintf (stderr, "  %-24s: %-24s\n", (FN), (INPUT))
69 # define MANGLE_TRACE_TREE(FN, NODE) \
70   fprintf (stderr, "  %-24s: %-24s (%p)\n", \
71            (FN), tree_code_name[TREE_CODE (NODE)], (void *) (NODE))
72 #else
73 # define MANGLE_TRACE(FN, INPUT)
74 # define MANGLE_TRACE_TREE(FN, NODE)
75 #endif
76
77 /* Non-zero if NODE is a class template-id.  We can't rely on
78    CLASSTYPE_USE_TEMPLATE here because of tricky bugs in the parser
79    that hard to distinguish A<T> from A, where A<T> is the type as
80    instantiated outside of the template, and A is the type used
81    without parameters inside the template.  */
82 #define CLASSTYPE_TEMPLATE_ID_P(NODE)                                 \
83   (TYPE_LANG_SPECIFIC (NODE) != NULL                                  \
84    && CLASSTYPE_TEMPLATE_INFO (NODE) != NULL                          \
85    && (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (NODE))))
86
87 /* Things we only need one of.  This module is not reentrant.  */
88 static struct globals
89 {
90   /* The name in which we're building the mangled name.  */
91   struct obstack name_obstack;
92
93   /* An array of the current substitution candidates, in the order
94      we've seen them.  */
95   varray_type substitutions;
96 } G;
97
98 /* Indices into subst_identifiers.  These are identifiers used in
99    special substitution rules.  */
100 typedef enum
101 {
102   SUBID_ALLOCATOR,
103   SUBID_BASIC_STRING,
104   SUBID_CHAR_TRAITS,
105   SUBID_BASIC_ISTREAM,
106   SUBID_BASIC_OSTREAM,
107   SUBID_BASIC_IOSTREAM,
108   SUBID_MAX
109 }
110 substitution_identifier_index_t;
111
112 /* For quick substitution checks, look up these common identifiers
113    once only.  */
114 static tree subst_identifiers[SUBID_MAX];
115
116 /* Single-letter codes for builtin integer types, defined in
117    <builtin-type>.  These are indexed by integer_type_kind values.  */
118 static char
119 integer_type_codes[itk_none] =
120 {
121   'c',  /* itk_char */
122   'a',  /* itk_signed_char */
123   'h',  /* itk_unsigned_char */
124   's',  /* itk_short */
125   't',  /* itk_unsigned_short */
126   'i',  /* itk_int */
127   'j',  /* itk_unsigned_int */
128   'l',  /* itk_long */
129   'm',  /* itk_unsigned_long */
130   'x',  /* itk_long_long */
131   'y'   /* itk_unsigned_long_long */
132 };
133
134 static int decl_is_template_id PARAMS ((tree, tree*));
135
136 /* Functions for handling substitutions.  */
137
138 static inline tree canonicalize_for_substitution PARAMS ((tree));
139 static void add_substitution PARAMS ((tree));
140 static inline int is_std_substitution PARAMS ((tree, substitution_identifier_index_t));
141 static inline int is_std_substitution_char PARAMS ((tree, substitution_identifier_index_t));
142 static int find_substitution PARAMS ((tree));
143
144 /* Functions for emitting mangled representations of things.  */
145
146 static void write_mangled_name PARAMS ((tree));
147 static void write_encoding PARAMS ((tree));
148 static void write_name PARAMS ((tree, int));
149 static void write_unscoped_name PARAMS ((tree));
150 static void write_unscoped_template_name PARAMS ((tree));
151 static void write_nested_name PARAMS ((tree));
152 static void write_prefix PARAMS ((tree));
153 static void write_template_prefix PARAMS ((tree));
154 static void write_unqualified_name PARAMS ((tree));
155 static void write_source_name PARAMS ((tree));
156 static int hwint_to_ascii PARAMS ((unsigned HOST_WIDE_INT, unsigned int, char *, unsigned));
157 static void write_number PARAMS ((unsigned HOST_WIDE_INT, int,
158                                   unsigned int));
159 static void write_integer_cst PARAMS ((tree));
160 static void write_identifier PARAMS ((const char *));
161 static void write_special_name_constructor PARAMS ((tree));
162 static void write_special_name_destructor PARAMS ((tree));
163 static void write_type PARAMS ((tree));
164 static int write_CV_qualifiers_for_type PARAMS ((tree));
165 static void write_builtin_type PARAMS ((tree));
166 static void write_function_type PARAMS ((tree));
167 static void write_bare_function_type PARAMS ((tree, int, tree));
168 static void write_method_parms PARAMS ((tree, int, tree));
169 static void write_class_enum_type PARAMS ((tree));
170 static void write_template_args PARAMS ((tree));
171 static void write_expression PARAMS ((tree));
172 static void write_template_arg_literal PARAMS ((tree));
173 static void write_template_arg PARAMS ((tree));
174 static void write_template_template_arg PARAMS ((tree));
175 static void write_array_type PARAMS ((tree));
176 static void write_pointer_to_member_type PARAMS ((tree));
177 static void write_template_param PARAMS ((tree));
178 static void write_template_template_param PARAMS ((tree));
179 static void write_substitution PARAMS ((int));
180 static int discriminator_for_local_entity PARAMS ((tree));
181 static int discriminator_for_string_literal PARAMS ((tree, tree));
182 static void write_discriminator PARAMS ((int));
183 static void write_local_name PARAMS ((tree, tree, tree));
184 static void dump_substitution_candidates PARAMS ((void));
185 static const char *mangle_decl_string PARAMS ((tree));
186
187 /* Control functions.  */
188
189 static inline void start_mangling PARAMS ((void));
190 static inline const char *finish_mangling PARAMS ((void));
191 static tree mangle_special_for_type PARAMS ((tree, const char *));
192
193 /* Foreign language functions. */
194
195 static void write_java_integer_type_codes PARAMS ((tree));
196
197 /* Append a single character to the end of the mangled
198    representation.  */
199 #define write_char(CHAR)                                              \
200   obstack_1grow (&G.name_obstack, (CHAR))
201
202 /* Append a sized buffer to the end of the mangled representation. */
203 #define write_chars(CHAR, LEN)                                        \
204   obstack_grow (&G.name_obstack, (CHAR), (LEN))
205
206 /* Append a NUL-terminated string to the end of the mangled
207    representation.  */
208 #define write_string(STRING)                                          \
209   obstack_grow (&G.name_obstack, (STRING), strlen (STRING))
210
211 /* Return the position at which the next character will be appended to
212    the mangled representation.  */
213 #define mangled_position()                                              \
214   obstack_object_size (&G.name_obstack)
215
216 /* Non-zero if NODE1 and NODE2 are both TREE_LIST nodes and have the
217    same purpose (context, which may be a type) and value (template
218    decl).  See write_template_prefix for more information on what this
219    is used for.  */
220 #define NESTED_TEMPLATE_MATCH(NODE1, NODE2)                         \
221   (TREE_CODE (NODE1) == TREE_LIST                                     \
222    && TREE_CODE (NODE2) == TREE_LIST                                  \
223    && ((TYPE_P (TREE_PURPOSE (NODE1))                                 \
224         && same_type_p (TREE_PURPOSE (NODE1), TREE_PURPOSE (NODE2)))\
225        || TREE_PURPOSE (NODE1) == TREE_PURPOSE (NODE2))             \
226    && TREE_VALUE (NODE1) == TREE_VALUE (NODE2))
227
228 /* Write out a signed quantity in base 10.  */
229 #define write_signed_number(NUMBER) \
230   write_number ((NUMBER), /*unsigned_p=*/0, 10)
231
232 /* Write out an unsigned quantity in base 10.  */
233 #define write_unsigned_number(NUMBER) \
234   write_number ((NUMBER), /*unsigned_p=*/1, 10)
235
236 /* If DECL is a template instance, return non-zero and, if
237    TEMPLATE_INFO is non-NULL, set *TEMPLATE_INFO to its template info.
238    Otherwise return zero.  */
239
240 static int
241 decl_is_template_id (decl, template_info)
242      tree decl;
243      tree* template_info;
244 {
245   if (TREE_CODE (decl) == TYPE_DECL)
246     {
247       /* TYPE_DECLs are handled specially.  Look at its type to decide
248          if this is a template instantiation.  */
249       tree type = TREE_TYPE (decl);
250
251       if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_ID_P (type))
252         {
253           if (template_info != NULL)
254             /* For a templated TYPE_DECL, the template info is hanging
255                off the type.  */
256             *template_info = CLASSTYPE_TEMPLATE_INFO (type);
257           return 1;
258         }
259     } 
260   else
261     {
262       /* Check if this is a primary template.  */
263       if (DECL_LANG_SPECIFIC (decl) != NULL
264           && DECL_USE_TEMPLATE (decl)
265           && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl))
266           && TREE_CODE (decl) != TEMPLATE_DECL)
267         {
268           if (template_info != NULL)
269             /* For most templated decls, the template info is hanging
270                off the decl.  */
271             *template_info = DECL_TEMPLATE_INFO (decl);
272           return 1;
273         }
274     }
275
276   /* It's not a template id.  */
277   return 0;
278 }
279
280 /* Produce debugging output of current substitution candidates.  */
281
282 static void
283 dump_substitution_candidates ()
284 {
285   unsigned i;
286
287   fprintf (stderr, "  ++ substitutions  ");
288   for (i = 0; i < VARRAY_ACTIVE_SIZE (G.substitutions); ++i)
289     {
290       tree el = VARRAY_TREE (G.substitutions, i);
291       const char *name = "???";
292
293       if (i > 0)
294         fprintf (stderr, "                    ");
295       if (DECL_P (el))
296         name = IDENTIFIER_POINTER (DECL_NAME (el));
297       else if (TREE_CODE (el) == TREE_LIST)
298         name = IDENTIFIER_POINTER (DECL_NAME (TREE_VALUE (el)));
299       else if (TYPE_NAME (el))
300         name = IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (el)));
301       fprintf (stderr, " S%d_ = ", i - 1);
302       if (TYPE_P (el) && 
303           (CP_TYPE_RESTRICT_P (el) 
304            || CP_TYPE_VOLATILE_P (el) 
305            || CP_TYPE_CONST_P (el)))
306         fprintf (stderr, "CV-");
307       fprintf (stderr, "%s (%s at %p)\n", 
308                name, tree_code_name[TREE_CODE (el)], (void *) el);
309     }
310 }
311
312 /* Both decls and types can be substitution candidates, but sometimes
313    they refer to the same thing.  For instance, a TYPE_DECL and
314    RECORD_TYPE for the same class refer to the same thing, and should
315    be treated accordinginly in substitutions.  This function returns a
316    canonicalized tree node representing NODE that is used when adding
317    and substitution candidates and finding matches.  */
318
319 static inline tree
320 canonicalize_for_substitution (node)
321      tree node;
322 {
323   /* For a TYPE_DECL, use the type instead.  */
324   if (TREE_CODE (node) == TYPE_DECL)
325     node = TREE_TYPE (node);
326   if (TYPE_P (node))
327     node = canonical_type_variant (node);
328
329   return node;
330 }
331
332 /* Add NODE as a substitution candidate.  NODE must not already be on
333    the list of candidates.  */
334
335 static void
336 add_substitution (node)
337      tree node;
338 {
339   tree c;
340
341   if (DEBUG_MANGLE)
342     fprintf (stderr, "  ++ add_substitution (%s at %10p)\n", 
343              tree_code_name[TREE_CODE (node)], (void *) node);
344
345   /* Get the canonicalized substitution candidate for NODE.  */
346   c = canonicalize_for_substitution (node);
347   if (DEBUG_MANGLE && c != node)
348     fprintf (stderr, "  ++ using candidate (%s at %10p)\n",
349              tree_code_name[TREE_CODE (node)], (void *) node);
350   node = c;
351
352 #if ENABLE_CHECKING
353   /* Make sure NODE isn't already a candidate.  */
354   {
355     int i;
356     for (i = VARRAY_ACTIVE_SIZE (G.substitutions); --i >= 0; )
357       {
358         tree candidate = VARRAY_TREE (G.substitutions, i);
359         if ((DECL_P (node) 
360              && node == candidate)
361             || (TYPE_P (node) 
362                 && TYPE_P (candidate) 
363                 && same_type_p (node, candidate)))
364           abort ();
365       }
366   }
367 #endif /* ENABLE_CHECKING */
368
369   /* Put the decl onto the varray of substitution candidates.  */
370   VARRAY_PUSH_TREE (G.substitutions, node);
371
372   if (DEBUG_MANGLE)
373     dump_substitution_candidates ();
374 }
375
376 /* Helper function for find_substitution.  Returns non-zero if NODE,
377    which may be a decl or a CLASS_TYPE, is a template-id with template
378    name of substitution_index[INDEX] in the ::std namespace.  */
379
380 static inline int 
381 is_std_substitution (node, index)
382      tree node;
383      substitution_identifier_index_t index;
384 {
385   tree type = NULL;
386   tree decl = NULL;
387
388   if (DECL_P (node))
389     {
390       type = TREE_TYPE (node);
391       decl = node;
392     }
393   else if (CLASS_TYPE_P (node))
394     {
395       type = node;
396       decl = TYPE_NAME (node);
397     }
398   else 
399     /* These are not the droids you're looking for.  */
400     return 0;
401
402   return (DECL_NAMESPACE_STD_P (CP_DECL_CONTEXT (decl))
403           && TYPE_LANG_SPECIFIC (type) 
404           && CLASSTYPE_TEMPLATE_INFO (type)
405           && (DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)) 
406               == subst_identifiers[index]));
407 }
408
409 /* Helper function for find_substitution.  Returns non-zero if NODE,
410    which may be a decl or a CLASS_TYPE, is the template-id
411    ::std::identifier<char>, where identifier is
412    substitution_index[INDEX].  */
413
414 static inline int
415 is_std_substitution_char (node, index)
416      tree node;
417      substitution_identifier_index_t index;
418 {
419   tree args;
420   /* Check NODE's name is ::std::identifier.  */
421   if (!is_std_substitution (node, index))
422     return 0;
423   /* Figure out its template args.  */
424   if (DECL_P (node))
425     args = DECL_TI_ARGS (node);  
426   else if (CLASS_TYPE_P (node))
427     args = CLASSTYPE_TI_ARGS (node);
428   else
429     /* Oops, not a template.  */
430     return 0;
431   /* NODE's template arg list should be <char>.  */
432   return 
433     TREE_VEC_LENGTH (args) == 1
434     && TREE_VEC_ELT (args, 0) == char_type_node;
435 }
436
437 /* Check whether a substitution should be used to represent NODE in
438    the mangling.
439
440    First, check standard special-case substitutions.
441
442      <substitution> ::= St     
443          # ::std
444
445                     ::= Sa     
446          # ::std::allocator
447
448                     ::= Sb     
449          # ::std::basic_string
450
451                     ::= Ss 
452          # ::std::basic_string<char,
453                                ::std::char_traits<char>,
454                                ::std::allocator<char> >
455
456                     ::= Si 
457          # ::std::basic_istream<char, ::std::char_traits<char> >
458
459                     ::= So 
460          # ::std::basic_ostream<char, ::std::char_traits<char> >
461
462                     ::= Sd 
463          # ::std::basic_iostream<char, ::std::char_traits<char> >   
464
465    Then examine the stack of currently available substitution
466    candidates for entities appearing earlier in the same mangling
467
468    If a substitution is found, write its mangled representation and
469    return non-zero.  If none is found, just return zero.  */
470
471 static int
472 find_substitution (node)
473      tree node;
474 {
475   int i;
476   int size = VARRAY_ACTIVE_SIZE (G.substitutions);
477   tree decl;
478   tree type;
479
480   if (DEBUG_MANGLE)
481     fprintf (stderr, "  ++ find_substitution (%s at %p)\n",
482              tree_code_name[TREE_CODE (node)], (void *) node);
483
484   /* Obtain the canonicalized substitution representation for NODE.
485      This is what we'll compare against.  */
486   node = canonicalize_for_substitution (node);
487
488   /* Check for builtin substitutions.  */
489
490   decl = TYPE_P (node) ? TYPE_NAME (node) : node;
491   type = TYPE_P (node) ? node : TREE_TYPE (node);
492
493   /* Check for std::allocator.  */
494   if (decl 
495       && is_std_substitution (decl, SUBID_ALLOCATOR)
496       && !CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)))
497     {
498       write_string ("Sa");
499       return 1;
500     }
501
502   /* Check for std::basic_string.  */
503   if (decl && is_std_substitution (decl, SUBID_BASIC_STRING))
504     {
505       if (TYPE_P (node))
506         {
507           /* If this is a type (i.e. a fully-qualified template-id), 
508              check for 
509                  std::basic_string <char,
510                                     std::char_traits<char>,
511                                     std::allocator<char> > .  */
512           if (cp_type_quals (type) == TYPE_UNQUALIFIED
513               && CLASSTYPE_USE_TEMPLATE (type))
514             {
515               tree args = CLASSTYPE_TI_ARGS (type);
516               if (TREE_VEC_LENGTH (args) == 3
517                   && same_type_p (TREE_VEC_ELT (args, 0), char_type_node)
518                   && is_std_substitution_char (TREE_VEC_ELT (args, 1),
519                                                SUBID_CHAR_TRAITS)
520                   && is_std_substitution_char (TREE_VEC_ELT (args, 2),
521                                                SUBID_ALLOCATOR))
522                 {
523                   write_string ("Ss");
524                   return 1;
525                 }
526             }
527         }
528       else
529         /* Substitute for the template name only if this isn't a type.  */
530         {
531           write_string ("Sb");
532           return 1;
533         }
534     }
535
536   /* Check for basic_{i,o,io}stream.  */
537   if (TYPE_P (node)
538       && cp_type_quals (type) == TYPE_UNQUALIFIED
539       && CLASS_TYPE_P (type)
540       && CLASSTYPE_USE_TEMPLATE (type)
541       && CLASSTYPE_TEMPLATE_INFO (type) != NULL)
542     {
543       /* First, check for the template 
544          args <char, std::char_traits<char> > .  */
545       tree args = CLASSTYPE_TI_ARGS (type);
546       if (TREE_VEC_LENGTH (args) == 2
547           && same_type_p (TREE_VEC_ELT (args, 0), char_type_node)
548           && is_std_substitution_char (TREE_VEC_ELT (args, 1),
549                                        SUBID_CHAR_TRAITS))
550         {
551           /* Got them.  Is this basic_istream?  */
552           tree name = DECL_NAME (CLASSTYPE_TI_TEMPLATE (type));
553           if (name == subst_identifiers[SUBID_BASIC_ISTREAM])
554             {
555               write_string ("Si");
556               return 1;
557             }
558           /* Or basic_ostream?  */
559           else if (name == subst_identifiers[SUBID_BASIC_OSTREAM])
560             {
561               write_string ("So");
562               return 1;
563             }
564           /* Or basic_iostream?  */
565           else if (name == subst_identifiers[SUBID_BASIC_IOSTREAM])
566             {
567               write_string ("Sd");
568               return 1;
569             }
570         }
571     }
572
573   /* Check for namespace std.  */
574   if (decl && DECL_NAMESPACE_STD_P (decl))
575     {
576       write_string ("St");
577       return 1;
578     }
579
580   /* Now check the list of available substitutions for this mangling
581      operation.    */
582   for (i = 0; i < size; ++i)
583     {
584       tree candidate = VARRAY_TREE (G.substitutions, i);
585       /* NODE is a matched to a candidate if it's the same decl node or
586          if it's the same type.  */
587       if (decl == candidate
588           || (TYPE_P (candidate) && type && TYPE_P (type)
589               && same_type_p (type, candidate))
590           || NESTED_TEMPLATE_MATCH (node, candidate))
591         {
592           write_substitution (i);
593           return 1;
594         }
595     }
596
597   /* No substitution found.  */
598   return 0;
599 }
600
601
602 /*  <mangled-name>      ::= _Z <encoding>  */
603
604 static inline void
605 write_mangled_name (decl)
606      tree decl;
607 {
608   MANGLE_TRACE_TREE ("mangled-name", decl);
609
610   if (DECL_LANG_SPECIFIC (decl)
611       && DECL_EXTERN_C_FUNCTION_P (decl)
612       && ! DECL_OVERLOADED_OPERATOR_P (decl))
613     /* The standard notes:
614          "The <encoding> of an extern "C" function is treated like
615          global-scope data, i.e. as its <source-name> without a type."
616        We cannot write overloaded operators that way though,
617        because it contains characters invalid in assembler.  */
618     write_source_name (DECL_NAME (decl));
619   else
620     /* C++ name; needs to be mangled.  */
621     {
622       write_string ("_Z");
623       write_encoding (decl);
624     }
625 }
626
627 /*   <encoding>         ::= <function name> <bare-function-type>
628                         ::= <data name>  */
629
630 static void
631 write_encoding (decl)
632      tree decl;
633 {
634   MANGLE_TRACE_TREE ("encoding", decl);
635
636   if (DECL_LANG_SPECIFIC (decl) && DECL_EXTERN_C_FUNCTION_P (decl))
637     {
638       /* For overloaded operators write just the mangled name
639          without arguments.  */
640       if (DECL_OVERLOADED_OPERATOR_P (decl))
641         write_name (decl, /*ignore_local_scope=*/0);
642       else
643         write_source_name (DECL_NAME (decl));
644       return;
645     }
646
647   write_name (decl, /*ignore_local_scope=*/0);
648   if (TREE_CODE (decl) == FUNCTION_DECL)
649     {
650       tree fn_type;
651
652       if (decl_is_template_id (decl, NULL))
653         fn_type = get_mostly_instantiated_function_type (decl, NULL, NULL);
654       else
655         fn_type = TREE_TYPE (decl);
656
657       write_bare_function_type (fn_type, 
658                                 (!DECL_CONSTRUCTOR_P (decl)
659                                  && !DECL_DESTRUCTOR_P (decl)
660                                  && !DECL_CONV_FN_P (decl)
661                                  && decl_is_template_id (decl, NULL)),
662                                 decl);
663     }
664 }
665
666 /* <name> ::= <unscoped-name>
667           ::= <unscoped-template-name> <template-args>
668           ::= <nested-name>
669           ::= <local-name>  
670
671    If IGNORE_LOCAL_SCOPE is non-zero, this production of <name> is
672    called from <local-name>, which mangles the enclosing scope
673    elsewhere and then uses this function to mangle just the part
674    underneath the function scope.  So don't use the <local-name>
675    production, to avoid an infinite recursion.  */
676
677 static void
678 write_name (decl, ignore_local_scope)
679      tree decl;
680      int ignore_local_scope;
681 {
682   tree context;
683
684   MANGLE_TRACE_TREE ("name", decl);
685
686   if (TREE_CODE (decl) == TYPE_DECL)
687     {
688       /* In case this is a typedef, fish out the corresponding
689          TYPE_DECL for the main variant.  */
690       decl = TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl)));
691       context = TYPE_CONTEXT (TYPE_MAIN_VARIANT (TREE_TYPE (decl)));
692     }
693   else
694     context = (DECL_CONTEXT (decl) == NULL) ? NULL : CP_DECL_CONTEXT (decl);
695
696   /* A decl in :: or ::std scope is treated specially.  The former is
697      mangled using <unscoped-name> or <unscoped-template-name>, the
698      latter with a special substitution.  Also, a name that is
699      directly in a local function scope is also mangled with
700      <unscoped-name> rather than a full <nested-name>.  */
701   if (context == NULL 
702       || context == global_namespace 
703       || DECL_NAMESPACE_STD_P (context)
704       || (ignore_local_scope && TREE_CODE (context) == FUNCTION_DECL))
705     {
706       tree template_info;
707       /* Is this a template instance?  */
708       if (decl_is_template_id (decl, &template_info))
709         {
710           /* Yes: use <unscoped-template-name>.  */
711           write_unscoped_template_name (TI_TEMPLATE (template_info));
712           write_template_args (TI_ARGS (template_info));
713         }
714       else
715         /* Everything else gets an <unqualified-name>.  */
716         write_unscoped_name (decl);
717     }
718   else
719     {
720       /* Handle local names, unless we asked not to (that is, invoked
721          under <local-name>, to handle only the part of the name under
722          the local scope).  */
723       if (!ignore_local_scope)
724         {
725           /* Scan up the list of scope context, looking for a
726              function.  If we find one, this entity is in local
727              function scope.  local_entity tracks context one scope
728              level down, so it will contain the element that's
729              directly in that function's scope, either decl or one of
730              its enclosing scopes.  */
731           tree local_entity = decl;
732           while (context != NULL && context != global_namespace)
733             {
734               /* Make sure we're always dealing with decls.  */
735               if (context != NULL && TYPE_P (context))
736                 context = TYPE_NAME (context);
737               /* Is this a function?  */
738               if (TREE_CODE (context) == FUNCTION_DECL)
739                 {
740                   /* Yes, we have local scope.  Use the <local-name>
741                      production for the innermost function scope.  */
742                   write_local_name (context, local_entity, decl);
743                   return;
744                 }
745               /* Up one scope level.  */
746               local_entity = context;
747               context = CP_DECL_CONTEXT (context);
748             }
749
750           /* No local scope found?  Fall through to <nested-name>.  */
751         }
752
753       /* Other decls get a <nested-name> to encode their scope.  */
754       write_nested_name (decl);
755     }
756 }
757
758 /* <unscoped-name> ::= <unqualified-name>
759                    ::= St <unqualified-name>   # ::std::  */
760
761 static void
762 write_unscoped_name (decl)
763      tree decl;
764 {
765   tree context = CP_DECL_CONTEXT (decl);
766
767   MANGLE_TRACE_TREE ("unscoped-name", decl);
768
769   /* Is DECL in ::std?  */
770   if (DECL_NAMESPACE_STD_P (context))
771     {
772       write_string ("St");
773       write_unqualified_name (decl);
774     }
775   /* If not, it should be either in the global namespace, or directly
776      in a local function scope.  */
777   else if (context == global_namespace 
778            || context == NULL
779            || TREE_CODE (context) == FUNCTION_DECL)
780     write_unqualified_name (decl);
781   else 
782     abort ();
783 }
784
785 /* <unscoped-template-name> ::= <unscoped-name>
786                             ::= <substitution>  */
787
788 static void
789 write_unscoped_template_name (decl)
790      tree decl;
791 {
792   MANGLE_TRACE_TREE ("unscoped-template-name", decl);
793
794   if (find_substitution (decl))
795     return;
796   write_unscoped_name (decl);
797   add_substitution (decl);
798 }
799
800 /* Write the nested name, including CV-qualifiers, of DECL.
801
802    <nested-name> ::= N [<CV-qualifiers>] <prefix> <unqualified-name> E  
803                  ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
804
805    <CV-qualifiers> ::= [r] [V] [K]  */
806
807 static void
808 write_nested_name (decl)
809      tree decl;
810 {
811   tree template_info;
812
813   MANGLE_TRACE_TREE ("nested-name", decl);
814
815   write_char ('N');
816   
817   /* Write CV-qualifiers, if this is a member function.  */
818   if (TREE_CODE (decl) == FUNCTION_DECL 
819       && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
820     {
821       if (DECL_VOLATILE_MEMFUNC_P (decl))
822         write_char ('V');
823       if (DECL_CONST_MEMFUNC_P (decl))
824         write_char ('K');
825     }
826
827   /* Is this a template instance?  */
828   if (decl_is_template_id (decl, &template_info))
829     {
830       /* Yes, use <template-prefix>.  */
831       write_template_prefix (decl);
832       write_template_args (TI_ARGS (template_info));
833     }
834   else
835     {
836       /* No, just use <prefix>  */
837       write_prefix (DECL_CONTEXT (decl));
838       write_unqualified_name (decl);
839     }
840   write_char ('E');
841 }
842
843 /* <prefix> ::= <prefix> <unqualified-name>>
844             ::= <template-prefix> <template-args>
845             ::= # empty
846             ::= <substitution>  */
847
848 static void
849 write_prefix (node)
850      tree node;
851 {
852   tree decl;
853   /* Non-NULL if NODE represents a template-id.  */
854   tree template_info = NULL;
855
856   MANGLE_TRACE_TREE ("prefix", node);
857
858   if (node == NULL
859       || node == global_namespace)
860     return;
861
862   if (find_substitution (node))
863     return;
864
865   if (DECL_P (node))
866     /* Node is a decl.  */
867     {
868       /* If this is a function decl, that means we've hit function
869          scope, so this prefix must be for a local name.  In this
870          case, we're under the <local-name> production, which encodes
871          the enclosing function scope elsewhere.  So don't continue
872          here.  */
873       if (TREE_CODE (node) == FUNCTION_DECL)
874         return;
875
876       decl = node;
877       decl_is_template_id (decl, &template_info);
878     }
879   else
880     /* Node is a type.  */
881     {
882       decl = TYPE_NAME (node);
883       if (CLASSTYPE_TEMPLATE_ID_P (node))
884         template_info = CLASSTYPE_TEMPLATE_INFO (node);
885     }
886
887   if (template_info != NULL)
888     /* Templated.  */
889     {
890       write_template_prefix (decl);
891       write_template_args (TI_ARGS (template_info));
892     }
893   else
894     /* Not templated.  */
895     {
896       write_prefix (CP_DECL_CONTEXT (decl));
897       write_unqualified_name (decl);
898     }
899
900   add_substitution (node);
901 }
902
903 /* <template-prefix> ::= <prefix> <template component>
904                      ::= <substitution>  */
905
906 static void
907 write_template_prefix (node)
908      tree node;
909 {
910   tree decl = DECL_P (node) ? node : TYPE_NAME (node);
911   tree type = DECL_P (node) ? TREE_TYPE (node) : node;
912   tree context = CP_DECL_CONTEXT (decl);
913   tree template_info;
914   tree template;
915   tree substitution;
916
917   MANGLE_TRACE_TREE ("template-prefix", node);
918
919   /* Find the template decl.  */
920   if (decl_is_template_id (decl, &template_info))
921     template = TI_TEMPLATE (template_info);
922   else if (CLASSTYPE_TEMPLATE_ID_P (type))
923     template = CLASSTYPE_TI_TEMPLATE (type);
924   else
925     /* Oops, not a template.  */
926     abort ();
927
928   /* For a member template, though, the template name for the
929      innermost name must have all the outer template levels
930      instantiated.  For instance, consider
931
932        template<typename T> struct Outer {
933          template<typename U> struct Inner {};
934        };
935
936      The template name for `Inner' in `Outer<int>::Inner<float>' is
937      `Outer<int>::Inner<U>'.  In g++, we don't instantiate the template
938      levels separately, so there's no TEMPLATE_DECL available for this
939      (there's only `Outer<T>::Inner<U>').
940
941      In order to get the substitutions right, we create a special
942      TREE_LIST to represent the substitution candidate for a nested
943      template.  The TREE_PURPOSE is the template's context, fully
944      instantiated, and the TREE_VALUE is the TEMPLATE_DECL for the inner
945      template.
946
947      So, for the example above, `Outer<int>::Inner' is represented as a
948      substitution candidate by a TREE_LIST whose purpose is `Outer<int>'
949      and whose value is `Outer<T>::Inner<U>'.  */
950   if (TYPE_P (context))
951     substitution = build_tree_list (context, template);
952   else
953     substitution = template;
954
955   if (find_substitution (substitution))
956     return;
957
958   write_prefix (context);
959   write_unqualified_name (decl);
960
961   add_substitution (substitution);
962 }
963
964 /* We don't need to handle thunks, vtables, or VTTs here.  Those are
965    mangled through special entry points.  
966
967     <unqualified-name>  ::= <operator-name>
968                         ::= <special-name>  
969                         ::= <source-name>  */
970
971 static void
972 write_unqualified_name (decl)
973      tree decl;
974 {
975   MANGLE_TRACE_TREE ("unqualified-name", decl);
976
977   if (DECL_LANG_SPECIFIC (decl) != NULL && DECL_CONSTRUCTOR_P (decl))
978     write_special_name_constructor (decl);
979   else if (DECL_LANG_SPECIFIC (decl) != NULL && DECL_DESTRUCTOR_P (decl))
980     write_special_name_destructor (decl);
981   else if (DECL_CONV_FN_P (decl)) 
982     {
983       /* Conversion operator. Handle it right here.  
984            <operator> ::= cv <type>  */
985       tree type;
986       if (decl_is_template_id (decl, NULL))
987         {
988           tree fn_type = get_mostly_instantiated_function_type (decl, NULL,
989                                                                 NULL);
990           type = TREE_TYPE (fn_type);
991         }
992       else
993         type = TREE_TYPE (DECL_NAME (decl));
994       write_string ("cv");
995       write_type (type);
996     }
997   else if (DECL_OVERLOADED_OPERATOR_P (decl))
998     {
999       operator_name_info_t *oni;
1000       if (DECL_ASSIGNMENT_OPERATOR_P (decl))
1001         oni = assignment_operator_name_info;
1002       else
1003         oni = operator_name_info;
1004       
1005       write_string (oni[DECL_OVERLOADED_OPERATOR_P (decl)].mangled_name);
1006     }
1007   else
1008     write_source_name (DECL_NAME (decl));
1009 }
1010
1011 /* Non-termial <source-name>.  IDENTIFIER is an IDENTIFIER_NODE.  
1012
1013      <source-name> ::= </length/ number> <identifier>  */
1014
1015 static void
1016 write_source_name (identifier)
1017      tree identifier;
1018 {
1019   MANGLE_TRACE_TREE ("source-name", identifier);
1020
1021   /* Never write the whole template-id name including the template
1022      arguments; we only want the template name.  */
1023   if (IDENTIFIER_TEMPLATE (identifier))
1024     identifier = IDENTIFIER_TEMPLATE (identifier);
1025
1026   write_unsigned_number (IDENTIFIER_LENGTH (identifier));
1027   write_identifier (IDENTIFIER_POINTER (identifier));
1028 }
1029
1030 /* Convert NUMBER to ascii using base BASE and generating at least
1031    MIN_DIGITS characters. BUFFER points to the _end_ of the buffer
1032    into which to store the characters. Returns the number of
1033    characters generated (these will be layed out in advance of where
1034    BUFFER points).  */
1035
1036 static int
1037 hwint_to_ascii (number, base, buffer, min_digits)
1038      unsigned HOST_WIDE_INT number;
1039      unsigned int base;
1040      char *buffer;
1041      unsigned min_digits;
1042 {
1043   static const char base_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1044   unsigned digits = 0;
1045   
1046   while (number)
1047     {
1048       unsigned HOST_WIDE_INT d = number / base;
1049       
1050       *--buffer = base_digits[number - d * base];
1051       digits++;
1052       number = d;
1053     }
1054   while (digits < min_digits)
1055     {
1056       *--buffer = base_digits[0];
1057       digits++;
1058     }
1059   return digits;
1060 }
1061
1062 /* Non-terminal <number>.
1063
1064      <number> ::= [n] </decimal integer/>  */
1065
1066 static void
1067 write_number (number, unsigned_p, base)
1068      unsigned HOST_WIDE_INT number;
1069      int unsigned_p;
1070      unsigned int base;
1071 {
1072   char buffer[sizeof (HOST_WIDE_INT) * 8];
1073   unsigned count = 0;
1074
1075   if (!unsigned_p && (HOST_WIDE_INT) number < 0)
1076     {
1077       write_char ('n');
1078       number = -((HOST_WIDE_INT) number);
1079     }
1080   count = hwint_to_ascii (number, base, buffer + sizeof (buffer), 1);
1081   write_chars (buffer + sizeof (buffer) - count, count);
1082 }
1083
1084 /* Write out an integral CST in decimal. Most numbers are small, and
1085    representable in a HOST_WIDE_INT. Occasionally we'll have numbers
1086    bigger than that, which we must deal with. */
1087
1088 static inline void
1089 write_integer_cst (cst)
1090      tree cst;
1091 {
1092   int sign = tree_int_cst_sgn (cst);
1093
1094   if (TREE_INT_CST_HIGH (cst) + (sign < 0))
1095     {
1096       /* A bignum. We do this in chunks, each of which fits in a
1097          HOST_WIDE_INT. */
1098       char buffer[sizeof (HOST_WIDE_INT) * 8 * 2];
1099       unsigned HOST_WIDE_INT chunk;
1100       unsigned chunk_digits;
1101       char *ptr = buffer + sizeof (buffer);
1102       unsigned count = 0;
1103       tree n, base, type;
1104       int done;
1105
1106       /* HOST_WIDE_INT must be at least 32 bits, so 10^9 is
1107          representable. */
1108       chunk = 1000000000;
1109       chunk_digits = 9;
1110       
1111       if (sizeof (HOST_WIDE_INT) >= 8)
1112         {
1113           /* It is at least 64 bits, so 10^18 is representable. */
1114           chunk_digits = 18;
1115           chunk *= chunk;
1116         }
1117       
1118       type = signed_or_unsigned_type (1, TREE_TYPE (cst));
1119       base = build_int_2 (chunk, 0);
1120       n = build_int_2 (TREE_INT_CST_LOW (cst), TREE_INT_CST_HIGH (cst));
1121       TREE_TYPE (n) = TREE_TYPE (base) = type;
1122
1123       if (sign < 0)
1124         {
1125           write_char ('n');
1126           n = fold (build1 (NEGATE_EXPR, type, n));
1127         }
1128       do
1129         {
1130           tree d = fold (build (FLOOR_DIV_EXPR, type, n, base));
1131           tree tmp = fold (build (MULT_EXPR, type, d, base));
1132           unsigned c;
1133           
1134           done = integer_zerop (d);
1135           tmp = fold (build (MINUS_EXPR, type, n, tmp));
1136           c = hwint_to_ascii (TREE_INT_CST_LOW (tmp), 10, ptr,
1137                                 done ? 1 : chunk_digits);
1138           ptr -= c;
1139           count += c;
1140           n = d;
1141         }
1142       while (!done);
1143       write_chars (ptr, count);
1144     }
1145   else 
1146     {
1147       /* A small num.  */
1148       unsigned HOST_WIDE_INT low = TREE_INT_CST_LOW (cst);
1149       
1150       if (sign < 0)
1151         {
1152           write_char ('n');
1153           low = -low;
1154         }
1155       write_unsigned_number (low);
1156     }
1157 }
1158
1159 /* Non-terminal <identifier>.
1160
1161      <identifier> ::= </unqualified source code identifier>  */
1162
1163 static void
1164 write_identifier (identifier)
1165      const char *identifier;
1166 {
1167   MANGLE_TRACE ("identifier", identifier);
1168   write_string (identifier);
1169 }
1170
1171 /* Handle constructor productions of non-terminal <special-name>.
1172    CTOR is a constructor FUNCTION_DECL. 
1173
1174      <special-name> ::= C1   # complete object constructor
1175                     ::= C2   # base object constructor
1176                     ::= C3   # complete object allocating constructor
1177
1178    Currently, allocating constructors are never used. 
1179
1180    We also need to provide mangled names for the maybe-in-charge
1181    constructor, so we treat it here too.  mangle_decl_string will
1182    append *INTERNAL* to that, to make sure we never emit it.  */
1183
1184 static void
1185 write_special_name_constructor (ctor)
1186      tree ctor;
1187 {
1188   if (DECL_COMPLETE_CONSTRUCTOR_P (ctor)
1189       /* Even though we don't ever emit a definition of the
1190          old-style destructor, we still have to consider entities
1191          (like static variables) nested inside it.  */
1192       || DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (ctor))
1193     write_string ("C1");
1194   else if (DECL_BASE_CONSTRUCTOR_P (ctor))
1195     write_string ("C2");
1196   else
1197     abort ();
1198 }
1199
1200 /* Handle destructor productions of non-terminal <special-name>.
1201    DTOR is a destructor FUNCTION_DECL. 
1202
1203      <special-name> ::= D0 # deleting (in-charge) destructor
1204                     ::= D1 # complete object (in-charge) destructor
1205                     ::= D2 # base object (not-in-charge) destructor
1206
1207    We also need to provide mangled names for the maybe-incharge
1208    destructor, so we treat it here too.  mangle_decl_string will
1209    append *INTERNAL* to that, to make sure we never emit it.  */
1210
1211 static void
1212 write_special_name_destructor (dtor)
1213      tree dtor;
1214 {
1215   if (DECL_DELETING_DESTRUCTOR_P (dtor))
1216     write_string ("D0");
1217   else if (DECL_COMPLETE_DESTRUCTOR_P (dtor)
1218            /* Even though we don't ever emit a definition of the
1219               old-style destructor, we still have to consider entities
1220               (like static variables) nested inside it.  */
1221            || DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (dtor))
1222     write_string ("D1");
1223   else if (DECL_BASE_DESTRUCTOR_P (dtor))
1224     write_string ("D2");
1225   else
1226     abort ();
1227 }
1228
1229 /* Return the discriminator for ENTITY appearing inside
1230    FUNCTION.  The discriminator is the lexical ordinal of VAR among
1231    entities with the same name in the same FUNCTION.  */
1232
1233 static int
1234 discriminator_for_local_entity (entity)
1235      tree entity;
1236 {
1237   tree *type;
1238   int discriminator;
1239
1240   /* Assume this is the only local entity with this name.  */
1241   discriminator = 0;
1242
1243   if (DECL_DISCRIMINATOR_P (entity) && DECL_LANG_SPECIFIC (entity))
1244     discriminator = DECL_DISCRIMINATOR (entity);
1245   else if (TREE_CODE (entity) == TYPE_DECL)
1246     {
1247       /* Scan the list of local classes.  */
1248       entity = TREE_TYPE (entity);
1249       for (type = &VARRAY_TREE (local_classes, 0); *type != entity; ++type)
1250         if (TYPE_IDENTIFIER (*type) == TYPE_IDENTIFIER (entity)
1251             && TYPE_CONTEXT (*type) == TYPE_CONTEXT (entity))
1252           ++discriminator;
1253     }  
1254
1255   return discriminator;
1256 }
1257
1258 /* Return the discriminator for STRING, a string literal used inside
1259    FUNCTION.  The disciminator is the lexical ordinal of STRING among
1260    string literals used in FUNCTION.  */
1261
1262 static int
1263 discriminator_for_string_literal (function, string)
1264      tree function ATTRIBUTE_UNUSED;
1265      tree string ATTRIBUTE_UNUSED;
1266 {
1267   /* For now, we don't discriminate amongst string literals.  */
1268   return 0;
1269 }
1270
1271 /*   <discriminator> := _ <number>   
1272
1273    The discriminator is used only for the second and later occurrences
1274    of the same name within a single function. In this case <number> is
1275    n - 2, if this is the nth occurrence, in lexical order.  */
1276
1277 static void
1278 write_discriminator (discriminator)
1279      int discriminator;
1280 {
1281   /* If discriminator is zero, don't write anything.  Otherwise... */
1282   if (discriminator > 0)
1283     {
1284       write_char ('_');
1285       write_unsigned_number (discriminator - 1);
1286     }
1287 }
1288
1289 /* Mangle the name of a function-scope entity.  FUNCTION is the
1290    FUNCTION_DECL for the enclosing function.  ENTITY is the decl for
1291    the entity itself.  LOCAL_ENTITY is the entity that's directly
1292    scoped in FUNCTION_DECL, either ENTITY itself or an enclosing scope
1293    of ENTITY.
1294
1295      <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1296                   := Z <function encoding> E s [<discriminator>]  */
1297
1298 static void
1299 write_local_name (function, local_entity, entity)
1300      tree function;
1301      tree local_entity;
1302      tree entity;
1303 {
1304   MANGLE_TRACE_TREE ("local-name", entity);
1305
1306   write_char ('Z');
1307   write_encoding (function);
1308   write_char ('E');
1309   if (TREE_CODE (entity) == STRING_CST)
1310     {
1311       write_char ('s');
1312       write_discriminator (discriminator_for_string_literal (function, 
1313                                                              entity));
1314     }
1315   else
1316     {
1317       /* Now the <entity name>.  Let write_name know its being called
1318          from <local-name>, so it doesn't try to process the enclosing
1319          function scope again.  */
1320       write_name (entity, /*ignore_local_scope=*/1);
1321       write_discriminator (discriminator_for_local_entity (local_entity));
1322     }
1323 }
1324
1325 /* Non-terminals <type> and <CV-qualifier>.  
1326
1327      <type> ::= <builtin-type>
1328             ::= <function-type>
1329             ::= <class-enum-type>
1330             ::= <array-type>
1331             ::= <pointer-to-member-type>
1332             ::= <template-param>
1333             ::= <substitution>
1334             ::= <CV-qualifier>
1335             ::= P <type>    # pointer-to
1336             ::= R <type>    # reference-to
1337             ::= C <type>    # complex pair (C 2000)
1338             ::= G <type>    # imaginary (C 2000)     [not supported]
1339             ::= U <source-name> <type>   # vendor extended type qualifier 
1340
1341    TYPE is a type node.  */
1342
1343 static void 
1344 write_type (type)
1345      tree type;
1346 {
1347   /* This gets set to non-zero if TYPE turns out to be a (possibly
1348      CV-qualified) builtin type.  */
1349   int is_builtin_type = 0;
1350
1351   MANGLE_TRACE_TREE ("type", type);
1352
1353   if (type == error_mark_node)
1354     return;
1355
1356   if (find_substitution (type))
1357     return;
1358   
1359   if (write_CV_qualifiers_for_type (type) > 0)
1360     /* If TYPE was CV-qualified, we just wrote the qualifiers; now
1361        mangle the unqualified type.  The recursive call is needed here
1362        since both the qualified and uqualified types are substitution
1363        candidates.  */
1364     write_type (TYPE_MAIN_VARIANT (type));
1365   else if (TREE_CODE (type) == ARRAY_TYPE)
1366     /* It is important not to use the TYPE_MAIN_VARIANT of TYPE here
1367        so that the cv-qualification of the element type is available
1368        in write_array_type.  */
1369     write_array_type (type);
1370   else
1371     {
1372       /* See through any typedefs.  */
1373       type = TYPE_MAIN_VARIANT (type);
1374
1375       switch (TREE_CODE (type))
1376         {
1377         case VOID_TYPE:
1378         case BOOLEAN_TYPE:
1379         case INTEGER_TYPE:  /* Includes wchar_t.  */
1380         case REAL_TYPE:
1381           /* If this is a typedef, TYPE may not be one of
1382              the standard builtin type nodes, but an alias of one.  Use
1383              TYPE_MAIN_VARIANT to get to the underlying builtin type.  */
1384           write_builtin_type (TYPE_MAIN_VARIANT (type));
1385           ++is_builtin_type;
1386           break;
1387
1388         case COMPLEX_TYPE:
1389           write_char ('C');
1390           write_type (TREE_TYPE (type));
1391           break;
1392
1393         case FUNCTION_TYPE:
1394         case METHOD_TYPE:
1395           write_function_type (type);
1396           break;
1397
1398         case UNION_TYPE:
1399         case RECORD_TYPE:
1400         case ENUMERAL_TYPE:
1401           /* A pointer-to-member function is represented as a special
1402              RECORD_TYPE, so check for this first.  */
1403           if (TYPE_PTRMEMFUNC_P (type))
1404             write_pointer_to_member_type (type);
1405           else
1406             write_class_enum_type (type);
1407           break;
1408
1409         case TYPENAME_TYPE:
1410         case UNBOUND_CLASS_TEMPLATE:
1411           /* We handle TYPENAME_TYPEs and UNBOUND_CLASS_TEMPLATEs like
1412              ordinary nested names.  */
1413           write_nested_name (TYPE_STUB_DECL (type));
1414           break;
1415
1416         case POINTER_TYPE:
1417           /* A pointer-to-member variable is represented by a POINTER_TYPE
1418              to an OFFSET_TYPE, so check for this first.  */
1419           if (TYPE_PTRMEM_P (type))
1420             write_pointer_to_member_type (type);
1421           else
1422             {
1423               write_char ('P');
1424               write_type (TREE_TYPE (type));
1425             }
1426           break;
1427
1428         case REFERENCE_TYPE:
1429           write_char ('R');
1430           write_type (TREE_TYPE (type));
1431           break;
1432
1433         case TEMPLATE_TYPE_PARM:
1434         case TEMPLATE_PARM_INDEX:
1435           write_template_param (type);
1436           break;
1437
1438         case TEMPLATE_TEMPLATE_PARM:
1439           write_template_template_param (type);
1440           break;
1441
1442         case BOUND_TEMPLATE_TEMPLATE_PARM:
1443           write_template_template_param (type);
1444           write_template_args 
1445             (TI_ARGS (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (type)));
1446           break;
1447
1448         case OFFSET_TYPE:
1449           write_pointer_to_member_type (build_pointer_type (type));
1450           break;
1451
1452         case VECTOR_TYPE:
1453           write_string ("U8__vector");
1454           write_type (TREE_TYPE (type));
1455           break;
1456
1457         default:
1458           abort ();
1459         }
1460     }
1461
1462   /* Types other than builtin types are substitution candidates.  */
1463   if (!is_builtin_type)
1464     add_substitution (type);
1465 }
1466
1467 /* Non-terminal <CV-qualifiers> for type nodes.  Returns the number of
1468    CV-qualifiers written for TYPE.
1469
1470      <CV-qualifiers> ::= [r] [V] [K]  */
1471
1472 static int
1473 write_CV_qualifiers_for_type (type)
1474      tree type;
1475 {
1476   int num_qualifiers = 0;
1477
1478   /* The order is specified by:
1479
1480        "In cases where multiple order-insensitive qualifiers are
1481        present, they should be ordered 'K' (closest to the base type),
1482        'V', 'r', and 'U' (farthest from the base type) ..."  
1483
1484      Note that we do not use cp_type_quals below; given "const
1485      int[3]", the "const" is emitted with the "int", not with the
1486      array.  */
1487
1488   if (TYPE_QUALS (type) & TYPE_QUAL_RESTRICT)
1489     {
1490       write_char ('r');
1491       ++num_qualifiers;
1492     }
1493   if (TYPE_QUALS (type) & TYPE_QUAL_VOLATILE)
1494     {
1495       write_char ('V');
1496       ++num_qualifiers;
1497     }
1498   if (TYPE_QUALS (type) & TYPE_QUAL_CONST)
1499     {
1500       write_char ('K');
1501       ++num_qualifiers;
1502     }
1503
1504   return num_qualifiers;
1505 }
1506
1507 /* Non-terminal <builtin-type>. 
1508
1509      <builtin-type> ::= v   # void 
1510                     ::= b   # bool
1511                     ::= w   # wchar_t
1512                     ::= c   # char
1513                     ::= a   # signed char
1514                     ::= h   # unsigned char
1515                     ::= s   # short
1516                     ::= t   # unsigned short
1517                     ::= i   # int
1518                     ::= j   # unsigned int
1519                     ::= l   # long
1520                     ::= m   # unsigned long
1521                     ::= x   # long long, __int64
1522                     ::= y   # unsigned long long, __int64  
1523                     ::= n   # __int128
1524                     ::= o   # unsigned __int128
1525                     ::= f   # float
1526                     ::= d   # double
1527                     ::= e   # long double, __float80 
1528                     ::= g   # __float128          [not supported]
1529                     ::= u <source-name>  # vendor extended type */
1530
1531 static void 
1532 write_builtin_type (type)
1533      tree type;
1534 {
1535   switch (TREE_CODE (type))
1536     {
1537     case VOID_TYPE:
1538       write_char ('v');
1539       break;
1540
1541     case BOOLEAN_TYPE:
1542       write_char ('b');
1543       break;
1544
1545     case INTEGER_TYPE:
1546       /* If this is size_t, get the underlying int type.  */
1547       if (TYPE_IS_SIZETYPE (type))
1548         type = TYPE_DOMAIN (type);
1549
1550       /* TYPE may still be wchar_t, since that isn't in
1551          integer_type_nodes.  */
1552       if (type == wchar_type_node)
1553         write_char ('w');
1554       else if (TYPE_FOR_JAVA (type))
1555         write_java_integer_type_codes (type);
1556       else
1557         {
1558           size_t itk;
1559           /* Assume TYPE is one of the shared integer type nodes.  Find
1560              it in the array of these nodes.  */
1561         iagain:
1562           for (itk = 0; itk < itk_none; ++itk)
1563             if (type == integer_types[itk])
1564               {
1565                 /* Print the corresponding single-letter code.  */
1566                 write_char (integer_type_codes[itk]);
1567                 break;
1568               }
1569
1570           if (itk == itk_none)
1571             {
1572               tree t = type_for_mode (TYPE_MODE (type), TREE_UNSIGNED (type));
1573               if (type == t)
1574                 {
1575                   if (TYPE_PRECISION (type) == 128)
1576                     write_char (TREE_UNSIGNED (type) ? 'o' : 'n');
1577                   else
1578                     /* Couldn't find this type.  */
1579                     abort ();
1580                 }
1581               else
1582                 {
1583                   type = t;
1584                   goto iagain;
1585                 }
1586             }
1587         }
1588       break;
1589
1590     case REAL_TYPE:
1591       if (type == float_type_node
1592           || type == java_float_type_node)
1593         write_char ('f');
1594       else if (type == double_type_node
1595                || type == java_double_type_node)
1596         write_char ('d');
1597       else if (type == long_double_type_node)
1598         write_char ('e');
1599       else
1600         abort ();
1601       break;
1602
1603     default:
1604       abort ();
1605     }
1606 }
1607
1608 /* Non-terminal <function-type>.  NODE is a FUNCTION_TYPE or
1609    METHOD_TYPE.  The return type is mangled before the parameter
1610    types.
1611
1612      <function-type> ::= F [Y] <bare-function-type> E   */
1613
1614 static void
1615 write_function_type (type)
1616      tree type;
1617 {
1618   MANGLE_TRACE_TREE ("function-type", type);
1619
1620   /* For a pointer to member function, the function type may have
1621      cv-qualifiers, indicating the quals for the artificial 'this'
1622      parameter.  */
1623   if (TREE_CODE (type) == METHOD_TYPE)
1624     {
1625       /* The first parameter must be a POINTER_TYPE pointing to the
1626          `this' parameter.  */
1627       tree this_type = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (type)));
1628       write_CV_qualifiers_for_type (this_type);
1629     }
1630
1631   write_char ('F');
1632   /* We don't track whether or not a type is `extern "C"'.  Note that
1633      you can have an `extern "C"' function that does not have
1634      `extern "C"' type, and vice versa:
1635
1636        extern "C" typedef void function_t();
1637        function_t f; // f has C++ linkage, but its type is
1638                      // `extern "C"'
1639
1640        typedef void function_t();
1641        extern "C" function_t f; // Vice versa.
1642
1643      See [dcl.link].  */
1644   write_bare_function_type (type, /*include_return_type_p=*/1, 
1645                             /*decl=*/NULL);
1646   write_char ('E');
1647 }
1648
1649 /* Non-terminal <bare-function-type>.  TYPE is a FUNCTION_TYPE or
1650    METHOD_TYPE.  If INCLUDE_RETURN_TYPE is non-zero, the return value
1651    is mangled before the parameter types.  If non-NULL, DECL is
1652    FUNCTION_DECL for the function whose type is being emitted.
1653
1654      <bare-function-type> ::= </signature/ type>+  */
1655
1656 static void
1657 write_bare_function_type (type, include_return_type_p, decl)
1658      tree type;
1659      int include_return_type_p;
1660      tree decl;
1661 {
1662   MANGLE_TRACE_TREE ("bare-function-type", type);
1663
1664   /* Mangle the return type, if requested.  */
1665   if (include_return_type_p)
1666     write_type (TREE_TYPE (type));
1667
1668   /* Now mangle the types of the arguments.  */
1669   write_method_parms (TYPE_ARG_TYPES (type), 
1670                       TREE_CODE (type) == METHOD_TYPE,
1671                       decl);
1672 }
1673
1674 /* Write the mangled representation of a method parameter list of
1675    types given in PARM_TYPES.  If METHOD_P is non-zero, the function is 
1676    considered a non-static method, and the this parameter is omitted.
1677    If non-NULL, DECL is the FUNCTION_DECL for the function whose
1678    parameters are being emitted.  */
1679
1680 static void
1681 write_method_parms (parm_types, method_p, decl)
1682      tree decl;
1683      tree parm_types;
1684      int method_p;
1685 {
1686   tree first_parm_type;
1687   tree parm_decl = decl ? DECL_ARGUMENTS (decl) : NULL_TREE;
1688
1689   /* Assume this parameter type list is variable-length.  If it ends
1690      with a void type, then it's not.  */
1691   int varargs_p = 1;
1692
1693   /* If this is a member function, skip the first arg, which is the
1694      this pointer.  
1695        "Member functions do not encode the type of their implicit this
1696        parameter."  
1697   
1698      Similarly, there's no need to mangle artificial parameters, like
1699      the VTT parameters for constructors and destructors.  */
1700   if (method_p)
1701     {
1702       parm_types = TREE_CHAIN (parm_types);
1703       parm_decl = parm_decl ? TREE_CHAIN (parm_decl) : NULL_TREE;
1704
1705       while (parm_decl && DECL_ARTIFICIAL (parm_decl))
1706         {
1707           parm_types = TREE_CHAIN (parm_types);
1708           parm_decl = TREE_CHAIN (parm_decl);
1709         }
1710     }
1711
1712   for (first_parm_type = parm_types; 
1713        parm_types; 
1714        parm_types = TREE_CHAIN (parm_types))
1715     {
1716       tree parm = TREE_VALUE (parm_types);
1717       if (parm == void_type_node)
1718         {
1719           /* "Empty parameter lists, whether declared as () or
1720              conventionally as (void), are encoded with a void parameter
1721              (v)."  */
1722           if (parm_types == first_parm_type)
1723             write_type (parm);
1724           /* If the parm list is terminated with a void type, it's
1725              fixed-length.  */
1726           varargs_p = 0;
1727           /* A void type better be the last one.  */
1728           my_friendly_assert (TREE_CHAIN (parm_types) == NULL, 20000523);
1729         }
1730       else
1731         write_type (parm);
1732     }
1733
1734   if (varargs_p)
1735     /* <builtin-type> ::= z  # ellipsis  */
1736     write_char ('z');
1737 }
1738
1739 /* <class-enum-type> ::= <name>  */
1740
1741 static void 
1742 write_class_enum_type (type)
1743      tree type;
1744 {
1745   write_name (TYPE_NAME (type), /*ignore_local_scope=*/0);
1746 }
1747
1748 /* Non-terminal <template-args>.  ARGS is a TREE_VEC of template
1749    arguments.
1750
1751      <template-args> ::= I <template-arg>+ E  */
1752
1753 static void
1754 write_template_args (args)
1755      tree args;
1756 {
1757   int i;
1758   int length = TREE_VEC_LENGTH (args);
1759
1760   MANGLE_TRACE_TREE ("template-args", args);
1761
1762   my_friendly_assert (length > 0, 20000422);
1763
1764   if (TREE_CODE (TREE_VEC_ELT (args, 0)) == TREE_VEC)
1765     {
1766       /* We have nested template args.  We want the innermost template
1767          argument list.  */
1768       args = TREE_VEC_ELT (args, length - 1);
1769       length = TREE_VEC_LENGTH (args);
1770     }
1771
1772   write_char ('I');
1773   for (i = 0; i < length; ++i)
1774     write_template_arg (TREE_VEC_ELT (args, i));
1775   write_char ('E');
1776 }
1777
1778 /* <expression> ::= <unary operator-name> <expression>
1779                 ::= <binary operator-name> <expression> <expression>
1780                 ::= <expr-primary>
1781
1782    <expr-primary> ::= <template-param>
1783                   ::= L <type> <value number> E  # literal
1784                   ::= L <mangled-name> E         # external name  */
1785
1786 static void
1787 write_expression (expr)
1788      tree expr;
1789 {
1790   enum tree_code code;
1791
1792   code = TREE_CODE (expr);
1793
1794   /* Handle pointers-to-members by making them look like expression
1795      nodes.  */
1796   if (code == PTRMEM_CST)
1797     {
1798       expr = build_nt (ADDR_EXPR,
1799                        build_nt (SCOPE_REF,
1800                                  PTRMEM_CST_CLASS (expr),
1801                                  PTRMEM_CST_MEMBER (expr)));
1802       code = TREE_CODE (expr);
1803     }
1804
1805   /* Skip NOP_EXPRs.  They can occur when (say) a pointer argument
1806      is converted (via qualification conversions) to another
1807      type.  */
1808   while (TREE_CODE (expr) == NOP_EXPR
1809          || TREE_CODE (expr) == NON_LVALUE_EXPR)
1810     {
1811       expr = TREE_OPERAND (expr, 0);
1812       code = TREE_CODE (expr);
1813     }
1814
1815   /* Handle template parameters. */
1816   if (code == TEMPLATE_TYPE_PARM 
1817       || code == TEMPLATE_TEMPLATE_PARM
1818       || code == BOUND_TEMPLATE_TEMPLATE_PARM
1819       || code == TEMPLATE_PARM_INDEX)
1820     write_template_param (expr);
1821   /* Handle literals.  */
1822   else if (TREE_CODE_CLASS (code) == 'c')
1823     write_template_arg_literal (expr);
1824   else if (DECL_P (expr))
1825     {
1826       write_char ('L');
1827       write_mangled_name (expr);
1828       write_char ('E');
1829     }
1830   else if (TREE_CODE (expr) == SIZEOF_EXPR 
1831            && TYPE_P (TREE_OPERAND (expr, 0)))
1832     {
1833       write_string ("st");
1834       write_type (TREE_OPERAND (expr, 0));
1835     }
1836   else
1837     {
1838       int i;
1839
1840       /* When we bind a variable or function to a non-type template
1841          argument with reference type, we create an ADDR_EXPR to show
1842          the fact that the entity's address has been taken.  But, we
1843          don't actually want to output a mangling code for the `&'.  */
1844       if (TREE_CODE (expr) == ADDR_EXPR
1845           && TREE_TYPE (expr)
1846           && TREE_CODE (TREE_TYPE (expr)) == REFERENCE_TYPE)
1847         {
1848           expr = TREE_OPERAND (expr, 0);
1849           if (DECL_P (expr))
1850             {
1851               write_expression (expr);
1852               return;
1853             }
1854
1855           code = TREE_CODE (expr);
1856         }
1857       
1858       /* If it wasn't any of those, recursively expand the expression.  */
1859       write_string (operator_name_info[(int) code].mangled_name);
1860
1861       switch (code)
1862         {
1863         case CAST_EXPR:
1864           write_type (TREE_TYPE (expr));
1865           write_expression (TREE_VALUE (TREE_OPERAND (expr, 0)));
1866           break;
1867
1868         case STATIC_CAST_EXPR:
1869         case CONST_CAST_EXPR:
1870           write_type (TREE_TYPE (expr));
1871           write_expression (TREE_OPERAND (expr, 0));
1872           break;
1873
1874           
1875         /* Handle pointers-to-members specially.  */
1876         case SCOPE_REF:
1877           write_type (TREE_OPERAND (expr, 0));
1878           if (TREE_CODE (TREE_OPERAND (expr, 1)) == IDENTIFIER_NODE)
1879             write_source_name (TREE_OPERAND (expr, 1));
1880           else
1881             write_encoding (TREE_OPERAND (expr, 1));
1882           break;
1883
1884         default:
1885           for (i = 0; i < TREE_CODE_LENGTH (code); ++i)
1886             write_expression (TREE_OPERAND (expr, i));
1887         }
1888     }
1889 }
1890
1891 /* Literal subcase of non-terminal <template-arg>.  
1892
1893      "Literal arguments, e.g. "A<42L>", are encoded with their type
1894      and value. Negative integer values are preceded with "n"; for
1895      example, "A<-42L>" becomes "1AILln42EE". The bool value false is
1896      encoded as 0, true as 1. If floating-point arguments are accepted
1897      as an extension, their values should be encoded using a
1898      fixed-length lowercase hexadecimal string corresponding to the
1899      internal representation (IEEE on IA-64), high-order bytes first,
1900      without leading zeroes. For example: "Lfbff000000E" is -1.0f."  */
1901
1902 static void
1903 write_template_arg_literal (value)
1904      tree value;
1905 {
1906   tree type = TREE_TYPE (value);
1907   write_char ('L');
1908   write_type (type);
1909
1910   if (TREE_CODE (value) == CONST_DECL)
1911     write_integer_cst (DECL_INITIAL (value));
1912   else if (TREE_CODE (value) == INTEGER_CST)
1913     {
1914       if (same_type_p (type, boolean_type_node))
1915         {
1916           if (value == boolean_false_node || integer_zerop (value))
1917             write_unsigned_number (0);
1918           else if (value == boolean_true_node)
1919             write_unsigned_number (1);
1920           else 
1921             abort ();
1922         }
1923       else
1924         write_integer_cst (value);
1925     }
1926   else if (TREE_CODE (value) == REAL_CST)
1927     {
1928 #ifdef CROSS_COMPILE
1929       static int explained;
1930
1931       if (!explained) 
1932         {
1933           sorry ("real-valued template parameters when cross-compiling");
1934           explained = 1;
1935         }
1936 #else
1937       size_t i;
1938       for (i = 0; i < sizeof (TREE_REAL_CST (value)); ++i)
1939         write_number (((unsigned char *) 
1940                        &TREE_REAL_CST (value))[i], 
1941                       /*unsigned_p=*/1,
1942                       16);
1943 #endif
1944     }
1945   else
1946     abort ();
1947
1948   write_char ('E');
1949 }
1950
1951 /* Non-terminal <tempalate-arg>.  
1952
1953      <template-arg> ::= <type>                        # type
1954                     ::= L <type> </value/ number> E   # literal
1955                     ::= LZ <name> E                   # external name
1956                     ::= X <expression> E              # expression  */
1957
1958 static void
1959 write_template_arg (node)
1960      tree node;
1961 {
1962   enum tree_code code = TREE_CODE (node);
1963
1964   MANGLE_TRACE_TREE ("template-arg", node);
1965
1966   /* A template template paramter's argument list contains TREE_LIST
1967      nodes of which the value field is the the actual argument.  */
1968   if (code == TREE_LIST)
1969     {
1970       node = TREE_VALUE (node);
1971       /* If it's a decl, deal with its type instead.  */
1972       if (DECL_P (node))
1973         {
1974           node = TREE_TYPE (node);
1975           code = TREE_CODE (node);
1976         }
1977     }
1978
1979   if (TYPE_P (node))
1980     write_type (node);
1981   else if (code == TEMPLATE_DECL)
1982     /* A template appearing as a template arg is a template template arg.  */
1983     write_template_template_arg (node);
1984   else if (DECL_P (node))
1985     {
1986       write_char ('L');
1987       write_char ('Z');
1988       write_encoding (node);
1989       write_char ('E');
1990     }
1991   else if (TREE_CODE_CLASS (code) == 'c' && code != PTRMEM_CST)
1992     write_template_arg_literal (node);
1993   else
1994     {
1995       /* Template arguments may be expressions.  */
1996       write_char ('X');
1997       write_expression (node);
1998       write_char ('E');
1999     }
2000 }
2001
2002 /*  <template-template-arg>
2003                         ::= <name>
2004                         ::= <substitution>  */
2005
2006 void
2007 write_template_template_arg (tree decl)
2008 {
2009   MANGLE_TRACE_TREE ("template-template-arg", decl);
2010
2011   if (find_substitution (decl))
2012     return;
2013   write_name (decl, /*ignore_local_scope=*/0);
2014   add_substitution (decl);
2015 }
2016
2017
2018 /* Non-terminal <array-type>.  TYPE is an ARRAY_TYPE.  
2019
2020      <array-type> ::= A [</dimension/ number>] _ </element/ type>  
2021                   ::= A <expression> _ </element/ type>
2022
2023      "Array types encode the dimension (number of elements) and the
2024      element type. For variable length arrays, the dimension (but not
2025      the '_' separator) is omitted."  */
2026
2027 static void 
2028 write_array_type (type)
2029   tree type;
2030 {
2031   write_char ('A');
2032   if (TYPE_DOMAIN (type))
2033     {
2034       tree index_type;
2035       tree max;
2036
2037       index_type = TYPE_DOMAIN (type);
2038       /* The INDEX_TYPE gives the upper and lower bounds of the
2039          array.  */
2040       max = TYPE_MAX_VALUE (index_type);
2041       if (TREE_CODE (max) == INTEGER_CST)
2042         {
2043           /* The ABI specifies that we should mangle the number of
2044              elements in the array, not the largest allowed index.  */
2045           max = size_binop (PLUS_EXPR, max, size_one_node);
2046           write_unsigned_number (tree_low_cst (max, 1));
2047         }
2048       else
2049         write_expression (TREE_OPERAND (max, 0));
2050     }
2051   write_char ('_');
2052   write_type (TREE_TYPE (type));
2053 }
2054
2055 /* Non-terminal <pointer-to-member-type> for pointer-to-member
2056    variables.  TYPE is a pointer-to-member POINTER_TYPE.
2057
2058      <pointer-to-member-type> ::= M </class/ type> </member/ type>  */
2059
2060 static void
2061 write_pointer_to_member_type (type)
2062      tree type;
2063 {
2064   write_char ('M');
2065   write_type (TYPE_PTRMEM_CLASS_TYPE (type));
2066   write_type (TYPE_PTRMEM_POINTED_TO_TYPE (type));
2067 }
2068
2069 /* Non-terminal <template-param>.  PARM is a TEMPLATE_TYPE_PARM,
2070    TEMPLATE_TEMPLATE_PARM, BOUND_TEMPLATE_TEMPLATE_PARM or a
2071    TEMPLATE_PARM_INDEX.
2072
2073      <template-param> ::= T </parameter/ number> _  */
2074
2075 static void
2076 write_template_param (parm)
2077      tree parm;
2078 {
2079   int parm_index;
2080
2081   MANGLE_TRACE_TREE ("template-parm", parm);
2082
2083   switch (TREE_CODE (parm))
2084     {
2085     case TEMPLATE_TYPE_PARM:
2086     case TEMPLATE_TEMPLATE_PARM:
2087     case BOUND_TEMPLATE_TEMPLATE_PARM:
2088       parm_index = TEMPLATE_TYPE_IDX (parm);
2089       break;
2090
2091     case TEMPLATE_PARM_INDEX:
2092       parm_index = TEMPLATE_PARM_IDX (parm);
2093       break;
2094
2095     default:
2096       abort ();
2097     }
2098
2099   write_char ('T');
2100   /* NUMBER as it appears in the mangling is (-1)-indexed, with the
2101      earliest template param denoted by `_'.  */
2102   if (parm_index > 0)
2103     write_unsigned_number (parm_index - 1);
2104   write_char ('_');
2105 }
2106
2107 /*  <template-template-param>
2108                         ::= <template-param> 
2109                         ::= <substitution>  */
2110
2111 static void
2112 write_template_template_param (parm)
2113      tree parm;
2114 {
2115   tree template = NULL_TREE;
2116
2117   /* PARM, a TEMPLATE_TEMPLATE_PARM, is an instantiation of the
2118      template template parameter.  The substitution candidate here is
2119      only the template.  */
2120   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
2121     {
2122       template 
2123         = TI_TEMPLATE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (parm));
2124       if (find_substitution (template))
2125         return;
2126     }
2127
2128   /* <template-param> encodes only the template parameter position,
2129      not its template arguments, which is fine here.  */
2130   write_template_param (parm);
2131   if (template)
2132     add_substitution (template);
2133 }
2134
2135 /* Non-terminal <substitution>.  
2136
2137       <substitution> ::= S <seq-id> _
2138                      ::= S_  */
2139
2140 static void
2141 write_substitution (seq_id)
2142      int seq_id;
2143 {
2144   MANGLE_TRACE ("substitution", "");
2145
2146   write_char ('S');
2147   if (seq_id > 0)
2148     write_number (seq_id - 1, /*unsigned=*/1, 36);
2149   write_char ('_');
2150 }
2151
2152 /* Start mangling a new name or type.  */
2153
2154 static inline void
2155 start_mangling ()
2156 {
2157   obstack_free (&G.name_obstack, obstack_base (&G.name_obstack));
2158 }
2159
2160 /* Done with mangling.  Return the generated mangled name.  */
2161
2162 static inline const char *
2163 finish_mangling ()
2164 {
2165   /* Clear all the substitutions.  */
2166   VARRAY_POP_ALL (G.substitutions);
2167
2168   /* Null-terminate the string.  */
2169   write_char ('\0');
2170
2171   return (const char *) obstack_base (&G.name_obstack);
2172 }
2173
2174 /* Initialize data structures for mangling.  */
2175
2176 void
2177 init_mangle ()
2178 {
2179   gcc_obstack_init (&G.name_obstack);
2180   VARRAY_TREE_INIT (G.substitutions, 1, "mangling substitutions");
2181
2182   /* Cache these identifiers for quick comparison when checking for
2183      standard substitutions.  */
2184   subst_identifiers[SUBID_ALLOCATOR] = get_identifier ("allocator");
2185   subst_identifiers[SUBID_BASIC_STRING] = get_identifier ("basic_string");
2186   subst_identifiers[SUBID_CHAR_TRAITS] = get_identifier ("char_traits");
2187   subst_identifiers[SUBID_BASIC_ISTREAM] = get_identifier ("basic_istream");
2188   subst_identifiers[SUBID_BASIC_OSTREAM] = get_identifier ("basic_ostream");
2189   subst_identifiers[SUBID_BASIC_IOSTREAM] = get_identifier ("basic_iostream");
2190 }
2191
2192 /* Generate the mangled name of DECL.  */
2193
2194 static const char *
2195 mangle_decl_string (decl)
2196      tree decl;
2197 {
2198   const char *result;
2199
2200   start_mangling ();
2201
2202   if (TREE_CODE (decl) == TYPE_DECL)
2203     write_type (TREE_TYPE (decl));
2204   else if (/* The names of `extern "C"' functions are not mangled.  */
2205            (DECL_EXTERN_C_FUNCTION_P (decl)
2206             /* But overloaded operator names *are* mangled.  */
2207             && !DECL_OVERLOADED_OPERATOR_P (decl))
2208            /* The names of global variables aren't mangled either.  */
2209            || (TREE_CODE (decl) == VAR_DECL
2210                && CP_DECL_CONTEXT (decl) == global_namespace)
2211            /* And neither are `extern "C"' variables.  */
2212            || (TREE_CODE (decl) == VAR_DECL
2213                && DECL_EXTERN_C_P (decl)))
2214     write_string (IDENTIFIER_POINTER (DECL_NAME (decl)));
2215   else
2216     {
2217       write_mangled_name (decl);
2218       if (DECL_LANG_SPECIFIC (decl)
2219           && (DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (decl)
2220               || DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl)))
2221         /* We need a distinct mangled name for these entities, but
2222            we should never actually output it.  So, we append some
2223            characters the assembler won't like.  */
2224         write_string (" *INTERNAL* ");
2225     }
2226
2227   result = finish_mangling ();
2228   if (DEBUG_MANGLE)
2229     fprintf (stderr, "mangle_decl_string = '%s'\n\n", result);
2230   return result;
2231 }
2232
2233 /* Create an identifier for the external mangled name of DECL.  */
2234
2235 void
2236 mangle_decl (decl)
2237      tree decl;
2238 {
2239   tree id = get_identifier (mangle_decl_string (decl));
2240
2241   SET_DECL_ASSEMBLER_NAME (decl, id);
2242 }
2243
2244 /* Generate the mangled representation of TYPE.  */
2245
2246 const char *
2247 mangle_type_string (type)
2248      tree type;
2249 {
2250   const char *result;
2251
2252   start_mangling ();
2253   write_type (type);
2254   result = finish_mangling ();
2255   if (DEBUG_MANGLE)
2256     fprintf (stderr, "mangle_type_string = '%s'\n\n", result);
2257   return result;
2258 }
2259
2260 /* Create an identifier for the mangled representation of TYPE.  */
2261
2262 tree
2263 mangle_type (type)
2264      tree type;
2265 {
2266   return get_identifier (mangle_type_string (type));
2267 }
2268
2269 /* Create an identifier for the mangled name of a special component
2270    for belonging to TYPE.  CODE is the ABI-specified code for this
2271    component.  */
2272
2273 static tree
2274 mangle_special_for_type (type, code)
2275      tree type;
2276      const char *code;
2277 {
2278   const char *result;
2279
2280   /* We don't have an actual decl here for the special component, so
2281      we can't just process the <encoded-name>.  Instead, fake it.  */
2282   start_mangling ();
2283
2284   /* Start the mangling.  */
2285   write_string ("_Z");
2286   write_string (code);
2287
2288   /* Add the type.  */
2289   write_type (type);
2290   result = finish_mangling ();
2291
2292   if (DEBUG_MANGLE)
2293     fprintf (stderr, "mangle_special_for_type = %s\n\n", result);
2294
2295   return get_identifier (result);
2296 }
2297
2298 /* Create an identifier for the mangled representation of the typeinfo
2299    structure for TYPE.  */
2300
2301 tree
2302 mangle_typeinfo_for_type (type)
2303      tree type;
2304 {
2305   return mangle_special_for_type (type, "TI");
2306 }
2307
2308 /* Create an identifier for the mangled name of the NTBS containing
2309    the mangled name of TYPE.  */
2310
2311 tree
2312 mangle_typeinfo_string_for_type (type)
2313      tree type;
2314 {
2315   return mangle_special_for_type (type, "TS");
2316 }
2317
2318 /* Create an identifier for the mangled name of the vtable for TYPE.  */
2319
2320 tree
2321 mangle_vtbl_for_type (type)
2322      tree type;
2323 {
2324   return mangle_special_for_type (type, "TV");
2325 }
2326
2327 /* Returns an identifier for the mangled name of the VTT for TYPE.  */
2328
2329 tree
2330 mangle_vtt_for_type (type)
2331      tree type;
2332 {
2333   return mangle_special_for_type (type, "TT");
2334 }
2335
2336 /* Return an identifier for a construction vtable group.  TYPE is
2337    the most derived class in the hierarchy; BINFO is the base
2338    subobject for which this construction vtable group will be used.  
2339
2340    This mangling isn't part of the ABI specification; in the ABI
2341    specification, the vtable group is dumped in the same COMDAT as the
2342    main vtable, and is referenced only from that vtable, so it doesn't
2343    need an external name.  For binary formats without COMDAT sections,
2344    though, we need external names for the vtable groups.  
2345
2346    We use the production
2347
2348     <special-name> ::= CT <type> <offset number> _ <base type>  */
2349
2350 tree
2351 mangle_ctor_vtbl_for_type (type, binfo)
2352      tree type;
2353      tree binfo;
2354 {
2355   const char *result;
2356
2357   start_mangling ();
2358
2359   write_string ("_Z");
2360   write_string ("TC");
2361   write_type (type);
2362   write_integer_cst (BINFO_OFFSET (binfo));
2363   write_char ('_');
2364   write_type (BINFO_TYPE (binfo));
2365
2366   result = finish_mangling ();
2367   if (DEBUG_MANGLE)
2368     fprintf (stderr, "mangle_ctor_vtbl_for_type = %s\n\n", result);
2369   return get_identifier (result);
2370 }
2371
2372 /* Return an identifier for the mangled name of a thunk to FN_DECL.
2373    OFFSET is the initial adjustment to this used to find the vptr.  If
2374    VCALL_OFFSET is non-NULL, this is a virtual thunk, and it is the
2375    vtbl offset in bytes.  
2376
2377     <special-name> ::= Th <offset number> _ <base encoding>
2378                    ::= Tv <offset number> _ <vcall offset number> _
2379                                                             <base encoding>
2380 */
2381
2382 tree
2383 mangle_thunk (fn_decl, offset, vcall_offset)
2384      tree fn_decl;
2385      tree offset;
2386      tree vcall_offset;
2387 {
2388   const char *result;
2389   
2390   start_mangling ();
2391
2392   write_string ("_Z");
2393   /* The <special-name> for virtual thunks is Tv, for non-virtual
2394      thunks Th.  */
2395   write_char ('T');
2396   if (vcall_offset != 0)
2397     write_char ('v');
2398   else
2399     write_char ('h');
2400
2401   /* For either flavor, write the offset to this.  */
2402   write_integer_cst (offset);
2403   write_char ('_');
2404
2405   /* For a virtual thunk, add the vcall offset.  */
2406   if (vcall_offset)
2407     {
2408       /* Virtual thunk.  Write the vcall offset and base type name.  */
2409       write_integer_cst (vcall_offset);
2410       write_char ('_');
2411     }
2412
2413   /* Scoped name.  */
2414   write_encoding (fn_decl);
2415
2416   result = finish_mangling ();
2417   if (DEBUG_MANGLE)
2418     fprintf (stderr, "mangle_thunk = %s\n\n", result);
2419   return get_identifier (result);
2420 }
2421
2422 /* Return an identifier for the mangled unqualified name for a
2423    conversion operator to TYPE.  This mangling is not specified by the
2424    ABI spec; it is only used internally.  */
2425
2426 tree
2427 mangle_conv_op_name_for_type (type)
2428      tree type;
2429 {
2430   tree identifier;
2431
2432   /* Build the mangling for TYPE.  */
2433   const char *mangled_type = mangle_type_string (type);
2434   /* Allocate a temporary buffer for the complete name.  */
2435   char *op_name = concat ("operator ", mangled_type, NULL);
2436   /* Find or create an identifier.  */
2437   identifier = get_identifier (op_name);
2438   /* Done with the temporary buffer.  */
2439   free (op_name);
2440   /* Set bits on the identifier so we know later it's a conversion.  */
2441   IDENTIFIER_OPNAME_P (identifier) = 1;
2442   IDENTIFIER_TYPENAME_P (identifier) = 1;
2443   /* Hang TYPE off the identifier so it can be found easily later when
2444      performing conversions.  */
2445   TREE_TYPE (identifier) = type;
2446
2447   return identifier;
2448 }
2449
2450 /* Return an identifier for the name of an initialization guard
2451    variable for indicated VARIABLE.  */
2452
2453 tree
2454 mangle_guard_variable (variable)
2455      tree variable;
2456 {
2457   start_mangling ();
2458   write_string ("_ZGV");
2459   if (strncmp (IDENTIFIER_POINTER (DECL_NAME (variable)), "_ZGR", 4) == 0)
2460     /* The name of a guard variable for a reference temporary should refer
2461        to the reference, not the temporary.  */
2462     write_string (IDENTIFIER_POINTER (DECL_NAME (variable)) + 4);
2463   else
2464     write_name (variable, /*ignore_local_scope=*/0);
2465   return get_identifier (finish_mangling ());
2466 }
2467
2468 /* Return an identifier for the name of a temporary variable used to
2469    initialize a static reference.  This isn't part of the ABI, but we might
2470    as well call them something readable.  */
2471
2472 tree
2473 mangle_ref_init_variable (variable)
2474      tree variable;
2475 {
2476   start_mangling ();
2477   write_string ("_ZGR");
2478   write_name (variable, /*ignore_local_scope=*/0);
2479   return get_identifier (finish_mangling ());
2480 }
2481 \f
2482
2483 /* Foreign language type mangling section.  */
2484
2485 /* How to write the type codes for the integer Java type.  */
2486
2487 static void
2488 write_java_integer_type_codes (type)
2489      tree type;
2490 {
2491   if (type == java_int_type_node)
2492     write_char ('i');
2493   else if (type == java_short_type_node)
2494     write_char ('s');
2495   else if (type == java_byte_type_node)
2496     write_char ('c');
2497   else if (type == java_char_type_node)
2498     write_char ('w');
2499   else if (type == java_long_type_node)
2500     write_char ('x');
2501   else if (type == java_boolean_type_node)
2502     write_char ('b');
2503   else
2504     abort ();
2505 }
2506