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