OSDN Git Service

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