OSDN Git Service

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