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