OSDN Git Service

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