OSDN Git Service

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